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,1172 @@
1
+ """Read-only metadata adapter for a consumer-owned DuckDB DB-API connection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any, Dict, Iterable, Tuple
7
+
8
+ from semantic_context_engine.sources.base import Source, SourceCapabilities
9
+
10
+
11
+ def assert_aggregate_only_query(query, dialect: str = "duckdb") -> None:
12
+ """Reject aggregate queries whose returned row can contain source records.
13
+
14
+ The contract is deliberately conservative: the outer SELECT must read a
15
+ single aggregate CTE, and that CTE must be a one-row aggregate projection.
16
+ Subqueries are recursively checked instead of being accepted merely because
17
+ they occur beneath a SELECT.
18
+ """
19
+ from sqlglot import exp, parse
20
+
21
+ statements = parse(query, read=dialect) if isinstance(query, str) else [query]
22
+ if len(statements) != 1 or not isinstance(statements[0], exp.Select):
23
+ raise ValueError("Aggregate query must be one SELECT")
24
+ outer = statements[0]
25
+ with_clause = outer.args.get("with_")
26
+ ctes = (
27
+ {cte.alias_or_name.casefold(): cte.this for cte in with_clause.expressions}
28
+ if with_clause
29
+ else {}
30
+ )
31
+ from_clause = outer.args.get("from_")
32
+ sources = list(from_clause.find_all(exp.Table)) if from_clause else []
33
+ if len(sources) != 1 or sources[0].name.casefold() not in ctes:
34
+ raise ValueError("Aggregate query must return from one validated aggregate CTE")
35
+ if not all(
36
+ isinstance(projection, exp.Star)
37
+ or (isinstance(projection, exp.Column) and projection.is_star)
38
+ for projection in outer.expressions
39
+ ):
40
+ raise ValueError("Aggregate query outer projection must not expose row expressions")
41
+
42
+ def aggregate_projection(select):
43
+ if not isinstance(select, exp.Select) or select.args.get("group") is not None:
44
+ return False
45
+ if not select.expressions:
46
+ return False
47
+ for projection in select.expressions:
48
+ node = projection.this if isinstance(projection, exp.Alias) else projection
49
+ if isinstance(node, exp.Subquery):
50
+ if not aggregate_projection(node.this):
51
+ return False
52
+ continue
53
+ nested_selects = list(node.find_all(exp.Subquery))
54
+ for nested in nested_selects:
55
+ if not aggregate_projection(nested.this):
56
+ return False
57
+
58
+ def inside_subquery(candidate):
59
+ parent = candidate.parent
60
+ while parent is not None and parent is not node.parent:
61
+ if isinstance(parent, exp.Subquery):
62
+ return True
63
+ parent = parent.parent
64
+ return False
65
+
66
+ aggregate_nodes = [
67
+ agg for agg in node.find_all(exp.AggFunc) if not inside_subquery(agg)
68
+ ]
69
+ if isinstance(node, exp.AggFunc):
70
+ aggregate_nodes.append(node)
71
+ if not aggregate_nodes:
72
+ return False
73
+ for column in node.find_all(exp.Column):
74
+ if inside_subquery(column):
75
+ continue
76
+ ancestor = column.parent
77
+ inside_aggregate = False
78
+ while ancestor is not None and ancestor is not node.parent:
79
+ if isinstance(ancestor, exp.AggFunc):
80
+ inside_aggregate = True
81
+ break
82
+ ancestor = ancestor.parent
83
+ if not inside_aggregate:
84
+ return False
85
+ return True
86
+
87
+ aggregate = ctes[sources[0].name.casefold()]
88
+ if not aggregate_projection(aggregate):
89
+ raise ValueError("Aggregate CTE contains a non-aggregate or row-returning projection")
90
+
91
+
92
+ _IDENTIFIER = re.compile(r"^[A-Za-z_][A-Za-z0-9_$]*$")
93
+
94
+
95
+ class DuckDBSource(Source):
96
+ """Describe explicitly configured DuckDB objects using a supplied connection.
97
+
98
+ No connection is opened or closed here. ``objects`` is the authorization
99
+ boundary: each item has a canonical ``key`` and a 1–3 part ``fqn``.
100
+ """
101
+
102
+ def __init__(self, connection, objects: Iterable[dict]):
103
+ self.connection = connection
104
+ self._objects: Dict[str, dict] = {}
105
+ self._resolved: Dict[str, tuple[str, str, str]] = {}
106
+ self._constraint_diagnostics: dict[str, list[str]] = {}
107
+ from semantic_context_engine.domain_contracts import (
108
+ DiscriminatorProfilePolicyContract,
109
+ JsonProfilePolicyContract,
110
+ )
111
+
112
+ for item in objects:
113
+ if not isinstance(item, dict) or not item.get("key") or not item.get("fqn"):
114
+ raise ValueError("DuckDB allowlist entries require key and fqn")
115
+ key, fqn = str(item["key"]), str(item["fqn"])
116
+ parts = fqn.split(".")
117
+ if not 1 <= len(parts) <= 3 or any(not _IDENTIFIER.fullmatch(p) for p in parts):
118
+ raise ValueError(f"Invalid DuckDB identifier in allowlist: {fqn!r}")
119
+ if key in self._objects:
120
+ raise ValueError(f"Duplicate DuckDB allowlist key: {key}")
121
+ raw_profiles = item.get("json_profiles", [])
122
+ if not isinstance(raw_profiles, list):
123
+ raise ValueError("DuckDB JSON profile policies must be a list")
124
+ try:
125
+ profiles = [
126
+ JsonProfilePolicyContract.model_validate(profile).model_dump()
127
+ for profile in raw_profiles
128
+ ]
129
+ except Exception as exc:
130
+ raise ValueError("DuckDB JSON profile policy is invalid") from exc
131
+ if any(
132
+ len(set(profile["approved_values"])) != len(profile["approved_values"])
133
+ for profile in profiles
134
+ ):
135
+ raise ValueError("DuckDB JSON profile values must be unique")
136
+ raw_slices = item.get("discriminator_profiles", [])
137
+ if not isinstance(raw_slices, list):
138
+ raise ValueError("DuckDB discriminator profiles must be a list")
139
+ try:
140
+ slice_profiles = [
141
+ DiscriminatorProfilePolicyContract.model_validate(policy).model_dump()
142
+ for policy in raw_slices
143
+ ]
144
+ except Exception as exc:
145
+ raise ValueError("DuckDB discriminator profile policy is invalid") from exc
146
+ if any(
147
+ len(set(policy["approved_values"])) != len(policy["approved_values"])
148
+ for policy in slice_profiles
149
+ ):
150
+ raise ValueError("DuckDB discriminator profile values must be unique")
151
+ hierarchy_columns = item.get("hierarchy_columns")
152
+ if hierarchy_columns is not None and (
153
+ not isinstance(hierarchy_columns, list)
154
+ or len(hierarchy_columns) > 32
155
+ or any(not isinstance(column, str) or not column for column in hierarchy_columns)
156
+ or len(set(hierarchy_columns)) != len(hierarchy_columns)
157
+ ):
158
+ raise ValueError("DuckDB hierarchy column policy is invalid")
159
+ self._objects[key] = {
160
+ **item,
161
+ "_parts": parts,
162
+ "_json_profiles": profiles,
163
+ "_discriminator_profiles": slice_profiles,
164
+ }
165
+
166
+ @property
167
+ def dialect(self) -> str:
168
+ return "duckdb"
169
+
170
+ @property
171
+ def capabilities(self) -> SourceCapabilities:
172
+ return SourceCapabilities(
173
+ ddl=True,
174
+ grain_aggregate=True,
175
+ relationship_aggregate=True,
176
+ semistructured_profile=True,
177
+ hierarchy_aggregate=True,
178
+ relationship_key_transforms=True,
179
+ bounded_sampling=True,
180
+ column_statistics=True,
181
+ )
182
+
183
+ def allowlist(self) -> Tuple[str, ...]:
184
+ return tuple(self._objects)
185
+
186
+ def all_fqns(self) -> Tuple[str, ...]:
187
+ return tuple(item["fqn"] for item in self._objects.values())
188
+
189
+ def describe(self, key: str) -> dict:
190
+ if key not in self._objects:
191
+ raise KeyError(f"Key {key} not in DuckDB allowlist")
192
+ # Diagnostics describe the current metadata resolution for this
193
+ # object only. Keep other objects' diagnostics intact across direct
194
+ # describe() calls while preventing stale entries for this key.
195
+ diagnostics = self._constraint_diagnostics
196
+ diagnostics.pop(key, None)
197
+ spec = self._objects[key]
198
+ parts = spec["_parts"]
199
+ if len(parts) == 3:
200
+ catalog, schema, name = parts
201
+ elif len(parts) == 2:
202
+ catalog, schema, name = "", parts[0], parts[1]
203
+ else:
204
+ catalog, schema, name = "", "main", parts[0]
205
+
206
+ # Resolve short FQNs only when they identify exactly one catalog.
207
+ # Otherwise fail closed instead of combining same-named columns.
208
+ matches = self.connection.execute(
209
+ "SELECT table_catalog, table_type FROM information_schema.tables "
210
+ "WHERE table_schema = ? AND table_name = ? "
211
+ "AND (? = '' OR table_catalog = ?) ORDER BY table_catalog",
212
+ [schema, name, catalog, catalog],
213
+ ).fetchall()
214
+ if not matches:
215
+ raise KeyError(f"Allowlisted DuckDB object not found: {spec['fqn']}")
216
+ if len(matches) != 1:
217
+ names = ", ".join(row[0] for row in matches)
218
+ raise ValueError(
219
+ f"Ambiguous DuckDB FQN {spec['fqn']!r}; qualify catalog.schema.name "
220
+ f"(matching catalogs: {names})"
221
+ )
222
+ catalog, table_type = matches[0]
223
+ self._resolved[key] = (catalog, schema, name)
224
+
225
+ cur = self.connection.execute(
226
+ "SELECT column_name, data_type, is_nullable "
227
+ "FROM information_schema.columns WHERE table_schema = ? AND table_name = ? "
228
+ "AND table_catalog = ? ORDER BY ordinal_position",
229
+ [schema, name, catalog],
230
+ )
231
+ rows = cur.fetchall()
232
+ if not rows:
233
+ raise KeyError(f"Allowlisted DuckDB object not found: {spec['fqn']}")
234
+ columns = {row[0]: row[1] for row in rows}
235
+
236
+ # Catalog functions provide type and view SQL without scanning user data.
237
+ view = self.connection.execute(
238
+ "SELECT sql, comment FROM duckdb_views() WHERE schema_name = ? "
239
+ "AND view_name = ? AND (? = '' OR database_name = ?)",
240
+ [schema, name, catalog, catalog],
241
+ ).fetchone()
242
+ table = self.connection.execute(
243
+ "SELECT comment FROM duckdb_tables() WHERE schema_name = ? "
244
+ "AND table_name = ? AND (? = '' OR database_name = ?)",
245
+ [schema, name, catalog, catalog],
246
+ ).fetchone()
247
+ object_type = "VIEW" if table_type.upper() == "VIEW" else "TABLE"
248
+ ddl_raw = (view[0] or "") if view else ""
249
+ comment = (view[1] if view else None) or (table[0] if table else None)
250
+ declared_constraints = []
251
+ for row in self.connection.execute(
252
+ "SELECT constraint_type, constraint_column_names, referenced_table, "
253
+ "referenced_column_names FROM duckdb_constraints() "
254
+ "WHERE database_name = ? AND schema_name = ? AND table_name = ? "
255
+ "ORDER BY constraint_index",
256
+ [catalog, schema, name],
257
+ ).fetchall():
258
+ constraint_type, cols, referenced_table, referenced_cols = row
259
+ cols = list(cols or [])
260
+ if constraint_type == "PRIMARY KEY":
261
+ declared_constraints.append({"type": "primary_key", "columns": cols})
262
+ elif constraint_type == "FOREIGN KEY":
263
+ # DuckDB FKs refer within the same catalog/schema. A target
264
+ # outside the explicit allowlist is never added to the catalog.
265
+ matches = []
266
+ for target_key, target_spec in self._objects.items():
267
+ target_parts = target_spec["_parts"]
268
+ if len(target_parts) == 3:
269
+ tc, ts, tn = target_parts
270
+ match = (tc.lower(), ts.lower(), tn.lower()) == (
271
+ catalog.lower(),
272
+ schema.lower(),
273
+ referenced_table.lower(),
274
+ )
275
+ elif len(target_parts) == 2:
276
+ ts, tn = target_parts
277
+ match = (catalog.lower(), ts.lower(), tn.lower()) == (
278
+ catalog.lower(),
279
+ schema.lower(),
280
+ referenced_table.lower(),
281
+ )
282
+ else:
283
+ match = (
284
+ schema.lower() == "main"
285
+ and target_parts[0].lower() == referenced_table.lower()
286
+ )
287
+ if match:
288
+ matches.append(target_key)
289
+ if len(matches) == 1:
290
+ declared_constraints.append(
291
+ {
292
+ "type": "foreign_key",
293
+ "columns": cols,
294
+ "target": matches[0],
295
+ "target_columns": list(referenced_cols or []),
296
+ }
297
+ )
298
+ else:
299
+ # Keep diagnostics deliberately value-free: do not echo the
300
+ # referenced name or inspect an object outside the allowlist.
301
+ code = (
302
+ "constraint_target_not_allowlisted"
303
+ if not matches
304
+ else "constraint_target_ambiguous_in_allowlist"
305
+ )
306
+ self._constraint_diagnostics.setdefault(key, []).append(code)
307
+ return {
308
+ "key": key,
309
+ "fqn": spec["fqn"],
310
+ "object_type": object_type,
311
+ "description": spec.get("description"),
312
+ "hint": spec.get("hint"),
313
+ "table_comment": comment,
314
+ "columns": columns,
315
+ "ddl_raw": ddl_raw,
316
+ "ddl_error": "DuckDB table DDL is not exposed by the metadata adapter"
317
+ if not view
318
+ else None,
319
+ "dependencies": None,
320
+ "variant_discriminators": spec.get("variant_discriminators"),
321
+ "json_profiles": [dict(item) for item in spec["_json_profiles"]],
322
+ "declared_constraints": declared_constraints,
323
+ "constraint_diagnostics": list(self._constraint_diagnostics.get(key, [])),
324
+ }
325
+
326
+ def describe_many(self, keys=None):
327
+ """Refresh per-read constraint diagnostics and describe only requested allowlisted objects."""
328
+ self._constraint_diagnostics = {}
329
+ return super().describe_many(keys)
330
+
331
+ def profile_policies(self, key: str) -> list[dict]:
332
+ """Return only the already validated opt-in profile policies."""
333
+ if key not in self._objects:
334
+ raise KeyError("Profile object is outside the source allowlist")
335
+ return list(self._objects[key]["_json_profiles"])
336
+
337
+ def discriminator_policies(self, key: str) -> list[dict]:
338
+ if key not in self._objects:
339
+ raise KeyError("Discriminator object is outside the source allowlist")
340
+ return list(self._objects[key]["_discriminator_profiles"])
341
+
342
+ def hierarchy_columns(self, key: str) -> list[str] | None:
343
+ if key not in self._objects:
344
+ raise KeyError("Hierarchy object is outside the source allowlist")
345
+ value = self._objects[key].get("hierarchy_columns")
346
+ return list(value) if isinstance(value, list) else None
347
+
348
+ def condition_is_approved(self, key: str, condition: dict) -> bool:
349
+ """Only configured discriminator values may constrain a proposal."""
350
+ if key not in self._objects:
351
+ return False
352
+ column, operator, value = (
353
+ condition.get("column"),
354
+ condition.get("operator"),
355
+ condition.get("value"),
356
+ )
357
+ for policy in self._objects[key]["_discriminator_profiles"]:
358
+ if column == policy["column"] and (
359
+ (operator == "eq" and value in policy["approved_values"])
360
+ or (
361
+ operator == "in"
362
+ and isinstance(value, list)
363
+ and set(value) <= set(policy["approved_values"])
364
+ )
365
+ ):
366
+ return True
367
+ return False
368
+
369
+ def column_coverage_by_slice(
370
+ self, structural, column: str, discriminator: str, approved_values: list[str]
371
+ ) -> list[dict]:
372
+ """Return bounded count/non-null aggregates for approved slices only."""
373
+ if (
374
+ structural.key not in self._objects
375
+ or column not in structural.columns
376
+ or discriminator not in structural.columns
377
+ ):
378
+ raise ValueError("Coverage requires allowlisted existing columns")
379
+ if (
380
+ not approved_values
381
+ or len(approved_values) > 16
382
+ or any(not isinstance(value, str) for value in approved_values)
383
+ ):
384
+ raise ValueError("Coverage slices must be explicitly approved and bounded")
385
+ if structural.key not in self._resolved:
386
+ self.describe(structural.key)
387
+ catalog, schema, name = self._resolved[structural.key]
388
+
389
+ def ident(value: str) -> str:
390
+ return '"' + value.replace('"', '""') + '"'
391
+
392
+ table_sql = ".".join(ident(part) for part in (catalog, schema, name) if part)
393
+ placeholders = ", ".join("?" for _ in approved_values)
394
+ query = (
395
+ f"SELECT CAST({ident(discriminator)} AS VARCHAR) AS slice, COUNT(*) AS rows, "
396
+ f"COUNT({ident(column)}) AS non_null FROM {table_sql} "
397
+ f"WHERE CAST({ident(discriminator)} AS VARCHAR) IN ({placeholders}) "
398
+ "GROUP BY 1 ORDER BY 1"
399
+ )
400
+ from sqlglot import exp, parse
401
+
402
+ statements = parse(query, read="duckdb")
403
+ if len(statements) != 1 or not isinstance(statements[0], exp.Select):
404
+ raise ValueError("Generated coverage query is invalid")
405
+ rows = self.connection.execute(query, approved_values).fetchall()
406
+ by_slice = {
407
+ row[0]: {"slice": row[0], "rows": int(row[1]), "non_null": int(row[2])} for row in rows
408
+ }
409
+ return [
410
+ by_slice.get(value, {"slice": value, "rows": 0, "non_null": 0})
411
+ for value in sorted(approved_values)
412
+ ]
413
+
414
+ def count_rows_and_distinct(self, structural, columns: list[str]) -> tuple[int, int]:
415
+ """Return only aggregate counts; SQL is composed and parsed with SQLGlot."""
416
+ from sqlglot import exp, parse_one
417
+
418
+ spec = self._objects.get(structural.key)
419
+ if spec is None:
420
+ raise KeyError(f"Key {structural.key} not in DuckDB allowlist")
421
+ if not columns or any(name not in structural.columns for name in columns):
422
+ raise ValueError("Grain query requires existing structural columns")
423
+ if structural.key not in self._resolved:
424
+ # Describing first performs the unambiguous catalog resolution.
425
+ self.describe(structural.key)
426
+ catalog, schema, name = self._resolved[structural.key]
427
+
428
+ table = exp.Table(
429
+ this=exp.to_identifier(name, quoted=True),
430
+ db=exp.to_identifier(schema, quoted=True),
431
+ catalog=exp.to_identifier(catalog, quoted=True),
432
+ )
433
+ grain_columns = [exp.column(col, quoted=True) for col in columns]
434
+ groups = exp.select(*grain_columns).from_(table.copy()).group_by(*grain_columns)
435
+ distinct_count = exp.select(exp.Count(this=exp.Star()).as_("n")).from_(
436
+ groups.subquery("grain_groups")
437
+ )
438
+ query = exp.select(
439
+ exp.Count(this=exp.Star()).as_("row_count"),
440
+ exp.Subquery(this=distinct_count).as_("distinct_count"),
441
+ ).from_(table)
442
+ sql = query.sql(dialect="duckdb")
443
+
444
+ # Defense in depth: only execute the generated, single SELECT aggregate.
445
+ parsed = parse_one(sql, read="duckdb")
446
+ if not isinstance(parsed, exp.Select) or not all(
447
+ isinstance(node, exp.Select) for node in parsed.find_all(exp.Select)
448
+ ):
449
+ raise ValueError("Grain query must be a single aggregate SELECT")
450
+ result = self.connection.execute(sql).fetchone()
451
+ if not result or len(result) != 2:
452
+ raise RuntimeError("DuckDB aggregate grain query returned an invalid result")
453
+ return int(result[0]), int(result[1])
454
+
455
+ def count_rows_and_distinct_by_slice(
456
+ self, structural, columns: list[str], discriminator: str, approved_values: list[str]
457
+ ) -> list[dict[str, Any]]:
458
+ """Return per-approved-slice grain counts; no source rows leave DuckDB."""
459
+ from sqlglot import exp, parse
460
+
461
+ if structural.key not in self._objects:
462
+ raise KeyError("Discriminator grain object is outside the source allowlist")
463
+ if not columns or any(name not in structural.columns for name in columns):
464
+ raise ValueError("Discriminator grain requires existing grain columns")
465
+ if discriminator not in structural.columns or not approved_values:
466
+ raise ValueError("Discriminator grain policy is invalid")
467
+ policies = self.discriminator_policies(structural.key)
468
+ if not any(
469
+ item["column"] == discriminator and item["approved_values"] == approved_values
470
+ for item in policies
471
+ ):
472
+ raise PermissionError("Discriminator values were not explicitly approved")
473
+ if structural.key not in self._resolved:
474
+ self.describe(structural.key)
475
+ catalog, schema, name = self._resolved[structural.key]
476
+
477
+ def ident(value: str) -> str:
478
+ return '"' + value.replace('"', '""') + '"'
479
+
480
+ table_sql = ".".join(ident(part) for part in (catalog, schema, name) if part)
481
+ discriminator_sql = ident(discriminator)
482
+ grain_sql = ", ".join(ident(column) for column in columns)
483
+ placeholders = ", ".join("?" for _ in approved_values)
484
+ query = f"""
485
+ WITH filtered AS (
486
+ SELECT CAST({discriminator_sql} AS VARCHAR) AS slice, {grain_sql}
487
+ FROM {table_sql}
488
+ WHERE CAST({discriminator_sql} AS VARCHAR) IN ({placeholders})
489
+ ), row_counts AS (
490
+ SELECT slice, COUNT(*) AS rows FROM filtered GROUP BY slice
491
+ ), grain_groups AS (
492
+ SELECT slice, {grain_sql} FROM filtered GROUP BY slice, {grain_sql}
493
+ ), grain_counts AS (
494
+ SELECT slice, COUNT(*) AS distinct_count FROM grain_groups GROUP BY slice
495
+ )
496
+ SELECT r.slice, r.rows, COALESCE(g.distinct_count, 0) AS distinct_count
497
+ FROM row_counts AS r
498
+ LEFT JOIN grain_counts AS g ON r.slice = g.slice
499
+ ORDER BY r.slice
500
+ """
501
+ statements = parse(query, read="duckdb")
502
+ if len(statements) != 1 or not isinstance(statements[0], exp.Select):
503
+ raise ValueError("Generated discriminator grain query is invalid")
504
+ result = self.connection.execute(query, approved_values).fetchall()
505
+ by_slice = {
506
+ row[0]: {"slice": row[0], "rows": int(row[1]), "distinct": int(row[2])}
507
+ for row in result
508
+ }
509
+ return [
510
+ by_slice.get(value, {"slice": value, "rows": 0, "distinct": 0})
511
+ for value in sorted(approved_values)
512
+ ]
513
+
514
+ def profile_json_keys(self, key: str, *, profile_index: int = 0) -> dict:
515
+ """Return approved-slice JSON path/type/count evidence, never leaf values.
516
+
517
+ Profiling is disabled unless the allowlist entry contains a validated
518
+ `json_profiles` policy. Depth and distinct paths are capped by policy;
519
+ approved discriminator values are SQL parameters.
520
+ """
521
+ if key not in self._objects:
522
+ raise KeyError("JSON profile object is outside the source allowlist")
523
+ profiles = self._objects[key]["_json_profiles"]
524
+ if isinstance(profile_index, bool) or not isinstance(profile_index, int):
525
+ raise ValueError("JSON profile index must be an integer")
526
+ if not 0 <= profile_index < len(profiles):
527
+ raise PermissionError("JSON profile was not explicitly approved")
528
+ policy = profiles[profile_index]
529
+ structural = self.describe(key)
530
+ json_column = policy["column"]
531
+ discriminator = policy["discriminator_column"]
532
+ if json_column not in structural["columns"] or discriminator not in structural["columns"]:
533
+ raise ValueError("JSON profile references a missing structural column")
534
+ if key not in self._resolved:
535
+ raise KeyError("JSON profile object could not be resolved")
536
+ catalog, schema, name = self._resolved[key]
537
+
538
+ def ident(value: str) -> str:
539
+ return '"' + value.replace('"', '""') + '"'
540
+
541
+ table_sql = ".".join(ident(part) for part in (catalog, schema, name) if part)
542
+ json_sql = ident(json_column)
543
+ discriminator_sql = ident(discriminator)
544
+ slices = policy["approved_values"]
545
+ placeholders = ", ".join("?" for _ in slices)
546
+ max_keys = policy["max_keys"]
547
+ max_depth = policy["max_depth"]
548
+ query = f"""
549
+ WITH RECURSIVE
550
+ filtered AS (
551
+ SELECT ROW_NUMBER() OVER () AS doc_id,
552
+ CAST({discriminator_sql} AS VARCHAR) AS slice,
553
+ TRY_CAST({json_sql} AS JSON) AS doc
554
+ FROM {table_sql}
555
+ WHERE CAST({discriminator_sql} AS VARCHAR) IN ({placeholders})
556
+ ),
557
+ slice_counts AS (
558
+ SELECT slice, COUNT(*) AS rows,
559
+ COUNT(*) FILTER (WHERE doc IS NULL) AS invalid_json_rows
560
+ FROM filtered GROUP BY slice
561
+ ),
562
+ tree AS (
563
+ SELECT f.doc_id, f.slice, j.id, j.parent, j.key, j.fullkey, j.type
564
+ FROM filtered AS f
565
+ CROSS JOIN LATERAL json_tree(f.doc) AS j
566
+ ),
567
+ tree_depth AS (
568
+ SELECT doc_id, slice, id, parent, key, fullkey, type, 0 AS depth
569
+ FROM tree WHERE parent IS NULL
570
+ UNION ALL
571
+ SELECT child.doc_id, child.slice, child.id, child.parent,
572
+ child.key, child.fullkey, child.type, parent.depth + 1
573
+ FROM tree_depth AS parent
574
+ JOIN tree AS child ON child.doc_id = parent.doc_id AND child.parent = parent.id
575
+ WHERE parent.depth < {max_depth}
576
+ ),
577
+ key_counts AS (
578
+ SELECT slice,
579
+ CASE WHEN depth = 1 THEN key
580
+ ELSE regexp_replace(fullkey, '\\[[0-9]+\\]', '[*]', 'g')
581
+ END AS json_key,
582
+ type AS value_type, COUNT(*) AS present
583
+ FROM tree_depth
584
+ WHERE depth BETWEEN 1 AND {max_depth}
585
+ GROUP BY slice, json_key, value_type
586
+ ),
587
+ key_names AS (
588
+ SELECT DISTINCT json_key FROM key_counts
589
+ ORDER BY json_key LIMIT {max_keys + 1}
590
+ )
591
+ SELECT s.slice, s.rows, s.invalid_json_rows,
592
+ k.json_key, k.value_type, k.present
593
+ FROM slice_counts AS s
594
+ LEFT JOIN key_counts AS k ON k.slice = s.slice
595
+ LEFT JOIN key_names AS n ON n.json_key = k.json_key
596
+ WHERE k.json_key IS NULL OR n.json_key IS NOT NULL
597
+ ORDER BY s.slice, k.json_key, k.value_type
598
+ """
599
+ # Identifiers are selected only from the validated policy and resolved
600
+ # allowlist. Values remain parameters. Parse before execution to reject
601
+ # malformed/multi-statement SQL; the query returns only aggregate rows.
602
+ from sqlglot import exp, parse
603
+
604
+ statements = parse(query, read="duckdb")
605
+ if len(statements) != 1 or not isinstance(statements[0], exp.Select):
606
+ raise ValueError("Generated JSON profile query is invalid")
607
+ rows = self.connection.execute(query, slices).fetchall()
608
+ discovered = sorted({row[3] for row in rows if row[3] is not None})
609
+ partial = len(discovered) > max_keys
610
+ permitted_keys = set(discovered[:max_keys])
611
+ per_slice: dict[str, dict] = {}
612
+ for slice_value, row_count, invalid_count, json_key, value_type, present in rows:
613
+ entry = per_slice.setdefault(
614
+ slice_value,
615
+ {
616
+ "value": slice_value,
617
+ "rows": int(row_count),
618
+ "invalid_json_rows": int(invalid_count),
619
+ "keys": [],
620
+ },
621
+ )
622
+ if json_key is not None and json_key in permitted_keys:
623
+ entry["keys"].append(
624
+ {"key": json_key, "value_type": value_type, "present": int(present)}
625
+ )
626
+ return {
627
+ "status": "partial" if partial else "complete",
628
+ "column": json_column,
629
+ "discriminator": discriminator,
630
+ "slices": [per_slice[value] for value in sorted(per_slice)],
631
+ "max_depth": max_depth,
632
+ "limitations": ["bounded_json_paths", "leaf_values_not_returned"],
633
+ }
634
+
635
+ def sample_values(
636
+ self,
637
+ structural,
638
+ columns: list[str],
639
+ *,
640
+ mode: str,
641
+ max_rows: int,
642
+ max_values: int,
643
+ max_queries: int,
644
+ ) -> dict:
645
+ """Return explicitly selected values for transient prompt context only.
646
+
647
+ Callers must enforce a column allowlist and redact before model use.
648
+ Sampling is never persisted by this adapter. Each SELECT is bounded by
649
+ LIMIT; the method reports its exact statement count.
650
+ """
651
+ if structural.key not in self._objects or structural.key not in self._resolved:
652
+ self.describe(structural.key)
653
+ if mode not in {"rows", "distinct"}:
654
+ raise ValueError("Unsupported sample mode")
655
+ if not columns or len(columns) > 32 or len(set(columns)) != len(columns):
656
+ raise ValueError("Sampling requires 1 to 32 unique columns")
657
+ if any(column not in structural.columns for column in columns):
658
+ raise ValueError("Sampling references a missing structural column")
659
+ if not 0 <= max_rows <= 100 or not 0 <= max_values <= 100:
660
+ raise ValueError("Sampling limits are outside supported bounds")
661
+ required_queries = 1 if mode == "rows" else len(columns)
662
+ if isinstance(max_queries, bool) or max_queries < required_queries:
663
+ raise ValueError("Sampling query budget is insufficient")
664
+ catalog, schema, table = self._resolved[structural.key]
665
+
666
+ def ident(value: str) -> str:
667
+ return '"' + value.replace('"', '""') + '"'
668
+
669
+ table_sql = ".".join(ident(part) for part in (catalog, schema, table) if part)
670
+ queries = 0
671
+ values: Any
672
+ if mode == "rows":
673
+ limit = max_rows
674
+ query = (
675
+ f"SELECT {', '.join(ident(column) for column in columns)} "
676
+ f"FROM {table_sql} LIMIT {limit}"
677
+ )
678
+ from sqlglot import exp, parse
679
+
680
+ parsed = parse(query, read="duckdb")
681
+ if len(parsed) != 1 or not isinstance(parsed[0], exp.Select):
682
+ raise ValueError("Generated sampling query is invalid")
683
+ queries = 1
684
+ rows = self.connection.execute(query).fetchmany(limit)
685
+ values = [dict(zip(columns, row, strict=True)) for row in rows]
686
+ else:
687
+ values = {}
688
+ from sqlglot import exp, parse
689
+
690
+ for column in columns:
691
+ query = (
692
+ f"SELECT DISTINCT {ident(column)} FROM {table_sql} "
693
+ f"WHERE {ident(column)} IS NOT NULL LIMIT {max_values}"
694
+ )
695
+ parsed = parse(query, read="duckdb")
696
+ if len(parsed) != 1 or not isinstance(parsed[0], exp.Select):
697
+ raise ValueError("Generated sampling query is invalid")
698
+ queries += 1
699
+ values[column] = [row[0] for row in self.connection.execute(query).fetchall()]
700
+ return {"status": "sampled", "mode": mode, "values": values, "query_count": queries}
701
+
702
+ def profile_column_statistics(self, structural, columns: list[str]) -> dict:
703
+ """Return bounded aggregate counts only; no profile values leave DuckDB."""
704
+ if structural.key not in self._objects or structural.key not in self._resolved:
705
+ self.describe(structural.key)
706
+ if not columns or len(columns) > 32 or len(set(columns)) != len(columns):
707
+ raise ValueError("Profiling requires 1 to 32 unique columns")
708
+ if any(column not in structural.columns for column in columns):
709
+ raise ValueError("Profiling references a missing structural column")
710
+ catalog, schema, table = self._resolved[structural.key]
711
+
712
+ def ident(value: str) -> str:
713
+ return '"' + value.replace('"', '""') + '"'
714
+
715
+ table_sql = ".".join(ident(part) for part in (catalog, schema, table) if part)
716
+ projections = ["COUNT(*) AS row_count"]
717
+ for index, column in enumerate(columns):
718
+ col = ident(column)
719
+ projections.extend(
720
+ [f"COUNT({col}) AS non_null_{index}", f"COUNT(DISTINCT {col}) AS distinct_{index}"]
721
+ )
722
+ query = f"SELECT {', '.join(projections)} FROM {table_sql}"
723
+ from sqlglot import exp, parse
724
+
725
+ statements = parse(query, read="duckdb")
726
+ if len(statements) != 1 or not isinstance(statements[0], exp.Select):
727
+ raise ValueError("Generated profile query is invalid")
728
+ row = self.connection.execute(query).fetchone()
729
+ statistics = {
730
+ column: {
731
+ "rows": int(row[0]),
732
+ "non_null": int(row[1 + index * 2]),
733
+ "distinct": int(row[2 + index * 2]),
734
+ }
735
+ for index, column in enumerate(columns)
736
+ }
737
+ return {"status": "measured", "statistics": statistics, "query_count": 1}
738
+
739
+ def hierarchy_dependency(self, structural, parent_column: str, child_column: str) -> dict:
740
+ """Measure child -> parent functional dependency using aggregate counts only."""
741
+ if structural.key not in self._objects:
742
+ raise KeyError("Hierarchy object is outside the source allowlist")
743
+ if parent_column not in structural.columns or child_column not in structural.columns:
744
+ raise ValueError("Hierarchy columns must exist in the structural snapshot")
745
+ if parent_column == child_column:
746
+ raise ValueError("Hierarchy parent and child columns must differ")
747
+ if structural.key not in self._resolved:
748
+ self.describe(structural.key)
749
+ catalog, schema, name = self._resolved[structural.key]
750
+ table_sql = ".".join(
751
+ '"' + part.replace('"', '""') + '"' for part in (catalog, schema, name) if part
752
+ )
753
+ parent_sql = '"' + parent_column.replace('"', '""') + '"'
754
+ child_sql = '"' + child_column.replace('"', '""') + '"'
755
+ query = f"""
756
+ WITH mapped AS (
757
+ SELECT {child_sql} AS child_value,
758
+ COUNT(DISTINCT {parent_sql}) +
759
+ CASE WHEN COUNT(*) FILTER (WHERE {parent_sql} IS NULL) > 0 THEN 1 ELSE 0 END
760
+ AS parent_values
761
+ FROM {table_sql}
762
+ GROUP BY {child_sql}
763
+ )
764
+ SELECT (SELECT COUNT(*) FROM {table_sql}) AS row_count,
765
+ COUNT(*) AS child_groups,
766
+ COUNT(*) FILTER (WHERE parent_values > 1) AS violating_groups,
767
+ COUNT(*) FILTER (WHERE child_value IS NULL) AS null_child_groups,
768
+ (SELECT COUNT(DISTINCT {parent_sql}) +
769
+ CASE WHEN COUNT(*) FILTER (WHERE {parent_sql} IS NULL) > 0 THEN 1 ELSE 0 END
770
+ FROM {table_sql}) AS parent_values
771
+ FROM mapped
772
+ """
773
+ from sqlglot import exp, parse
774
+
775
+ statements = parse(query, read="duckdb")
776
+ if len(statements) != 1 or not isinstance(statements[0], exp.Select):
777
+ raise ValueError("Generated hierarchy aggregate query is invalid")
778
+ row = self.connection.execute(query).fetchone()
779
+ if row is None:
780
+ raise RuntimeError("Hierarchy aggregate returned no result")
781
+ rows, groups, violations, null_groups, parent_values = (int(value or 0) for value in row)
782
+ status = (
783
+ "unverified"
784
+ if rows == 0 or groups <= 1 or parent_values <= 1
785
+ else "failed"
786
+ if violations > 0
787
+ else "verified"
788
+ )
789
+ return {
790
+ "status": status,
791
+ "rows": rows,
792
+ "child_groups": groups,
793
+ "parent_values": parent_values,
794
+ "violating_child_groups": violations,
795
+ "null_child_groups": null_groups,
796
+ "nulls_count_as_a_mapping_value": True,
797
+ }
798
+
799
+ def relationship_metrics(
800
+ self,
801
+ left,
802
+ right,
803
+ left_keys: list[str],
804
+ right_keys: list[str],
805
+ *,
806
+ conditions: list[dict] | None = None,
807
+ key_transforms: list[dict] | None = None,
808
+ ) -> dict:
809
+ """One aggregate query. Match rate = matched normalized distinct keys / all
810
+ normalized distinct keys (a NULL group counts once and never matches).
811
+ Directional fanout is joined rows / matched rows on that side; legacy
812
+ ``fanout`` remains joined rows / all source rows for compatibility.
813
+ """
814
+ from sqlglot import exp, parse_one
815
+
816
+ if left.key not in self._objects or right.key not in self._objects:
817
+ raise KeyError("Relationship objects must both be in the DuckDB allowlist")
818
+ if left.key not in self._resolved:
819
+ self.describe(left.key)
820
+ if right.key not in self._resolved:
821
+ self.describe(right.key)
822
+ if (
823
+ not left_keys
824
+ or len(left_keys) != len(right_keys)
825
+ or any(k not in left.columns for k in left_keys)
826
+ or any(k not in right.columns for k in right_keys)
827
+ ):
828
+ raise ValueError(
829
+ "Relationship keys must be non-empty existing columns with matching arity"
830
+ )
831
+ key_transforms = key_transforms or [
832
+ {"source_transform": "identity", "target_transform": "identity"} for _ in left_keys
833
+ ]
834
+ if len(key_transforms) != len(left_keys):
835
+ raise ValueError("Relationship transformations must match key arity")
836
+
837
+ def category(dtype):
838
+ upper = dtype.upper()
839
+ if "DATE" in upper or "TIME" in upper:
840
+ return "temporal"
841
+ if any(t in upper for t in ("INT", "DECIMAL", "NUMERIC", "DOUBLE", "FLOAT", "REAL")):
842
+ return "numeric"
843
+ if any(t in upper for t in ("CHAR", "TEXT", "STRING", "VARCHAR")):
844
+ return "text"
845
+ return "other"
846
+
847
+ def effective_category(structural, column, transform, path):
848
+ if transform in {"date", "month"}:
849
+ return "temporal"
850
+ if transform != "json_path":
851
+ return category(structural.columns[column].data_type)
852
+ for evidence in getattr(structural, "variant_keys", []):
853
+ evidence_path = (
854
+ evidence.key if evidence.key.startswith("$.") else "$." + evidence.key
855
+ )
856
+ if evidence.column == column and evidence_path == path:
857
+ return category(evidence.value_type)
858
+ return "other"
859
+
860
+ for index, (left_key, right_key) in enumerate(zip(left_keys, right_keys)):
861
+ transform = key_transforms[index]
862
+ if effective_category(
863
+ left,
864
+ left_key,
865
+ transform.get("source_transform", "identity"),
866
+ transform.get("source_path"),
867
+ ) != effective_category(
868
+ right,
869
+ right_key,
870
+ transform.get("target_transform", "identity"),
871
+ transform.get("target_path"),
872
+ ):
873
+ raise ValueError(
874
+ "Relationship key types are incompatible; explicit normalization is required"
875
+ )
876
+
877
+ def physical_table(key: str) -> exp.Table:
878
+ catalog, schema, name = self._resolved[key]
879
+ parts = [part for part in (catalog, schema, name) if part]
880
+ value: exp.Expression = exp.to_identifier(parts[-1], quoted=True)
881
+ for part in reversed(parts[:-1]):
882
+ value = exp.Dot(this=exp.to_identifier(part, quoted=True), expression=value)
883
+ return exp.Table(this=value)
884
+
885
+ condition_params: list[Any] = []
886
+ filter_ctes: dict[str, exp.Select] = {}
887
+ for side, structural in (("source", left), ("target", right)):
888
+ side_conditions = [item for item in (conditions or []) if item.get("side") == side]
889
+ if not side_conditions:
890
+ continue
891
+ projection = exp.select(exp.Star()).from_(physical_table(structural.key))
892
+ predicates: list[exp.Expression] = []
893
+ for item in side_conditions:
894
+ column = item["column"]
895
+ if column not in (left.columns if side == "source" else right.columns):
896
+ raise ValueError("Relationship condition references a missing column")
897
+ col = exp.Cast(
898
+ this=exp.column(column, quoted=True),
899
+ to=exp.DataType.build("VARCHAR", dialect="duckdb"),
900
+ )
901
+ operator = item["operator"]
902
+ if operator == "eq":
903
+ condition_params.append(item["value"])
904
+ predicates.append(exp.EQ(this=col, expression=exp.Placeholder()))
905
+ elif operator == "in":
906
+ condition_params.extend(item["value"])
907
+ values = [exp.Placeholder() for _ in item["value"]]
908
+ predicates.append(exp.In(this=col, expressions=values))
909
+ elif operator == "is_null":
910
+ predicates.append(exp.Is(this=col, expression=exp.Null()))
911
+ elif operator == "not_null":
912
+ predicates.append(exp.Not(this=exp.Is(this=col, expression=exp.Null())))
913
+ else:
914
+ raise ValueError("Unsupported relationship condition")
915
+ for predicate in predicates:
916
+ projection = projection.where(predicate)
917
+ filter_ctes[f"{side}_filtered"] = projection
918
+
919
+ def table(key: str, side: str) -> exp.Expression:
920
+ if any(item.get("side") == side for item in (conditions or [])):
921
+ return exp.Table(this=exp.to_identifier(f"{side}_filtered"))
922
+ return physical_table(key)
923
+
924
+ def ident(value):
925
+ return '"' + value.replace('"', '""') + '"'
926
+
927
+ def transform_expression(alias, structural, key, index, side):
928
+ column = f"{alias}.{ident(key)}"
929
+ policy = key_transforms[index]
930
+ kind = policy.get(f"{side}_transform", "identity")
931
+ if kind == "identity":
932
+ return column
933
+ if kind == "date":
934
+ return f"CAST({column} AS DATE)"
935
+ if kind == "month":
936
+ return f"CAST(DATE_TRUNC('month', CAST({column} AS TIMESTAMP)) AS DATE)"
937
+ if kind == "json_path":
938
+ path = policy[f"{side}_path"]
939
+ path_sql = exp.Literal.string(path).sql(dialect="duckdb")
940
+ json_value = f"JSON_EXTRACT({column}, {path_sql})"
941
+ value_category = effective_category(structural, key, kind, path)
942
+ if value_category == "numeric":
943
+ return f"TRY_CAST({json_value} AS DECIMAL(38, 10))"
944
+ if value_category == "text":
945
+ return f"JSON_EXTRACT_STRING({column}, {path_sql})"
946
+ raise ValueError("JSON path relationship value type is unsupported")
947
+ raise ValueError("Relationship transform is unsupported")
948
+
949
+ def normalized_key(alias, structural, keys, side):
950
+ pieces = []
951
+ empty_tests = []
952
+ null_tests = []
953
+ for index, key in enumerate(keys):
954
+ transform = key_transforms[index].get(f"{side}_transform", "identity")
955
+ dtype = effective_category(
956
+ structural,
957
+ key,
958
+ transform,
959
+ key_transforms[index].get(f"{side}_path"),
960
+ )
961
+ col = transform_expression(alias, structural, key, index, side)
962
+ null_tests.append(f"{col} IS NULL")
963
+ if dtype == "temporal":
964
+ pieces.append(f"CAST({col} AS DATE)::VARCHAR")
965
+ elif dtype == "numeric":
966
+ pieces.append(f"CAST(CAST({col} AS DECIMAL(38, 10)) AS VARCHAR)")
967
+ else:
968
+ normalized = (
969
+ f"REGEXP_REPLACE(UPPER(TRIM(CAST({col} AS VARCHAR))), '[^A-Z0-9]', '', 'g')"
970
+ )
971
+ pieces.append(normalized)
972
+ empty_tests.append(f"{normalized} = ''")
973
+ empty_test = " OR ".join(empty_tests) or "FALSE"
974
+ return (
975
+ f"CASE WHEN ({' OR '.join(null_tests)}) OR ({empty_test}) THEN NULL "
976
+ f"ELSE CONCAT_WS('|', {', '.join(pieces)}) END"
977
+ )
978
+
979
+ def null_test(alias, structural, keys, side):
980
+ return " OR ".join(
981
+ f"{transform_expression(alias, structural, key, index, side)} IS NULL"
982
+ for index, key in enumerate(keys)
983
+ )
984
+
985
+ def empty_test(alias, structural, keys, side):
986
+ tests = []
987
+ for index, key in enumerate(keys):
988
+ dtype = effective_category(
989
+ structural,
990
+ key,
991
+ key_transforms[index].get(f"{side}_transform", "identity"),
992
+ key_transforms[index].get(f"{side}_path"),
993
+ )
994
+ if dtype in {"temporal", "numeric"}:
995
+ continue
996
+ col = transform_expression(alias, structural, key, index, side)
997
+ tests.append(
998
+ f"REGEXP_REPLACE(UPPER(TRIM(CAST({col} AS VARCHAR))), '[^A-Z0-9]', '', 'g') = ''"
999
+ )
1000
+ return " OR ".join(tests) or "FALSE"
1001
+
1002
+ def raw_tuple(alias, structural, keys, side):
1003
+ values = []
1004
+ for index, key in enumerate(keys):
1005
+ col = transform_expression(alias, structural, key, index, side)
1006
+ dtype = effective_category(
1007
+ structural,
1008
+ key,
1009
+ key_transforms[index].get(f"{side}_transform", "identity"),
1010
+ key_transforms[index].get(f"{side}_path"),
1011
+ )
1012
+ values.append(
1013
+ f"CAST({col} AS DECIMAL(38, 10))"
1014
+ if dtype == "numeric"
1015
+ else f"CAST({col} AS VARCHAR)"
1016
+ )
1017
+ return "(" + ", ".join(values) + ")"
1018
+
1019
+ def parsed_expression(sql, alias=None):
1020
+ node = parse_one(sql, read="duckdb")
1021
+ return node.as_(alias) if alias else node
1022
+
1023
+ lkeys = (
1024
+ exp.select(
1025
+ parsed_expression(normalized_key("l", left, left_keys, "source"), "k"),
1026
+ parsed_expression("COUNT(*)", "n"),
1027
+ parsed_expression(
1028
+ f"COUNT(DISTINCT {raw_tuple('l', left, left_keys, 'source')})", "raw_variants"
1029
+ ),
1030
+ parsed_expression(
1031
+ f"SUM(CASE WHEN {null_test('l', left, left_keys, 'source')} THEN 1 ELSE 0 END)",
1032
+ "null_rows",
1033
+ ),
1034
+ parsed_expression(
1035
+ f"SUM(CASE WHEN {empty_test('l', left, left_keys, 'source')} THEN 1 ELSE 0 END)",
1036
+ "empty_rows",
1037
+ ),
1038
+ )
1039
+ .from_(table(left.key, "source").as_("l"))
1040
+ .group_by(exp.Literal.number(1))
1041
+ )
1042
+ rkeys = (
1043
+ exp.select(
1044
+ parsed_expression(normalized_key("r", right, right_keys, "target"), "k"),
1045
+ parsed_expression("COUNT(*)", "n"),
1046
+ parsed_expression(
1047
+ f"COUNT(DISTINCT {raw_tuple('r', right, right_keys, 'target')})",
1048
+ "raw_variants",
1049
+ ),
1050
+ parsed_expression(
1051
+ f"SUM(CASE WHEN {null_test('r', right, right_keys, 'target')} THEN 1 ELSE 0 END)",
1052
+ "null_rows",
1053
+ ),
1054
+ parsed_expression(
1055
+ f"SUM(CASE WHEN {empty_test('r', right, right_keys, 'target')} THEN 1 ELSE 0 END)",
1056
+ "empty_rows",
1057
+ ),
1058
+ )
1059
+ .from_(table(right.key, "target").as_("r"))
1060
+ .group_by(exp.Literal.number(1))
1061
+ )
1062
+ matched = exp.select(
1063
+ parsed_expression("l.k"),
1064
+ parsed_expression("l.n").as_("ln"),
1065
+ parsed_expression("r.n").as_("rn"),
1066
+ parsed_expression("l.raw_variants").as_("lv"),
1067
+ parsed_expression("r.raw_variants").as_("rv"),
1068
+ ).from_(exp.Table(this=exp.to_identifier("lkeys")).as_("l"))
1069
+ matched = matched.join(
1070
+ exp.Table(this=exp.to_identifier("rkeys")).as_("r"),
1071
+ on=parsed_expression("l.k = r.k"),
1072
+ )
1073
+
1074
+ def scalar_count(source):
1075
+ return exp.Subquery(this=exp.select(exp.Count(this=exp.Star())).from_(source))
1076
+
1077
+ def scalar_sum(cte, field):
1078
+ select = exp.select(parsed_expression(f"COALESCE(SUM({field}), 0)"))
1079
+ select = select.from_(exp.Table(this=exp.to_identifier(cte)))
1080
+ return exp.Subquery(this=select.where(parsed_expression("k IS NULL")))
1081
+
1082
+ agg = exp.select(
1083
+ scalar_count(table(left.key, "source")).as_("left_rows"),
1084
+ scalar_count(table(right.key, "target")).as_("right_rows"),
1085
+ scalar_count(exp.Table(this=exp.to_identifier("lkeys"))).as_("left_keys"),
1086
+ scalar_count(exp.Table(this=exp.to_identifier("rkeys"))).as_("right_keys"),
1087
+ scalar_sum("lkeys", "null_rows").as_("left_null_rows"),
1088
+ scalar_sum("rkeys", "null_rows").as_("right_null_rows"),
1089
+ scalar_sum("lkeys", "empty_rows").as_("left_empty_rows"),
1090
+ scalar_sum("rkeys", "empty_rows").as_("right_empty_rows"),
1091
+ parsed_expression("COUNT(*)", "matched_keys"),
1092
+ parsed_expression("COALESCE(SUM(m.ln), 0)", "matched_left_keys"),
1093
+ parsed_expression("COALESCE(SUM(m.rn), 0)", "matched_right_keys"),
1094
+ parsed_expression("COALESCE(SUM(m.ln * m.rn), 0)", "joined_rows"),
1095
+ parsed_expression("COALESCE(BOOL_OR(m.ln > 1), FALSE)", "left_dupes"),
1096
+ parsed_expression("COALESCE(BOOL_OR(m.rn > 1), FALSE)", "right_dupes"),
1097
+ parsed_expression("COALESCE(BOOL_OR(m.lv > 1), FALSE)", "left_normalization_collision"),
1098
+ parsed_expression(
1099
+ "COALESCE(BOOL_OR(m.rv > 1), FALSE)", "right_normalization_collision"
1100
+ ),
1101
+ ).from_(exp.Table(this=exp.to_identifier("matched")).as_("m"))
1102
+ query = exp.select(exp.Star()).from_(exp.Table(this=exp.to_identifier("agg")))
1103
+ for alias, cte in filter_ctes.items():
1104
+ query = query.with_(alias, as_=cte)
1105
+ query = (
1106
+ query.with_("lkeys", as_=lkeys)
1107
+ .with_("rkeys", as_=rkeys)
1108
+ .with_("matched", as_=matched)
1109
+ .with_("agg", as_=agg)
1110
+ )
1111
+ sql = query.sql(dialect="duckdb")
1112
+ assert_aggregate_only_query(query, dialect="duckdb")
1113
+ row = self.connection.execute(sql, condition_params).fetchone()
1114
+ if row is None or len(row) != 16:
1115
+ raise RuntimeError("DuckDB relationship aggregate returned invalid result")
1116
+ (
1117
+ left_rows,
1118
+ right_rows,
1119
+ left_count,
1120
+ right_count,
1121
+ left_null_rows,
1122
+ right_null_rows,
1123
+ left_empty_rows,
1124
+ right_empty_rows,
1125
+ matched_count,
1126
+ matched_left,
1127
+ matched_right,
1128
+ joined_rows,
1129
+ left_dupes,
1130
+ right_dupes,
1131
+ left_collision,
1132
+ right_collision,
1133
+ ) = row
1134
+ left_rate = matched_count / left_count if left_count else 0.0
1135
+ right_rate = matched_count / right_count if right_count else 0.0
1136
+ cardinality = (
1137
+ "unknown"
1138
+ if not matched_count
1139
+ else "1:1"
1140
+ if not left_dupes and not right_dupes
1141
+ else "N:1"
1142
+ if left_dupes and not right_dupes
1143
+ else "1:N"
1144
+ if not left_dupes
1145
+ else "N:N"
1146
+ )
1147
+ fanout = joined_rows / left_rows if left_rows else 0.0
1148
+ source_fanout = joined_rows / matched_left if matched_left else 0.0
1149
+ target_fanout = joined_rows / matched_right if matched_right else 0.0
1150
+ return {
1151
+ "source_match_rate": left_rate,
1152
+ "target_match_rate": right_rate,
1153
+ "cardinality": cardinality,
1154
+ "fanout": fanout,
1155
+ "left_rows": int(left_rows),
1156
+ "right_rows": int(right_rows),
1157
+ "joined_rows": int(joined_rows),
1158
+ "matched_keys": int(matched_count),
1159
+ "source_distinct_keys": int(left_count),
1160
+ "target_distinct_keys": int(right_count),
1161
+ "source_null_key_rows": int(left_null_rows),
1162
+ "target_null_key_rows": int(right_null_rows),
1163
+ "source_empty_key_rows": int(left_empty_rows),
1164
+ "target_empty_key_rows": int(right_empty_rows),
1165
+ "matched_source_rows": int(matched_left),
1166
+ "matched_target_rows": int(matched_right),
1167
+ "source_fanout": source_fanout,
1168
+ "target_fanout": target_fanout,
1169
+ "source_side_preserved": source_fanout <= 1.0,
1170
+ "target_side_preserved": target_fanout <= 1.0,
1171
+ "normalization_collision": bool(left_collision or right_collision),
1172
+ }