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,1114 @@
1
+ """Build-time relationship candidates and evidence-based validation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import json
7
+ import hashlib
8
+ import re
9
+ from typing import AbstractSet
10
+ from semantic_context_engine.sources.base import (
11
+ RelationshipAggregateSource,
12
+ SourceCapabilities,
13
+ )
14
+ from semantic_context_engine.domain_contracts import RelationshipMetricsContract
15
+ from semantic_context_engine.errors import (
16
+ AggregateQueryBudgetExceeded,
17
+ AggregateQueryExecutionError,
18
+ UnsupportedCapabilityError,
19
+ safe_error_label,
20
+ )
21
+
22
+
23
+ def _norm(name: str) -> str:
24
+ return re.sub(r"[^A-Z0-9]", "", name.upper())
25
+
26
+
27
+ def temporal_candidates(structural) -> list[str]:
28
+ return sorted(
29
+ name
30
+ for name, column in structural.columns.items()
31
+ if "DATE" in column.data_type.upper() or "TIME" in column.data_type.upper()
32
+ )
33
+
34
+
35
+ def candidate_identity(candidate: dict) -> str:
36
+ """Return a stable, orientation-preserving identity for a relation candidate."""
37
+ identity = {
38
+ key: candidate.get(key)
39
+ for key in (
40
+ "source",
41
+ "target",
42
+ "type",
43
+ "source_keys",
44
+ "target_keys",
45
+ "transformations",
46
+ "conditions",
47
+ )
48
+ }
49
+ encoded = json.dumps(identity, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
50
+ return "rel_" + hashlib.sha256(encoded.encode("utf-8")).hexdigest()
51
+
52
+
53
+ def _measure_guidance(
54
+ object_key: str,
55
+ entity: dict,
56
+ join_keys: list[str],
57
+ *,
58
+ side_preserved: bool,
59
+ match_rate: float,
60
+ ) -> list[dict]:
61
+ """Describe per-measure handling without promoting proposed roles to truth."""
62
+ columns = entity.get("columns", [])
63
+ if not isinstance(columns, list):
64
+ return []
65
+ grain_check = entity.get("grain_check", {})
66
+ grain_verified = isinstance(grain_check, dict) and grain_check.get("status") in {
67
+ "verified",
68
+ "corrected",
69
+ }
70
+ verified_grain = entity.get("grain", [])
71
+ grain_covers_join_keys = (
72
+ grain_verified
73
+ and isinstance(verified_grain, list)
74
+ and bool(join_keys)
75
+ and set(join_keys) <= set(verified_grain)
76
+ )
77
+ guidance = []
78
+ for column in columns:
79
+ if not isinstance(column, dict):
80
+ continue
81
+ name, role = column.get("name"), column.get("role")
82
+ if not isinstance(name, str) or role not in {"additive_measure", "non_additive_measure"}:
83
+ continue
84
+ row = {
85
+ "object": object_key,
86
+ "column": name,
87
+ "role": role,
88
+ "role_evidence": "semantic_proposal_requires_review",
89
+ "join_keys": list(join_keys),
90
+ "consumer_target_grain": "not_requested",
91
+ }
92
+ if role == "additive_measure":
93
+ condition_met = grain_covers_join_keys and side_preserved and match_rate == 1.0
94
+ row.update(
95
+ {
96
+ "status": "conditional" if condition_met else "not_established",
97
+ "treatment": (
98
+ "sum_only_after_confirming_target_grain_and_join_keys"
99
+ if condition_met
100
+ else "preaggregate_separately_or_do_not_sum_after_join"
101
+ ),
102
+ "reason": (
103
+ "verified grain, full key coverage, and row preservation support a "
104
+ "conditional additive recommendation"
105
+ if condition_met
106
+ else "verified grain covering the join keys, full key coverage, or "
107
+ "row preservation is not established"
108
+ ),
109
+ }
110
+ )
111
+ else:
112
+ selected = column.get("recompute_from", [])
113
+ formula_state = column.get("formula_choice_status", "unverified")
114
+ operator = column.get("formula_operator", "unknown")
115
+ proposals = column.get("formula_proposals", [])
116
+ if operator == "unknown" and isinstance(proposals, list):
117
+ matching = [
118
+ proposal
119
+ for proposal in proposals
120
+ if isinstance(proposal, dict)
121
+ and proposal.get("operands") == selected
122
+ and proposal.get("approval_status") in {"approved", "human_approved"}
123
+ ]
124
+ if len(matching) == 1:
125
+ operator = matching[0].get("operator", "unknown")
126
+ if (
127
+ formula_state in {"unique_full_coverage", "human_approved"}
128
+ and isinstance(selected, list)
129
+ and selected
130
+ ):
131
+ row.update(
132
+ {
133
+ "status": "review_required",
134
+ "treatment": "recompute_from_selected_additive_operands_after_formula_review",
135
+ "operands": list(selected),
136
+ "operator": operator if operator in {"sum", "ratio_of_sums"} else "unknown",
137
+ "reason": "coverage supports operand availability, not business formula correctness",
138
+ }
139
+ )
140
+ else:
141
+ row.update(
142
+ {
143
+ "status": "not_established",
144
+ "treatment": "do_not_sum_or_average",
145
+ "reason": "no uniquely covered, reviewed recomputation formula is available",
146
+ }
147
+ )
148
+ guidance.append(row)
149
+ return guidance
150
+
151
+
152
+ def _effective_measure_entity(entity: dict, object_override: dict) -> dict:
153
+ """Apply human semantic fields for advice without changing measured evidence."""
154
+ effective = dict(entity)
155
+ columns = [dict(item) for item in entity.get("columns", []) if isinstance(item, dict)]
156
+ by_name = {item.get("name"): item for item in columns}
157
+ if isinstance(object_override.get("grain"), list):
158
+ if object_override["grain"] != entity.get("grain", []):
159
+ effective["grain_check"] = {"status": "unverified"}
160
+ effective["grain"] = list(object_override["grain"])
161
+ for column_name, override in object_override.get("columns", {}).items():
162
+ if not isinstance(override, dict) or column_name not in by_name:
163
+ continue
164
+ column = by_name[column_name]
165
+ if "role" in override:
166
+ column["role"] = override["role"]
167
+ formula = override.get("formula", {})
168
+ formula = formula if isinstance(formula, dict) else {}
169
+ recompute_from = formula.get("recompute_from", override.get("recompute_from"))
170
+ if isinstance(recompute_from, list):
171
+ column["recompute_from"] = list(recompute_from)
172
+ column["formula_choice_status"] = "human_approved"
173
+ aggregation = formula.get("aggregation")
174
+ if aggregation == "ratio_of_sums":
175
+ column["formula_operator"] = "ratio_of_sums"
176
+ elif aggregation == "additive" and formula.get("expression"):
177
+ column["formula_operator"] = "sum"
178
+ if isinstance(formula.get("operator"), str):
179
+ column["formula_operator"] = formula["operator"]
180
+ effective["columns"] = columns
181
+ return effective
182
+
183
+
184
+ def measure_guidance_signature(
185
+ source_key: str,
186
+ target_key: str,
187
+ entities: dict,
188
+ object_overrides: dict,
189
+ ) -> str:
190
+ """Fingerprint only semantic inputs used by conditional measure advice."""
191
+ relevant = {}
192
+ for key in (source_key, target_key):
193
+ entity = entities.get(key, {}) if isinstance(entities, dict) else {}
194
+ override = object_overrides.get(key, {}) if isinstance(object_overrides, dict) else {}
195
+ effective = _effective_measure_entity(entity, override)
196
+ relevant[key] = {
197
+ "grain": effective.get("grain", []),
198
+ "grain_check": effective.get("grain_check", {}),
199
+ "columns": [
200
+ {
201
+ "name": item.get("name"),
202
+ "role": item.get("role"),
203
+ "recompute_from": item.get("recompute_from", []),
204
+ "formula_choice_status": item.get("formula_choice_status", "unverified"),
205
+ "formula_operator": item.get("formula_operator", "unknown"),
206
+ "formula_proposals": item.get("formula_proposals", []),
207
+ }
208
+ for item in effective.get("columns", [])
209
+ if isinstance(item, dict)
210
+ ],
211
+ }
212
+ encoded = json.dumps(relevant, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
213
+ return hashlib.sha256(encoded.encode("utf-8")).hexdigest()
214
+
215
+
216
+ def suppress_unverified_preaggregation_advice(
217
+ relationship: dict,
218
+ *,
219
+ basis_changed: bool,
220
+ ) -> dict:
221
+ """Withdraw legacy pre-aggregation advice without discarding join evidence.
222
+
223
+ A matching semantic signature only proves that the semantic inputs have not
224
+ changed; it does not establish measure-specific safety or a consumer grain.
225
+ """
226
+ result = dict(relationship)
227
+ safety = result.get("aggregation_safety")
228
+ safety = dict(safety) if isinstance(safety, dict) else {}
229
+ has_advice = bool(
230
+ result.get("aggregate_first")
231
+ or result.get("recommended_preaggregation")
232
+ or safety.get("recommended_preaggregation")
233
+ )
234
+ if not has_advice:
235
+ if basis_changed and safety and result.get("aggregation_guidance_signature"):
236
+ safety["status"] = "stale"
237
+ safety["reason"] = "semantic basis changed; prior safety assessment is stale"
238
+ result["aggregation_safety"] = safety
239
+ return result
240
+
241
+ result["aggregate_first"] = None
242
+ result["recommended_preaggregation"] = None
243
+ safety.update(
244
+ {
245
+ "status": "stale" if basis_changed else "not_established",
246
+ "recommended_preaggregation": None,
247
+ "measure_specific_safety": "not_established",
248
+ "reason": (
249
+ "legacy pre-aggregation advice was withdrawn because the semantic basis changed"
250
+ if basis_changed
251
+ else "legacy pre-aggregation advice does not establish measure-specific safety"
252
+ ),
253
+ }
254
+ )
255
+ result["aggregation_safety"] = safety
256
+
257
+ caution = result.get("caution")
258
+ if isinstance(caution, str) and caution:
259
+ obsolete = "; any pre-aggregation hint is conditional and does not establish measure-specific safety"
260
+ if caution.endswith(obsolete):
261
+ caution = caution[: -len(obsolete)]
262
+ notice = (
263
+ "legacy pre-aggregation advice withdrawn; measure-specific safety is not established"
264
+ )
265
+ if notice not in caution:
266
+ result["caution"] = f"{caution}; {notice}" if caution else notice
267
+ return result
268
+
269
+
270
+ def refreshed_measure_guidance(
271
+ relation: dict,
272
+ entities: dict,
273
+ object_overrides: dict,
274
+ min_match_rate: float,
275
+ ) -> list[dict]:
276
+ """Rebuild advice from unchanged measured metrics and current semantics."""
277
+ metrics = relation.get("metrics", {})
278
+ if (
279
+ relation.get("type") not in {"join", "temporal"}
280
+ or relation.get("verdict") == "below_threshold"
281
+ or metrics.get("normalization_collision")
282
+ or not isinstance(metrics.get("source_match_rate"), (int, float))
283
+ or not isinstance(metrics.get("target_match_rate"), (int, float))
284
+ or min(metrics["source_match_rate"], metrics["target_match_rate"]) <= min_match_rate
285
+ ):
286
+ return []
287
+ source_key, target_key = relation.get("source"), relation.get("target")
288
+ if not isinstance(source_key, str) or not isinstance(target_key, str):
289
+ return []
290
+ source_entity = _effective_measure_entity(
291
+ entities.get(source_key, {}), object_overrides.get(source_key, {})
292
+ )
293
+ target_entity = _effective_measure_entity(
294
+ entities.get(target_key, {}), object_overrides.get(target_key, {})
295
+ )
296
+ source_preserved = metrics.get("source_side_preserved")
297
+ target_preserved = metrics.get("target_side_preserved")
298
+ if not isinstance(source_preserved, bool):
299
+ source_preserved = metrics.get("source_fanout", metrics.get("fanout", 1)) <= 1
300
+ if not isinstance(target_preserved, bool):
301
+ target_preserved = metrics.get("target_fanout", 1) <= 1
302
+ source_keys = relation.get("source_keys") or []
303
+ target_keys = relation.get("target_keys") or []
304
+ return _measure_guidance(
305
+ source_key,
306
+ source_entity,
307
+ source_keys,
308
+ side_preserved=source_preserved,
309
+ match_rate=metrics["source_match_rate"],
310
+ ) + _measure_guidance(
311
+ target_key,
312
+ target_entity,
313
+ target_keys,
314
+ side_preserved=target_preserved,
315
+ match_rate=metrics["target_match_rate"],
316
+ )
317
+
318
+
319
+ def deterministic_candidates(objects: dict) -> list[dict]:
320
+ """Generate name and declared-constraint candidates (D19/D24/D25)."""
321
+ keys = list(objects)
322
+ candidates = []
323
+ for i, left_key in enumerate(keys):
324
+ left = objects[left_key]
325
+ for right_key in keys[i + 1 :]:
326
+ right = objects[right_key]
327
+ left_cols: dict[str, list[str]] = {}
328
+ right_cols: dict[str, list[str]] = {}
329
+ for name in left.columns:
330
+ normalized = _norm(name)
331
+ if normalized:
332
+ left_cols.setdefault(normalized, []).append(name)
333
+ for name in right.columns:
334
+ normalized = _norm(name)
335
+ if normalized:
336
+ right_cols.setdefault(normalized, []).append(name)
337
+ # A normalized name is safe only when it identifies one real
338
+ # column on each side. Never pick an arbitrary collision winner.
339
+ matches = [
340
+ (names[0], right_cols[normalized][0])
341
+ for normalized, names in left_cols.items()
342
+ if len(names) == 1 and len(right_cols.get(normalized, [])) == 1
343
+ ]
344
+ temporal = []
345
+ entities = []
346
+ for source_col, target_col in matches:
347
+ source_type = left.columns[source_col].data_type.upper()
348
+ target_type = right.columns[target_col].data_type.upper()
349
+ source_time = "DATE" in source_type or "TIME" in source_type
350
+ target_time = "DATE" in target_type or "TIME" in target_type
351
+ if source_time and target_time:
352
+ temporal.append((source_col, target_col))
353
+ elif source_time != target_time:
354
+ # Incompatible semantic key types are not guessed from names.
355
+ continue
356
+ else:
357
+ entities.append((source_col, target_col))
358
+ if entities:
359
+ candidates.append(
360
+ {
361
+ "source": left_key,
362
+ "target": right_key,
363
+ "source_keys": [p[0] for p in entities],
364
+ "target_keys": [p[1] for p in entities],
365
+ "origin": "deterministic",
366
+ "type": "join",
367
+ }
368
+ )
369
+ if temporal:
370
+ composite = entities + temporal
371
+ candidates.append(
372
+ {
373
+ "source": left_key,
374
+ "target": right_key,
375
+ "source_keys": [p[0] for p in composite],
376
+ "target_keys": [p[1] for p in composite],
377
+ "origin": "deterministic",
378
+ "type": "temporal",
379
+ }
380
+ )
381
+ elif len(temporal_candidates(left)) == 1 and len(temporal_candidates(right)) == 1:
382
+ source_time_column = temporal_candidates(left)[0]
383
+ target_time_column = temporal_candidates(right)[0]
384
+ composite = entities + [(source_time_column, target_time_column)]
385
+ candidates.append(
386
+ {
387
+ "source": left_key,
388
+ "target": right_key,
389
+ "source_keys": [p[0] for p in composite],
390
+ "target_keys": [p[1] for p in composite],
391
+ "transformations": [
392
+ {"source_transform": "identity", "target_transform": "identity"}
393
+ for _ in entities
394
+ ]
395
+ + [{"source_transform": "month", "target_transform": "identity"}],
396
+ "origin": "deterministic",
397
+ "type": "temporal",
398
+ }
399
+ )
400
+
401
+ # Approved JSON scalar keys can extend an entity-key match. The
402
+ # discriminator condition keeps observed key evidence in scope.
403
+ if entities:
404
+ for variant in getattr(left, "variant_keys", []):
405
+ if variant.status not in {"complete", "partial"} or variant.present <= 0:
406
+ continue
407
+ base_name = variant.key.rsplit(".", 1)[-1]
408
+ normalized = _norm(base_name)
409
+ targets = [name for name in right.columns if _norm(name) == normalized]
410
+ if not normalized or len(targets) != 1:
411
+ continue
412
+ if "=" not in variant.discriminator:
413
+ continue
414
+ discriminator, discriminator_value = variant.discriminator.split("=", 1)
415
+ source_json_column = variant.column
416
+ if source_json_column in [pair[0] for pair in entities]:
417
+ continue
418
+ target_column = targets[0]
419
+ source_json_value = variant.value_type.upper()
420
+ target_type = right.columns[target_column].data_type.upper()
421
+ source_numeric = any(
422
+ t in source_json_value
423
+ for t in ("INT", "DECIMAL", "NUMERIC", "DOUBLE", "FLOAT")
424
+ )
425
+ target_numeric = any(
426
+ t in target_type
427
+ for t in ("INT", "DECIMAL", "NUMERIC", "NUMBER", "DOUBLE", "FLOAT", "REAL")
428
+ )
429
+ source_text = any(t in source_json_value for t in ("VARCHAR", "STRING", "TEXT"))
430
+ target_text = any(
431
+ t in target_type for t in ("CHAR", "TEXT", "STRING", "VARCHAR")
432
+ )
433
+ if source_numeric != target_numeric or source_text != target_text:
434
+ continue
435
+ mappings = entities + [(source_json_column, target_column)]
436
+ candidates.append(
437
+ {
438
+ "source": left_key,
439
+ "target": right_key,
440
+ "source_keys": [pair[0] for pair in mappings],
441
+ "target_keys": [pair[1] for pair in mappings],
442
+ "transformations": [
443
+ {"source_transform": "identity", "target_transform": "identity"}
444
+ for _ in entities
445
+ ]
446
+ + [
447
+ {
448
+ "source_transform": "json_path",
449
+ "source_path": variant.key,
450
+ "target_transform": "identity",
451
+ }
452
+ ],
453
+ "conditions": [
454
+ {
455
+ "side": "source",
456
+ "column": discriminator,
457
+ "operator": "eq",
458
+ "value": discriminator_value,
459
+ }
460
+ ],
461
+ "origin": "deterministic",
462
+ "type": "join",
463
+ }
464
+ )
465
+ # D28 lineage matches SCHEMA.OBJECT across databases; it is surfaced as
466
+ # structural evidence only and validate_candidates never scans it.
467
+ by_schema_object = {
468
+ ".".join(obj.fqn.upper().split(".")[-2:]): key for key, obj in objects.items()
469
+ }
470
+ suffix_groups: dict[str, list[tuple[str, str]]] = {}
471
+ for key, obj in objects.items():
472
+ parts = obj.fqn.upper().split(".")
473
+ if len(parts) >= 3:
474
+ suffix_groups.setdefault(".".join(parts[-2:]), []).append((key, parts[0]))
475
+ for group in suffix_groups.values():
476
+ for i, (left, left_catalog) in enumerate(group):
477
+ for right, right_catalog in group[i + 1 :]:
478
+ if left_catalog != right_catalog:
479
+ candidates.append(
480
+ {
481
+ "source": left,
482
+ "target": right,
483
+ "source_keys": [],
484
+ "target_keys": [],
485
+ "origin": "lineage",
486
+ "type": "lineage",
487
+ "environment_mismatch": True,
488
+ }
489
+ )
490
+ for source_key, obj in objects.items():
491
+ for dep in getattr(obj, "dependencies", set()) or ():
492
+ suffix = ".".join(str(dep).upper().split(".")[-2:])
493
+ target_key = by_schema_object.get(suffix)
494
+ if target_key and source_key != target_key:
495
+ candidates.append(
496
+ {
497
+ "source": source_key,
498
+ "target": target_key,
499
+ "source_keys": [],
500
+ "target_keys": [],
501
+ "origin": "lineage",
502
+ "type": "lineage",
503
+ }
504
+ )
505
+ # D19: constraints are evidence, never verdicts. Only explicit allowlisted
506
+ # targets with existing, unique key columns become candidates; validation
507
+ # still runs through validate_candidates and the aggregate Source method.
508
+ for source_key, obj in objects.items():
509
+ for constraint in getattr(obj, "declared_constraints", []) or []:
510
+ if not isinstance(constraint, dict) or constraint.get("type") != "foreign_key":
511
+ continue
512
+ target_key = constraint.get("target")
513
+ source_keys = constraint.get("columns")
514
+ target_keys = constraint.get("target_columns")
515
+ if (
516
+ target_key not in objects
517
+ or not isinstance(source_keys, list)
518
+ or not isinstance(target_keys, list)
519
+ or not source_keys
520
+ or len(source_keys) != len(target_keys)
521
+ or len(set(source_keys)) != len(source_keys)
522
+ or len(set(target_keys)) != len(target_keys)
523
+ or any(k not in obj.columns for k in source_keys)
524
+ or any(k not in objects[target_key].columns for k in target_keys)
525
+ ):
526
+ continue
527
+ candidates.append(
528
+ {
529
+ "source": source_key,
530
+ "target": target_key,
531
+ "source_keys": list(source_keys),
532
+ "target_keys": list(target_keys),
533
+ "origin": "declared",
534
+ "type": "join",
535
+ }
536
+ )
537
+ # If name inference and a constraint describe the same directed key pair,
538
+ # keep one candidate and retain the declared provenance.
539
+ unique: dict[tuple[object, ...], dict] = {}
540
+ for candidate in candidates:
541
+ signature = (
542
+ candidate.get("source"),
543
+ candidate.get("target"),
544
+ tuple(candidate.get("source_keys", [])),
545
+ tuple(candidate.get("target_keys", [])),
546
+ candidate.get("type"),
547
+ )
548
+ existing = unique.get(signature)
549
+ if existing is None or candidate.get("origin") == "declared":
550
+ unique[signature] = candidate
551
+ return list(unique.values())
552
+
553
+
554
+ def validate_candidates(
555
+ source,
556
+ objects: dict,
557
+ candidates: list[dict],
558
+ *,
559
+ min_match_rate: float,
560
+ query_budget_per_pair: int,
561
+ forbidden_pairs: AbstractSet[frozenset[str]] = frozenset(),
562
+ entities: dict | None = None,
563
+ ) -> list[dict]:
564
+ """Validate each candidate through source aggregate capability; proposals never self-approve."""
565
+ results = []
566
+ # This public helper accepts batches as well as the pipeline's one-item
567
+ # resumable calls. Keep the pair budget here too so callers cannot bypass
568
+ # the configured limit by passing several candidates for the same pair.
569
+ statements_by_pair: dict[frozenset[str], int] = {}
570
+ for candidate in candidates:
571
+ if not isinstance(candidate, dict):
572
+ results.append(
573
+ {
574
+ "verdict": "not_checked",
575
+ "served": False,
576
+ "metrics": {},
577
+ "caution": "invalid relationship candidate; aggregate query skipped",
578
+ }
579
+ )
580
+ continue
581
+ left_key, right_key = candidate.get("source"), candidate.get("target")
582
+ if (
583
+ not isinstance(left_key, str)
584
+ or not isinstance(right_key, str)
585
+ or left_key not in objects
586
+ or right_key not in objects
587
+ ):
588
+ results.append(
589
+ {
590
+ **candidate,
591
+ "verdict": "not_checked",
592
+ "served": False,
593
+ "metrics": {},
594
+ "caution": "relationship references an unknown object; aggregate query skipped",
595
+ }
596
+ )
597
+ continue
598
+ pair = frozenset((left_key, right_key))
599
+ candidate_key_names = candidate.get("source_keys")
600
+ id_keys = candidate_key_names if isinstance(candidate_key_names, list) else []
601
+ base = {
602
+ **candidate,
603
+ "id": f"{left_key}__{right_key}__" + "_".join(str(k) for k in id_keys),
604
+ "conditions": candidate.get("conditions", []),
605
+ "aggregate_first": None,
606
+ "answers": [],
607
+ "caution": "",
608
+ "served": False,
609
+ "metrics": {},
610
+ "verdict": "not_checked",
611
+ }
612
+ if left_key == right_key:
613
+ base["caution"] = "self-relationships are unsupported; aggregate query skipped"
614
+ results.append(base)
615
+ continue
616
+ if pair in forbidden_pairs:
617
+ base.update({"verdict": "rejected", "caution": "forbidden by human override"})
618
+ results.append(base)
619
+ continue
620
+ conditions = candidate.get("conditions", [])
621
+ if not isinstance(conditions, list):
622
+ base["caution"] = "invalid relationship conditions; aggregate query skipped"
623
+ results.append(base)
624
+ continue
625
+ valid_conditions = True
626
+ for condition in conditions:
627
+ if not isinstance(condition, dict) or set(condition) - {
628
+ "side",
629
+ "column",
630
+ "operator",
631
+ "value",
632
+ }:
633
+ valid_conditions = False
634
+ break
635
+ side, column, operator = (
636
+ condition.get("side"),
637
+ condition.get("column"),
638
+ condition.get("operator"),
639
+ )
640
+ target_obj = (
641
+ objects[left_key]
642
+ if side == "source"
643
+ else objects[right_key]
644
+ if side == "target"
645
+ else None
646
+ )
647
+ value = condition.get("value")
648
+ if (
649
+ target_obj is None
650
+ or not isinstance(column, str)
651
+ or column not in target_obj.columns
652
+ or operator not in {"eq", "in", "is_null", "not_null"}
653
+ or (operator == "eq" and (isinstance(value, (dict, list)) or value is None))
654
+ or (
655
+ operator == "in"
656
+ and (
657
+ not isinstance(value, list)
658
+ or not value
659
+ or len(value) > 16
660
+ or any(isinstance(v, (dict, list)) or v is None for v in value)
661
+ )
662
+ )
663
+ or (operator in {"is_null", "not_null"} and value is not None)
664
+ ):
665
+ valid_conditions = False
666
+ break
667
+ approval_key = left_key if side == "source" else right_key
668
+ approval_check = getattr(source, "condition_is_approved", None)
669
+ if not callable(approval_check) or not approval_check(approval_key, condition):
670
+ valid_conditions = False
671
+ break
672
+ if not valid_conditions:
673
+ base["caution"] = (
674
+ "invalid or unsupported relationship condition; aggregate query skipped"
675
+ )
676
+ results.append(base)
677
+ continue
678
+ if candidate.get("type") == "lineage":
679
+ base.update(
680
+ {
681
+ "origin": "lineage",
682
+ "verdict": "not_checked",
683
+ "caution": "lineage is structural evidence, not data validation",
684
+ }
685
+ )
686
+ left_fqn = objects[left_key].fqn.upper().split(".")
687
+ right_fqn = objects[right_key].fqn.upper().split(".")
688
+ base["environment_mismatch"] = candidate.get("environment_mismatch", False) or (
689
+ len(left_fqn) >= 2
690
+ and len(right_fqn) >= 2
691
+ and left_fqn[-2:] == right_fqn[-2:]
692
+ and left_fqn[0] != right_fqn[0]
693
+ )
694
+ if base["environment_mismatch"]:
695
+ base["caution"] += "; environment_mismatch"
696
+ results.append(base)
697
+ continue
698
+ source_keys = candidate.get("source_keys")
699
+ target_keys = candidate.get("target_keys")
700
+ if (
701
+ not isinstance(source_keys, list)
702
+ or not isinstance(target_keys, list)
703
+ or not source_keys
704
+ or len(source_keys) != len(target_keys)
705
+ or not all(isinstance(key, str) for key in source_keys + target_keys)
706
+ or len(set(source_keys)) != len(source_keys)
707
+ or len(set(target_keys)) != len(target_keys)
708
+ or any(key not in objects[left_key].columns for key in source_keys)
709
+ or any(key not in objects[right_key].columns for key in target_keys)
710
+ ):
711
+ base["caution"] = (
712
+ "invalid or duplicate relationship key columns; aggregate query skipped"
713
+ )
714
+ results.append(base)
715
+ continue
716
+
717
+ raw_transforms = candidate.get("transformations") or []
718
+ transforms = []
719
+ if not isinstance(raw_transforms, list) or (
720
+ raw_transforms and len(raw_transforms) != len(source_keys)
721
+ ):
722
+ base["caution"] = "invalid relationship key transformations; aggregate query skipped"
723
+ results.append(base)
724
+ continue
725
+ invalid_transform = False
726
+
727
+ def category(dtype: str) -> str:
728
+ upper = dtype.upper()
729
+ if any(kind in upper for kind in ("DATE", "TIME")):
730
+ return "temporal"
731
+ if any(
732
+ kind in upper
733
+ for kind in ("INT", "DECIMAL", "NUMERIC", "NUMBER", "FLOAT", "DOUBLE", "REAL")
734
+ ):
735
+ return "numeric"
736
+ if any(kind in upper for kind in ("CHAR", "TEXT", "STRING", "VARCHAR")):
737
+ return "text"
738
+ return "other"
739
+
740
+ def approved_json_path(obj, column: str, path: str, side: str) -> str | None:
741
+ if not re.fullmatch(
742
+ r"(?:\$\.)?[A-Za-z_][A-Za-z0-9_$]*(?:\.[A-Za-z_][A-Za-z0-9_$]*)*", path
743
+ ):
744
+ return None
745
+ normalized = path if path.startswith("$.") else "$." + path
746
+ evidence = [
747
+ item
748
+ for item in getattr(obj, "variant_keys", [])
749
+ if item.column == column
750
+ and item.status in {"complete", "partial"}
751
+ and item.present > 0
752
+ and (item.key if item.key.startswith("$.") else "$." + item.key) == normalized
753
+ ]
754
+ if not evidence:
755
+ return None
756
+ slices_by_discriminator: dict[str, set[str]] = {}
757
+ for item in evidence:
758
+ if "=" in item.discriminator:
759
+ disc, value = item.discriminator.split("=", 1)
760
+ slices_by_discriminator.setdefault(disc, set()).add(value)
761
+ condition_values: set[str] = set()
762
+ for condition in conditions:
763
+ if condition.get("side") != side:
764
+ continue
765
+ for discriminator, values in slices_by_discriminator.items():
766
+ if condition.get("column") == discriminator:
767
+ if condition.get("operator") == "eq":
768
+ condition_values.add(str(condition.get("value")))
769
+ elif condition.get("operator") == "in":
770
+ condition_values.update(
771
+ str(value) for value in condition.get("value", [])
772
+ )
773
+ return (
774
+ normalized
775
+ if any(condition_values & values for values in slices_by_discriminator.values())
776
+ else None
777
+ )
778
+
779
+ for index, item in enumerate(raw_transforms):
780
+ if not isinstance(item, dict) or set(item) - {
781
+ "source_transform",
782
+ "target_transform",
783
+ "source_path",
784
+ "target_path",
785
+ }:
786
+ invalid_transform = True
787
+ break
788
+ source_transform = item.get("source_transform", "identity")
789
+ target_transform = item.get("target_transform", "identity")
790
+ if source_transform not in {
791
+ "identity",
792
+ "date",
793
+ "month",
794
+ "json_path",
795
+ } or target_transform not in {"identity", "date", "month", "json_path"}:
796
+ invalid_transform = True
797
+ break
798
+ normalized_item = {
799
+ "source_transform": source_transform,
800
+ "target_transform": target_transform,
801
+ }
802
+ if source_transform == "json_path":
803
+ path = item.get("source_path")
804
+ approved = (
805
+ approved_json_path(objects[left_key], source_keys[index], path, "source")
806
+ if isinstance(path, str)
807
+ else None
808
+ )
809
+ if approved is None:
810
+ invalid_transform = True
811
+ break
812
+ normalized_item["source_path"] = approved
813
+ elif item.get("source_path") is not None:
814
+ invalid_transform = True
815
+ break
816
+ if target_transform == "json_path":
817
+ path = item.get("target_path")
818
+ approved = (
819
+ approved_json_path(objects[right_key], target_keys[index], path, "target")
820
+ if isinstance(path, str)
821
+ else None
822
+ )
823
+ if approved is None:
824
+ invalid_transform = True
825
+ break
826
+ normalized_item["target_path"] = approved
827
+ elif item.get("target_path") is not None:
828
+ invalid_transform = True
829
+ break
830
+
831
+ def transformed_category(obj, column, transform, path):
832
+ if transform in {"date", "month"}:
833
+ return "temporal"
834
+ if transform != "json_path":
835
+ return category(obj.columns[column].data_type)
836
+ for evidence in getattr(obj, "variant_keys", []):
837
+ evidence_path = (
838
+ evidence.key if evidence.key.startswith("$.") else "$." + evidence.key
839
+ )
840
+ if evidence.column == column and evidence_path == path:
841
+ return category(evidence.value_type)
842
+ return "other"
843
+
844
+ if transformed_category(
845
+ objects[left_key],
846
+ source_keys[index],
847
+ source_transform,
848
+ normalized_item.get("source_path"),
849
+ ) != transformed_category(
850
+ objects[right_key],
851
+ target_keys[index],
852
+ target_transform,
853
+ normalized_item.get("target_path"),
854
+ ):
855
+ invalid_transform = True
856
+ break
857
+ if (
858
+ source_transform in {"date", "month"}
859
+ and category(objects[left_key].columns[source_keys[index]].data_type) != "temporal"
860
+ ):
861
+ invalid_transform = True
862
+ break
863
+ if (
864
+ target_transform in {"date", "month"}
865
+ and category(objects[right_key].columns[target_keys[index]].data_type) != "temporal"
866
+ ):
867
+ invalid_transform = True
868
+ break
869
+ transforms.append(normalized_item)
870
+ if invalid_transform:
871
+ base["caution"] = (
872
+ "invalid or unapproved relationship transformation; aggregate query skipped"
873
+ )
874
+ results.append(base)
875
+ continue
876
+ source_temporal = all(
877
+ any(tag in objects[left_key].columns[key].data_type.upper() for tag in ("DATE", "TIME"))
878
+ for key in source_keys
879
+ )
880
+ target_temporal = all(
881
+ any(
882
+ tag in objects[right_key].columns[key].data_type.upper() for tag in ("DATE", "TIME")
883
+ )
884
+ for key in target_keys
885
+ )
886
+ if source_temporal and target_temporal:
887
+ base["caution"] = "time-only relationship keys are unsupported; aggregate query skipped"
888
+ results.append(base)
889
+ continue
890
+ capabilities = getattr(source, "capabilities", None)
891
+ if (
892
+ query_budget_per_pair < 1
893
+ or not isinstance(capabilities, SourceCapabilities)
894
+ or not capabilities.relationship_aggregate
895
+ ):
896
+ base["caution"] = (
897
+ "aggregate_validation_unavailable_or_budget_zero"
898
+ if query_budget_per_pair < 1
899
+ else "unsupported_capability"
900
+ )
901
+ results.append(base)
902
+ continue
903
+ if transforms and not capabilities.relationship_key_transforms:
904
+ base["caution"] = "unsupported_capability"
905
+ results.append(base)
906
+ continue
907
+ if not isinstance(source, RelationshipAggregateSource):
908
+ base["caution"] = safe_error_label(UnsupportedCapabilityError())
909
+ results.append(base)
910
+ continue
911
+ pair = frozenset((left_key, right_key))
912
+ used = statements_by_pair.get(pair, 0)
913
+ remaining = query_budget_per_pair - used
914
+ if remaining <= 0:
915
+ base["caution"] = "aggregate_query_budget_exhausted"
916
+ results.append(base)
917
+ continue
918
+ try:
919
+ counted = getattr(source, "relationship_metrics_counted", None)
920
+ call_kwargs = {}
921
+ if conditions:
922
+ call_kwargs["conditions"] = conditions
923
+ if transforms:
924
+ call_kwargs["key_transforms"] = transforms
925
+ if callable(counted):
926
+ # Reserve the remaining budget during the call. If the adapter
927
+ # fails after issuing SQL, a later candidate must not reuse an
928
+ # unknown number of statements. A budget-exhaustion exception
929
+ # is the adapter's preflight signal and therefore releases it.
930
+ statements_by_pair[pair] = used + remaining
931
+ try:
932
+ metrics, statement_count = counted(
933
+ objects[left_key],
934
+ objects[right_key],
935
+ candidate["source_keys"],
936
+ candidate["target_keys"],
937
+ max_aggregate_queries=remaining,
938
+ **call_kwargs,
939
+ )
940
+ except AggregateQueryBudgetExceeded:
941
+ statements_by_pair[pair] = used
942
+ raise
943
+ except AggregateQueryExecutionError as exc:
944
+ statements_by_pair[pair] = used + min(exc.executed_count, remaining)
945
+ raise
946
+ if (
947
+ isinstance(statement_count, bool)
948
+ or not isinstance(statement_count, int)
949
+ or statement_count <= 0
950
+ ):
951
+ raise ValueError("Aggregate adapter returned invalid statement evidence")
952
+ statements_by_pair[pair] = used + statement_count
953
+ if statement_count > remaining:
954
+ base["caution"] = "aggregate_query_budget_exhausted"
955
+ results.append(base)
956
+ continue
957
+ else:
958
+ # Legacy adapters are contractually limited to one aggregate
959
+ # statement per call. Charge before dispatch so an exception
960
+ # after SQL execution cannot let a later candidate exceed the
961
+ # pair budget.
962
+ statements_by_pair[pair] = used + 1
963
+ metrics = source.relationship_metrics(
964
+ objects[left_key],
965
+ objects[right_key],
966
+ candidate["source_keys"],
967
+ candidate["target_keys"],
968
+ **call_kwargs,
969
+ )
970
+ except PermissionError:
971
+ base["caution"] = "source_permission_unavailable"
972
+ results.append(base)
973
+ continue
974
+ except AggregateQueryBudgetExceeded:
975
+ base["caution"] = "aggregate_query_budget_exhausted"
976
+ results.append(base)
977
+ continue
978
+ except Exception as exc:
979
+ base["caution"] = safe_error_label(exc)
980
+ results.append(base)
981
+ continue
982
+ numeric_fields = (
983
+ "source_match_rate",
984
+ "target_match_rate",
985
+ "fanout",
986
+ "source_fanout",
987
+ "target_fanout",
988
+ )
989
+ valid_metrics = (
990
+ isinstance(metrics, dict)
991
+ and all(
992
+ isinstance(metrics.get(field), (int, float))
993
+ and not isinstance(metrics.get(field), bool)
994
+ and math.isfinite(metrics[field])
995
+ for field in numeric_fields
996
+ )
997
+ and all(0 <= metrics[field] <= 1 for field in numeric_fields[:2])
998
+ and all(metrics[field] >= 0 for field in numeric_fields[2:])
999
+ and metrics.get("cardinality") in {"1:1", "N:1", "1:N", "N:N", "unknown"}
1000
+ and isinstance(metrics.get("normalization_collision", False), bool)
1001
+ )
1002
+ if not valid_metrics:
1003
+ base["caution"] = (
1004
+ "aggregate source returned invalid relationship metrics; validation is not trusted"
1005
+ )
1006
+ results.append(base)
1007
+ continue
1008
+ try:
1009
+ RelationshipMetricsContract.model_validate(metrics)
1010
+ except Exception:
1011
+ base["caution"] = (
1012
+ "aggregate source returned invalid typed metrics; validation is not trusted"
1013
+ )
1014
+ results.append(base)
1015
+ continue
1016
+ if conditions:
1017
+ metrics = {
1018
+ **metrics,
1019
+ "condition_scope": "filtered_rows_on_declared_sides",
1020
+ "conditions_applied": len(conditions),
1021
+ }
1022
+ base["metrics"] = metrics
1023
+ if metrics.get("normalization_collision"):
1024
+ base["verdict"] = "not_checked"
1025
+ base["served"] = False
1026
+ base["caution"] = "lossy key normalization collision detected; validation is unsafe"
1027
+ results.append(base)
1028
+ continue
1029
+ good = min(metrics["source_match_rate"], metrics["target_match_rate"]) > min_match_rate
1030
+ if not good:
1031
+ base["verdict"] = "below_threshold"
1032
+ base["caution"] = f"match below configured minimum {min_match_rate:g}"
1033
+ else:
1034
+ left_entity = (entities or {}).get(left_key, {})
1035
+ right_entity = (entities or {}).get(right_key, {})
1036
+ source_preserved = metrics.get("source_side_preserved")
1037
+ target_preserved = metrics.get("target_side_preserved")
1038
+ if not isinstance(source_preserved, bool):
1039
+ source_preserved = metrics.get("source_fanout", metrics["fanout"]) <= 1
1040
+ if not isinstance(target_preserved, bool):
1041
+ target_preserved = metrics.get("target_fanout", 1.0) <= 1
1042
+ base["measure_guidance"] = _measure_guidance(
1043
+ left_key,
1044
+ left_entity if isinstance(left_entity, dict) else {},
1045
+ candidate["source_keys"],
1046
+ side_preserved=source_preserved,
1047
+ match_rate=metrics["source_match_rate"],
1048
+ ) + _measure_guidance(
1049
+ right_key,
1050
+ right_entity if isinstance(right_entity, dict) else {},
1051
+ candidate["target_keys"],
1052
+ side_preserved=target_preserved,
1053
+ match_rate=metrics["target_match_rate"],
1054
+ )
1055
+ if good and metrics.get("source_fanout", metrics["fanout"]) > 1:
1056
+ if metrics["cardinality"] == "1:N":
1057
+ base["verdict"] = "warning_one_to_many"
1058
+ elif metrics["cardinality"] == "N:N":
1059
+ base["verdict"] = "warning_many_to_many"
1060
+ else:
1061
+ base["verdict"] = "warning_row_multiplication"
1062
+ left_entity = (entities or {}).get(left_key, {})
1063
+ right_entity = (entities or {}).get(right_key, {})
1064
+ # Verified grain and measured fanout establish join behavior, not
1065
+ # that any particular measure is additive or safe to collapse.
1066
+ # Never emit generic pre-aggregation advice until measure-specific
1067
+ # semantics and the consumer's target grain have been established.
1068
+ base["aggregate_first"] = None
1069
+ base["aggregation_safety"] = {
1070
+ "status": "not_established",
1071
+ "recommended_preaggregation": None,
1072
+ "measure_specific_safety": "not_established",
1073
+ "reason": (
1074
+ "measured join fanout does not establish measure-specific safety "
1075
+ "or a consumer target grain"
1076
+ ),
1077
+ }
1078
+ base["served"] = True
1079
+ cardinality = metrics["cardinality"]
1080
+ if cardinality == "1:N":
1081
+ risk = "1:N join can multiply source-side rows"
1082
+ elif cardinality == "N:1":
1083
+ risk = "N:1 relationship; this join direction does not multiply source-side rows"
1084
+ elif cardinality == "N:N":
1085
+ risk = "N:N relationship can multiply rows"
1086
+ elif cardinality == "1:1":
1087
+ risk = "1:1 relationship with directional fanout reported above one"
1088
+ else:
1089
+ risk = "join direction has measured row multiplication"
1090
+ base["caution"] = risk + "; measure-specific pre-aggregation safety is not established"
1091
+ elif good:
1092
+ base["verdict"] = "accepted"
1093
+ base["served"] = True
1094
+ if metrics.get("target_fanout", 1.0) > 1:
1095
+ base["aggregation_safety"] = {
1096
+ "status": "not_established",
1097
+ "recommended_preaggregation": None,
1098
+ "measure_specific_safety": "not_established",
1099
+ "reason": (
1100
+ "target-side rows repeat in this direction; metric and target grain "
1101
+ "were not specified"
1102
+ ),
1103
+ }
1104
+ base["caution"] = (
1105
+ "source rows are preserved in this direction; target-side measures may be "
1106
+ "multiplied when joining back toward the source"
1107
+ )
1108
+ if candidate.get("type") == "temporal":
1109
+ temporal_caution = "temporal association is not evidence of causation"
1110
+ base["caution"] = "; ".join(
1111
+ part for part in (base["caution"], temporal_caution) if part
1112
+ )
1113
+ results.append(base)
1114
+ return results