pipeverify 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.
- pipeverify/__init__.py +8 -0
- pipeverify/checks.py +285 -0
- pipeverify/cli.py +159 -0
- pipeverify/core.py +112 -0
- pipeverify/explain.py +70 -0
- pipeverify/report.py +81 -0
- pipeverify/sources.py +148 -0
- pipeverify-0.1.0.dist-info/METADATA +234 -0
- pipeverify-0.1.0.dist-info/RECORD +13 -0
- pipeverify-0.1.0.dist-info/WHEEL +4 -0
- pipeverify-0.1.0.dist-info/entry_points.txt +2 -0
- pipeverify-0.1.0.dist-info/licenses/LICENSE +202 -0
- pipeverify-0.1.0.dist-info/licenses/NOTICE +2 -0
pipeverify/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""pipeverify: check that a pipeline change left the data right, not just the job green."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
|
|
5
|
+
from .checks import Finding, Thresholds # noqa: E402
|
|
6
|
+
from .core import RunResult, TableResult, run_config, verify # noqa: E402
|
|
7
|
+
|
|
8
|
+
__all__ = ["verify", "run_config", "Thresholds", "Finding", "TableResult", "RunResult", "__version__"]
|
pipeverify/checks.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
"""Checks that compare a table before and after a change.
|
|
2
|
+
|
|
3
|
+
Each check looks for a kind of silent harm: the job succeeds and tests stay green,
|
|
4
|
+
but the data is no longer right. Checks return Findings; the policy turns them
|
|
5
|
+
into a verdict.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import asdict, dataclass, field
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
import duckdb
|
|
13
|
+
|
|
14
|
+
PASS, INFO, REVIEW, BLOCK = "pass", "info", "review", "block"
|
|
15
|
+
RANK = {PASS: 0, INFO: 0, REVIEW: 1, BLOCK: 2}
|
|
16
|
+
|
|
17
|
+
NUMERIC_TYPES = ("TINYINT", "SMALLINT", "INTEGER", "BIGINT", "HUGEINT", "UTINYINT", "USMALLINT",
|
|
18
|
+
"UINTEGER", "UBIGINT", "FLOAT", "REAL", "DOUBLE", "DECIMAL")
|
|
19
|
+
TEXT_TYPES = ("VARCHAR", "TEXT", "STRING", "CHAR", "ENUM")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class Thresholds:
|
|
24
|
+
"""When a difference becomes worth a human look (review) or should stop the change (block).
|
|
25
|
+
|
|
26
|
+
Percentages are shares of rows, from 0 to 100.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
row_change_review_pct: float = 1.0
|
|
30
|
+
row_change_block_pct: float = 10.0
|
|
31
|
+
missing_keys_review_pct: float = 0.0 # any lost key gets a review
|
|
32
|
+
missing_keys_block_pct: float = 5.0
|
|
33
|
+
null_rate_review_pts: float = 1.0
|
|
34
|
+
null_rate_block_pts: float = 10.0
|
|
35
|
+
changed_values_review_pct: float = 0.0 # any unexpected changed value gets a review
|
|
36
|
+
changed_values_block_pct: float = 10.0
|
|
37
|
+
sum_shift_review_pct: float = 0.5
|
|
38
|
+
sum_shift_block_pct: float = 5.0
|
|
39
|
+
category_max_distinct: int = 50 # treat text columns with few values as categories
|
|
40
|
+
float_tolerance: float = 1e-9
|
|
41
|
+
|
|
42
|
+
@classmethod
|
|
43
|
+
def from_dict(cls, data: dict[str, Any] | None) -> "Thresholds":
|
|
44
|
+
if not data:
|
|
45
|
+
return cls()
|
|
46
|
+
known = {f for f in cls.__dataclass_fields__}
|
|
47
|
+
unknown = set(data) - known
|
|
48
|
+
if unknown:
|
|
49
|
+
raise ValueError(f"Unknown threshold(s): {', '.join(sorted(unknown))}")
|
|
50
|
+
return cls(**data)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass
|
|
54
|
+
class Finding:
|
|
55
|
+
check: str
|
|
56
|
+
severity: str
|
|
57
|
+
message: str
|
|
58
|
+
column: str | None = None
|
|
59
|
+
metrics: dict[str, Any] = field(default_factory=dict)
|
|
60
|
+
|
|
61
|
+
def to_dict(self) -> dict[str, Any]:
|
|
62
|
+
return asdict(self)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def q(name: str) -> str:
|
|
66
|
+
return '"' + name.replace('"', '""') + '"'
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _grade(value: float, review: float, block: float) -> str:
|
|
70
|
+
if value >= block and value > 0:
|
|
71
|
+
return BLOCK
|
|
72
|
+
if value > review or (review == 0 and value > 0):
|
|
73
|
+
return REVIEW
|
|
74
|
+
return PASS
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _schema(con: duckdb.DuckDBPyConnection, table: str) -> dict[str, str]:
|
|
78
|
+
rows = con.execute(f"DESCRIBE {q(table)}").fetchall()
|
|
79
|
+
return {r[0]: str(r[1]).upper() for r in rows}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _is_numeric(dtype: str) -> bool:
|
|
83
|
+
return dtype.startswith(NUMERIC_TYPES)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _is_text(dtype: str) -> bool:
|
|
87
|
+
return dtype.startswith(TEXT_TYPES)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def run_checks(
|
|
91
|
+
con: duckdb.DuckDBPyConnection,
|
|
92
|
+
before: str,
|
|
93
|
+
after: str,
|
|
94
|
+
key: list[str] | None = None,
|
|
95
|
+
expect_change: list[str] | None = None,
|
|
96
|
+
ignore: list[str] | None = None,
|
|
97
|
+
expect_row_change: bool = False,
|
|
98
|
+
thresholds: Thresholds | None = None,
|
|
99
|
+
) -> tuple[list[Finding], dict[str, Any]]:
|
|
100
|
+
"""Run every check on two tables already loaded in `con`."""
|
|
101
|
+
t = thresholds or Thresholds()
|
|
102
|
+
key = list(key or [])
|
|
103
|
+
expect = set(expect_change or [])
|
|
104
|
+
ignore = set(ignore or [])
|
|
105
|
+
findings: list[Finding] = []
|
|
106
|
+
|
|
107
|
+
sb, sa = _schema(con, before), _schema(con, after)
|
|
108
|
+
for k in key:
|
|
109
|
+
if k not in sb or k not in sa:
|
|
110
|
+
raise ValueError(f"Key column '{k}' is missing from the before or after table")
|
|
111
|
+
|
|
112
|
+
n_before = con.execute(f"SELECT count(*) FROM {q(before)}").fetchone()[0]
|
|
113
|
+
n_after = con.execute(f"SELECT count(*) FROM {q(after)}").fetchone()[0]
|
|
114
|
+
stats: dict[str, Any] = {"rows_before": n_before, "rows_after": n_after,
|
|
115
|
+
"columns_before": len(sb), "columns_after": len(sa)}
|
|
116
|
+
|
|
117
|
+
# 1. schema
|
|
118
|
+
removed = [c for c in sb if c not in sa and c not in ignore]
|
|
119
|
+
added = [c for c in sa if c not in sb and c not in ignore]
|
|
120
|
+
retyped = [c for c in sb if c in sa and c not in ignore and sb[c] != sa[c]]
|
|
121
|
+
for c in removed:
|
|
122
|
+
findings.append(Finding("schema", BLOCK, f"Column '{c}' was removed", c, {"type": sb[c]}))
|
|
123
|
+
for c in added:
|
|
124
|
+
findings.append(Finding("schema", INFO, f"Column '{c}' was added", c, {"type": sa[c]}))
|
|
125
|
+
for c in retyped:
|
|
126
|
+
findings.append(Finding("schema", REVIEW, f"Column '{c}' changed type {sb[c]} -> {sa[c]}",
|
|
127
|
+
c, {"before": sb[c], "after": sa[c]}))
|
|
128
|
+
|
|
129
|
+
# 2. row count
|
|
130
|
+
if n_before == 0 and n_after == 0:
|
|
131
|
+
findings.append(Finding("row_count", INFO, "Both tables are empty"))
|
|
132
|
+
else:
|
|
133
|
+
base = max(n_before, 1)
|
|
134
|
+
pct = abs(n_after - n_before) / base * 100
|
|
135
|
+
sev = INFO if expect_row_change else _grade(pct, t.row_change_review_pct, t.row_change_block_pct)
|
|
136
|
+
if n_before > 0 and n_after == 0:
|
|
137
|
+
sev = BLOCK
|
|
138
|
+
if n_after != n_before:
|
|
139
|
+
direction = "lost" if n_after < n_before else "gained"
|
|
140
|
+
findings.append(Finding("row_count", sev,
|
|
141
|
+
f"Table {direction} {abs(n_after - n_before):,} rows ({pct:.2f}%)",
|
|
142
|
+
None, {"before": n_before, "after": n_after, "pct": round(pct, 4)}))
|
|
143
|
+
|
|
144
|
+
common = [c for c in sb if c in sa and c not in ignore]
|
|
145
|
+
|
|
146
|
+
# 3. keys
|
|
147
|
+
unique_keys_join = None
|
|
148
|
+
if key:
|
|
149
|
+
kcols = ", ".join(q(k) for k in key)
|
|
150
|
+
dup_before = con.execute(
|
|
151
|
+
f"SELECT count(*) FROM (SELECT {kcols} FROM {q(before)} GROUP BY ALL HAVING count(*) > 1)").fetchone()[0]
|
|
152
|
+
dup_after = con.execute(
|
|
153
|
+
f"SELECT count(*) FROM (SELECT {kcols} FROM {q(after)} GROUP BY ALL HAVING count(*) > 1)").fetchone()[0]
|
|
154
|
+
stats.update(duplicate_keys_before=dup_before, duplicate_keys_after=dup_after)
|
|
155
|
+
if dup_after > dup_before:
|
|
156
|
+
findings.append(Finding("duplicate_keys", BLOCK,
|
|
157
|
+
f"{dup_after - dup_before:,} key value(s) now appear more than once",
|
|
158
|
+
None, {"before": dup_before, "after": dup_after}))
|
|
159
|
+
elif dup_after < dup_before:
|
|
160
|
+
findings.append(Finding("duplicate_keys", INFO,
|
|
161
|
+
f"Duplicate keys went down from {dup_before:,} to {dup_after:,}",
|
|
162
|
+
None, {"before": dup_before, "after": dup_after}))
|
|
163
|
+
on = " AND ".join(f"b.{q(k)} IS NOT DISTINCT FROM a.{q(k)}" for k in key)
|
|
164
|
+
missing = con.execute(
|
|
165
|
+
f"SELECT count(*) FROM (SELECT DISTINCT {kcols} FROM {q(before)}) b "
|
|
166
|
+
f"WHERE NOT EXISTS (SELECT 1 FROM {q(after)} a WHERE {on})").fetchone()[0]
|
|
167
|
+
new = con.execute(
|
|
168
|
+
f"SELECT count(*) FROM (SELECT DISTINCT {kcols} FROM {q(after)}) a "
|
|
169
|
+
f"WHERE NOT EXISTS (SELECT 1 FROM {q(before)} b WHERE {on})").fetchone()[0]
|
|
170
|
+
distinct_before = con.execute(f"SELECT count(*) FROM (SELECT DISTINCT {kcols} FROM {q(before)})").fetchone()[0]
|
|
171
|
+
stats.update(missing_keys=missing, new_keys=new)
|
|
172
|
+
if missing:
|
|
173
|
+
pct = missing / max(distinct_before, 1) * 100
|
|
174
|
+
sev = INFO if expect_row_change else _grade(pct, t.missing_keys_review_pct, t.missing_keys_block_pct)
|
|
175
|
+
findings.append(Finding("missing_keys", sev,
|
|
176
|
+
f"{missing:,} key(s) present before are gone after ({pct:.2f}%)",
|
|
177
|
+
None, {"count": missing, "pct": round(pct, 4)}))
|
|
178
|
+
if new:
|
|
179
|
+
findings.append(Finding("new_keys", INFO if expect_row_change else REVIEW,
|
|
180
|
+
f"{new:,} new key(s) appeared", None, {"count": new}))
|
|
181
|
+
# rows whose key is unique on both sides, used for value comparison
|
|
182
|
+
con.execute(f"CREATE OR REPLACE TEMP VIEW _pv_ub AS SELECT * FROM {q(before)} "
|
|
183
|
+
f"QUALIFY count(*) OVER (PARTITION BY {kcols}) = 1")
|
|
184
|
+
con.execute(f"CREATE OR REPLACE TEMP VIEW _pv_ua AS SELECT * FROM {q(after)} "
|
|
185
|
+
f"QUALIFY count(*) OVER (PARTITION BY {kcols}) = 1")
|
|
186
|
+
unique_keys_join = " AND ".join(f"b.{q(k)} IS NOT DISTINCT FROM a.{q(k)}" for k in key)
|
|
187
|
+
|
|
188
|
+
# 4. null rates
|
|
189
|
+
for c in common:
|
|
190
|
+
nb, na = con.execute(
|
|
191
|
+
f"SELECT (SELECT avg(CASE WHEN {q(c)} IS NULL THEN 1.0 ELSE 0 END) FROM {q(before)}), "
|
|
192
|
+
f"(SELECT avg(CASE WHEN {q(c)} IS NULL THEN 1.0 ELSE 0 END) FROM {q(after)})").fetchone()
|
|
193
|
+
nb, na = float(nb or 0) * 100, float(na or 0) * 100
|
|
194
|
+
rise = na - nb
|
|
195
|
+
if rise > 0:
|
|
196
|
+
sev = _grade(rise, t.null_rate_review_pts, t.null_rate_block_pts)
|
|
197
|
+
if c in expect and sev != PASS:
|
|
198
|
+
sev = INFO
|
|
199
|
+
if sev != PASS:
|
|
200
|
+
findings.append(Finding("null_rate", sev,
|
|
201
|
+
f"Nulls in '{c}' rose from {nb:.2f}% to {na:.2f}%",
|
|
202
|
+
c, {"before_pct": round(nb, 4), "after_pct": round(na, 4)}))
|
|
203
|
+
|
|
204
|
+
# 5. changed values on matched keys
|
|
205
|
+
if unique_keys_join is not None:
|
|
206
|
+
matched = con.execute(f"SELECT count(*) FROM _pv_ub b JOIN _pv_ua a ON {unique_keys_join}").fetchone()[0]
|
|
207
|
+
stats["matched_rows"] = matched
|
|
208
|
+
for c in common:
|
|
209
|
+
if c in key:
|
|
210
|
+
continue
|
|
211
|
+
if _is_numeric(sb[c]) and _is_numeric(sa[c]):
|
|
212
|
+
diff = (f"(b.{q(c)} IS NULL) <> (a.{q(c)} IS NULL) OR "
|
|
213
|
+
f"abs(CAST(a.{q(c)} AS DOUBLE) - CAST(b.{q(c)} AS DOUBLE)) > "
|
|
214
|
+
f"{t.float_tolerance} * greatest(1.0, abs(CAST(b.{q(c)} AS DOUBLE)))")
|
|
215
|
+
else:
|
|
216
|
+
diff = f"CAST(b.{q(c)} AS VARCHAR) IS DISTINCT FROM CAST(a.{q(c)} AS VARCHAR)"
|
|
217
|
+
changed = con.execute(
|
|
218
|
+
f"SELECT count(*) FROM _pv_ub b JOIN _pv_ua a ON {unique_keys_join} WHERE {diff}").fetchone()[0]
|
|
219
|
+
if not changed:
|
|
220
|
+
continue
|
|
221
|
+
pct = changed / max(matched, 1) * 100
|
|
222
|
+
if c in expect:
|
|
223
|
+
sev = INFO
|
|
224
|
+
else:
|
|
225
|
+
sev = _grade(pct, t.changed_values_review_pct, t.changed_values_block_pct)
|
|
226
|
+
sample = con.execute(
|
|
227
|
+
f"SELECT {', '.join('b.' + q(k) for k in key)}, b.{q(c)} AS before_value, a.{q(c)} AS after_value "
|
|
228
|
+
f"FROM _pv_ub b JOIN _pv_ua a ON {unique_keys_join} WHERE {diff} LIMIT 3").fetchall()
|
|
229
|
+
findings.append(Finding(
|
|
230
|
+
"changed_values", sev,
|
|
231
|
+
f"{changed:,} row(s) changed '{c}' ({pct:.2f}% of matched rows)"
|
|
232
|
+
+ ("" if c not in expect else ", as expected"),
|
|
233
|
+
c, {"count": changed, "pct": round(pct, 4),
|
|
234
|
+
"examples": [[str(v) for v in row] for row in sample]}))
|
|
235
|
+
|
|
236
|
+
# 6. totals of numeric columns
|
|
237
|
+
for c in common:
|
|
238
|
+
if c in key or not (_is_numeric(sb[c]) and _is_numeric(sa[c])):
|
|
239
|
+
continue
|
|
240
|
+
tb, ta = con.execute(
|
|
241
|
+
f"SELECT (SELECT sum(CAST({q(c)} AS DOUBLE)) FROM {q(before)}), "
|
|
242
|
+
f"(SELECT sum(CAST({q(c)} AS DOUBLE)) FROM {q(after)})").fetchone()
|
|
243
|
+
if tb is None and ta is None:
|
|
244
|
+
continue
|
|
245
|
+
tb, ta = float(tb or 0), float(ta or 0)
|
|
246
|
+
if tb == ta:
|
|
247
|
+
continue
|
|
248
|
+
pct = abs(ta - tb) / max(abs(tb), 1e-12) * 100
|
|
249
|
+
if c in expect or expect_row_change:
|
|
250
|
+
sev = INFO
|
|
251
|
+
else:
|
|
252
|
+
sev = _grade(pct, t.sum_shift_review_pct, t.sum_shift_block_pct)
|
|
253
|
+
if sev != PASS:
|
|
254
|
+
findings.append(Finding("total_shift", sev,
|
|
255
|
+
f"Total of '{c}' moved {pct:.2f}% ({tb:,.2f} -> {ta:,.2f})",
|
|
256
|
+
c, {"before": tb, "after": ta, "pct": round(pct, 4)}))
|
|
257
|
+
|
|
258
|
+
# 7. category values
|
|
259
|
+
for c in common:
|
|
260
|
+
if c in key or not (_is_text(sb[c]) and _is_text(sa[c])):
|
|
261
|
+
continue
|
|
262
|
+
d = con.execute(f"SELECT count(DISTINCT {q(c)}) FROM {q(before)}").fetchone()[0]
|
|
263
|
+
if d == 0 or d > t.category_max_distinct:
|
|
264
|
+
continue
|
|
265
|
+
new_vals = [r[0] for r in con.execute(
|
|
266
|
+
f"SELECT DISTINCT {q(c)} FROM {q(after)} WHERE {q(c)} IS NOT NULL EXCEPT "
|
|
267
|
+
f"SELECT DISTINCT {q(c)} FROM {q(before)} ORDER BY 1 LIMIT 10").fetchall()]
|
|
268
|
+
gone_vals = [r[0] for r in con.execute(
|
|
269
|
+
f"SELECT DISTINCT {q(c)} FROM {q(before)} WHERE {q(c)} IS NOT NULL EXCEPT "
|
|
270
|
+
f"SELECT DISTINCT {q(c)} FROM {q(after)} ORDER BY 1 LIMIT 10").fetchall()]
|
|
271
|
+
if new_vals:
|
|
272
|
+
findings.append(Finding("category_values", INFO if c in expect else REVIEW,
|
|
273
|
+
f"'{c}' has new value(s): {', '.join(map(str, new_vals))}",
|
|
274
|
+
c, {"new": new_vals}))
|
|
275
|
+
if gone_vals:
|
|
276
|
+
findings.append(Finding("category_values", INFO,
|
|
277
|
+
f"'{c}' no longer has value(s): {', '.join(map(str, gone_vals))}",
|
|
278
|
+
c, {"gone": gone_vals}))
|
|
279
|
+
|
|
280
|
+
return findings, stats
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def verdict(findings: list[Finding]) -> str:
|
|
284
|
+
worst = max((RANK[f.severity] for f in findings), default=0)
|
|
285
|
+
return {0: PASS, 1: REVIEW, 2: BLOCK}[worst]
|
pipeverify/cli.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""Command line interface: pipeverify compare | run | init."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
|
|
9
|
+
from . import __version__
|
|
10
|
+
from .checks import RANK
|
|
11
|
+
from .core import RunResult, run_config, verify
|
|
12
|
+
from .report import to_json, to_markdown, to_text
|
|
13
|
+
|
|
14
|
+
SAMPLE_CONFIG = """\
|
|
15
|
+
# pipeverify config: one entry per table you want to check after a change.
|
|
16
|
+
# before/after can be a file (csv, parquet, json), duckdb:<file.db>:<table>,
|
|
17
|
+
# or a mapping such as {url: postgresql://..., table: schema.table}.
|
|
18
|
+
thresholds:
|
|
19
|
+
row_change_block_pct: 10
|
|
20
|
+
tables:
|
|
21
|
+
- name: gold.daily_sales
|
|
22
|
+
before: snapshots/before/daily_sales.parquet
|
|
23
|
+
after: snapshots/after/daily_sales.parquet
|
|
24
|
+
key: [store_id, sale_date]
|
|
25
|
+
expect_change: [] # columns this change is meant to modify
|
|
26
|
+
ignore: [loaded_at] # columns that always change, such as load timestamps
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _emit(result: RunResult, fmt: str, output: str | None, summary: str | None, show_info: bool,
|
|
31
|
+
json_out: str | None = None, markdown_out: str | None = None) -> None:
|
|
32
|
+
for path, render in ((json_out, to_json), (markdown_out, to_markdown)):
|
|
33
|
+
if path:
|
|
34
|
+
with open(path, "w", encoding="utf-8") as fh:
|
|
35
|
+
body = render(result)
|
|
36
|
+
fh.write(body if body.endswith("\n") else body + "\n")
|
|
37
|
+
text = {"text": lambda: to_text(result, show_info), "markdown": lambda: to_markdown(result),
|
|
38
|
+
"json": lambda: to_json(result)}[fmt]()
|
|
39
|
+
if output:
|
|
40
|
+
with open(output, "w", encoding="utf-8") as fh:
|
|
41
|
+
fh.write(text if text.endswith("\n") else text + "\n")
|
|
42
|
+
if fmt != "text":
|
|
43
|
+
click.echo(to_text(result, show_info))
|
|
44
|
+
else:
|
|
45
|
+
click.echo(text)
|
|
46
|
+
if summary:
|
|
47
|
+
with open(summary, "a", encoding="utf-8") as fh:
|
|
48
|
+
fh.write(to_markdown(result))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _maybe_explain(result: RunResult, explain: bool) -> None:
|
|
52
|
+
if not explain:
|
|
53
|
+
return
|
|
54
|
+
from .explain import ExplainError, explain as do_explain
|
|
55
|
+
try:
|
|
56
|
+
result.explanation = do_explain(result)
|
|
57
|
+
except ExplainError as exc:
|
|
58
|
+
click.echo(f"note: explanation skipped: {exc}", err=True)
|
|
59
|
+
except Exception as exc: # network or provider errors must not hide the verdict
|
|
60
|
+
click.echo(f"note: explanation failed: {exc}", err=True)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _exit(result: RunResult, fail_on: str) -> None:
|
|
64
|
+
if fail_on == "never":
|
|
65
|
+
sys.exit(0)
|
|
66
|
+
threshold = RANK[fail_on]
|
|
67
|
+
sys.exit(1 if RANK[result.verdict] >= threshold else 0)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
output_options = [
|
|
71
|
+
click.option("--format", "fmt", type=click.Choice(["text", "markdown", "json"]), default="text",
|
|
72
|
+
show_default=True, help="Report format."),
|
|
73
|
+
click.option("--output", "-o", type=click.Path(dir_okay=False), help="Write the report to a file."),
|
|
74
|
+
click.option("--summary", type=click.Path(dir_okay=False), envvar="GITHUB_STEP_SUMMARY",
|
|
75
|
+
help="Append a Markdown report here (set automatically in GitHub Actions)."),
|
|
76
|
+
click.option("--fail-on", type=click.Choice(["review", "block", "never"]), default="block",
|
|
77
|
+
show_default=True, help="Exit with code 1 at this verdict or worse."),
|
|
78
|
+
click.option("--explain", is_flag=True, help="Add a plain-English explanation from an LLM (needs an API key)."),
|
|
79
|
+
click.option("--show-info", is_flag=True, help="Also print informational findings."),
|
|
80
|
+
click.option("--json-out", type=click.Path(dir_okay=False), help="Also write a JSON report here."),
|
|
81
|
+
click.option("--markdown-out", type=click.Path(dir_okay=False), help="Also write a Markdown report here."),
|
|
82
|
+
]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def with_output_options(fn):
|
|
86
|
+
for opt in reversed(output_options):
|
|
87
|
+
fn = opt(fn)
|
|
88
|
+
return fn
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@click.group()
|
|
92
|
+
@click.version_option(__version__, prog_name="pipeverify")
|
|
93
|
+
def main() -> None:
|
|
94
|
+
"""Verify that a pipeline change left the data right, not just the job green."""
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@main.command()
|
|
98
|
+
@click.argument("before")
|
|
99
|
+
@click.argument("after")
|
|
100
|
+
@click.option("--key", "-k", help="Comma-separated key column(s) that identify a row.")
|
|
101
|
+
@click.option("--expect-change", "-e", multiple=True, help="Column this change is meant to modify. Repeatable.")
|
|
102
|
+
@click.option("--ignore", "-i", multiple=True, help="Column to skip, such as a load timestamp. Repeatable.")
|
|
103
|
+
@click.option("--expect-row-change", is_flag=True, help="Rows are expected to be added or removed.")
|
|
104
|
+
@click.option("--name", default=None, help="Name to show for the table.")
|
|
105
|
+
@with_output_options
|
|
106
|
+
def compare(before, after, key, expect_change, ignore, expect_row_change, name,
|
|
107
|
+
fmt, output, summary, fail_on, explain, show_info, json_out, markdown_out):
|
|
108
|
+
"""Compare one table BEFORE and AFTER a change.
|
|
109
|
+
|
|
110
|
+
\b
|
|
111
|
+
Examples:
|
|
112
|
+
pipeverify compare before.parquet after.parquet --key order_id
|
|
113
|
+
pipeverify compare duckdb:prod.db:gold.sales duckdb:dev.db:gold.sales -k id
|
|
114
|
+
"""
|
|
115
|
+
import time
|
|
116
|
+
start = time.perf_counter()
|
|
117
|
+
try:
|
|
118
|
+
res = verify(before, after, name=name or os.path.basename(str(after)), key=key,
|
|
119
|
+
expect_change=list(expect_change), ignore=list(ignore),
|
|
120
|
+
expect_row_change=expect_row_change)
|
|
121
|
+
except Exception as exc:
|
|
122
|
+
raise click.ClickException(str(exc))
|
|
123
|
+
result = RunResult(tables=[res], seconds=time.perf_counter() - start)
|
|
124
|
+
_maybe_explain(result, explain)
|
|
125
|
+
_emit(result, fmt, output, summary, show_info, json_out, markdown_out)
|
|
126
|
+
_exit(result, fail_on)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
@main.command()
|
|
130
|
+
@click.option("--config", "-c", default="pipeverify.yml", show_default=True,
|
|
131
|
+
type=click.Path(exists=True, dir_okay=False), help="Config file listing the tables.")
|
|
132
|
+
@click.option("--table", "-t", multiple=True, help="Only check these table names. Repeatable.")
|
|
133
|
+
@with_output_options
|
|
134
|
+
def run(config, table, fmt, output, summary, fail_on, explain, show_info, json_out, markdown_out):
|
|
135
|
+
"""Check every table listed in a config file."""
|
|
136
|
+
try:
|
|
137
|
+
result = run_config(config, only=list(table) or None)
|
|
138
|
+
except Exception as exc:
|
|
139
|
+
raise click.ClickException(str(exc))
|
|
140
|
+
if not result.tables:
|
|
141
|
+
raise click.ClickException("No tables matched")
|
|
142
|
+
_maybe_explain(result, explain)
|
|
143
|
+
_emit(result, fmt, output, summary, show_info, json_out, markdown_out)
|
|
144
|
+
_exit(result, fail_on)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
@main.command()
|
|
148
|
+
@click.option("--path", default="pipeverify.yml", show_default=True)
|
|
149
|
+
def init(path):
|
|
150
|
+
"""Write a starter config file."""
|
|
151
|
+
if os.path.exists(path):
|
|
152
|
+
raise click.ClickException(f"{path} already exists")
|
|
153
|
+
with open(path, "w", encoding="utf-8") as fh:
|
|
154
|
+
fh.write(SAMPLE_CONFIG)
|
|
155
|
+
click.echo(f"Wrote {path}. Edit the table entries, then run: pipeverify run")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
if __name__ == "__main__": # pragma: no cover
|
|
159
|
+
main()
|
pipeverify/core.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Public API: verify one table or a whole config of tables."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
import time
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import duckdb
|
|
10
|
+
import yaml
|
|
11
|
+
|
|
12
|
+
from .checks import BLOCK, PASS, RANK, REVIEW, Finding, Thresholds, run_checks, verdict
|
|
13
|
+
from .sources import load, parse_source
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class TableResult:
|
|
18
|
+
name: str
|
|
19
|
+
verdict: str
|
|
20
|
+
findings: list[Finding]
|
|
21
|
+
stats: dict[str, Any]
|
|
22
|
+
before: str
|
|
23
|
+
after: str
|
|
24
|
+
error: str | None = None
|
|
25
|
+
|
|
26
|
+
def to_dict(self) -> dict[str, Any]:
|
|
27
|
+
return {"name": self.name, "verdict": self.verdict, "before": self.before, "after": self.after,
|
|
28
|
+
"stats": self.stats, "error": self.error,
|
|
29
|
+
"findings": [f.to_dict() for f in self.findings]}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class RunResult:
|
|
34
|
+
tables: list[TableResult] = field(default_factory=list)
|
|
35
|
+
seconds: float = 0.0
|
|
36
|
+
explanation: str | None = None
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def verdict(self) -> str:
|
|
40
|
+
worst = max((RANK[t.verdict] for t in self.tables), default=0)
|
|
41
|
+
return {0: PASS, 1: REVIEW, 2: BLOCK}[worst]
|
|
42
|
+
|
|
43
|
+
def to_dict(self) -> dict[str, Any]:
|
|
44
|
+
from . import __version__
|
|
45
|
+
return {"tool": "pipeverify", "version": __version__, "verdict": self.verdict,
|
|
46
|
+
"seconds": round(self.seconds, 3), "explanation": self.explanation,
|
|
47
|
+
"tables": [t.to_dict() for t in self.tables]}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def verify(before: Any, after: Any, *, name: str = "table", key: list[str] | str | None = None,
|
|
51
|
+
expect_change: list[str] | None = None, ignore: list[str] | None = None,
|
|
52
|
+
expect_row_change: bool = False, thresholds: Thresholds | dict | None = None,
|
|
53
|
+
base_dir: str = ".") -> TableResult:
|
|
54
|
+
"""Compare two snapshots of one table.
|
|
55
|
+
|
|
56
|
+
`before` and `after` can be file paths, duckdb:<file>:<table> strings,
|
|
57
|
+
config mappings, or pandas DataFrames.
|
|
58
|
+
"""
|
|
59
|
+
if isinstance(key, str):
|
|
60
|
+
key = [k.strip() for k in key.split(",") if k.strip()]
|
|
61
|
+
if not isinstance(thresholds, Thresholds):
|
|
62
|
+
thresholds = Thresholds.from_dict(thresholds)
|
|
63
|
+
src_b, src_a = parse_source(before, base_dir), parse_source(after, base_dir)
|
|
64
|
+
con = duckdb.connect()
|
|
65
|
+
try:
|
|
66
|
+
load(con, src_b, "before")
|
|
67
|
+
load(con, src_a, "after")
|
|
68
|
+
findings, stats = run_checks(con, "before", "after", key=key, expect_change=expect_change,
|
|
69
|
+
ignore=ignore, expect_row_change=expect_row_change,
|
|
70
|
+
thresholds=thresholds)
|
|
71
|
+
if not key:
|
|
72
|
+
findings.append(Finding("keys", "info",
|
|
73
|
+
"No key given, so row-level changes were not compared. Add a key for stronger checks."))
|
|
74
|
+
finally:
|
|
75
|
+
con.close()
|
|
76
|
+
order = {BLOCK: 0, REVIEW: 1, "info": 2, PASS: 3}
|
|
77
|
+
findings.sort(key=lambda f: order[f.severity])
|
|
78
|
+
return TableResult(name=name, verdict=verdict(findings), findings=findings, stats=stats,
|
|
79
|
+
before=src_b.describe(), after=src_a.describe())
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def load_config(path: str) -> dict[str, Any]:
|
|
83
|
+
with open(path, encoding="utf-8") as fh:
|
|
84
|
+
cfg = yaml.safe_load(fh) or {}
|
|
85
|
+
if not isinstance(cfg, dict) or "tables" not in cfg:
|
|
86
|
+
raise ValueError(f"{path}: config needs a 'tables' list")
|
|
87
|
+
return cfg
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def run_config(path: str, only: list[str] | None = None) -> RunResult:
|
|
91
|
+
cfg = load_config(path)
|
|
92
|
+
base_dir = os.path.dirname(os.path.abspath(path))
|
|
93
|
+
defaults = cfg.get("thresholds") or {}
|
|
94
|
+
result = RunResult()
|
|
95
|
+
start = time.perf_counter()
|
|
96
|
+
for spec in cfg["tables"]:
|
|
97
|
+
name = spec.get("name") or spec.get("after")
|
|
98
|
+
if only and name not in only:
|
|
99
|
+
continue
|
|
100
|
+
th = {**defaults, **(spec.get("thresholds") or {})}
|
|
101
|
+
try:
|
|
102
|
+
res = verify(spec["before"], spec["after"], name=str(name), key=spec.get("key"),
|
|
103
|
+
expect_change=spec.get("expect_change"), ignore=spec.get("ignore"),
|
|
104
|
+
expect_row_change=bool(spec.get("expect_row_change", False)),
|
|
105
|
+
thresholds=th, base_dir=base_dir)
|
|
106
|
+
except Exception as exc: # report the table as blocked, keep checking the rest
|
|
107
|
+
res = TableResult(name=str(name), verdict=BLOCK, stats={},
|
|
108
|
+
findings=[Finding("error", BLOCK, f"Could not check this table: {exc}")],
|
|
109
|
+
before=str(spec.get("before")), after=str(spec.get("after")), error=str(exc))
|
|
110
|
+
result.tables.append(res)
|
|
111
|
+
result.seconds = time.perf_counter() - start
|
|
112
|
+
return result
|
pipeverify/explain.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Optional plain-English explanation of a result by an LLM. Off unless asked for.
|
|
2
|
+
|
|
3
|
+
Only the findings are sent: check names, counts, percentages and column names.
|
|
4
|
+
Example values from the data are removed first unless `include_examples` is set.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
|
|
11
|
+
from .core import RunResult
|
|
12
|
+
|
|
13
|
+
PROMPT = """You review data changes for a data engineering team.
|
|
14
|
+
Below is the output of pipeverify, which compared tables before and after a pipeline change.
|
|
15
|
+
Write a short explanation (at most 120 words) for the engineer who made the change:
|
|
16
|
+
1. What most likely happened to the data, in plain words.
|
|
17
|
+
2. Which finding matters most and why.
|
|
18
|
+
3. One concrete thing to check or fix next.
|
|
19
|
+
Do not invent numbers. If the verdict is PASS, say so in one sentence.
|
|
20
|
+
|
|
21
|
+
Result:
|
|
22
|
+
{payload}
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ExplainError(RuntimeError):
|
|
27
|
+
pass
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _payload(result: RunResult, include_examples: bool) -> str:
|
|
31
|
+
data = result.to_dict()
|
|
32
|
+
data.pop("explanation", None)
|
|
33
|
+
for t in data["tables"]:
|
|
34
|
+
for f in t["findings"]:
|
|
35
|
+
if not include_examples:
|
|
36
|
+
f.get("metrics", {}).pop("examples", None)
|
|
37
|
+
return json.dumps(data, default=str)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def explain(result: RunResult, provider: str | None = None, model: str | None = None,
|
|
41
|
+
include_examples: bool = False) -> str:
|
|
42
|
+
provider = (provider or os.environ.get("PIPEVERIFY_LLM_PROVIDER") or "").lower()
|
|
43
|
+
if not provider:
|
|
44
|
+
provider = "anthropic" if os.environ.get("ANTHROPIC_API_KEY") else (
|
|
45
|
+
"openai" if os.environ.get("OPENAI_API_KEY") else "")
|
|
46
|
+
if not provider:
|
|
47
|
+
raise ExplainError("Set ANTHROPIC_API_KEY or OPENAI_API_KEY to use --explain")
|
|
48
|
+
prompt = PROMPT.format(payload=_payload(result, include_examples))
|
|
49
|
+
model = model or os.environ.get("PIPEVERIFY_LLM_MODEL")
|
|
50
|
+
if provider == "anthropic":
|
|
51
|
+
try:
|
|
52
|
+
import anthropic
|
|
53
|
+
except ImportError as exc:
|
|
54
|
+
raise ExplainError("Install the AI extra: pip install 'pipeverify[ai]'") from exc
|
|
55
|
+
client = anthropic.Anthropic()
|
|
56
|
+
msg = client.messages.create(model=model or "claude-sonnet-5-5", max_tokens=400,
|
|
57
|
+
messages=[{"role": "user", "content": prompt}])
|
|
58
|
+
return "".join(getattr(b, "text", "") for b in msg.content).strip()
|
|
59
|
+
if provider == "openai":
|
|
60
|
+
try:
|
|
61
|
+
import openai
|
|
62
|
+
except ImportError as exc:
|
|
63
|
+
raise ExplainError("Install the AI extra: pip install 'pipeverify[ai]'") from exc
|
|
64
|
+
if not model:
|
|
65
|
+
raise ExplainError("Set PIPEVERIFY_LLM_MODEL to the OpenAI model you want to use")
|
|
66
|
+
client = openai.OpenAI()
|
|
67
|
+
resp = client.chat.completions.create(model=model,
|
|
68
|
+
messages=[{"role": "user", "content": prompt}])
|
|
69
|
+
return (resp.choices[0].message.content or "").strip()
|
|
70
|
+
raise ExplainError(f"Unknown provider '{provider}'. Use anthropic or openai.")
|
pipeverify/report.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Render results for a terminal, a pull request comment (Markdown) or machines (JSON)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from .core import RunResult
|
|
9
|
+
|
|
10
|
+
ICON = {"pass": "✅", "review": "🟡", "block": "⛔", "info": "ℹ️"}
|
|
11
|
+
LABEL = {"pass": "PASS", "review": "REVIEW", "block": "BLOCK", "info": "INFO"}
|
|
12
|
+
HEADLINE = {
|
|
13
|
+
"pass": "Data looks the same where it should. Safe to merge.",
|
|
14
|
+
"review": "Something changed that tests would not catch. A person should look before merging.",
|
|
15
|
+
"block": "This change damages the data. Do not merge as is.",
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _headline(result: RunResult) -> str:
|
|
20
|
+
if any(t.error for t in result.tables):
|
|
21
|
+
return "Some tables could not be checked. Fix the errors below and run again."
|
|
22
|
+
return HEADLINE[result.verdict]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _color(text: str, sev: str) -> str:
|
|
26
|
+
if not sys.stdout.isatty() or os.environ.get("NO_COLOR"):
|
|
27
|
+
return text
|
|
28
|
+
code = {"pass": "32", "review": "33", "block": "31", "info": "36"}.get(sev, "0")
|
|
29
|
+
return f"\033[{code}m{text}\033[0m"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def to_text(result: RunResult, show_info: bool = False) -> str:
|
|
33
|
+
lines = []
|
|
34
|
+
for t in result.tables:
|
|
35
|
+
lines.append(_color(f"{LABEL[t.verdict]:<7}", t.verdict) + f" {t.name}")
|
|
36
|
+
s = t.stats
|
|
37
|
+
if s:
|
|
38
|
+
extra = f", matched {s['matched_rows']:,}" if "matched_rows" in s else ""
|
|
39
|
+
lines.append(f" rows {s.get('rows_before', 0):,} -> {s.get('rows_after', 0):,}{extra}")
|
|
40
|
+
for f in t.findings:
|
|
41
|
+
if f.severity == "info" and not show_info:
|
|
42
|
+
continue
|
|
43
|
+
lines.append(" " + _color(f"{LABEL[f.severity]:<6}", f.severity) + f" {f.message}")
|
|
44
|
+
ex = f.metrics.get("examples") if f.metrics else None
|
|
45
|
+
if ex:
|
|
46
|
+
lines.append(f" e.g. {ex[0]}")
|
|
47
|
+
lines.append("")
|
|
48
|
+
lines.append(_color(f"Verdict: {LABEL[result.verdict]}", result.verdict) + f" {_headline(result)}")
|
|
49
|
+
if result.explanation:
|
|
50
|
+
lines += ["", "Explanation:", result.explanation]
|
|
51
|
+
return "\n".join(lines)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def to_markdown(result: RunResult) -> str:
|
|
55
|
+
out = [f"## {ICON[result.verdict]} pipeverify: {LABEL[result.verdict]}", "", _headline(result), ""]
|
|
56
|
+
out += ["| Table | Verdict | Rows before → after | Issues |", "|---|---|---|---|"]
|
|
57
|
+
for t in result.tables:
|
|
58
|
+
issues = sum(1 for f in t.findings if f.severity in ("review", "block"))
|
|
59
|
+
s = t.stats or {}
|
|
60
|
+
rows = f"{s.get('rows_before', '?'):,} → {s.get('rows_after', '?'):,}" if s else "n/a"
|
|
61
|
+
out.append(f"| `{t.name}` | {ICON[t.verdict]} {LABEL[t.verdict]} | {rows} | {issues} |")
|
|
62
|
+
for t in result.tables:
|
|
63
|
+
notable = [f for f in t.findings if f.severity in ("review", "block")]
|
|
64
|
+
info = [f for f in t.findings if f.severity == "info"]
|
|
65
|
+
if not notable and not info:
|
|
66
|
+
continue
|
|
67
|
+
out += ["", f"<details{' open' if notable else ''}><summary><b>{t.name}</b></summary>", ""]
|
|
68
|
+
for f in notable + info:
|
|
69
|
+
out.append(f"- {ICON[f.severity]} **{LABEL[f.severity]}** {f.message}")
|
|
70
|
+
ex = f.metrics.get("examples") if f.metrics else None
|
|
71
|
+
if ex:
|
|
72
|
+
out.append(f" - example (key…, before, after): `{ex[0]}`")
|
|
73
|
+
out += ["", "</details>"]
|
|
74
|
+
if result.explanation:
|
|
75
|
+
out += ["", "### Explanation", "", result.explanation]
|
|
76
|
+
out += ["", f"<sub>Checked in {result.seconds:.2f}s by pipeverify. Verdicts compare data, not job status.</sub>"]
|
|
77
|
+
return "\n".join(out) + "\n"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def to_json(result: RunResult) -> str:
|
|
81
|
+
return json.dumps(result.to_dict(), indent=2, default=str)
|
pipeverify/sources.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""Load a table snapshot from a file, a DuckDB database, any SQL database or a DataFrame.
|
|
2
|
+
|
|
3
|
+
Every source ends up as a table inside one DuckDB connection, where the checks run.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Any, Mapping
|
|
10
|
+
|
|
11
|
+
import duckdb
|
|
12
|
+
|
|
13
|
+
FILE_READERS = {
|
|
14
|
+
".csv": "read_csv_auto",
|
|
15
|
+
".tsv": "read_csv_auto",
|
|
16
|
+
".parquet": "read_parquet",
|
|
17
|
+
".pq": "read_parquet",
|
|
18
|
+
".json": "read_json_auto",
|
|
19
|
+
".jsonl": "read_json_auto",
|
|
20
|
+
".ndjson": "read_json_auto",
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class SourceError(ValueError):
|
|
25
|
+
"""Raised when a source spec cannot be understood or loaded."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class Source:
|
|
30
|
+
"""A normalized description of where a table snapshot lives."""
|
|
31
|
+
|
|
32
|
+
kind: str # file | duckdb | sql | dataframe
|
|
33
|
+
path: str | None = None
|
|
34
|
+
table: str | None = None
|
|
35
|
+
query: str | None = None
|
|
36
|
+
url: str | None = None
|
|
37
|
+
frame: Any = None
|
|
38
|
+
|
|
39
|
+
def describe(self) -> str:
|
|
40
|
+
if self.kind == "file":
|
|
41
|
+
return self.path or ""
|
|
42
|
+
if self.kind == "duckdb":
|
|
43
|
+
return f"duckdb:{self.path}:{self.table or 'query'}"
|
|
44
|
+
if self.kind == "sql":
|
|
45
|
+
return f"sql:{_redact(self.url or '')}:{self.table or 'query'}"
|
|
46
|
+
return "dataframe"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _redact(url: str) -> str:
|
|
50
|
+
# hide passwords in connection strings that end up in reports
|
|
51
|
+
if "@" in url and "://" in url:
|
|
52
|
+
scheme, rest = url.split("://", 1)
|
|
53
|
+
creds, host = rest.split("@", 1)
|
|
54
|
+
user = creds.split(":", 1)[0]
|
|
55
|
+
return f"{scheme}://{user}:***@{host}"
|
|
56
|
+
return url
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def parse_source(spec: Any, base_dir: str = ".") -> Source:
|
|
60
|
+
"""Turn a CLI string, a config mapping or a DataFrame into a Source.
|
|
61
|
+
|
|
62
|
+
String forms:
|
|
63
|
+
data/orders.parquet a file (csv, parquet, json)
|
|
64
|
+
duckdb:warehouse.db:gold.orders a table in a DuckDB file
|
|
65
|
+
duckdb:warehouse.db:SELECT ... a query against a DuckDB file
|
|
66
|
+
Mapping forms (config file):
|
|
67
|
+
{path: ...} | {duckdb: ..., table|query: ...} | {url: ..., table|query: ...}
|
|
68
|
+
"""
|
|
69
|
+
if hasattr(spec, "columns") and hasattr(spec, "dtypes"):
|
|
70
|
+
return Source(kind="dataframe", frame=spec)
|
|
71
|
+
if isinstance(spec, str):
|
|
72
|
+
if spec.startswith("duckdb:"):
|
|
73
|
+
parts = spec.split(":", 2)
|
|
74
|
+
if len(parts) != 3:
|
|
75
|
+
raise SourceError("DuckDB sources look like duckdb:<file.db>:<table or query>")
|
|
76
|
+
_, path, target = parts
|
|
77
|
+
path = _resolve(path, base_dir)
|
|
78
|
+
if target.strip().lower().startswith(("select", "with")):
|
|
79
|
+
return Source(kind="duckdb", path=path, query=target)
|
|
80
|
+
return Source(kind="duckdb", path=path, table=target)
|
|
81
|
+
return Source(kind="file", path=_resolve(spec, base_dir))
|
|
82
|
+
if isinstance(spec, Mapping):
|
|
83
|
+
if "path" in spec:
|
|
84
|
+
return Source(kind="file", path=_resolve(str(spec["path"]), base_dir))
|
|
85
|
+
if "duckdb" in spec:
|
|
86
|
+
return Source(kind="duckdb", path=_resolve(str(spec["duckdb"]), base_dir),
|
|
87
|
+
table=spec.get("table"), query=spec.get("query"))
|
|
88
|
+
if "url" in spec:
|
|
89
|
+
url = os.path.expandvars(str(spec["url"]))
|
|
90
|
+
return Source(kind="sql", url=url, table=spec.get("table"), query=spec.get("query"))
|
|
91
|
+
raise SourceError(f"Unrecognized source: {spec!r}")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _resolve(path: str, base_dir: str) -> str:
|
|
95
|
+
path = os.path.expanduser(os.path.expandvars(path))
|
|
96
|
+
return path if os.path.isabs(path) else os.path.normpath(os.path.join(base_dir, path))
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def load(con: duckdb.DuckDBPyConnection, source: Source, name: str) -> None:
|
|
100
|
+
"""Materialize a source as table `name` in the DuckDB connection."""
|
|
101
|
+
if source.kind == "dataframe":
|
|
102
|
+
con.register(f"{name}_df", source.frame)
|
|
103
|
+
con.execute(f'CREATE OR REPLACE TABLE "{name}" AS SELECT * FROM "{name}_df"')
|
|
104
|
+
con.unregister(f"{name}_df")
|
|
105
|
+
return
|
|
106
|
+
if source.kind == "file":
|
|
107
|
+
path = source.path or ""
|
|
108
|
+
if not os.path.exists(path):
|
|
109
|
+
raise SourceError(f"File not found: {path}")
|
|
110
|
+
ext = os.path.splitext(path)[1].lower()
|
|
111
|
+
reader = FILE_READERS.get(ext)
|
|
112
|
+
if reader is None:
|
|
113
|
+
raise SourceError(f"Unsupported file type '{ext}'. Use csv, parquet or json.")
|
|
114
|
+
con.execute(f'CREATE OR REPLACE TABLE "{name}" AS SELECT * FROM {reader}(?)', [path])
|
|
115
|
+
return
|
|
116
|
+
if source.kind == "duckdb":
|
|
117
|
+
if not source.path or not os.path.exists(source.path):
|
|
118
|
+
raise SourceError(f"DuckDB file not found: {source.path}")
|
|
119
|
+
alias = f"src_{name}"
|
|
120
|
+
lit = source.path.replace("'", "''")
|
|
121
|
+
con.execute(f"ATTACH '{lit}' AS {alias} (READ_ONLY)")
|
|
122
|
+
try:
|
|
123
|
+
if source.query:
|
|
124
|
+
con.execute(f"USE {alias}")
|
|
125
|
+
try:
|
|
126
|
+
con.execute(f'CREATE OR REPLACE TABLE memory.main."{name}" AS {source.query}')
|
|
127
|
+
finally:
|
|
128
|
+
con.execute("USE memory")
|
|
129
|
+
elif source.table:
|
|
130
|
+
con.execute(f'CREATE OR REPLACE TABLE "{name}" AS SELECT * FROM {alias}.{source.table}')
|
|
131
|
+
else:
|
|
132
|
+
raise SourceError("A DuckDB source needs a table or a query")
|
|
133
|
+
finally:
|
|
134
|
+
con.execute(f"DETACH {alias}")
|
|
135
|
+
return
|
|
136
|
+
if source.kind == "sql":
|
|
137
|
+
try:
|
|
138
|
+
import pandas as pd
|
|
139
|
+
import sqlalchemy
|
|
140
|
+
except ImportError as exc: # pragma: no cover - depends on extras
|
|
141
|
+
raise SourceError("SQL sources need the sql extra: pip install 'pipeverify[sql]'") from exc
|
|
142
|
+
engine = sqlalchemy.create_engine(source.url)
|
|
143
|
+
query = source.query or f"SELECT * FROM {source.table}"
|
|
144
|
+
with engine.connect() as conn:
|
|
145
|
+
frame = pd.read_sql(sqlalchemy.text(query), conn)
|
|
146
|
+
load(con, Source(kind="dataframe", frame=frame), name)
|
|
147
|
+
return
|
|
148
|
+
raise SourceError(f"Unknown source kind {source.kind}")
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: pipeverify
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Check that a pipeline change left the data right, not just the job green.
|
|
5
|
+
Project-URL: Homepage, https://github.com/akshaysharma1088/pipeverify
|
|
6
|
+
Project-URL: Issues, https://github.com/akshaysharma1088/pipeverify/issues
|
|
7
|
+
Author: Akshay Sharma
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
License-File: NOTICE
|
|
11
|
+
Keywords: ci,data-diff,data-engineering,data-quality,duckdb,etl,llm-agents
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: Database
|
|
16
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
17
|
+
Requires-Python: >=3.9
|
|
18
|
+
Requires-Dist: click>=8.1
|
|
19
|
+
Requires-Dist: duckdb>=1.0
|
|
20
|
+
Requires-Dist: pyyaml>=6.0
|
|
21
|
+
Provides-Extra: ai
|
|
22
|
+
Requires-Dist: anthropic>=0.40; extra == 'ai'
|
|
23
|
+
Requires-Dist: openai>=1.40; extra == 'ai'
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: pandas>=2.0; extra == 'dev'
|
|
26
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
27
|
+
Provides-Extra: sql
|
|
28
|
+
Requires-Dist: pandas>=2.0; extra == 'sql'
|
|
29
|
+
Requires-Dist: sqlalchemy>=2.0; extra == 'sql'
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+
# pipeverify
|
|
33
|
+
|
|
34
|
+
**Check that a pipeline change left the data right, not just the job green.**
|
|
35
|
+
|
|
36
|
+
[](https://github.com/akshaysharma1088/pipeverify/actions/workflows/ci.yml)
|
|
37
|
+
[](LICENSE)
|
|
38
|
+

|
|
39
|
+

|
|
40
|
+
|
|
41
|
+
A pipeline change can pass every test, finish on time and keep the schema intact while quietly
|
|
42
|
+
dropping rows, duplicating keys or changing what a column means. More of these changes are now
|
|
43
|
+
written by AI coding agents, which makes "the job succeeded" an even weaker signal.
|
|
44
|
+
|
|
45
|
+
pipeverify compares your tables **before and after** a change and gives a verdict:
|
|
46
|
+
|
|
47
|
+
| Verdict | Meaning | Default CI behaviour |
|
|
48
|
+
|---|---|---|
|
|
49
|
+
| ✅ **PASS** | The data is the same where it should be. | Merge |
|
|
50
|
+
| 🟡 **REVIEW** | Something changed that tests would not catch. A person should look. | Merge allowed, flagged |
|
|
51
|
+
| ⛔ **BLOCK** | The change damages the data. | Fail the check |
|
|
52
|
+
|
|
53
|
+
It works with any tool that produces tables: SQL scripts, Spark jobs, dbt, Airflow tasks or an AI
|
|
54
|
+
agent's fix. It needs two snapshots, nothing else.
|
|
55
|
+
|
|
56
|
+
## Why
|
|
57
|
+
|
|
58
|
+
In the [PipeMend benchmark](https://github.com/akshaysharma1088/pipemend)
|
|
59
|
+
([DOI 10.5281/zenodo.23510784](https://doi.org/10.5281/zenodo.23510784)), LLM agents repaired
|
|
60
|
+
64 data pipeline incidents. Production-style data quality monitors approved **every** harmful fix
|
|
61
|
+
the agents made. What caught them was comparing the data itself. pipeverify packages that check
|
|
62
|
+
so any team can run it on every change.
|
|
63
|
+
|
|
64
|
+
## Quick start
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
pip install pipeverify
|
|
68
|
+
|
|
69
|
+
# compare two snapshots of one table
|
|
70
|
+
pipeverify compare before/orders.parquet after/orders.parquet --key order_id
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
```
|
|
74
|
+
BLOCK orders.parquet
|
|
75
|
+
rows 1,200 -> 1,000, matched 1,000
|
|
76
|
+
BLOCK Table lost 200 rows (16.67%)
|
|
77
|
+
BLOCK 200 key(s) present before are gone after (16.67%)
|
|
78
|
+
BLOCK Total of 'revenue' moved 16.71% (1,383,131.25 -> 1,152,000.00)
|
|
79
|
+
|
|
80
|
+
Verdict: BLOCK This change damages the data. Do not merge as is.
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Try the bundled demo, five realistic changes to a retail sales table:
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
git clone https://github.com/akshaysharma1088/pipeverify && cd pipeverify
|
|
87
|
+
pip install -e .
|
|
88
|
+
python examples/retail/make_demo.py
|
|
89
|
+
for s in examples/retail/scenarios/*/; do pipeverify run -c "$s/pipeverify.yml"; done
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
| Scenario | What happened | Verdict |
|
|
93
|
+
|---|---|---|
|
|
94
|
+
| `1_safe_fix` | Revenue restated for late refunds on one day, as intended | ✅ PASS |
|
|
95
|
+
| `2_dedupe_drops_rows` | Duplicates removed on the wrong columns, real days dropped | ⛔ BLOCK |
|
|
96
|
+
| `3_join_fanout` | A join to a dimension with a duplicate row doubled one store | ⛔ BLOCK |
|
|
97
|
+
| `4_unit_change` | Upstream started sending one region's revenue in cents | ⛔ BLOCK |
|
|
98
|
+
| `5_null_creep` | A renamed source field left region empty for new stores | 🟡 REVIEW |
|
|
99
|
+
|
|
100
|
+
Every one of these runs successfully and keeps the same schema.
|
|
101
|
+
|
|
102
|
+
## Sources
|
|
103
|
+
|
|
104
|
+
`before` and `after` can each be:
|
|
105
|
+
|
|
106
|
+
| Source | CLI form | Config form |
|
|
107
|
+
|---|---|---|
|
|
108
|
+
| CSV, Parquet, JSON file | `data/orders.parquet` | `path: data/orders.parquet` |
|
|
109
|
+
| DuckDB table | `duckdb:warehouse.db:gold.orders` | `{duckdb: warehouse.db, table: gold.orders}` |
|
|
110
|
+
| DuckDB query | `"duckdb:warehouse.db:SELECT ..."` | `{duckdb: warehouse.db, query: "SELECT ..."}` |
|
|
111
|
+
| Any SQLAlchemy database (Postgres, Snowflake, BigQuery, ...) | | `{url: "postgresql://${PGUSER}@host/db", table: gold.orders}` |
|
|
112
|
+
| pandas DataFrame | | Python API |
|
|
113
|
+
|
|
114
|
+
SQL databases need `pip install "pipeverify[sql]"` plus the driver for your database. Environment
|
|
115
|
+
variables in URLs are expanded, so credentials stay out of the config file.
|
|
116
|
+
|
|
117
|
+
## Config
|
|
118
|
+
|
|
119
|
+
Check many tables at once with `pipeverify.yml` (`pipeverify init` writes a starter file):
|
|
120
|
+
|
|
121
|
+
```yaml
|
|
122
|
+
thresholds: # optional, overrides the defaults below for every table
|
|
123
|
+
row_change_block_pct: 10
|
|
124
|
+
tables:
|
|
125
|
+
- name: gold.daily_sales
|
|
126
|
+
before: snapshots/main/daily_sales.parquet
|
|
127
|
+
after: snapshots/pr/daily_sales.parquet
|
|
128
|
+
key: [store_id, sale_date]
|
|
129
|
+
expect_change: [revenue] # columns this change is meant to modify
|
|
130
|
+
ignore: [loaded_at] # columns that always change
|
|
131
|
+
- name: gold.customers
|
|
132
|
+
before: {url: "${WAREHOUSE_URL}", table: prod.customers}
|
|
133
|
+
after: {url: "${WAREHOUSE_URL}", table: pr_123.customers}
|
|
134
|
+
key: [customer_id]
|
|
135
|
+
expect_row_change: true # this change is meant to add or remove rows
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
```bash
|
|
139
|
+
pipeverify run # uses ./pipeverify.yml
|
|
140
|
+
pipeverify run --fail-on review # stricter: fail CI on REVIEW too
|
|
141
|
+
pipeverify run --format markdown -o report.md
|
|
142
|
+
pipeverify run --json-out report.json
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
Exit code is `1` when the verdict reaches `--fail-on` (default `block`), otherwise `0`.
|
|
146
|
+
|
|
147
|
+
## What it checks
|
|
148
|
+
|
|
149
|
+
| Check | Catches | Default |
|
|
150
|
+
|---|---|---|
|
|
151
|
+
| Schema | Removed, added or retyped columns | removed: BLOCK, retyped: REVIEW |
|
|
152
|
+
| Row count | Rows lost or gained | REVIEW > 1%, BLOCK ≥ 10% |
|
|
153
|
+
| Missing keys | Rows that existed before and are gone | REVIEW on any, BLOCK ≥ 5% |
|
|
154
|
+
| New keys | Rows that did not exist before | REVIEW |
|
|
155
|
+
| Duplicate keys | Fan-out from joins, double loads | BLOCK on any new duplicate |
|
|
156
|
+
| Null rate | Columns going empty | REVIEW > 1 pt, BLOCK ≥ 10 pts |
|
|
157
|
+
| Changed values | Matched rows whose values changed, per column | REVIEW on any, BLOCK ≥ 10% |
|
|
158
|
+
| Column totals | Unit changes, partial loads, double counting | REVIEW > 0.5%, BLOCK ≥ 5% |
|
|
159
|
+
| Category values | New codes in low-cardinality text columns | REVIEW |
|
|
160
|
+
|
|
161
|
+
Columns listed in `expect_change` are reported but never raise the verdict. All thresholds can be
|
|
162
|
+
changed globally or per table; see [`pipeverify/checks.py`](pipeverify/checks.py) for every option.
|
|
163
|
+
|
|
164
|
+
## GitHub Action
|
|
165
|
+
|
|
166
|
+
```yaml
|
|
167
|
+
# .github/workflows/pipeverify.yml
|
|
168
|
+
on: pull_request
|
|
169
|
+
permissions:
|
|
170
|
+
contents: read
|
|
171
|
+
pull-requests: write
|
|
172
|
+
jobs:
|
|
173
|
+
verify:
|
|
174
|
+
runs-on: ubuntu-latest
|
|
175
|
+
steps:
|
|
176
|
+
- uses: actions/checkout@v4
|
|
177
|
+
# ... build the "after" snapshots for this PR here ...
|
|
178
|
+
- uses: akshaysharma1088/pipeverify@v0.1.0
|
|
179
|
+
with:
|
|
180
|
+
config: pipeverify.yml
|
|
181
|
+
fail-on: block # or review, or never
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
The action posts the report as a PR comment and in the job summary, and exposes the verdict as an
|
|
185
|
+
output.
|
|
186
|
+
|
|
187
|
+
## Python API
|
|
188
|
+
|
|
189
|
+
```python
|
|
190
|
+
import pipeverify
|
|
191
|
+
|
|
192
|
+
result = pipeverify.verify(before_df, after_df, key="order_id", expect_change=["status"])
|
|
193
|
+
print(result.verdict) # "pass" | "review" | "block"
|
|
194
|
+
for f in result.findings:
|
|
195
|
+
print(f.severity, f.message)
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
Useful inside an Airflow task, a notebook, or an AI agent's own loop: let the agent propose a fix,
|
|
199
|
+
run `verify`, and only apply the fix on PASS.
|
|
200
|
+
|
|
201
|
+
## Optional AI explanation
|
|
202
|
+
|
|
203
|
+
```bash
|
|
204
|
+
export ANTHROPIC_API_KEY=... # or OPENAI_API_KEY with PIPEVERIFY_LLM_MODEL
|
|
205
|
+
pip install "pipeverify[ai]"
|
|
206
|
+
pipeverify run --explain
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
This adds a short plain-English explanation of what probably happened and what to check next.
|
|
210
|
+
It is off by default. Only the findings are sent (check names, counts, percentages, column names);
|
|
211
|
+
example values from your data are removed first. The verdict never depends on the LLM.
|
|
212
|
+
|
|
213
|
+
## Roadmap
|
|
214
|
+
|
|
215
|
+
- Native adapters for dbt (compare a PR's models against production), Airflow and Spark
|
|
216
|
+
- Sampling and pushdown for very large tables, so checks run in the warehouse
|
|
217
|
+
- Rules learned from history: what "normal" change looks like for each table
|
|
218
|
+
- Agent integration: a guardrail that coding and data agents call before applying a change
|
|
219
|
+
|
|
220
|
+
Ideas and pull requests are welcome; see [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
221
|
+
|
|
222
|
+
## Status
|
|
223
|
+
|
|
224
|
+
Alpha. The checks and verdicts are stable enough to try in CI; options and output formats may
|
|
225
|
+
still change before 1.0.
|
|
226
|
+
|
|
227
|
+
## Citation
|
|
228
|
+
|
|
229
|
+
If you use pipeverify in research, please cite the PipeMend benchmark that motivated it
|
|
230
|
+
(see [CITATION.cff](CITATION.cff)).
|
|
231
|
+
|
|
232
|
+
## License
|
|
233
|
+
|
|
234
|
+
Apache-2.0
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
pipeverify/__init__.py,sha256=0547yOB-etlZB5UyIrvI-OV2ZKnQaRz4UCt_GC8_TbM,349
|
|
2
|
+
pipeverify/checks.py,sha256=aeqhFnPksVeGFo9oVMWpy0at1njrZAtLW5IoEcnLCDo,13087
|
|
3
|
+
pipeverify/cli.py,sha256=rWh_UFOBVI5FcSevY0Lfx4eQaefTNvLVTxfg9CCccPU,6694
|
|
4
|
+
pipeverify/core.py,sha256=7vYCMjU0-C6mWm8diZXLclJe7AtyQiLPw5VbNX2jjV8,4578
|
|
5
|
+
pipeverify/explain.py,sha256=7tZBqFXkN5ySEtrNEt8dBXxm8dNYeFSSqb8GWxVLuOs,2950
|
|
6
|
+
pipeverify/report.py,sha256=WBnDYA3mbIUOfMLcf8qGi8roykhh6HJfRWPUk2eaIjo,3619
|
|
7
|
+
pipeverify/sources.py,sha256=XI2IfVaeYCD5cZ7be1kzbDHMaChq4G7mN87XxaXw3UM,5890
|
|
8
|
+
pipeverify-0.1.0.dist-info/METADATA,sha256=Ldy55YLKZzgYFDD9oldW5sqFhIF9aq2o_3flVNdTeQE,9101
|
|
9
|
+
pipeverify-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
10
|
+
pipeverify-0.1.0.dist-info/entry_points.txt,sha256=hg3tJswAuG4J0DJauqOQMrGZKjH7_5qA_C-mMQP7x-Y,51
|
|
11
|
+
pipeverify-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
12
|
+
pipeverify-0.1.0.dist-info/licenses/NOTICE,sha256=-Ei0_DtJMBByRJekSqwRIF-bZeDyj-zpkUHIXArp4KI,40
|
|
13
|
+
pipeverify-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|