glosslayer 0.1.0__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.
glosslayer/checks.py ADDED
@@ -0,0 +1,512 @@
1
+ """Data quality checks attached to semantic types and fields.
2
+
3
+ from glosslayer import checks
4
+
5
+ checks.not_null()
6
+ checks.unique()
7
+ checks.matches(r"^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$")
8
+ checks.one_of(["open", "shipped", "cancelled"])
9
+ checks.between(0, 10_000)
10
+ checks.length(2, 2)
11
+ checks.sql("{column} >= 0") # escape hatch: any boolean SQL over the column
12
+
13
+ Checks are *declarations*: plain data stored as facts (``checks`` attribute), so they
14
+ are reviewed and logged like everything else. A field's effective checks are its
15
+ semantic type's checks plus its own.
16
+
17
+ Running them:
18
+
19
+ * ``run_polars(g, "shop.orders", df)`` evaluates on a Polars DataFrame (pip install polars);
20
+ * ``polars_plan(g, "shop.orders", lazy_frame)`` returns one ``LazyFrame`` that counts every
21
+ failure in a single pass, for hosts that never collect in the calling process: ship
22
+ ``plan.frame`` to wherever the data is, collect it there, and hand the one-row result to
23
+ ``plan.results(row)``;
24
+ * ``to_sql(g, "shop.orders", dialect="duckdb")`` produces one query per check to run anywhere.
25
+
26
+ Results can be logged with ``g.record_check_results(results, run_id=...)`` and read back with
27
+ ``g.check_history(subject)``.
28
+
29
+ Custom checks: subclass :class:`Check`, implement ``polars`` and/or ``sql``, and
30
+ decorate with :func:`register`.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import re
36
+ from collections.abc import Sequence
37
+ from dataclasses import asdict, dataclass, field, fields, replace
38
+ from datetime import datetime, timezone
39
+ from typing import TYPE_CHECKING, Any, ClassVar
40
+
41
+ if TYPE_CHECKING:
42
+ from .ledger import Gloss
43
+
44
+ _REGISTRY: dict[str, type[Check]] = {}
45
+
46
+
47
+ def register(cls: type[Check]) -> type[Check]:
48
+ """Class decorator: make a check type known so stored checks can be rebuilt."""
49
+ if not cls.kind:
50
+ raise ValueError(f"{cls.__name__} needs a `kind`")
51
+ _REGISTRY[cls.kind] = cls
52
+ return cls
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class Check:
57
+ """Base of the check declarations: a frozen dataclass whose fields are its parameters."""
58
+
59
+ kind: ClassVar[str] = ""
60
+ row_level: ClassVar[bool] = True # False: evaluated over the whole column (e.g. unique)
61
+
62
+ def to_dict(self) -> dict[str, Any]:
63
+ """The stored form: ``{"check": kind, **parameters}``, leaving out parameters that are None."""
64
+ return {"check": self.kind, **{k: v for k, v in asdict(self).items() if v is not None}}
65
+
66
+ @staticmethod
67
+ def from_dict(d: dict[str, Any]) -> Check:
68
+ """Rebuild a check from its stored form; an unregistered kind becomes :class:`Unknown`."""
69
+ d = dict(d)
70
+ kind = d.pop("check")
71
+ cls = _REGISTRY.get(kind)
72
+ if cls is None:
73
+ return Unknown(kind=kind, params=d) # kept, not runnable until registered
74
+ return cls(**d)
75
+
76
+ def describe(self) -> str:
77
+ """A short readable form, e.g. ``between(min=0, max=10)``."""
78
+ args = ", ".join(f"{f.name}={getattr(self, f.name)!r}" for f in fields(self) if getattr(self, f.name) is not None)
79
+ return f"{self.kind}({args})"
80
+
81
+ # Implement one or both. Each returns a *pass* condition.
82
+ def polars(self, col: str) -> Any: # -> pl.Expr (True = row passes)
83
+ """A Polars expression that is true for rows of ``col`` that pass.
84
+
85
+ A null result counts as a failure, so a check that lets nulls pass must say so explicitly.
86
+ """
87
+ raise NotImplementedError(f"check {self.kind} has no Polars implementation")
88
+
89
+ def sql(self, col: str, dialect: str = "ansi") -> str: # boolean SQL, TRUE = row passes
90
+ """A boolean SQL condition over ``col``, TRUE for rows that pass; a NULL result counts as a failure.
91
+
92
+ Only row-level checks need one: ``to_sql`` writes its own query for checks with ``row_level`` False.
93
+ """
94
+ raise NotImplementedError(f"check {self.kind} has no SQL implementation")
95
+
96
+
97
+ def _q(col: str) -> str:
98
+ return '"' + col.replace('"', '""') + '"'
99
+
100
+
101
+ def _lit(v: Any) -> str:
102
+ if isinstance(v, str):
103
+ return "'" + v.replace("'", "''") + "'"
104
+ if isinstance(v, bool):
105
+ return "TRUE" if v else "FALSE"
106
+ return repr(v)
107
+
108
+
109
+ @register
110
+ @dataclass(frozen=True)
111
+ class NotNull(Check):
112
+ """Passes when the value is not null."""
113
+
114
+ kind: ClassVar[str] = "not_null"
115
+
116
+ def polars(self, col: str) -> Any:
117
+ import polars as pl
118
+
119
+ return pl.col(col).is_not_null()
120
+
121
+ def sql(self, col: str, dialect: str = "ansi") -> str:
122
+ return f"{_q(col)} IS NOT NULL"
123
+
124
+
125
+ @register
126
+ @dataclass(frozen=True)
127
+ class Unique(Check):
128
+ """Passes when no other row has the same value; nulls pass.
129
+
130
+ Polars fails every copy of a duplicated value, while the SQL query from ``to_sql`` counts only
131
+ the extra copies, so the two report different ``failed_rows`` for the same data.
132
+ """
133
+
134
+ kind: ClassVar[str] = "unique"
135
+ row_level: ClassVar[bool] = False
136
+
137
+ def polars(self, col: str) -> Any:
138
+ import polars as pl
139
+
140
+ return ~pl.col(col).is_duplicated() | pl.col(col).is_null()
141
+
142
+
143
+ @register
144
+ @dataclass(frozen=True)
145
+ class Matches(Check):
146
+ """Passes when the value, as text, contains a match for the regular expression ``pattern``; nulls pass.
147
+
148
+ The pattern is not anchored (add ``^``/``$``), except where the SQL dialect anchors it: Snowflake's
149
+ ``REGEXP_LIKE`` and the ANSI fallback ``SIMILAR TO`` (which has its own syntax) match the whole value.
150
+ """
151
+
152
+ pattern: str = ""
153
+ kind: ClassVar[str] = "matches"
154
+
155
+ def __post_init__(self) -> None:
156
+ re.compile(self.pattern)
157
+
158
+ def polars(self, col: str) -> Any:
159
+ import polars as pl
160
+
161
+ return pl.col(col).cast(pl.String).str.contains(self.pattern) | pl.col(col).is_null()
162
+
163
+ def sql(self, col: str, dialect: str = "ansi") -> str:
164
+ c, p = _q(col), _lit(self.pattern)
165
+ if dialect == "postgres":
166
+ cond = f"{c} ~ {p}"
167
+ elif dialect == "duckdb":
168
+ cond = f"REGEXP_MATCHES({c}, {p})"
169
+ elif dialect in ("snowflake", "oracle", "mysql"):
170
+ cond = f"REGEXP_LIKE({c}, {p})"
171
+ elif dialect == "bigquery":
172
+ cond = f"REGEXP_CONTAINS({c}, {p})"
173
+ else:
174
+ cond = f"{c} SIMILAR TO {p}" # ANSI; patterns may need adapting
175
+ return f"({c} IS NULL OR {cond})"
176
+
177
+
178
+ @register
179
+ @dataclass(frozen=True)
180
+ class OneOf(Check):
181
+ """Passes when the value is one of ``values``; nulls pass."""
182
+
183
+ values: tuple[Any, ...] = ()
184
+ kind: ClassVar[str] = "one_of"
185
+
186
+ def __post_init__(self) -> None:
187
+ object.__setattr__(self, "values", tuple(self.values))
188
+
189
+ def to_dict(self) -> dict[str, Any]:
190
+ return {"check": self.kind, "values": list(self.values)}
191
+
192
+ def polars(self, col: str) -> Any:
193
+ import polars as pl
194
+
195
+ return pl.col(col).is_in(list(self.values)) | pl.col(col).is_null()
196
+
197
+ def sql(self, col: str, dialect: str = "ansi") -> str:
198
+ return f"({_q(col)} IS NULL OR {_q(col)} IN ({', '.join(_lit(v) for v in self.values)}))"
199
+
200
+
201
+ @register
202
+ @dataclass(frozen=True)
203
+ class Between(Check):
204
+ """Passes when ``min <= value <= max`` (either bound may be None); nulls pass."""
205
+
206
+ min: Any = None
207
+ max: Any = None
208
+ kind: ClassVar[str] = "between"
209
+
210
+ def polars(self, col: str) -> Any:
211
+ import polars as pl
212
+
213
+ e = pl.col(col)
214
+ cond = pl.lit(True)
215
+ if self.min is not None:
216
+ cond = cond & (e >= self.min)
217
+ if self.max is not None:
218
+ cond = cond & (e <= self.max)
219
+ return cond | e.is_null()
220
+
221
+ def sql(self, col: str, dialect: str = "ansi") -> str:
222
+ parts = [f"{_q(col)} >= {_lit(self.min)}" if self.min is not None else "",
223
+ f"{_q(col)} <= {_lit(self.max)}" if self.max is not None else ""]
224
+ return f"({_q(col)} IS NULL OR ({' AND '.join(p for p in parts if p) or 'TRUE'}))"
225
+
226
+
227
+ @register
228
+ @dataclass(frozen=True)
229
+ class Length(Check):
230
+ """Passes when the value's length in characters is within ``min`` and ``max`` (inclusive); nulls pass."""
231
+
232
+ min: int | None = None
233
+ max: int | None = None
234
+ kind: ClassVar[str] = "length"
235
+
236
+ def polars(self, col: str) -> Any:
237
+ import polars as pl
238
+
239
+ n = pl.col(col).cast(pl.String).str.len_chars()
240
+ cond = pl.lit(True)
241
+ if self.min is not None:
242
+ cond = cond & (n >= self.min)
243
+ if self.max is not None:
244
+ cond = cond & (n <= self.max)
245
+ return cond | pl.col(col).is_null()
246
+
247
+ def sql(self, col: str, dialect: str = "ansi") -> str:
248
+ n = f"CHAR_LENGTH({_q(col)})"
249
+ parts = [f"{n} >= {self.min}" if self.min is not None else "", f"{n} <= {self.max}" if self.max is not None else ""]
250
+ return f"({_q(col)} IS NULL OR ({' AND '.join(p for p in parts if p) or 'TRUE'}))"
251
+
252
+
253
+ @register
254
+ @dataclass(frozen=True)
255
+ class Sql(Check):
256
+ """Any boolean SQL expression; ``{column}`` is replaced by the quoted column name."""
257
+
258
+ expression: str = ""
259
+ kind: ClassVar[str] = "sql"
260
+
261
+ def polars(self, col: str) -> Any:
262
+ import polars as pl
263
+
264
+ return pl.sql_expr(self._filled(col))
265
+
266
+ def sql(self, col: str, dialect: str = "ansi") -> str:
267
+ return f"({self._filled(col)})"
268
+
269
+ def _filled(self, col: str) -> str:
270
+ # plain replacement: SQL is full of braces ("'^[A-Z]{2}$'") that str.format would trip over
271
+ return self.expression.replace("{column}", _q(col))
272
+
273
+
274
+ @dataclass(frozen=True)
275
+ class Unknown(Check):
276
+ """A stored check whose kind isn't registered in this process."""
277
+
278
+ kind: str = "" # type: ignore[misc]
279
+ params: dict[str, Any] = field(default_factory=dict)
280
+
281
+ def to_dict(self) -> dict[str, Any]:
282
+ return {"check": self.kind, **self.params}
283
+
284
+ def describe(self) -> str:
285
+ return f"{self.kind}(…)"
286
+
287
+
288
+ # Friendly constructors
289
+ def not_null() -> Check:
290
+ """A :class:`NotNull` check."""
291
+ return NotNull()
292
+
293
+
294
+ def unique() -> Check:
295
+ """A :class:`Unique` check."""
296
+ return Unique()
297
+
298
+
299
+ def matches(pattern: str) -> Check:
300
+ """A :class:`Matches` check; the pattern is compiled now, so a bad one fails here."""
301
+ return Matches(pattern)
302
+
303
+
304
+ def one_of(values: Sequence[Any]) -> Check:
305
+ """A :class:`OneOf` check."""
306
+ return OneOf(tuple(values))
307
+
308
+
309
+ def between(min: Any = None, max: Any = None) -> Check: # noqa: A002
310
+ """A :class:`Between` check."""
311
+ return Between(min, max)
312
+
313
+
314
+ def length(min: int | None = None, max: int | None = None) -> Check: # noqa: A002
315
+ """A :class:`Length` check."""
316
+ return Length(min, max)
317
+
318
+
319
+ def sql(expression: str) -> Check:
320
+ """A :class:`Sql` check: any boolean SQL, with ``{column}`` for the column; a NULL result fails."""
321
+ return Sql(expression)
322
+
323
+
324
+ def normalise(items: Sequence[Check | dict[str, Any]]) -> list[dict[str, Any]]:
325
+ """Checks as stored: a list of dicts with a ``check`` key."""
326
+ out = []
327
+ for c in items:
328
+ d = c.to_dict() if isinstance(c, Check) else dict(c)
329
+ if not isinstance(d.get("check"), str):
330
+ raise ValueError(f"A check needs a 'check' kind: {d!r}")
331
+ out.append(d)
332
+ return out
333
+
334
+
335
+ # ---------------------------------------------------------------------- running
336
+ @dataclass
337
+ class CheckResult:
338
+ """The outcome of one check on one field; ``error`` is set when it could not be evaluated."""
339
+
340
+ subject: str # field subject, e.g. field:shop.customers/email
341
+ check: dict[str, Any]
342
+ passed: bool
343
+ failed_rows: int
344
+ total_rows: int
345
+ origin: str | None = None # "type:email_address" when inherited from a semantic type
346
+ sample: list[Any] = field(default_factory=list) # a few failing values (omitted for confidential fields)
347
+ error: str | None = None
348
+ ts: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
349
+
350
+ def __str__(self) -> str:
351
+ mark = "PASS" if self.passed else ("ERROR" if self.error else "FAIL")
352
+ via = f" (from {self.origin})" if self.origin else ""
353
+ detail = self.error or f"{self.failed_rows}/{self.total_rows} rows fail"
354
+ return f"{mark:<5} {self.subject:<40} {Check.from_dict(self.check).describe():<38} {detail}{via}"
355
+
356
+ def to_dict(self) -> dict[str, Any]:
357
+ """The wire form, for results computed on one machine and recorded on another.
358
+
359
+ Failing sample values are data, so they are left out.
360
+ """
361
+ return {
362
+ "subject": self.subject, "check": self.check, "passed": self.passed,
363
+ "failed_rows": self.failed_rows, "total_rows": self.total_rows, "origin": self.origin,
364
+ "error": self.error, "ts": self.ts.isoformat(),
365
+ }
366
+
367
+ @classmethod
368
+ def from_dict(cls, d: dict[str, Any]) -> CheckResult:
369
+ """Rebuild a result from :meth:`to_dict`; without a timestamp it is stamped now."""
370
+ ts = d.get("ts")
371
+ return cls(
372
+ d["subject"], d["check"], bool(d["passed"]), int(d["failed_rows"]), int(d["total_rows"]),
373
+ d.get("origin"), [], d.get("error"),
374
+ datetime.fromisoformat(ts) if isinstance(ts, str) else ts or datetime.now(timezone.utc),
375
+ )
376
+
377
+
378
+ def effective_checks(gloss: Gloss, dataset: str) -> dict[str, list[tuple[dict[str, Any], str | None]]]:
379
+ """{field: [(check, origin), ...]} for a dataset, from accepted facts (types included)."""
380
+ from .model import Status
381
+
382
+ state = gloss.snapshot([Status.ACCEPTED], datasets=[dataset], relationships=False)
383
+ if dataset not in state.datasets:
384
+ raise KeyError(f"No accepted facts for dataset {dataset!r}")
385
+ out: dict[str, list[tuple[dict[str, Any], str | None]]] = {}
386
+ for fname, f in state.datasets[dataset].fields.items():
387
+ items = [(c, f.check_origins.get(i)) for i, c in enumerate(f.attrs.get("checks") or [])]
388
+ if items:
389
+ out[fname] = items
390
+ return out
391
+
392
+
393
+ @dataclass
394
+ class CheckPlan:
395
+ """Every effective check of a dataset as one lazy query.
396
+
397
+ ``frame`` yields a single row: ``__total__`` and one failure count per runnable check. Nothing
398
+ is collected here. Checks that could not be planned (column missing, no Polars form) are in
399
+ ``errors`` already.
400
+ """
401
+
402
+ frame: Any # pl.LazyFrame
403
+ items: list[tuple[str, dict[str, Any], str | None, str]] # (subject, check, origin, result column)
404
+ errors: list[CheckResult]
405
+ conditions: dict[str, Any] = field(default_factory=dict) # result column -> pass condition
406
+ source: Any = None # the LazyFrame the plan reads
407
+
408
+ def results(self, row: Any) -> list[CheckResult]:
409
+ """Turn the collected one-row result (a mapping or a one-row DataFrame) into results."""
410
+ if hasattr(row, "row"):
411
+ row = row.row(0, named=True)
412
+ total = int(row["__total__"])
413
+ out = [CheckResult(subj, chk, int(row[col]) == 0, int(row[col]), total, origin)
414
+ for subj, chk, origin, col in self.items]
415
+ return out + [replace(e, total_rows=total) for e in self.errors]
416
+
417
+ def failing(self, column: str) -> Any:
418
+ """A LazyFrame of the rows failing one check, for an optional second pass that samples them."""
419
+ return self.source.filter(~self.conditions[column].fill_null(False))
420
+
421
+
422
+ def polars_plan(gloss: Gloss, dataset: str, frame: Any) -> CheckPlan:
423
+ """Plan every effective check of ``dataset`` over a Polars LazyFrame (or DataFrame), in one pass."""
424
+ import polars as pl
425
+
426
+ from .ids import SubjectId
427
+
428
+ lf = frame.lazy()
429
+ columns = set(lf.collect_schema().names())
430
+ exprs = [pl.len().alias("__total__")]
431
+ plan = CheckPlan(None, [], [], source=lf)
432
+ for fname, items in effective_checks(gloss, dataset).items():
433
+ subj = str(SubjectId.for_field(dataset, fname))
434
+ for chk, origin in items:
435
+ if fname not in columns:
436
+ plan.errors.append(CheckResult(subj, chk, False, 0, 0, origin, error=f"column {fname!r} not in data"))
437
+ continue
438
+ try:
439
+ passes = Check.from_dict(chk).polars(fname)
440
+ except (NotImplementedError, ValueError, TypeError, pl.exceptions.PolarsError) as exc:
441
+ plan.errors.append(CheckResult(subj, chk, False, 0, 0, origin, error=str(exc)))
442
+ continue
443
+ col = f"c{len(plan.items)}"
444
+ plan.conditions[col] = passes
445
+ exprs.append((~passes.fill_null(False)).sum().alias(col))
446
+ plan.items.append((subj, chk, origin, col))
447
+ plan.frame = lf.select(exprs)
448
+ return plan
449
+
450
+
451
+ def run_polars(gloss: Gloss, dataset: str, df: Any, *, sample_size: int = 5) -> list[CheckResult]:
452
+ """Evaluate every effective check of ``dataset`` on a Polars DataFrame.
453
+
454
+ One pass counts all failures; a few failing values are then sampled per failed check,
455
+ except for fields above ``internal`` confidentiality.
456
+ """
457
+ import polars as pl
458
+
459
+ from .model import Confidentiality
460
+ from .visibility import levels
461
+
462
+ plan = polars_plan(gloss, dataset, df)
463
+ try:
464
+ results = plan.results(plan.frame.collect())
465
+ except pl.exceptions.PolarsError:
466
+ # one check cannot be evaluated on this data: run them one by one so the rest still report
467
+ total = df.lazy().select(pl.len()).collect().item()
468
+ results = []
469
+ for subj, chk, origin, col in plan.items:
470
+ try:
471
+ n = plan.failing(col).select(pl.len()).collect().item()
472
+ results.append(CheckResult(subj, chk, n == 0, n, total, origin))
473
+ except pl.exceptions.PolarsError as exc:
474
+ results.append(CheckResult(subj, chk, False, 0, total, origin, error=str(exc)))
475
+ results += [replace(e, total_rows=total) for e in plan.errors]
476
+ if sample_size:
477
+ columns = {subj: col for subj, _chk, _origin, col in plan.items}
478
+ hidden = {s for s, lv in levels(gloss.store, columns).items() if lv > Confidentiality.INTERNAL}
479
+ by_item = {(subj, id(chk)): col for subj, chk, _origin, col in plan.items}
480
+ for r in results:
481
+ col = by_item.get((r.subject, id(r.check)))
482
+ if col and not r.passed and not r.error and r.subject not in hidden:
483
+ fname = r.subject.rsplit("/", 1)[-1]
484
+ r.sample = plan.failing(col).select(fname).head(sample_size).collect().get_column(fname).to_list()
485
+ order = {subj: i for i, subj in enumerate(dict.fromkeys(
486
+ str(s) for s in [x[0] for x in plan.items] + [e.subject for e in plan.errors]))}
487
+ return sorted(results, key=lambda r: order.get(r.subject, 0))
488
+
489
+
490
+ def to_sql(gloss: Gloss, dataset: str, *, dialect: str = "ansi", table: str | None = None) -> list[tuple[str, dict[str, Any], str]]:
491
+ """[(field subject, check, query)]: each query returns ``failed_rows`` and ``total_rows``."""
492
+ from .ids import SubjectId
493
+
494
+ src = table or gloss.current(SubjectId.for_dataset(dataset)).get("source") or dataset
495
+ out = []
496
+ for fname, items in effective_checks(gloss, dataset).items():
497
+ subj = str(SubjectId.for_field(dataset, fname))
498
+ for chk, _origin in items:
499
+ c = Check.from_dict(chk)
500
+ if not c.row_level:
501
+ q = f"SELECT COUNT({_q(fname)}) - COUNT(DISTINCT {_q(fname)}) AS failed_rows, COUNT(*) AS total_rows FROM {src}"
502
+ else:
503
+ try:
504
+ cond = c.sql(fname, dialect)
505
+ except NotImplementedError:
506
+ continue
507
+ q = (
508
+ f"SELECT SUM(CASE WHEN {cond} THEN 0 ELSE 1 END) AS failed_rows, "
509
+ f"COUNT(*) AS total_rows FROM {src}"
510
+ )
511
+ out.append((subj, chk, q))
512
+ return out