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,351 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Dict, List, Mapping, Optional, Set, Tuple
4
+
5
+ from semantic_context_engine.models import ColumnMeta, ObjectSnapshot, VariantKey
6
+
7
+ import json
8
+ import re
9
+
10
+
11
+ def canonical_ddl(ddl_raw: str, dialect: Optional[str] = None) -> Tuple[str, Optional[str]]:
12
+ """Return comment-free canonical SQL, preserving raw text on parse failure."""
13
+ try:
14
+ import sqlglot
15
+ from sqlglot import exp
16
+
17
+ expression = sqlglot.parse_one(
18
+ ddl_raw, read=dialect if dialect and dialect != "generic" else None
19
+ )
20
+ if expression is None or not isinstance(expression, exp.Create):
21
+ raise ValueError("DDL is not a CREATE statement")
22
+ return expression.sql(
23
+ dialect=dialect if dialect and dialect != "generic" else None,
24
+ comments=False,
25
+ ), None
26
+ except Exception:
27
+ normalized = _normalize_whitespace(ddl_raw)
28
+ # Parser exceptions can include literal SQL fragments; keep a stable
29
+ # diagnostic without copying potentially sensitive DDL into reports.
30
+ return (
31
+ normalized,
32
+ "DDL could not be parsed; inferred dependencies are unavailable",
33
+ )
34
+
35
+
36
+ def _normalize_whitespace(ddl: str) -> str:
37
+ """Normaliza whitespace no DDL."""
38
+ # Replace newlines with Spaces, collapse multiple spaces
39
+ result = ddl.replace("\r\n", "\n").replace("\r", "\n")
40
+ # Preserve structure: split by common SQL keywords and re-join
41
+ # A abordagem simples: lowercase normalize e collapse spaces
42
+ result = re.sub(r"\s+", " ", result)
43
+ # Ensure single spaces around key tokens
44
+ result = result.strip()
45
+ return result
46
+
47
+
48
+ def extract_dependencies(
49
+ ddl_canonical: str, ddl_raw: str, dialect: Optional[str] = None
50
+ ) -> Set[str]:
51
+ """Extract physical table references from SQLGlot scopes.
52
+
53
+ CTE/subquery aliases are represented as scopes and excluded. Physical table
54
+ references are deduplicated; the CREATE target is excluded as self-reference.
55
+ On parse failure return no inferred dependencies (the caller retains the
56
+ parser diagnostic and must not treat uncertainty as verified lineage).
57
+ """
58
+ try:
59
+ import sqlglot
60
+ from sqlglot import exp
61
+ from sqlglot.optimizer.scope import traverse_scope
62
+
63
+ sql = ddl_canonical or ddl_raw
64
+ statements = sqlglot.parse(sql, read=dialect if dialect and dialect != "generic" else None)
65
+ if len(statements) != 1 or statements[0] is None:
66
+ return set()
67
+ statement = statements[0]
68
+ if not isinstance(statement, exp.Create):
69
+ return set()
70
+ target = statement.this
71
+ target_parts = tuple(
72
+ part.name.casefold() for part in target.parts if isinstance(part, exp.Identifier)
73
+ )
74
+ query = statement.expression
75
+ if query is None:
76
+ return set()
77
+ result: Set[str] = set()
78
+ for scope in traverse_scope(query):
79
+ for source in scope.sources.values():
80
+ if not isinstance(source, exp.Table):
81
+ continue
82
+ if not all(isinstance(part, exp.Identifier) for part in source.parts):
83
+ continue
84
+ parts = tuple(part.name for part in source.parts)
85
+ if not parts or tuple(part.casefold() for part in parts) == target_parts:
86
+ continue
87
+ result.add(".".join(parts).upper())
88
+ return result
89
+ except Exception:
90
+ return set()
91
+
92
+
93
+ def compute_fingerprint(
94
+ fqn: str,
95
+ object_type: str,
96
+ description: Optional[str],
97
+ hint: Optional[str],
98
+ table_comment: Optional[str],
99
+ columns: Mapping[str, object], # name -> data_type or canonical column fields
100
+ ddl_canonical: str,
101
+ variant_keys: Optional[List[dict]] = None,
102
+ declared_constraints: Optional[List[dict]] = None,
103
+ ) -> str:
104
+ """Computa o fingerprint de um objeto (spec §5.5).
105
+
106
+ Cobre: fqn, object_type, description, hint, table_comment,
107
+ columns, ddl_canonical, variant_keys. Fica fora: ddl_raw, ddl_error,
108
+ dependencies (derivado), discovered_at.
109
+ """
110
+ import hashlib
111
+
112
+ # Normalize columns: sort by key, ensure data_type strings
113
+ norm_columns: Dict[str, object] = {}
114
+ for name, value in sorted(columns.items()):
115
+ if isinstance(value, dict):
116
+ norm_columns[name] = {
117
+ "data_type": value.get("data_type", ""),
118
+ "nullable": value.get("nullable", True),
119
+ "comment": value.get("comment"),
120
+ }
121
+ else:
122
+ # Keep the historical helper form for callers supplying only types.
123
+ norm_columns[name] = str(value)
124
+
125
+ # Normalize variant_keys
126
+ norm_variant_keys: List[dict] = []
127
+ if variant_keys:
128
+ for vk in sorted(
129
+ variant_keys,
130
+ key=lambda x: (
131
+ x.get("column", ""),
132
+ x.get("discriminator", ""),
133
+ x.get("key", ""),
134
+ x.get("value_type", ""),
135
+ ),
136
+ ):
137
+ norm_variant_keys.append(
138
+ {
139
+ "column": vk.get("column", ""),
140
+ "discriminator": vk.get("discriminator", ""),
141
+ "key": vk.get("key", ""),
142
+ "value_type": vk.get("value_type", ""),
143
+ "status": vk.get("status", "complete"),
144
+ }
145
+ )
146
+
147
+ fingerprint_data = {
148
+ "fqn": fqn,
149
+ "object_type": object_type,
150
+ "description": description or "",
151
+ "hint": hint or "",
152
+ "table_comment": table_comment or "",
153
+ "columns": norm_columns,
154
+ "ddl_canonical": ddl_canonical,
155
+ "variant_keys": norm_variant_keys,
156
+ "declared_constraints": declared_constraints or [],
157
+ }
158
+
159
+ fingerprint_str = json.dumps(fingerprint_data, sort_keys=True, separators=(",", ":"))
160
+ return hashlib.sha256(fingerprint_str.encode("utf-8")).hexdigest()[:32]
161
+
162
+
163
+ def normalize_object_metadata(metadata: dict, dialect: Optional[str] = None) -> ObjectSnapshot:
164
+ """Normaliza dict RawObjectMetadata em ObjectSnapshot (pure Python)."""
165
+ if not isinstance(metadata, dict):
166
+ raise TypeError("Object metadata must be a mapping")
167
+ # Extract fields
168
+ key = metadata.get("key", "")
169
+ fqn = metadata.get("fqn", "")
170
+ object_type = metadata.get("object_type", "VIEW")
171
+ if not isinstance(key, str) or not key.strip():
172
+ raise ValueError("Object metadata requires a non-empty canonical key")
173
+ if not isinstance(fqn, str) or not fqn.strip():
174
+ raise ValueError(f"Object {key!r} requires a non-empty FQN")
175
+ if not isinstance(object_type, str) or not object_type.strip():
176
+ raise ValueError(f"Object {key!r} requires a non-empty object_type")
177
+ description = metadata.get("description")
178
+ hint = metadata.get("hint")
179
+ table_comment = metadata.get("table_comment")
180
+
181
+ # Columns
182
+ columns_raw = metadata.get("columns", {})
183
+ if not isinstance(columns_raw, dict) or not columns_raw:
184
+ raise ValueError(f"Object {key!r} requires a non-empty columns mapping")
185
+ columns: Dict[str, ColumnMeta] = {}
186
+ for name, value in columns_raw.items():
187
+ if not isinstance(name, str) or not name:
188
+ raise ValueError(f"Object {key!r} has an invalid column name")
189
+ if isinstance(value, dict):
190
+ if set(value) - {"data_type", "nullable", "comment"}:
191
+ raise ValueError(f"Object {key!r} column {name!r} has unknown fields")
192
+ dtype = value.get("data_type")
193
+ nullable = value.get("nullable", True)
194
+ comment = value.get("comment")
195
+ if (
196
+ not isinstance(dtype, str)
197
+ or not dtype.strip()
198
+ or type(nullable) is not bool
199
+ or (comment is not None and not isinstance(comment, str))
200
+ ):
201
+ raise ValueError(f"Object {key!r} column {name!r} has invalid metadata")
202
+ columns[name] = ColumnMeta(
203
+ name=name, data_type=dtype, nullable=nullable, comment=comment
204
+ )
205
+ elif isinstance(value, str) and value.strip():
206
+ columns[name] = ColumnMeta(name=name, data_type=value, nullable=True)
207
+ else:
208
+ raise ValueError(f"Object {key!r} column {name!r} requires a data type")
209
+
210
+ # DDL
211
+ ddl_raw = metadata.get("ddl_raw", "")
212
+ ddl_canonical, ddl_error = canonical_ddl(ddl_raw, dialect=dialect)
213
+ # A connector may deliberately omit DDL when permissions prevent reading it.
214
+ # Preserve that source diagnostic instead of replacing it with the generic
215
+ # validation error produced for an empty string.
216
+ source_ddl_error = metadata.get("ddl_error")
217
+ if source_ddl_error:
218
+ ddl_error = str(source_ddl_error)
219
+
220
+ # Dependencies
221
+ deps_raw = metadata.get("dependencies")
222
+ if deps_raw is None:
223
+ deps = extract_dependencies(ddl_canonical, ddl_raw, dialect=dialect) if ddl_raw else set()
224
+ elif isinstance(deps_raw, (list, tuple, set, frozenset)):
225
+ deps = set(deps_raw)
226
+ else:
227
+ raise ValueError(f"Object {key!r} dependencies must be a sequence")
228
+
229
+ # Filter out the view's own name from dependencies
230
+ # Extract the base name from fqn
231
+ fqn_parts = fqn.split(".")
232
+ base_name = fqn_parts[-1] if fqn_parts else ""
233
+
234
+ # Remove the view's own name from deps if present
235
+ deps.discard(base_name)
236
+
237
+ # Compute fingerprint (excluindo ddl_raw, ddl_error, dependencies, discovered_at)
238
+ # variant_discriminators may be None or dict
239
+ vd = metadata.get("variant_discriminators") or {}
240
+ if not isinstance(vd, dict):
241
+ raise ValueError(f"Object {key!r} variant_discriminators must be a mapping")
242
+ variant_keys_list: List[dict] = []
243
+ for col_name, discriminator_expr in vd.items():
244
+ if not isinstance(col_name, str) or col_name not in columns:
245
+ raise ValueError(f"Object {key!r} has a discriminator for an unknown column")
246
+ if not isinstance(discriminator_expr, str) or not discriminator_expr.strip():
247
+ raise ValueError(f"Object {key!r} has an invalid discriminator expression")
248
+ # Parse discriminator like "PAYLOAD:type::string"
249
+ parts = discriminator_expr.split(":")
250
+ if len(parts) >= 2:
251
+ col = parts[0].strip()
252
+ type_part = ":".join(parts[1:])
253
+ if "::" in type_part:
254
+ _, value_type = type_part.split("::", 1)
255
+ else:
256
+ value_type = type_part
257
+ variant_keys_list.append(
258
+ {
259
+ "column": col,
260
+ "discriminator": discriminator_expr,
261
+ "key": col,
262
+ "value_type": value_type,
263
+ }
264
+ )
265
+
266
+ # D19: declared constraints are evidence only; never trust them as an
267
+ # approval. Normalize a small explicit contract so malformed connector
268
+ # metadata cannot silently create arbitrary joins.
269
+ raw_constraints = metadata.get("declared_constraints", [])
270
+ if not isinstance(raw_constraints, list):
271
+ raise ValueError(f"Object {key!r} declared_constraints must be a list")
272
+ constraints = []
273
+ for item in raw_constraints:
274
+ if not isinstance(item, dict) or set(item) - {
275
+ "type",
276
+ "columns",
277
+ "target",
278
+ "target_columns",
279
+ }:
280
+ raise ValueError(f"Object {key!r} has an invalid declared constraint")
281
+ ctype = item.get("type")
282
+ cols = item.get("columns")
283
+ if not isinstance(ctype, str) or ctype not in {"primary_key", "foreign_key"}:
284
+ raise ValueError(f"Object {key!r} has an unsupported declared constraint type")
285
+ if (
286
+ not isinstance(cols, list)
287
+ or not cols
288
+ or any(not isinstance(col, str) for col in cols)
289
+ or len(set(cols)) != len(cols)
290
+ or any(col not in columns for col in cols)
291
+ ):
292
+ raise ValueError(f"Object {key!r} declared constraint has invalid columns")
293
+ normalized = {"type": ctype, "columns": list(cols)}
294
+ if ctype == "foreign_key":
295
+ target = item.get("target")
296
+ target_cols = item.get("target_columns")
297
+ if (
298
+ not isinstance(target, str)
299
+ or not target.strip()
300
+ or not isinstance(target_cols, list)
301
+ or not target_cols
302
+ or len(target_cols) != len(cols)
303
+ or any(not isinstance(col, str) or not col.strip() for col in target_cols)
304
+ or len(set(target_cols)) != len(target_cols)
305
+ ):
306
+ raise ValueError(f"Object {key!r} has an invalid declared foreign key")
307
+ normalized.update({"target": target, "target_columns": list(target_cols)})
308
+ elif "target" in item or "target_columns" in item:
309
+ raise ValueError(f"Object {key!r} primary key cannot have a target")
310
+ constraints.append(normalized)
311
+ constraints.sort(key=lambda x: json.dumps(x, sort_keys=True, separators=(",", ":")))
312
+
313
+ # Columns as dict of str for fingerprint (data_type strings)
314
+ columns_for_fp = {
315
+ name: {
316
+ "data_type": col.data_type,
317
+ "nullable": col.nullable,
318
+ "comment": col.comment,
319
+ }
320
+ for name, col in columns.items()
321
+ }
322
+
323
+ fingerprint = compute_fingerprint(
324
+ fqn=fqn,
325
+ object_type=object_type,
326
+ description=description,
327
+ hint=hint,
328
+ table_comment=table_comment,
329
+ columns=columns_for_fp,
330
+ ddl_canonical=ddl_canonical,
331
+ variant_keys=variant_keys_list,
332
+ declared_constraints=constraints,
333
+ )
334
+
335
+ return ObjectSnapshot(
336
+ key=key,
337
+ fqn=fqn,
338
+ object_type=object_type,
339
+ description=description,
340
+ hint=hint,
341
+ table_comment=table_comment,
342
+ columns=columns,
343
+ ddl_canonical=ddl_canonical,
344
+ ddl_raw=ddl_raw,
345
+ ddl_error=ddl_error,
346
+ dependencies=deps,
347
+ variant_keys=[VariantKey(**item) for item in variant_keys_list],
348
+ declared_constraints=constraints,
349
+ fingerprint=fingerprint,
350
+ discovered_at=metadata.get("discovered_at", ""),
351
+ )