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,1685 @@
1
+ """Independent semantic and relationship processing stages for sync."""
2
+
3
+ import json
4
+ import hashlib
5
+ import re
6
+ import math
7
+ import time
8
+ from datetime import date, datetime
9
+ from decimal import Decimal
10
+ from typing import Any
11
+
12
+ from semantic_context_engine.sources.base import Source
13
+ from semantic_context_engine.enrichment import StructuredLLM
14
+ from semantic_context_engine.registry import Registry
15
+ from semantic_context_engine.errors import (
16
+ AggregateQueryBudgetExceeded,
17
+ AggregateQueryExecutionError,
18
+ ProviderDiagnosticError,
19
+ ProviderError,
20
+ SemanticValidationError,
21
+ SourceError,
22
+ StorageError,
23
+ safe_error_label,
24
+ )
25
+
26
+
27
+ _ENRICHMENT_STAGES = ("taxonomy", "families", "synthesis", "grain_correction")
28
+
29
+
30
+ def _safe_identity(value: Any) -> str:
31
+ if (
32
+ type(value) is str
33
+ and 0 < len(value) <= 128
34
+ and re.fullmatch(r"[A-Za-z0-9_.:/+-]+", value)
35
+ and not re.search(
36
+ r"(?i)(secret|token|api[_-]?key|bearer|credential|password|private[_-]?key|authorization)",
37
+ value,
38
+ )
39
+ and not re.fullmatch(r"[A-Za-z0-9_-]{32,}", value)
40
+ ):
41
+ return value
42
+ return "unknown"
43
+
44
+
45
+ def _safe_count(value: Any) -> int | None:
46
+ if isinstance(value, int) and not isinstance(value, bool) and value >= 0:
47
+ return value
48
+ return None
49
+
50
+
51
+ class _ObservedStructuredLLM:
52
+ """Count adapter calls and bounded telemetry without retaining inputs/outputs."""
53
+
54
+ def __init__(self, adapter: StructuredLLM) -> None:
55
+ self._adapter = adapter
56
+ self.invocations = 0
57
+ self.stage_calls: dict[str, int] = {}
58
+ self.stage_durations: dict[str, float] = {}
59
+ self.last_stage = "unknown_stage"
60
+ self._retry_start = _safe_count(getattr(adapter, "retry_count", None))
61
+ usage = getattr(adapter, "usage_totals", None)
62
+ self._usage_start: dict[str, int] = {}
63
+ if isinstance(usage, dict):
64
+ for key, item in usage.items():
65
+ value = _safe_count(item)
66
+ if type(key) is str and value is not None:
67
+ self._usage_start[key] = value
68
+
69
+ def __getattr__(self, name: str) -> Any:
70
+ return getattr(self._adapter, name)
71
+
72
+ def record_retry(self) -> None:
73
+ value = _safe_count(getattr(self._adapter, "retry_count", None))
74
+ if value is not None:
75
+ try:
76
+ setattr(self._adapter, "retry_count", value + 1)
77
+ except (AttributeError, TypeError):
78
+ pass
79
+
80
+ def generate(self, stage, context, schema, *, timeout_seconds):
81
+ self.invocations += 1
82
+ self.last_stage = stage if stage in _ENRICHMENT_STAGES else "unknown_stage"
83
+ self.stage_calls[self.last_stage] = self.stage_calls.get(self.last_stage, 0) + 1
84
+ started = time.perf_counter()
85
+ try:
86
+ return self._adapter.generate(stage, context, schema, timeout_seconds=timeout_seconds)
87
+ finally:
88
+ elapsed = max(0.0, time.perf_counter() - started)
89
+ self.stage_durations[self.last_stage] = (
90
+ self.stage_durations.get(self.last_stage, 0.0) + elapsed
91
+ )
92
+
93
+ def telemetry(self) -> dict[str, Any]:
94
+ retry_end = _safe_count(getattr(self._adapter, "retry_count", None))
95
+ retry_delta: int | str = (
96
+ max(0, retry_end - self._retry_start)
97
+ if retry_end is not None and self._retry_start is not None
98
+ else "unknown"
99
+ )
100
+ usage = getattr(self._adapter, "usage_totals", None)
101
+ tokens: dict[str, int] | str = "unknown"
102
+ if isinstance(usage, dict):
103
+ tokens = {}
104
+ for key in ("input_tokens", "output_tokens", "total_tokens"):
105
+ value = _safe_count(usage.get(key))
106
+ if value is not None:
107
+ tokens[key] = max(0, value - self._usage_start.get(key, 0))
108
+ if not tokens:
109
+ tokens = "unknown"
110
+ if hasattr(self._adapter, "configured_provider_name"):
111
+ configured_provider = getattr(self._adapter, "configured_provider_name")
112
+ else:
113
+ configured_provider = getattr(self._adapter, "provider_name", None)
114
+ if hasattr(self._adapter, "configured_model_name"):
115
+ configured_model = getattr(self._adapter, "configured_model_name")
116
+ else:
117
+ configured_model = getattr(self._adapter, "model_name", None)
118
+ observed_provider = getattr(self._adapter, "observed_provider_name", None)
119
+ observed_model = getattr(self._adapter, "observed_model_name", None)
120
+ finish_reason = getattr(self._adapter, "last_finish_reason", None)
121
+ if finish_reason not in {"stop", "length", "tool_calls", "content_filter", "error"}:
122
+ finish_reason = "unknown"
123
+ return {
124
+ "adapter_identity": _safe_identity(type(self._adapter).__name__) or "unknown",
125
+ "configured_provider_identity": _safe_identity(configured_provider),
126
+ "configured_model_identity": _safe_identity(configured_model),
127
+ "observed_provider_identity": _safe_identity(observed_provider),
128
+ "observed_model_identity": _safe_identity(observed_model),
129
+ "adapter_invocation_count": self.invocations,
130
+ "stage_call_counts": dict(self.stage_calls),
131
+ "stage_duration_seconds": {
132
+ stage: round(seconds, 6) for stage, seconds in self.stage_durations.items()
133
+ },
134
+ "retry_count": retry_delta,
135
+ "token_usage": tokens,
136
+ "finish_reason": finish_reason,
137
+ "http_request_count": "unknown",
138
+ }
139
+
140
+
141
+ def _enrichment_diagnostic(
142
+ object_key: str, exc: BaseException, llm: _ObservedStructuredLLM
143
+ ) -> dict[str, Any]:
144
+ if isinstance(exc, SemanticValidationError):
145
+ result = exc.to_diagnostic(object_key)
146
+ elif isinstance(exc, ProviderDiagnosticError):
147
+ result = exc.to_diagnostic(object_key)
148
+ elif isinstance(exc, SourceError):
149
+ result = {
150
+ "object": object_key,
151
+ "stage": llm.last_stage,
152
+ "category": "source_failure",
153
+ "code": "source_unavailable",
154
+ "retryable": False,
155
+ }
156
+ elif isinstance(exc, StorageError):
157
+ result = {
158
+ "object": object_key,
159
+ "stage": llm.last_stage,
160
+ "category": "storage_failure",
161
+ "code": "storage_unavailable",
162
+ "retryable": False,
163
+ }
164
+ elif isinstance(exc, ProviderError):
165
+ result = {
166
+ "object": object_key,
167
+ "stage": llm.last_stage,
168
+ "category": "transport_failure",
169
+ "code": "provider_invocation_failed",
170
+ "retryable": False,
171
+ }
172
+ else:
173
+ result = {
174
+ "object": object_key,
175
+ "stage": llm.last_stage,
176
+ "category": "internal_error",
177
+ "code": "unexpected_error",
178
+ "retryable": False,
179
+ }
180
+ result["telemetry"] = llm.telemetry()
181
+ return result
182
+
183
+
184
+ def _sanitize_sample_context(
185
+ object_key: str,
186
+ values: Any,
187
+ transform,
188
+ *,
189
+ allowed_columns: list[str],
190
+ max_payload_bytes: int,
191
+ max_value_bytes: int,
192
+ ) -> Any:
193
+ if not isinstance(values, (dict, list)):
194
+ raise ValueError("Sampling returned malformed bounded values")
195
+
196
+ def safe_value(column: str, value: Any) -> Any:
197
+ if transform is not None:
198
+ value = transform(object_key, column, value)
199
+ if value is None or isinstance(value, bool):
200
+ if len(json.dumps(value).encode("utf-8")) > max_value_bytes:
201
+ raise ValueError("Sample value exceeds configured byte budget")
202
+ return value
203
+ if isinstance(value, int):
204
+ if len(str(value).encode("utf-8")) > max_value_bytes:
205
+ raise ValueError("Sample value exceeds configured byte budget")
206
+ return value
207
+ if isinstance(value, float):
208
+ if not math.isfinite(value):
209
+ raise ValueError("Sample numeric value is not finite")
210
+ if len(str(value).encode("utf-8")) > max_value_bytes:
211
+ raise ValueError("Sample value exceeds configured byte budget")
212
+ return value
213
+ if isinstance(value, (date, datetime)):
214
+ value = value.isoformat()
215
+ elif isinstance(value, Decimal):
216
+ value = str(value)
217
+ if not isinstance(value, str):
218
+ raise ValueError("Sample transform must return JSON scalar values")
219
+ raw = value.encode("utf-8")
220
+ if len(raw) > max_value_bytes:
221
+ raise ValueError("Sample value exceeds configured byte budget")
222
+ return value
223
+
224
+ safe: Any
225
+ if isinstance(values, list):
226
+ safe = [
227
+ {str(column): safe_value(str(column), value) for column, value in row.items()}
228
+ for row in values
229
+ if isinstance(row, dict)
230
+ ]
231
+ else:
232
+ safe = {
233
+ str(column): [safe_value(str(column), item) for item in items]
234
+ for column, items in values.items()
235
+ if isinstance(items, list)
236
+ }
237
+ returned_columns = (
238
+ {name for row in safe for name in row} if isinstance(safe, list) else set(safe)
239
+ )
240
+ if not returned_columns <= set(allowed_columns):
241
+ raise ValueError("Sampling source returned a non-allowlisted column")
242
+ size = len(json.dumps(safe, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))
243
+ if size > max_payload_bytes:
244
+ raise ValueError("Sample payload exceeds configured byte budget")
245
+ return safe
246
+
247
+
248
+ def _contains_sample_value(entity: Any, sample: Any) -> bool:
249
+ candidates: list[Any] = []
250
+
251
+ def collect(value: Any) -> None:
252
+ if isinstance(value, dict):
253
+ for item in value.values():
254
+ collect(item)
255
+ elif isinstance(value, list):
256
+ for item in value:
257
+ collect(item)
258
+ elif isinstance(value, str) and value:
259
+ candidates.append(value)
260
+ elif isinstance(value, (bool, int, float)):
261
+ candidates.append(str(value))
262
+
263
+ collect(sample)
264
+ serialized: list[str] = []
265
+
266
+ def scan(value: Any) -> None:
267
+ if isinstance(value, dict):
268
+ for item in value.values():
269
+ scan(item)
270
+ elif isinstance(value, list):
271
+ for item in value:
272
+ scan(item)
273
+ elif isinstance(value, str):
274
+ serialized.append(value)
275
+ elif value is not None:
276
+ serialized.append(str(value))
277
+
278
+ scan(entity)
279
+ for candidate in candidates:
280
+ if candidate in (None, ""):
281
+ continue
282
+ if any(value == candidate for value in serialized):
283
+ return True
284
+ if isinstance(candidate, str):
285
+ if len(candidate) >= 4 and any(candidate in value for value in serialized):
286
+ return True
287
+ if len(candidate) < 4:
288
+ token = re.compile(r"(?<![\w])" + re.escape(candidate) + r"(?![\w])")
289
+ if any(token.search(value) for value in serialized):
290
+ return True
291
+ return False
292
+
293
+
294
+ def _relationship_semantic_projection(
295
+ semantic_data: dict | None,
296
+ object_keys: set[str],
297
+ candidates: list[dict],
298
+ object_overrides: dict,
299
+ *,
300
+ max_bytes: int = 131072,
301
+ max_columns_per_object: int = 64,
302
+ ) -> dict[str, Any]:
303
+ entities = (semantic_data or {}).get("entities", {})
304
+ needed: dict[str, set[str]] = {key: set() for key in object_keys}
305
+ for candidate in candidates:
306
+ for side in ("source", "target"):
307
+ key = candidate.get(side)
308
+ if key not in needed:
309
+ continue
310
+ needed[key].update(candidate.get(f"{side}_keys", []))
311
+ projection: dict[str, Any] = {}
312
+ for key in sorted(object_keys):
313
+ entity = entities.get(key)
314
+ if not isinstance(entity, dict):
315
+ projection[key] = {"status": "semantic_unavailable"}
316
+ continue
317
+ columns = entity.get("columns", [])
318
+ if not isinstance(columns, list):
319
+ projection[key] = {"status": "semantic_unavailable"}
320
+ continue
321
+ by_name = {
322
+ name: item
323
+ for item in columns
324
+ if isinstance(item, dict) and isinstance((name := item.get("name")), str)
325
+ }
326
+ essential = set(needed[key]) | set(entity.get("grain", []))
327
+ for column in columns:
328
+ if not isinstance(column, dict):
329
+ continue
330
+ if column.get("role") in {"additive_measure", "non_additive_measure"}:
331
+ name = column.get("name")
332
+ if isinstance(name, str):
333
+ essential.add(name)
334
+ essential.update(
335
+ item for item in column.get("recompute_from", []) if isinstance(item, str)
336
+ )
337
+ if entity.get("time_column"):
338
+ essential.add(entity["time_column"])
339
+ for path in entity.get("hierarchies", []):
340
+ if isinstance(path, list):
341
+ essential.update(item for item in path if isinstance(item, str))
342
+ essential_order = sorted(essential)
343
+ if len(essential_order) > max_columns_per_object:
344
+ raise ValueError("Relationship semantic context exceeds essential column limit")
345
+ selected = essential_order + [
346
+ name
347
+ for name in sorted(by_name)
348
+ if name not in essential and len(essential_order) < max_columns_per_object
349
+ ]
350
+ selected = selected[:max_columns_per_object]
351
+ overrides = object_overrides.get(key, {})
352
+ relevant_override = {
353
+ field: overrides[field]
354
+ for field in ("role", "family", "description", "time_column", "grain", "limitations")
355
+ if field in overrides
356
+ }
357
+ override_columns = overrides.get("columns", {})
358
+ if isinstance(override_columns, dict):
359
+ relevant_override["columns"] = {
360
+ name: override_columns[name] for name in selected if name in override_columns
361
+ }
362
+ projected_columns = []
363
+ for name in selected:
364
+ if name not in by_name:
365
+ continue
366
+ item = dict(by_name[name])
367
+ column_override = (
368
+ override_columns.get(name, {}) if isinstance(override_columns, dict) else {}
369
+ )
370
+ if isinstance(column_override, dict):
371
+ item.update(column_override)
372
+ projected_columns.append(item)
373
+ projection[key] = {
374
+ "description": entity.get("description", ""),
375
+ "purpose": entity.get("purpose", entity.get("description", "")),
376
+ "families": entity.get("families", {}),
377
+ "grain": {
378
+ "proposed": entity.get("grain", []),
379
+ "verification": entity.get("grain_check", {}).get("status", "unknown"),
380
+ "verified": entity.get("grain_check", {}).get("final")
381
+ if entity.get("grain_check", {}).get("status") == "verified"
382
+ else None,
383
+ },
384
+ "time_column": entity.get("time_column"),
385
+ "columns": projected_columns,
386
+ "hierarchies": [
387
+ {"path": path, "status": "verified"} for path in entity.get("hierarchies", [])
388
+ ],
389
+ "hierarchy_evidence": entity.get("hierarchy_evidence", [])[:32],
390
+ "discriminator_grain_evidence": entity.get("discriminator_grain_evidence", [])[:32],
391
+ "formula_coverage": entity.get("formula_coverage", [])[:32],
392
+ "limitations": entity.get("limitations", [])[:32],
393
+ "effective_human_overrides": relevant_override,
394
+ "omitted_column_count": max(0, len(by_name) - len(selected)),
395
+ }
396
+ encoded = json.dumps(projection, sort_keys=True, ensure_ascii=False, default=str).encode()
397
+ if len(encoded) > max_bytes:
398
+ raise ValueError("Relationship semantic context exceeds payload budget")
399
+ return projection
400
+
401
+
402
+ class SemanticPipeline:
403
+ """Preserve, enrich, and invalidate semantic artifacts for a candidate."""
404
+
405
+ def __init__(
406
+ self,
407
+ *,
408
+ config: Any,
409
+ source: Source,
410
+ llm: StructuredLLM | None,
411
+ sample_transform=None,
412
+ ):
413
+ self.config = config
414
+ self.source = source
415
+ self.llm = llm
416
+ self.sample_transform = sample_transform
417
+
418
+ def process(
419
+ self,
420
+ registry: Registry,
421
+ baseline,
422
+ candidate,
423
+ report: dict,
424
+ snapshots_objects: dict,
425
+ enrich: bool,
426
+ relations: bool,
427
+ recompute_relations: bool,
428
+ publish: bool,
429
+ recompile: bool = False,
430
+ fail_fast: bool = False,
431
+ ):
432
+ if not isinstance(fail_fast, bool):
433
+ raise ValueError("fail_fast must be a boolean")
434
+ semantic_data = None
435
+ enrichment_report = None
436
+ if not enrich:
437
+ try:
438
+ prior_semantic = registry.load_semantic(baseline.version) if baseline else {}
439
+ if prior_semantic or (baseline and report.get("status") != "no_changes"):
440
+ changed_keys = (
441
+ set(report.get("added", []))
442
+ | set(report.get("changed", {}))
443
+ | set(report.get("removed", []))
444
+ )
445
+ live_keys = set(candidate.objects)
446
+ entities = {
447
+ k: v
448
+ for k, v in prior_semantic.get("entities", {}).items()
449
+ if k in live_keys and k not in changed_keys
450
+ }
451
+ relationships = []
452
+ for rel in prior_semantic.get("relationships", []):
453
+ pair = (
454
+ {rel.get("source"), rel.get("target")}
455
+ if isinstance(rel, dict)
456
+ else set()
457
+ )
458
+ if pair & changed_keys:
459
+ stale = dict(rel)
460
+ stale.update(
461
+ {
462
+ "verdict": "not_checked",
463
+ "served": False,
464
+ "metrics": {},
465
+ "caution": "underlying structure changed; relationship validation is pending",
466
+ }
467
+ )
468
+ relationships.append(stale)
469
+ else:
470
+ relationships.append(rel)
471
+ cache = {}
472
+ for token, value in prior_semantic.get("relationship_cache", {}).items():
473
+ try:
474
+ pair = set(json.loads(token))
475
+ except Exception as exc:
476
+ raise ValueError(f"Corrupt relationship cache token: {exc}") from exc
477
+ if not pair & changed_keys and pair <= live_keys:
478
+ cache[token] = value
479
+ semantic_data = {
480
+ **prior_semantic,
481
+ "schema_version": prior_semantic.get("schema_version", 1),
482
+ "entities": entities,
483
+ "relationships": relationships,
484
+ "relationship_cache": cache,
485
+ }
486
+ pending = set(prior_semantic.get("semantic_pending", [])) & live_keys
487
+ pending.update(
488
+ (set(report.get("added", [])) | set(report.get("changed", {}))) & live_keys
489
+ )
490
+ pending_list = sorted(pending)
491
+ if pending_list or "semantic_pending" in prior_semantic:
492
+ semantic_data["semantic_pending"] = pending_list
493
+ except Exception:
494
+ report["status"] = "failed"
495
+ report["enrichment_failed"] = {
496
+ "semantic": "Could not preserve baseline semantic artifact (storage_unavailable)"
497
+ }
498
+ return {"early_report": report}
499
+ if enrich:
500
+ if self.llm is None:
501
+ report["status"] = "failed"
502
+ report["enrichment_failed"] = {
503
+ "llm": "StructuredLLM must be injected when enrich=True"
504
+ }
505
+ return {"early_report": report}
506
+ try:
507
+ previous = registry.load_semantic(baseline.version) if baseline else {}
508
+ except Exception:
509
+ report["status"] = "failed"
510
+ report["enrichment_failed"] = {
511
+ "semantic": "Could not read baseline semantic artifact (storage_unavailable)"
512
+ }
513
+ return {"early_report": report}
514
+ entities = dict(previous.get("entities", {}))
515
+ for removed_key in report.get("removed", []):
516
+ entities.pop(removed_key, None)
517
+ if recompile:
518
+ # This is deliberately explicit: prompt/model changes do not
519
+ # trigger provider work on ordinary unchanged syncs.
520
+ enrichment_keys = sorted(candidate.objects)
521
+ else:
522
+ enrichment_keys = list(report.get("added", [])) + list(
523
+ report.get("changed", {}).keys()
524
+ )
525
+ # A prior structural-only publish can be enriched later without
526
+ # pretending that its structure changed.
527
+ enrichment_keys.extend(
528
+ key
529
+ for key in candidate.objects
530
+ if key not in entities and key not in enrichment_keys
531
+ )
532
+ from semantic_context_engine.enrichment import enrich_object
533
+
534
+ enriched_keys = []
535
+ grain_checks = {}
536
+ enrichment_failed = {}
537
+ enrichment_diagnostics: list[dict[str, Any]] = []
538
+ stage_events: list[dict[str, str]] = []
539
+ sampling_report: dict[str, dict[str, Any]] = {}
540
+ sampling_queries = 0
541
+ profile_report: dict[str, dict[str, Any]] = {}
542
+ profile_queries = 0
543
+ sample_policy = getattr(self.config, "sampling", {})
544
+ sampling_enabled = bool(sample_policy.get("enabled", False))
545
+ allowed_samples = sample_policy.get("allowed_columns", {})
546
+ sample_mode = sample_policy.get("mode", "rows")
547
+ sample_policy_revision = hashlib.sha256(
548
+ json.dumps(sample_policy, sort_keys=True, separators=(",", ":")).encode()
549
+ ).hexdigest()
550
+ profile_policy = getattr(self.config, "profiling", {})
551
+ profile_enabled = bool(profile_policy.get("enabled", False))
552
+ profile_columns = profile_policy.get("allowed_columns", {})
553
+ profile_budget = int(profile_policy.get("max_queries_per_run", 0))
554
+ profile_policy_revision = hashlib.sha256(
555
+ json.dumps(profile_policy, sort_keys=True, separators=(",", ":")).encode()
556
+ ).hexdigest()
557
+ for object_index, key in enumerate(enrichment_keys):
558
+ observed_llm = _ObservedStructuredLLM(self.llm)
559
+
560
+ def record_stage(stage: str, status: str, *, _object_key=key) -> None:
561
+ if stage in _ENRICHMENT_STAGES and status == "completed":
562
+ stage_events.append(
563
+ {"object": _object_key, "stage": stage, "status": "completed"}
564
+ )
565
+
566
+ try:
567
+ sample_context = None
568
+ profile_context = None
569
+ if profile_enabled:
570
+ allowed_profile_columns = profile_columns.get(key, [])
571
+ if not allowed_profile_columns:
572
+ profile_report[key] = {"status": "no_approved_columns", "queries": 0}
573
+ elif profile_queries >= profile_budget:
574
+ profile_report[key] = {"status": "budget_exhausted", "queries": 0}
575
+ elif not getattr(
576
+ getattr(self.source, "capabilities", None), "column_statistics", False
577
+ ) or not callable(getattr(self.source, "profile_column_statistics", None)):
578
+ profile_report[key] = {"status": "unsupported", "queries": 0}
579
+ else:
580
+ profile_method = getattr(self.source, "profile_column_statistics")
581
+ measured = profile_method(
582
+ candidate.objects[key], allowed_profile_columns
583
+ )
584
+ actual = measured.get("query_count", 0)
585
+ if actual != 1 or profile_queries + actual > profile_budget:
586
+ raise ValueError(
587
+ "Profile source exceeded its declared query budget"
588
+ )
589
+ profile_queries += actual
590
+ profile_context = measured.get("statistics")
591
+ if not isinstance(profile_context, dict):
592
+ raise ValueError("Profile source returned malformed statistics")
593
+ profile_report[key] = {"status": "measured", "queries": actual}
594
+ if sampling_enabled:
595
+ allowed_columns = allowed_samples.get(key, [])
596
+ budget = int(sample_policy.get("max_queries_per_run", 0))
597
+ cost = 1 if sample_mode == "rows" else len(allowed_columns)
598
+ if not allowed_columns:
599
+ sampling_report[key] = {"status": "no_approved_columns", "queries": 0}
600
+ elif sampling_queries + cost > budget:
601
+ sampling_report[key] = {"status": "budget_exhausted", "queries": 0}
602
+ elif not getattr(
603
+ getattr(self.source, "capabilities", None), "bounded_sampling", False
604
+ ) or not callable(getattr(self.source, "sample_values", None)):
605
+ sampling_report[key] = {"status": "unsupported", "queries": 0}
606
+ else:
607
+ sample_method = getattr(self.source, "sample_values")
608
+ sampled = sample_method(
609
+ candidate.objects[key],
610
+ allowed_columns,
611
+ mode=sample_mode,
612
+ max_rows=int(sample_policy.get("max_rows_per_object", 5)),
613
+ max_values=int(sample_policy.get("max_values_per_column", 5)),
614
+ max_queries=budget - sampling_queries,
615
+ )
616
+ actual_queries = sampled.get("query_count", 0)
617
+ if (
618
+ isinstance(actual_queries, bool)
619
+ or not isinstance(actual_queries, int)
620
+ or actual_queries < 0
621
+ or actual_queries > budget - sampling_queries
622
+ ):
623
+ raise ValueError(
624
+ "Sampling source exceeded its declared query budget"
625
+ )
626
+ sampling_queries += actual_queries
627
+ sample_context = _sanitize_sample_context(
628
+ key,
629
+ sampled.get("values"),
630
+ self.sample_transform,
631
+ allowed_columns=allowed_columns,
632
+ max_payload_bytes=int(sample_policy.get("max_payload_bytes", 8192)),
633
+ max_value_bytes=int(sample_policy.get("max_value_bytes", 256)),
634
+ )
635
+ sampling_report[key] = {
636
+ "status": "sampled",
637
+ "queries": actual_queries,
638
+ "payload_bytes": len(
639
+ json.dumps(sample_context, ensure_ascii=False).encode("utf-8")
640
+ ),
641
+ }
642
+ entity = enrich_object(
643
+ self.source,
644
+ candidate.objects[key],
645
+ observed_llm,
646
+ query_budget=self.config.enrichment_query_budget,
647
+ hierarchy_query_budget=getattr(self.config, "hierarchy_query_budget", 0),
648
+ formula_query_budget=getattr(self.config, "formula_query_budget", 4),
649
+ discriminator_query_budget=getattr(
650
+ self.config, "discriminator_query_budget", 0
651
+ ),
652
+ sample_context=sample_context,
653
+ profile_context=profile_context,
654
+ profiling_policy_revision=(
655
+ profile_policy_revision if profile_enabled else None
656
+ ),
657
+ sampling_policy_revision=(
658
+ sample_policy_revision if sampling_enabled else None
659
+ ),
660
+ stage_event_callback=record_stage,
661
+ ).to_dict()
662
+ if sample_context and _contains_sample_value(entity, sample_context):
663
+ raise SemanticValidationError(
664
+ "persistence", "sample_persistence_violation", invalid_count=1
665
+ )
666
+ entities[key] = entity
667
+ enriched_keys.append(key)
668
+ grain_checks[key] = entity["grain_check"]
669
+ except Exception as exc:
670
+ # Provider output and validation errors may contain model
671
+ # text or source values. Reports expose only stable labels.
672
+ enrichment_failed[key] = safe_error_label(exc)
673
+ diagnostic = _enrichment_diagnostic(key, exc, observed_llm)
674
+ enrichment_diagnostics.append(diagnostic)
675
+ failed_stage = diagnostic["stage"]
676
+ stage_events.append({"object": key, "stage": failed_stage, "status": "failed"})
677
+ if fail_fast:
678
+ completed_for_object = {
679
+ event["stage"]
680
+ for event in stage_events
681
+ if event["object"] == key and event["status"] == "completed"
682
+ }
683
+ remaining_stages: tuple[str, ...] = _ENRICHMENT_STAGES
684
+ if failed_stage in _ENRICHMENT_STAGES:
685
+ remaining_stages = _ENRICHMENT_STAGES[
686
+ _ENRICHMENT_STAGES.index(failed_stage) + 1 :
687
+ ]
688
+ for stage in remaining_stages:
689
+ if stage not in completed_for_object:
690
+ stage_events.append(
691
+ {
692
+ "object": key,
693
+ "stage": stage,
694
+ "status": "skipped",
695
+ "reason": "fail_fast",
696
+ }
697
+ )
698
+ for remaining_key in enrichment_keys[object_index + 1 :]:
699
+ for stage in _ENRICHMENT_STAGES:
700
+ stage_events.append(
701
+ {
702
+ "object": remaining_key,
703
+ "stage": stage,
704
+ "status": "unattempted",
705
+ "reason": "fail_fast",
706
+ }
707
+ )
708
+ if relations:
709
+ stage_events.append(
710
+ {
711
+ "object": "__relationships__",
712
+ "stage": "relations",
713
+ "status": "skipped",
714
+ "reason": "enrichment_failure",
715
+ }
716
+ )
717
+ if publish:
718
+ stage_events.append(
719
+ {
720
+ "object": "__catalog__",
721
+ "stage": "publication",
722
+ "status": "skipped",
723
+ "reason": "enrichment_failure",
724
+ }
725
+ )
726
+ report["status"] = "failed"
727
+ report["enrichment_failed"] = enrichment_failed
728
+ report["enrichment_diagnostics"] = enrichment_diagnostics[:1000]
729
+ report["semantic_execution"] = {
730
+ "fail_fast": True,
731
+ "stages": stage_events,
732
+ }
733
+ return {"early_report": report}
734
+ if enrichment_failed:
735
+ report["status"] = "failed"
736
+ report["enrichment_failed"] = enrichment_failed
737
+ report["enrichment_diagnostics"] = enrichment_diagnostics[:1000]
738
+ if relations:
739
+ stage_events.append(
740
+ {
741
+ "object": "__relationships__",
742
+ "stage": "relations",
743
+ "status": "skipped",
744
+ "reason": "enrichment_failure",
745
+ }
746
+ )
747
+ if publish:
748
+ stage_events.append(
749
+ {
750
+ "object": "__catalog__",
751
+ "stage": "publication",
752
+ "status": "skipped",
753
+ "reason": "enrichment_failure",
754
+ }
755
+ )
756
+ report["semantic_execution"] = {
757
+ "fail_fast": False,
758
+ "stages": stage_events,
759
+ }
760
+ return {"early_report": report}
761
+ semantic_data = {
762
+ **previous,
763
+ "schema_version": previous.get("schema_version", 1),
764
+ "entities": entities,
765
+ }
766
+ if "semantic_pending" in previous:
767
+ semantic_data["semantic_pending"] = []
768
+ enrichment_report = {
769
+ "status": "complete",
770
+ "enriched": enriched_keys,
771
+ "grain_checks": grain_checks,
772
+ "recompiled": recompile,
773
+ "sampling": sampling_report,
774
+ "sampling_queries": sampling_queries,
775
+ "profiling": profile_report,
776
+ "profiling_queries": profile_queries,
777
+ }
778
+ if enriched_keys and report.get("status") == "no_changes":
779
+ report["status"] = "published" if publish else "dry_run"
780
+
781
+ # If relationship validation is skipped, retain its records for audit
782
+ # while invalidating evidence affected by structural change. A later
783
+ # relations-enabled run can identify these pairs as pending and retry.
784
+ if semantic_data is not None and not (relations or recompute_relations):
785
+ changed_for_relations = (
786
+ set(report.get("added", []))
787
+ | set(report.get("changed", {}))
788
+ | set(report.get("removed", []))
789
+ )
790
+ if changed_for_relations:
791
+ for rel in semantic_data.get("relationships", []):
792
+ if (
793
+ isinstance(rel, dict)
794
+ and {rel.get("source"), rel.get("target")} & changed_for_relations
795
+ ):
796
+ rel.update(
797
+ {
798
+ "verdict": "not_checked",
799
+ "served": False,
800
+ "metrics": {},
801
+ "caution": "underlying structure changed; relationship validation is pending",
802
+ }
803
+ )
804
+ semantic_data["relationship_cache"] = {
805
+ token: value
806
+ for token, value in semantic_data.get("relationship_cache", {}).items()
807
+ if not (set(json.loads(token)) & changed_for_relations)
808
+ }
809
+
810
+ return {
811
+ "semantic_data": semantic_data,
812
+ "enrichment_report": enrichment_report,
813
+ "report": report,
814
+ }
815
+
816
+
817
+ class RelationPipeline:
818
+ """Generate, validate, cache, budget, and report relationship candidates."""
819
+
820
+ def __init__(self, *, config: Any, source: Source, llm: StructuredLLM | None):
821
+ self.config = config
822
+ self.source = source
823
+ self.llm = llm
824
+
825
+ def process(
826
+ self,
827
+ registry: Registry,
828
+ baseline,
829
+ candidate,
830
+ report: dict,
831
+ snapshots_objects: dict,
832
+ semantic_data: dict | None,
833
+ relations: bool,
834
+ recompute_relations: bool,
835
+ ):
836
+ if relations or recompute_relations:
837
+ from semantic_context_engine.relations import (
838
+ candidate_identity,
839
+ deterministic_candidates,
840
+ measure_guidance_signature,
841
+ refreshed_measure_guidance,
842
+ suppress_unverified_preaggregation_advice,
843
+ validate_candidates,
844
+ )
845
+ from semantic_context_engine.enrichment import _prompt_bundle_hash, _safe_identity
846
+ import hashlib
847
+
848
+ def llm_provenance_snapshot():
849
+ usage = getattr(self.llm, "usage_totals", {})
850
+ stages = getattr(self.llm, "stage_calls", {})
851
+ fake_calls = getattr(self.llm, "calls", None)
852
+ return {
853
+ "calls": getattr(self.llm, "request_count", None),
854
+ "retries": getattr(self.llm, "retry_count", None),
855
+ "duration": getattr(self.llm, "total_duration_seconds", None),
856
+ "usage": dict(usage) if isinstance(usage, dict) else {},
857
+ "stages": dict(stages) if isinstance(stages, dict) else {},
858
+ "fake_calls": len(fake_calls) if isinstance(fake_calls, list) else None,
859
+ }
860
+
861
+ llm_start = llm_provenance_snapshot()
862
+
863
+ def pair_key(left, right):
864
+ return json.dumps(sorted((left, right)), separators=(",", ":"), ensure_ascii=False)
865
+
866
+ def pair_members(token):
867
+ return json.loads(token)
868
+
869
+ def pair_of(item):
870
+ left, right = item.get("source"), item.get("target")
871
+ return (
872
+ pair_key(left, right)
873
+ if isinstance(left, str) and isinstance(right, str)
874
+ else None
875
+ )
876
+
877
+ overrides = []
878
+ object_overrides = {}
879
+ try:
880
+ override_document = registry.load_overrides()
881
+ overrides = override_document.get("relationships", [])
882
+ object_overrides = {
883
+ **override_document.get("objects", {}),
884
+ **override_document.get("entities", {}),
885
+ }
886
+ except Exception as exc:
887
+ report["status"] = "failed"
888
+ report.setdefault("failed", {})["relations"] = (
889
+ f"Could not load relationship overrides ({safe_error_label(exc)})"
890
+ )
891
+ return {"early_report": report}
892
+
893
+ def override_signature(token):
894
+ scoped = [rel for rel in overrides if pair_of(rel) == token]
895
+ raw = json.dumps(scoped, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
896
+ return hashlib.sha256(raw.encode("utf-8")).hexdigest()
897
+
898
+ forbidden = {
899
+ frozenset((rel.get("source"), rel.get("target")))
900
+ for rel in overrides
901
+ if rel.get("type") == "forbidden" and rel.get("source") and rel.get("target")
902
+ }
903
+
904
+ prior_semantic = {}
905
+ if baseline:
906
+ try:
907
+ prior_semantic = registry.load_semantic(baseline.version)
908
+ except Exception as exc:
909
+ report["status"] = "failed"
910
+ report.setdefault("failed", {})["relations"] = (
911
+ f"Could not read baseline relationships ({safe_error_label(exc)})"
912
+ )
913
+ return {"early_report": report}
914
+ prior_relationships = prior_semantic.get("relationships", [])
915
+ prior_cache = prior_semantic.get("relationship_cache", {})
916
+ prior_work = prior_semantic.get("relationship_work", {})
917
+ if not isinstance(prior_relationships, list):
918
+ report["status"] = "failed"
919
+ report.setdefault("failed", {})["relations"] = "Baseline relationships are corrupt"
920
+ return {"early_report": report}
921
+ if not isinstance(prior_cache, dict):
922
+ prior_cache = {}
923
+ if not isinstance(prior_work, dict):
924
+ prior_work = {}
925
+
926
+ candidates = deterministic_candidates(snapshots_objects)
927
+ # Keep previous model proposals in the work set so an interrupted
928
+ # run can resume them even when a later invocation has no provider.
929
+ known_candidate_ids = {candidate_identity(item) for item in candidates}
930
+ for old in prior_relationships:
931
+ if (
932
+ isinstance(old, dict)
933
+ and old.get("origin") == "llm"
934
+ and isinstance(old.get("source"), str)
935
+ and isinstance(old.get("target"), str)
936
+ and old["source"] in snapshots_objects
937
+ and old["target"] in snapshots_objects
938
+ ):
939
+ candidate = {
940
+ key: old[key]
941
+ for key in (
942
+ "source",
943
+ "target",
944
+ "source_keys",
945
+ "target_keys",
946
+ "type",
947
+ "origin",
948
+ "conditions",
949
+ "transformations",
950
+ )
951
+ if key in old
952
+ }
953
+ if candidate_identity(candidate) not in known_candidate_ids:
954
+ candidates.append(candidate)
955
+ known_candidate_ids.add(candidate_identity(candidate))
956
+
957
+ def work_signature(item):
958
+ pair_token = pair_of(item)
959
+ source_obj = snapshots_objects.get(item.get("source"))
960
+ target_obj = snapshots_objects.get(item.get("target"))
961
+ payload = {
962
+ "candidate": candidate_identity(item),
963
+ "source_fingerprint": getattr(source_obj, "fingerprint", None),
964
+ "target_fingerprint": getattr(target_obj, "fingerprint", None),
965
+ "override_signature": override_signature(pair_token) if pair_token else None,
966
+ "min_match_rate": self.config.relation_min_match_rate,
967
+ "evidence_policy": "relationship-validation-v1",
968
+ "aggregate_capability": bool(
969
+ getattr(
970
+ getattr(self.source, "capabilities", None),
971
+ "relationship_aggregate",
972
+ False,
973
+ )
974
+ ),
975
+ }
976
+ raw = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
977
+ return hashlib.sha256(raw.encode("utf-8")).hexdigest()
978
+
979
+ candidate_signatures = {
980
+ candidate_identity(item): work_signature(item) for item in candidates
981
+ }
982
+ prior_result_by_id = {}
983
+ for old in prior_relationships:
984
+ if isinstance(old, dict):
985
+ old_id = old.get("candidate_id") or candidate_identity(old)
986
+ prior_result_by_id[old_id] = old
987
+
988
+ candidates_per_pair: dict[str, int] = {}
989
+ for item in candidates:
990
+ token = pair_of(item)
991
+ if token:
992
+ candidates_per_pair[token] = candidates_per_pair.get(token, 0) + 1
993
+ legacy_reusable_ids = set()
994
+ if not prior_work and not recompute_relations:
995
+ for item in candidates:
996
+ cid = candidate_identity(item)
997
+ token = pair_of(item)
998
+ old = prior_result_by_id.get(cid)
999
+ if (
1000
+ token
1001
+ and candidates_per_pair.get(token) == 1
1002
+ and prior_cache.get(token) == override_signature(token)
1003
+ and isinstance(old, dict)
1004
+ and (
1005
+ old.get("verdict") != "not_checked"
1006
+ or old.get("metrics")
1007
+ or "unsupported" in old.get("caution", "")
1008
+ or "forbidden" in old.get("caution", "")
1009
+ or "lineage is structural evidence" in old.get("caution", "")
1010
+ )
1011
+ ):
1012
+ legacy_reusable_ids.add(cid)
1013
+
1014
+ prior_pairs = {pair_of(item) for item in prior_relationships if pair_of(item)}
1015
+ object_keys = set(snapshots_objects)
1016
+ import itertools
1017
+
1018
+ potential_pairs = {
1019
+ pair_key(left, right)
1020
+ for left, right in itertools.combinations(sorted(object_keys), 2)
1021
+ }
1022
+ current_pairs = potential_pairs | {
1023
+ token for token in prior_pairs if set(pair_members(token)) <= object_keys
1024
+ }
1025
+ prior_semantic_signatures = prior_semantic.get("relationship_semantic_signatures", {})
1026
+ if not isinstance(prior_semantic_signatures, dict):
1027
+ prior_semantic_signatures = {}
1028
+ current_semantic_signatures: dict[str, str] = {}
1029
+ for token in current_pairs:
1030
+ pair_objects = set(pair_members(token))
1031
+ pair_candidates = [item for item in candidates if pair_of(item) == token]
1032
+ projection = _relationship_semantic_projection(
1033
+ semantic_data, pair_objects, pair_candidates, object_overrides
1034
+ )
1035
+ payload = json.dumps(
1036
+ projection, sort_keys=True, separators=(",", ":"), ensure_ascii=False
1037
+ )
1038
+ current_semantic_signatures[token] = hashlib.sha256(
1039
+ payload.encode("utf-8")
1040
+ ).hexdigest()
1041
+ override_pairs = {pair_of(item) for item in overrides if pair_of(item)}
1042
+ changed_objects = (
1043
+ set(report.get("added", []))
1044
+ | set(report.get("changed", {}))
1045
+ | set(report.get("removed", []))
1046
+ )
1047
+
1048
+ all_pair_tokens = current_pairs | prior_pairs | override_pairs | set(prior_cache)
1049
+ if recompute_relations or (not prior_cache and not prior_work):
1050
+ affected_pairs = set(current_pairs) | (prior_pairs & current_pairs)
1051
+ else:
1052
+ affected_pairs = {
1053
+ token
1054
+ for token in all_pair_tokens
1055
+ if token in current_pairs
1056
+ and (
1057
+ set(pair_members(token)) & changed_objects
1058
+ or prior_cache.get(token) != override_signature(token)
1059
+ )
1060
+ }
1061
+ affected_pairs.update(
1062
+ token
1063
+ for token, signature in current_semantic_signatures.items()
1064
+ if prior_semantic_signatures.get(token) != signature
1065
+ )
1066
+ # A candidate-level pending/retryable record always reopens its
1067
+ # pair; a pair digest alone cannot mark a partially processed pair
1068
+ # complete.
1069
+ for item in candidates:
1070
+ cid = candidate_identity(item)
1071
+ work = prior_work.get(cid)
1072
+ if not isinstance(work, dict) and cid in legacy_reusable_ids:
1073
+ continue
1074
+ if not isinstance(work, dict) or work.get("signature") != candidate_signatures[cid]:
1075
+ if pair_of(item) in current_pairs:
1076
+ affected_pairs.add(pair_of(item))
1077
+ elif work.get("state") in {"pending", "retryable"}:
1078
+ if pair_of(item) in current_pairs:
1079
+ affected_pairs.add(pair_of(item))
1080
+ ordered_pairs = sorted(affected_pairs)
1081
+ cursor = prior_semantic.get("relation_pair_cursor")
1082
+ if isinstance(cursor, str) and ordered_pairs:
1083
+ ordered_pairs = [token for token in ordered_pairs if token > cursor] + [
1084
+ token for token in ordered_pairs if token <= cursor
1085
+ ]
1086
+ run_pair_tokens = ordered_pairs[: self.config.relation_max_pairs]
1087
+ run_pair_set = set(run_pair_tokens)
1088
+ all_candidate_specs = list(candidates)
1089
+ candidates = [item for item in candidates if pair_of(item) in run_pair_set]
1090
+ llm_rejections = 0
1091
+ generated: dict[str, list[dict[str, Any]]] = {"proposals": [], "annotations": []}
1092
+ relation_llm_invoked = False
1093
+ if self.llm is not None and affected_pairs:
1094
+ try:
1095
+ affected_objects = {
1096
+ key: obj
1097
+ for key, obj in snapshots_objects.items()
1098
+ if any(key in pair_members(token) for token in run_pair_tokens)
1099
+ }
1100
+ from semantic_context_engine.enrichment import _generate
1101
+
1102
+ relation_llm_invoked = True
1103
+ generated = _generate(
1104
+ self.llm,
1105
+ "relations",
1106
+ {
1107
+ "semantic_context": _relationship_semantic_projection(
1108
+ semantic_data,
1109
+ set(affected_objects),
1110
+ candidates,
1111
+ object_overrides,
1112
+ ),
1113
+ "objects": {
1114
+ key: {
1115
+ "fqn": obj.fqn,
1116
+ "columns": {
1117
+ name: col.data_type for name, col in obj.columns.items()
1118
+ },
1119
+ "variant_keys": [
1120
+ {
1121
+ "column": item.column,
1122
+ "discriminator": item.discriminator,
1123
+ "key": item.key,
1124
+ "value_type": item.value_type,
1125
+ "status": item.status,
1126
+ }
1127
+ for item in obj.variant_keys
1128
+ ],
1129
+ }
1130
+ for key, obj in affected_objects.items()
1131
+ },
1132
+ "candidates": candidates,
1133
+ },
1134
+ {
1135
+ "proposals": "candidate objects and existing key columns",
1136
+ "annotations": "candidate id, answers, caution",
1137
+ },
1138
+ )
1139
+ from semantic_context_engine.enrichment import RelationsOutput
1140
+
1141
+ generated = RelationsOutput.model_validate(generated).model_dump(mode="python")
1142
+ if not isinstance(generated, dict) or set(generated) != {
1143
+ "proposals",
1144
+ "annotations",
1145
+ }:
1146
+ raise ValueError(
1147
+ "relations output must contain exactly proposals and annotations"
1148
+ )
1149
+ if not isinstance(generated["proposals"], list) or not isinstance(
1150
+ generated["annotations"], list
1151
+ ):
1152
+ raise ValueError("relations proposals and annotations must be lists")
1153
+ known = {candidate_identity(item) for item in candidates}
1154
+ for item in generated["proposals"]:
1155
+ if (
1156
+ not isinstance(item, dict)
1157
+ or set(item)
1158
+ - {
1159
+ "source",
1160
+ "target",
1161
+ "source_keys",
1162
+ "target_keys",
1163
+ "transformations",
1164
+ "conditions",
1165
+ }
1166
+ or not {"source", "target", "source_keys", "target_keys"} <= set(item)
1167
+ ):
1168
+ llm_rejections += 1
1169
+ continue
1170
+ sk, tk = item["source_keys"], item["target_keys"]
1171
+ if (
1172
+ item["source"] not in affected_objects
1173
+ or item["target"] not in affected_objects
1174
+ or pair_of(item) not in run_pair_set
1175
+ or not isinstance(sk, list)
1176
+ or not isinstance(tk, list)
1177
+ or not sk
1178
+ or len(sk) != len(tk)
1179
+ or any(k not in snapshots_objects[item["source"]].columns for k in sk)
1180
+ or any(k not in snapshots_objects[item["target"]].columns for k in tk)
1181
+ ):
1182
+ llm_rejections += 1
1183
+ continue
1184
+ if all(
1185
+ "DATE" in snapshots_objects[item["source"]].columns[k].data_type.upper()
1186
+ or "TIME"
1187
+ in snapshots_objects[item["source"]].columns[k].data_type.upper()
1188
+ for k in sk
1189
+ ) and all(
1190
+ "DATE" in snapshots_objects[item["target"]].columns[k].data_type.upper()
1191
+ or "TIME"
1192
+ in snapshots_objects[item["target"]].columns[k].data_type.upper()
1193
+ for k in tk
1194
+ ):
1195
+ llm_rejections += 1
1196
+ continue
1197
+ proposal = {**item, "origin": "llm", "type": "join"}
1198
+ signature = candidate_identity(proposal)
1199
+ if signature not in known:
1200
+ candidates.append(proposal)
1201
+ all_candidate_specs.append(proposal)
1202
+ known.add(signature)
1203
+ except Exception as exc:
1204
+ report["status"] = "failed"
1205
+ report.setdefault("failed", {})["relations"] = safe_error_label(exc)
1206
+ return {"early_report": report}
1207
+
1208
+ # Persist work per candidate; pair selection and pair cache are not
1209
+ # evidence that every candidate in that pair completed.
1210
+ def candidate_priority(item):
1211
+ cid = candidate_identity(item)
1212
+ old_work = prior_work.get(cid)
1213
+ if not isinstance(old_work, dict) or old_work.get("signature") != work_signature(
1214
+ item
1215
+ ):
1216
+ return (1, cid)
1217
+ state = old_work.get("state")
1218
+ return (
1219
+ 0 if state in {"completed", "blocked"} else 2 if state == "retryable" else 1,
1220
+ cid,
1221
+ )
1222
+
1223
+ all_candidate_specs.sort(key=candidate_priority)
1224
+ work_records: dict[str, dict[str, str]] = {}
1225
+ result_records: dict[str, dict[str, Any]] = {}
1226
+ query_counts: dict[str, int] = {}
1227
+ aggregate_queries = 0
1228
+ aggregate_query_count_unknown = False
1229
+ processed_pairs: set[str] = set()
1230
+ reused_candidate_ids: set[str] = set()
1231
+ for item in all_candidate_specs:
1232
+ cid = candidate_identity(item)
1233
+ token = pair_of(item)
1234
+ forbidden_candidate = (
1235
+ frozenset((item.get("source"), item.get("target"))) in forbidden
1236
+ )
1237
+ signature = work_signature(item)
1238
+ previous = prior_work.get(cid)
1239
+ same_evidence = (
1240
+ isinstance(previous, dict) and previous.get("signature") == signature
1241
+ )
1242
+ previous_state = (
1243
+ previous.get("state")
1244
+ if isinstance(previous, dict) and previous.get("signature") == signature
1245
+ else None
1246
+ )
1247
+ reusable = (
1248
+ (
1249
+ same_evidence
1250
+ and previous_state in {"completed", "blocked"}
1251
+ or cid in legacy_reusable_ids
1252
+ )
1253
+ and not recompute_relations
1254
+ and cid in prior_result_by_id
1255
+ )
1256
+ if reusable:
1257
+ result = dict(prior_result_by_id[cid])
1258
+ result["candidate_id"] = cid
1259
+ reused_candidate_ids.add(cid)
1260
+ latest_entities = (semantic_data or {}).get(
1261
+ "entities", prior_semantic.get("entities", {})
1262
+ )
1263
+ expected_aggregation_signature = measure_guidance_signature(
1264
+ result.get("source", ""),
1265
+ result.get("target", ""),
1266
+ latest_entities,
1267
+ object_overrides,
1268
+ )
1269
+ result = suppress_unverified_preaggregation_advice(
1270
+ result,
1271
+ basis_changed=(
1272
+ result.get("aggregation_guidance_signature")
1273
+ != expected_aggregation_signature
1274
+ ),
1275
+ )
1276
+ state = previous_state
1277
+ if cid in legacy_reusable_ids and state is None:
1278
+ state = (
1279
+ "completed"
1280
+ if result.get("verdict") != "not_checked" or result.get("metrics")
1281
+ else "blocked"
1282
+ )
1283
+ assert state in {"completed", "blocked"}
1284
+ work_records[cid] = {
1285
+ "signature": signature,
1286
+ "state": str(state),
1287
+ }
1288
+ result_records[cid] = result
1289
+ continue
1290
+
1291
+ if token not in run_pair_set:
1292
+ state = "retryable" if previous_state == "retryable" else "pending"
1293
+ result = {
1294
+ **item,
1295
+ "candidate_id": cid,
1296
+ "verdict": "not_checked",
1297
+ "served": False,
1298
+ "metrics": {},
1299
+ "caution": "affected pair not revalidated because the run budget was exhausted",
1300
+ }
1301
+ work_records[cid] = {"signature": signature, "state": state}
1302
+ result_records[cid] = result
1303
+ continue
1304
+
1305
+ # A zero aggregate budget still permits deterministic no-query
1306
+ # outcomes (forbidden and lineage); join evidence stays pending.
1307
+ if (
1308
+ self.config.relation_query_budget_per_pair < 1
1309
+ and not forbidden_candidate
1310
+ and item.get("type") != "lineage"
1311
+ ):
1312
+ state = "retryable" if previous_state == "retryable" else "pending"
1313
+ result = {
1314
+ **item,
1315
+ "candidate_id": cid,
1316
+ "verdict": "not_checked",
1317
+ "served": False,
1318
+ "metrics": {},
1319
+ "caution": "affected pair not revalidated because the run budget was exhausted",
1320
+ }
1321
+ work_records[cid] = {"signature": signature, "state": state}
1322
+ result_records[cid] = result
1323
+ continue
1324
+
1325
+ # Rejected-forbidden and structural lineage candidates consume
1326
+ # no aggregate budget. Other work is bounded per pair and the
1327
+ # remaining candidates stay explicitly pending for the next run.
1328
+ no_query = forbidden_candidate or item.get("type") == "lineage"
1329
+ if (
1330
+ not no_query
1331
+ and query_counts.get(token, 0) >= self.config.relation_query_budget_per_pair
1332
+ ):
1333
+ state = "retryable" if previous_state == "retryable" else "pending"
1334
+ result = {
1335
+ **item,
1336
+ "candidate_id": cid,
1337
+ "verdict": "not_checked",
1338
+ "served": False,
1339
+ "metrics": {},
1340
+ "caution": "affected pair not revalidated because the run budget was exhausted",
1341
+ }
1342
+ work_records[cid] = {"signature": signature, "state": state}
1343
+ result_records[cid] = result
1344
+ continue
1345
+
1346
+ class CountingSource:
1347
+ def __init__(self, wrapped, remaining):
1348
+ self.wrapped = wrapped
1349
+ self.aggregate_queries = 0
1350
+ self.charged_queries = 0
1351
+ self.count_unknown = False
1352
+ self.remaining = remaining
1353
+
1354
+ @property
1355
+ def capabilities(self):
1356
+ return self.wrapped.capabilities
1357
+
1358
+ def condition_is_approved(self, *args, **kwargs):
1359
+ checker = getattr(self.wrapped, "condition_is_approved", None)
1360
+ return bool(callable(checker) and checker(*args, **kwargs))
1361
+
1362
+ def relationship_metrics(self, *args, **kwargs):
1363
+ counted = getattr(self.wrapped, "relationship_metrics_counted", None)
1364
+ if callable(counted):
1365
+ try:
1366
+ metrics, count = counted(
1367
+ *args,
1368
+ max_aggregate_queries=self.remaining,
1369
+ **kwargs,
1370
+ )
1371
+ except AggregateQueryExecutionError as exc:
1372
+ count = exc.executed_count
1373
+ if count > self.remaining:
1374
+ self.aggregate_queries += count
1375
+ self.charged_queries += count
1376
+ raise AggregateQueryBudgetExceeded(
1377
+ "Source exceeded its aggregate statement budget"
1378
+ ) from None
1379
+ self.aggregate_queries += count
1380
+ self.charged_queries += count
1381
+ raise
1382
+ except AggregateQueryBudgetExceeded:
1383
+ raise
1384
+ except Exception:
1385
+ # The source may have issued statements before
1386
+ # failing. Keep the report truthful (unknown)
1387
+ # and reserve the rest of the pair budget.
1388
+ self.count_unknown = True
1389
+ self.charged_queries += self.remaining
1390
+ raise
1391
+ if isinstance(count, bool) or not isinstance(count, int) or count < 0:
1392
+ self.count_unknown = True
1393
+ self.charged_queries += self.remaining
1394
+ raise RuntimeError(
1395
+ "Source returned an invalid aggregate statement count"
1396
+ )
1397
+ self.aggregate_queries += count
1398
+ self.charged_queries += count
1399
+ if count == 0:
1400
+ raise AggregateQueryBudgetExceeded(
1401
+ "Source returned no aggregate statement evidence"
1402
+ )
1403
+ if count > self.remaining:
1404
+ raise AggregateQueryBudgetExceeded(
1405
+ "Source exceeded its aggregate statement budget"
1406
+ )
1407
+ return metrics
1408
+ # The original extension contract is one aggregate SQL
1409
+ # statement per relationship_metrics call. Multi-query
1410
+ # adapters must implement relationship_metrics_counted.
1411
+ self.aggregate_queries += 1
1412
+ self.charged_queries += 1
1413
+ return self.wrapped.relationship_metrics(*args, **kwargs)
1414
+
1415
+ remaining_query_budget = (
1416
+ self.config.relation_query_budget_per_pair - query_counts.get(token, 0)
1417
+ )
1418
+ counting_source = CountingSource(self.source, remaining_query_budget)
1419
+ result = validate_candidates(
1420
+ counting_source,
1421
+ snapshots_objects,
1422
+ [item],
1423
+ min_match_rate=self.config.relation_min_match_rate,
1424
+ query_budget_per_pair=1,
1425
+ forbidden_pairs=forbidden,
1426
+ entities=(semantic_data or {}).get("entities", {}),
1427
+ )[0]
1428
+ aggregate_queries += counting_source.aggregate_queries
1429
+ aggregate_query_count_unknown |= counting_source.count_unknown
1430
+ if counting_source.charged_queries:
1431
+ query_counts[token] = (
1432
+ query_counts.get(token, 0) + counting_source.charged_queries
1433
+ )
1434
+ result["candidate_id"] = cid
1435
+ caution = result.get("caution", "")
1436
+ if forbidden_candidate:
1437
+ state = "blocked"
1438
+ elif item.get("type") == "lineage":
1439
+ state = "completed"
1440
+ elif result.get("verdict") != "not_checked" or result.get("metrics"):
1441
+ state = "completed"
1442
+ elif (
1443
+ "unsupported_capability" in caution
1444
+ or "validation_failed" in caution
1445
+ or "invalid" in caution
1446
+ or "unsupported" in caution
1447
+ or "time-only" in caution
1448
+ ):
1449
+ state = "blocked"
1450
+ else:
1451
+ state = "retryable"
1452
+ work_records[cid] = {"signature": signature, "state": state}
1453
+ result_records[cid] = result
1454
+ processed_pairs.add(token)
1455
+
1456
+ relation_results = [result_records[cid] for cid in sorted(result_records)]
1457
+ current_entities = (semantic_data or {}).get(
1458
+ "entities", prior_semantic.get("entities", {})
1459
+ )
1460
+ for rel in relation_results:
1461
+ if not isinstance(rel, dict):
1462
+ continue
1463
+ # Persist explicit provenance only on newly generated records.
1464
+ # Reused legacy rows may have merged deterministic and model
1465
+ # caution with no origin marker, so preserve that uncertainty.
1466
+ if rel.get("candidate_id") not in reused_candidate_ids:
1467
+ rel.setdefault("llm_annotations_status", "not_provided")
1468
+ rel["measure_guidance"] = refreshed_measure_guidance(
1469
+ rel,
1470
+ current_entities,
1471
+ object_overrides,
1472
+ self.config.relation_min_match_rate,
1473
+ )
1474
+ rel["measure_guidance_signature"] = measure_guidance_signature(
1475
+ rel.get("source", ""),
1476
+ rel.get("target", ""),
1477
+ current_entities,
1478
+ object_overrides,
1479
+ )
1480
+ rel["aggregation_guidance_signature"] = measure_guidance_signature(
1481
+ rel.get("source", ""),
1482
+ rel.get("target", ""),
1483
+ current_entities,
1484
+ object_overrides,
1485
+ )
1486
+ if self.llm is not None and generated["annotations"]:
1487
+ by_id = {r["id"]: r for r in relation_results if r.get("id")}
1488
+ for annotation in generated["annotations"]:
1489
+ if (
1490
+ not isinstance(annotation, dict)
1491
+ or set(annotation) != {"id", "answers", "caution"}
1492
+ or annotation.get("id") not in by_id
1493
+ or not isinstance(annotation.get("answers"), list)
1494
+ or any(not isinstance(x, str) for x in annotation["answers"])
1495
+ or not isinstance(annotation.get("caution"), str)
1496
+ ):
1497
+ llm_rejections += 1
1498
+ continue
1499
+ rel = by_id[annotation["id"]]
1500
+ rel["answers"] = annotation["answers"]
1501
+ rel["llm_annotations_status"] = "unverified"
1502
+ if annotation["caution"]:
1503
+ rel["caution"] = (
1504
+ rel["caution"] + "; " if rel["caution"] else ""
1505
+ ) + annotation["caution"]
1506
+ unfinished_pairs = {
1507
+ pair_of(item)
1508
+ for item in all_candidate_specs
1509
+ if work_records.get(candidate_identity(item), {}).get("state")
1510
+ in {"pending", "retryable"}
1511
+ }
1512
+ relation_cache = {
1513
+ token: override_signature(token)
1514
+ for token in current_pairs
1515
+ if token not in unfinished_pairs
1516
+ and (
1517
+ token in run_pair_set or (token not in affected_pairs and token in prior_cache)
1518
+ )
1519
+ }
1520
+ evaluated_tokens = processed_pairs
1521
+ reused_pairs = {
1522
+ pair_of(prior_result_by_id[cid])
1523
+ for cid, work in work_records.items()
1524
+ if work.get("state") == "completed"
1525
+ and cid in prior_result_by_id
1526
+ and pair_of(prior_result_by_id[cid]) not in processed_pairs
1527
+ }
1528
+ relation_summary = {
1529
+ "pairs_computed": len(evaluated_tokens),
1530
+ "pairs_carried": len(reused_pairs),
1531
+ "aggregate_queries": aggregate_queries,
1532
+ "aggregate_query_count_unknown": aggregate_query_count_unknown,
1533
+ "pairs_deferred_budget": len(
1534
+ (affected_pairs - run_pair_set) | (unfinished_pairs & run_pair_set)
1535
+ ),
1536
+ "llm_proposals_rejected": llm_rejections,
1537
+ "pairs_forbidden_skipped": sum(
1538
+ "forbidden" in r.get("caution", "") for r in relation_results
1539
+ ),
1540
+ "accepted": sum(r.get("verdict") == "accepted" for r in relation_results),
1541
+ "warning_many_to_many": sum(
1542
+ r.get("verdict") == "warning_many_to_many" for r in relation_results
1543
+ ),
1544
+ "warning_one_to_many": sum(
1545
+ r.get("verdict") == "warning_one_to_many" for r in relation_results
1546
+ ),
1547
+ "warning_row_multiplication": sum(
1548
+ r.get("verdict")
1549
+ in {
1550
+ "warning_many_to_many",
1551
+ "warning_one_to_many",
1552
+ "warning_row_multiplication",
1553
+ }
1554
+ for r in relation_results
1555
+ ),
1556
+ "below_threshold": sum(
1557
+ r.get("verdict") == "below_threshold" for r in relation_results
1558
+ ),
1559
+ }
1560
+ # Keep semantic entities and add relation state to the same immutable artifact.
1561
+ if semantic_data is None:
1562
+ semantic_data = {
1563
+ "schema_version": 1,
1564
+ "entities": dict(prior_semantic.get("entities", {})),
1565
+ }
1566
+ semantic_data["relationships"] = relation_results
1567
+ semantic_data["relationship_cache"] = relation_cache
1568
+ semantic_data["relationship_work"] = dict(sorted(work_records.items()))
1569
+ semantic_data["relationship_semantic_signatures"] = {
1570
+ **prior_semantic_signatures,
1571
+ **current_semantic_signatures,
1572
+ }
1573
+ previous_relation_provenance = prior_semantic.get("relationship_provenance", {})
1574
+ if not isinstance(previous_relation_provenance, dict):
1575
+ previous_relation_provenance = {}
1576
+ current_stage_calls = llm_provenance_snapshot()
1577
+ provider_calls = None
1578
+ if isinstance(llm_start["calls"], int) and isinstance(
1579
+ current_stage_calls["calls"], int
1580
+ ):
1581
+ provider_calls = max(0, current_stage_calls["calls"] - llm_start["calls"])
1582
+ elif isinstance(llm_start["stages"].get("relations"), int) and isinstance(
1583
+ current_stage_calls["stages"].get("relations"), int
1584
+ ):
1585
+ provider_calls = max(
1586
+ 0,
1587
+ current_stage_calls["stages"]["relations"] - llm_start["stages"]["relations"],
1588
+ )
1589
+ elif isinstance(llm_start["fake_calls"], int) and isinstance(
1590
+ current_stage_calls["fake_calls"], int
1591
+ ):
1592
+ provider_calls = max(0, current_stage_calls["fake_calls"] - llm_start["fake_calls"])
1593
+ if self.llm is None:
1594
+ semantic_revision = hashlib.sha256(
1595
+ json.dumps(
1596
+ current_semantic_signatures,
1597
+ sort_keys=True,
1598
+ separators=(",", ":"),
1599
+ ).encode("utf-8")
1600
+ ).hexdigest()
1601
+ relationship_provenance = {
1602
+ "provider": "deterministic",
1603
+ "model": "none",
1604
+ "stage": "relations",
1605
+ "provider_calls": "0",
1606
+ "prompt_version": "none",
1607
+ "prompt_bundle_sha256": _prompt_bundle_hash(),
1608
+ "semantic_input_revision": semantic_revision,
1609
+ }
1610
+ elif relation_llm_invoked or provider_calls:
1611
+ provenance_payload = {
1612
+ key: {
1613
+ "profiling": entity.get("provenance", {}).get("profiling_policy_revision"),
1614
+ "sampling": entity.get("provenance", {}).get("sampling_policy_revision"),
1615
+ }
1616
+ for key, entity in (semantic_data or {}).get("entities", {}).items()
1617
+ if isinstance(entity, dict) and isinstance(entity.get("provenance"), dict)
1618
+ }
1619
+ usage_delta = {
1620
+ key: max(0, value - llm_start["usage"].get(key, 0))
1621
+ for key, value in current_stage_calls["usage"].items()
1622
+ if isinstance(value, int)
1623
+ and not isinstance(value, bool)
1624
+ and isinstance(llm_start["usage"].get(key, 0), int)
1625
+ }
1626
+ stage_delta = {
1627
+ key: max(0, value - llm_start["stages"].get(key, 0))
1628
+ for key, value in current_stage_calls["stages"].items()
1629
+ if isinstance(value, int)
1630
+ and not isinstance(value, bool)
1631
+ and isinstance(llm_start["stages"].get(key, 0), int)
1632
+ }
1633
+ semantic_revision = hashlib.sha256(
1634
+ json.dumps(
1635
+ current_semantic_signatures,
1636
+ sort_keys=True,
1637
+ separators=(",", ":"),
1638
+ ).encode("utf-8")
1639
+ ).hexdigest()
1640
+ relationship_provenance = {
1641
+ "provider": _safe_identity(
1642
+ getattr(self.llm, "provider_name", type(self.llm).__module__)
1643
+ ),
1644
+ "model": _safe_identity(
1645
+ getattr(self.llm, "model_name", type(self.llm).__name__)
1646
+ ),
1647
+ "stage": "relations",
1648
+ "provider_calls": str(provider_calls)
1649
+ if provider_calls is not None
1650
+ else "unknown",
1651
+ "provider_retries": (
1652
+ str(max(0, current_stage_calls["retries"] - llm_start["retries"]))
1653
+ if isinstance(current_stage_calls["retries"], int)
1654
+ and isinstance(llm_start["retries"], int)
1655
+ else "unknown"
1656
+ ),
1657
+ "prompt_version": _safe_identity(
1658
+ getattr(self.llm, "prompt_version", "unknown")
1659
+ ),
1660
+ "prompt_bundle_sha256": _prompt_bundle_hash(),
1661
+ "semantic_input_revision": semantic_revision,
1662
+ "policy_revisions": json.dumps(
1663
+ provenance_payload, sort_keys=True, separators=(",", ":")
1664
+ ),
1665
+ "stage_calls": json.dumps(stage_delta, sort_keys=True, separators=(",", ":")),
1666
+ "token_usage": json.dumps(usage_delta, sort_keys=True, separators=(",", ":")),
1667
+ }
1668
+ duration_delta = current_stage_calls["duration"]
1669
+ if (
1670
+ isinstance(duration_delta, (int, float))
1671
+ and not isinstance(duration_delta, bool)
1672
+ and isinstance(llm_start["duration"], (int, float))
1673
+ ):
1674
+ relationship_provenance["duration_seconds"] = (
1675
+ f"{max(0.0, duration_delta - llm_start['duration']):.6f}"
1676
+ )
1677
+ else:
1678
+ relationship_provenance = dict(previous_relation_provenance)
1679
+ semantic_data["relationship_provenance"] = relationship_provenance
1680
+ semantic_data["schema_version"] = 2
1681
+ if run_pair_tokens:
1682
+ semantic_data["relation_pair_cursor"] = run_pair_tokens[-1]
1683
+ report["relations"] = {**relation_summary, "items": relation_results}
1684
+
1685
+ return {"semantic_data": semantic_data, "report": report}