batchgate 0.2.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.
- batchgate/__init__.py +5 -0
- batchgate/cli.py +109 -0
- batchgate/drift.py +47 -0
- batchgate/gate.py +167 -0
- batchgate/rules.py +368 -0
- batchgate-0.2.0.dist-info/METADATA +160 -0
- batchgate-0.2.0.dist-info/RECORD +11 -0
- batchgate-0.2.0.dist-info/WHEEL +5 -0
- batchgate-0.2.0.dist-info/entry_points.txt +2 -0
- batchgate-0.2.0.dist-info/licenses/LICENSE +21 -0
- batchgate-0.2.0.dist-info/top_level.txt +1 -0
batchgate/__init__.py
ADDED
batchgate/cli.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Command line.
|
|
2
|
+
|
|
3
|
+
batchgate fit past1.csv past2.csv ... -o rules.json [--ref NAME=table.csv:COLUMN ...]
|
|
4
|
+
batchgate fit all_history.parquet --split-by DATE_COLUMN -o rules.json [--skip order] [--numeric qty,units]
|
|
5
|
+
batchgate show rules.json
|
|
6
|
+
batchgate drop rules.json 4 7
|
|
7
|
+
batchgate check new.csv -r rules.json [--ref NAME=table.csv:COLUMN ...] [--day 2024-04-01] [--rules-only]
|
|
8
|
+
|
|
9
|
+
`check` exits with 1 when the batch should be blocked, 0 when it passes (so it can stop a pipeline step).
|
|
10
|
+
"""
|
|
11
|
+
import argparse
|
|
12
|
+
import sys
|
|
13
|
+
|
|
14
|
+
import pandas as pd
|
|
15
|
+
|
|
16
|
+
from . import rules as R
|
|
17
|
+
from .gate import Gate
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _parse_dates(df):
|
|
21
|
+
"""Text columns that plainly hold dates (2024-04-01, 04/01/2024 10:00 ...) become dates."""
|
|
22
|
+
for c in df.columns:
|
|
23
|
+
if not R.is_text(df[c]):
|
|
24
|
+
continue
|
|
25
|
+
s = df[c].dropna().astype(str).head(200)
|
|
26
|
+
if len(s) and (s.str.len() >= 8).all() and s.str.contains(r"\d[-/]\d").all():
|
|
27
|
+
conv = pd.to_datetime(df[c], errors="coerce")
|
|
28
|
+
if conv.notna().sum() >= 0.95 * df[c].notna().sum():
|
|
29
|
+
df[c] = conv
|
|
30
|
+
return df
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def read(path, dates=True):
|
|
34
|
+
p = path.lower()
|
|
35
|
+
if p.endswith(".parquet"):
|
|
36
|
+
return pd.read_parquet(path)
|
|
37
|
+
if p.endswith(".json") or p.endswith(".jsonl"):
|
|
38
|
+
df = pd.read_json(path, lines=p.endswith(".jsonl"))
|
|
39
|
+
else:
|
|
40
|
+
df = pd.read_csv(path, low_memory=False)
|
|
41
|
+
return _parse_dates(df) if dates else df
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def refs_from(args):
|
|
45
|
+
out = {}
|
|
46
|
+
for spec in args.ref or []:
|
|
47
|
+
name, _, rest = spec.partition("=")
|
|
48
|
+
path, _, col = rest.rpartition(":")
|
|
49
|
+
if not (name and path and col):
|
|
50
|
+
sys.exit("--ref must look like NAME=table.csv:COLUMN")
|
|
51
|
+
out[name] = set(read(path, dates=False)[col].dropna().tolist())
|
|
52
|
+
return out
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def main(argv=None):
|
|
56
|
+
ap = argparse.ArgumentParser(prog="batchgate", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
57
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
58
|
+
f = sub.add_parser("fit", help="learn rules from past batches and freeze them in a file")
|
|
59
|
+
f.add_argument("files", nargs="+")
|
|
60
|
+
f.add_argument("-o", "--out", required=True)
|
|
61
|
+
f.add_argument("--split-by", help="date/time column: one batch per calendar day of it")
|
|
62
|
+
f.add_argument("--ref", action="append", help="reference table NAME=path:COLUMN")
|
|
63
|
+
f.add_argument("--skip", default="", help="rule kinds to leave out, comma separated: " + ", ".join(R.KINDS))
|
|
64
|
+
f.add_argument("--numeric", default="", help="whole-number columns to treat as amounts (for sums and order rules)")
|
|
65
|
+
c = sub.add_parser("check", help="check one new batch against frozen rules")
|
|
66
|
+
c.add_argument("file")
|
|
67
|
+
c.add_argument("-r", "--rules", required=True)
|
|
68
|
+
c.add_argument("--day", help="the batch's day, enables the date-equals-batch-day rules")
|
|
69
|
+
c.add_argument("--ref", action="append", help="reference table NAME=path:COLUMN")
|
|
70
|
+
c.add_argument("--rules-only", action="store_true", help="never block on drift alone, only on broken rules")
|
|
71
|
+
s = sub.add_parser("show", help="list the rules in a rules file, numbered")
|
|
72
|
+
s.add_argument("rules")
|
|
73
|
+
d = sub.add_parser("drop", help="remove rules from a rules file by their number in `show`")
|
|
74
|
+
d.add_argument("rules")
|
|
75
|
+
d.add_argument("numbers", nargs="+", type=int)
|
|
76
|
+
a = ap.parse_args(argv)
|
|
77
|
+
|
|
78
|
+
if a.cmd == "fit":
|
|
79
|
+
frames = [read(p) for p in a.files]
|
|
80
|
+
if a.split_by:
|
|
81
|
+
df = pd.concat(frames, ignore_index=True)
|
|
82
|
+
df[a.split_by] = pd.to_datetime(df[a.split_by])
|
|
83
|
+
hist = [(d, g.reset_index(drop=True)) for d, g in df.groupby(df[a.split_by].dt.normalize())]
|
|
84
|
+
else:
|
|
85
|
+
hist = frames
|
|
86
|
+
g = Gate.fit(hist, refs_from(a), skip=[x for x in a.skip.split(",") if x],
|
|
87
|
+
kinds={x: "numeric" for x in a.numeric.split(",") if x})
|
|
88
|
+
g.save(a.out)
|
|
89
|
+
print("%d rules learned from %d batches -> %s" % (len(g.rules), len(hist), a.out))
|
|
90
|
+
return 0
|
|
91
|
+
if a.cmd == "show":
|
|
92
|
+
print("\n".join(Gate.load(a.rules).describe()))
|
|
93
|
+
return 0
|
|
94
|
+
if a.cmd == "drop":
|
|
95
|
+
g = Gate.load(a.rules)
|
|
96
|
+
for text in g.drop(*a.numbers):
|
|
97
|
+
print("dropped:", text)
|
|
98
|
+
g.save(a.rules)
|
|
99
|
+
return 0
|
|
100
|
+
g = Gate.load(a.rules)
|
|
101
|
+
if a.rules_only:
|
|
102
|
+
g.drift_block = None
|
|
103
|
+
v = g.check(read(a.file, dates=False), pd.Timestamp(a.day) if a.day else None, refs_from(a))
|
|
104
|
+
print(v)
|
|
105
|
+
return 1 if v.block else 0
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
if __name__ == "__main__":
|
|
109
|
+
sys.exit(main())
|
batchgate/drift.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Drift log: simple metric z-scores against past batches."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
import pandas as pd
|
|
4
|
+
from .rules import kinds
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def metrics(df, cols):
|
|
8
|
+
m = {"rows": float(len(df))}
|
|
9
|
+
for c in cols:
|
|
10
|
+
if c not in df.columns: # a lost column shows up as missing metrics
|
|
11
|
+
continue
|
|
12
|
+
s = df[c]
|
|
13
|
+
m[c + ".complete"] = float(s.notna().mean())
|
|
14
|
+
m[c + ".distinct"] = float(s.nunique())
|
|
15
|
+
if pd.api.types.is_numeric_dtype(s) and not pd.api.types.is_bool_dtype(s):
|
|
16
|
+
m[c + ".mean"] = float(s.mean()) if s.notna().any() else 0.0
|
|
17
|
+
m[c + ".sd"] = float(s.std()) if s.notna().sum() > 1 else 0.0
|
|
18
|
+
return m
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class DriftLog:
|
|
22
|
+
"""Coarse drift: per batch, row count and per column completeness, distinct count, mean and sd, each as a
|
|
23
|
+
z-score against the past batches (the style of Deequ's OnlineNormal check). Kept as a log and as a last-resort
|
|
24
|
+
block for extreme changes; ordinary drift never blocks a batch on its own."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, cols, mu, sd):
|
|
27
|
+
self.cols, self.mu, self.sd = cols, pd.Series(mu, dtype=float), pd.Series(sd, dtype=float)
|
|
28
|
+
|
|
29
|
+
@classmethod
|
|
30
|
+
def fit(cls, hist):
|
|
31
|
+
cols = [c for c, k in kinds(hist[0][1]).items() if k in ("numeric", "code")]
|
|
32
|
+
H = pd.DataFrame([metrics(df, cols) for _, df in hist])
|
|
33
|
+
return cls(cols, H.mean(), H.std().replace(0, np.nan))
|
|
34
|
+
|
|
35
|
+
def to_dict(self):
|
|
36
|
+
return dict(cols=self.cols, mu={k: float(v) for k, v in self.mu.items()},
|
|
37
|
+
sd={k: (None if pd.isna(v) else float(v)) for k, v in self.sd.items()})
|
|
38
|
+
|
|
39
|
+
@classmethod
|
|
40
|
+
def from_dict(cls, d):
|
|
41
|
+
return cls(d["cols"], d["mu"], {k: (np.nan if v is None else v) for k, v in d["sd"].items()})
|
|
42
|
+
|
|
43
|
+
def score(self, df):
|
|
44
|
+
"""-> (max |z|, metric name)"""
|
|
45
|
+
z = ((pd.Series(metrics(df, self.cols)) - self.mu) / self.sd).abs().replace([np.inf], np.nan).fillna(0)
|
|
46
|
+
z = z.reindex(self.mu.index).fillna(1e6) # a metric missing from the batch = an anomaly
|
|
47
|
+
return float(z.max()), str(z.idxmax())
|
batchgate/gate.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""The gate: block a new batch when a rule that held in every past batch breaks; log drift; block on drift only when
|
|
2
|
+
it is extreme.
|
|
3
|
+
|
|
4
|
+
Decision (thresholds fixed in advance, never tuned on the batches being checked):
|
|
5
|
+
block if any rule breaks clearly (rate > max(3h, h + 0.01), h = the rule's worst rate in history)
|
|
6
|
+
block if a rule breaks slightly (rate > max(1.5h, h + 0.002)) while drift is unusual (z > drift_warn)
|
|
7
|
+
block if drift alone is extreme (z > drift_block)
|
|
8
|
+
block if the batch is empty, or a column the rules read is missing or no longer holds its type
|
|
9
|
+
pass otherwise; unusual drift alone is reported, not blocked
|
|
10
|
+
"""
|
|
11
|
+
import json
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
|
|
14
|
+
import pandas as pd
|
|
15
|
+
|
|
16
|
+
from . import rules as R
|
|
17
|
+
from .drift import DriftLog
|
|
18
|
+
|
|
19
|
+
FORMAT = 2
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class Break:
|
|
24
|
+
rule: str
|
|
25
|
+
rate: float
|
|
26
|
+
tolerance: float
|
|
27
|
+
level: str # "clear" or "slight"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class Verdict:
|
|
32
|
+
block: bool
|
|
33
|
+
reasons: list = field(default_factory=list)
|
|
34
|
+
breaks: list = field(default_factory=list)
|
|
35
|
+
drift_z: float = 0.0
|
|
36
|
+
drift_metric: str = ""
|
|
37
|
+
|
|
38
|
+
def __str__(self):
|
|
39
|
+
head = "BLOCK" if self.block else "PASS"
|
|
40
|
+
lines = [head + (": " + "; ".join(self.reasons) if self.reasons else "")]
|
|
41
|
+
for b in self.breaks:
|
|
42
|
+
lines.append(" %-6s %s (%.2f%% of rows, history at most %.2f%%)" % (b.level, b.rule, 100 * b.rate, 100 * b.tolerance))
|
|
43
|
+
lines.append(" drift: largest z %.1f on %s" % (self.drift_z, self.drift_metric))
|
|
44
|
+
return "\n".join(lines)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _cls(s):
|
|
48
|
+
"""What a column holds: time, bool, number, text or other."""
|
|
49
|
+
if pd.api.types.is_datetime64_any_dtype(s):
|
|
50
|
+
return "time"
|
|
51
|
+
if pd.api.types.is_bool_dtype(s):
|
|
52
|
+
return "bool"
|
|
53
|
+
if pd.api.types.is_numeric_dtype(s):
|
|
54
|
+
return "number"
|
|
55
|
+
return "text" if R.is_text(s) else "other"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Gate:
|
|
59
|
+
def __init__(self, rules=None, drift=None, drift_warn=3.0, drift_block=8.0, ref_names=(), schema=None):
|
|
60
|
+
self.rules, self.drift = rules or [], drift
|
|
61
|
+
self.drift_warn, self.drift_block = drift_warn, drift_block
|
|
62
|
+
self.ref_names = list(ref_names)
|
|
63
|
+
self.schema = schema or {}
|
|
64
|
+
|
|
65
|
+
# ---- learning ----
|
|
66
|
+
@classmethod
|
|
67
|
+
def fit(cls, history, refs=None, skip=(), kinds=None, **kw):
|
|
68
|
+
"""history: list of (day, DataFrame) or of DataFrames, one per past batch, oldest first. At least 5 batches;
|
|
69
|
+
30 or more, covering the seasons you will check, is better.
|
|
70
|
+
refs: {name: set of valid keys} for reference tables (optional).
|
|
71
|
+
skip: rule kinds to leave out, from batchgate.rules.KINDS (e.g. skip=["order"]).
|
|
72
|
+
kinds: {column: "numeric" | "code" | "other"} to overrule how a column is read, e.g. a whole-number
|
|
73
|
+
quantity column that should take part in sums: kinds={"qty": "numeric"}.
|
|
74
|
+
drift_block=None blocks on rules only (drift is still reported)."""
|
|
75
|
+
hist = [(h if isinstance(h, tuple) else (None, h)) for h in history]
|
|
76
|
+
if len(hist) < 5:
|
|
77
|
+
raise ValueError("need at least 5 past batches to learn from, got %d" % len(hist))
|
|
78
|
+
bad = [s for s in skip if s not in R.KINDS]
|
|
79
|
+
if bad:
|
|
80
|
+
raise ValueError("unknown rule kind(s) %s; choose from %s" % (bad, ", ".join(R.KINDS)))
|
|
81
|
+
refs = refs or {}
|
|
82
|
+
if all(d is not None for d, _ in hist):
|
|
83
|
+
rules = R.mine(hist, refs, skip, kinds)
|
|
84
|
+
else:
|
|
85
|
+
fake = [(pd.Timestamp("1970-01-01"), df) for _, df in hist]
|
|
86
|
+
rules = R.mine(fake, refs, tuple(skip) + ("batch_day",), kinds)
|
|
87
|
+
return cls(rules, DriftLog.fit(hist), ref_names=refs.keys(),
|
|
88
|
+
schema={c: _cls(hist[-1][1][c]) for c in hist[-1][1].columns}, **kw)
|
|
89
|
+
|
|
90
|
+
def drop(self, *numbers):
|
|
91
|
+
"""Remove rules by their number in describe() (1 = first). Returns the removed rules' texts."""
|
|
92
|
+
gone = [R.describe(self.rules[n - 1]) for n in numbers]
|
|
93
|
+
self.rules = [r for i, r in enumerate(self.rules, 1) if i not in numbers]
|
|
94
|
+
return gone
|
|
95
|
+
|
|
96
|
+
# ---- checking ----
|
|
97
|
+
def _prepare(self, df):
|
|
98
|
+
"""Bring the batch's columns to the types they had in history (a CSV gives dates and sometimes numbers as
|
|
99
|
+
text). Values that cannot be read as that type are reported as a broken type and become empty."""
|
|
100
|
+
df, breaks = df.copy(), []
|
|
101
|
+
for c, want in self.schema.items():
|
|
102
|
+
if c not in df.columns:
|
|
103
|
+
continue
|
|
104
|
+
s = df[c]
|
|
105
|
+
if isinstance(s.dtype, pd.CategoricalDtype):
|
|
106
|
+
s = df[c] = s.astype(object)
|
|
107
|
+
have, conv = _cls(s), None
|
|
108
|
+
if want == "time" and have != "time":
|
|
109
|
+
conv, what = pd.to_datetime(s, errors="coerce"), "dates"
|
|
110
|
+
elif want == "number" and have != "number":
|
|
111
|
+
conv, what = pd.to_numeric(s, errors="coerce"), "numbers"
|
|
112
|
+
elif want == "text" and have == "number":
|
|
113
|
+
df[c] = s.map(R.norm_key, na_action="ignore").astype(object)
|
|
114
|
+
if conv is not None:
|
|
115
|
+
lost = float((conv.isna() & s.notna()).mean()) if len(s) else 0.0
|
|
116
|
+
lv = R.level(lost, 0.0)
|
|
117
|
+
if lv:
|
|
118
|
+
breaks.append(Break("%s holds %s" % (c, what), lost, 0.0, lv))
|
|
119
|
+
df[c] = conv
|
|
120
|
+
if want == "time" and getattr(df[c].dt, "tz", None) is not None:
|
|
121
|
+
df[c] = df[c].dt.tz_localize(None)
|
|
122
|
+
return df, breaks
|
|
123
|
+
|
|
124
|
+
def check(self, df, day=None, refs=None):
|
|
125
|
+
refs = refs or {}
|
|
126
|
+
missing = [n for n in self.ref_names if n not in refs and any(r.get("ref") == n for r in self.rules)]
|
|
127
|
+
if missing:
|
|
128
|
+
raise ValueError("reference tables needed for checking: %s" % ", ".join(missing))
|
|
129
|
+
if len(df) == 0:
|
|
130
|
+
return Verdict(True, ["the batch is empty"])
|
|
131
|
+
df, breaks = self._prepare(df)
|
|
132
|
+
rules = [r for r in self.rules if day is not None or r["type"] != "batch_day"]
|
|
133
|
+
absent = [r for r in rules if any(c not in df.columns for c in R.columns(r))]
|
|
134
|
+
present = [r for r in rules if not any(c not in df.columns for c in R.columns(r))]
|
|
135
|
+
breaks += [Break(R.describe(i), rate, i["hist_max"], lvl) for i, rate, lvl in R.check(present, df, day, refs)]
|
|
136
|
+
breaks += [Break(R.describe(r) + " (column missing)", 1.0, r["hist_max"], "clear") for r in absent]
|
|
137
|
+
z, where = self.drift.score(df) if self.drift else (0.0, "")
|
|
138
|
+
reasons = []
|
|
139
|
+
if any(b.level == "clear" for b in breaks):
|
|
140
|
+
reasons.append("%d rule(s) clearly broken" % sum(b.level == "clear" for b in breaks))
|
|
141
|
+
elif breaks and z > self.drift_warn:
|
|
142
|
+
reasons.append("rule(s) slightly broken while drift is unusual")
|
|
143
|
+
if self.drift_block is not None and z > self.drift_block:
|
|
144
|
+
reasons.append("extreme drift (z %.1f on %s)" % (z, where))
|
|
145
|
+
return Verdict(bool(reasons), reasons, sorted(breaks, key=lambda b: -b.rate), z, where)
|
|
146
|
+
|
|
147
|
+
def describe(self):
|
|
148
|
+
return ["%3d %-60s history at most %.4f" % (i, R.describe(r), r["hist_max"]) for i, r in enumerate(self.rules, 1)]
|
|
149
|
+
|
|
150
|
+
# ---- saving: rules are frozen in a file and never re-learned from checked batches ----
|
|
151
|
+
def to_dict(self):
|
|
152
|
+
return dict(format=FORMAT, drift_warn=self.drift_warn, drift_block=self.drift_block, ref_names=self.ref_names,
|
|
153
|
+
schema=self.schema, rules=[R.to_dict(r) for r in self.rules],
|
|
154
|
+
drift=self.drift.to_dict() if self.drift else None)
|
|
155
|
+
|
|
156
|
+
def save(self, path):
|
|
157
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
158
|
+
json.dump(self.to_dict(), f, indent=1)
|
|
159
|
+
|
|
160
|
+
@classmethod
|
|
161
|
+
def load(cls, path):
|
|
162
|
+
with open(path, encoding="utf-8") as f:
|
|
163
|
+
d = json.load(f)
|
|
164
|
+
if d.get("format") not in (1, FORMAT):
|
|
165
|
+
raise ValueError("unknown rules file format")
|
|
166
|
+
return cls(d["rules"], DriftLog.from_dict(d["drift"]) if d["drift"] else None,
|
|
167
|
+
d["drift_warn"], d["drift_block"], d["ref_names"], d.get("schema"))
|
batchgate/rules.py
ADDED
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
"""Rule mining: find rules that held (almost) exactly in every past batch, then check a new batch against them.
|
|
2
|
+
|
|
3
|
+
Generic: nothing here knows the dataset. Column kinds are inferred: float -> numeric, datetime -> time, integer,
|
|
4
|
+
text or true/false with few values -> code (integer or text keys with many values are still checked against
|
|
5
|
+
reference tables, uniqueness and lookups). Rule kinds:
|
|
6
|
+
|
|
7
|
+
sum target == sum of a subset of other numeric columns (within 1 cent), missing parts counted as 0;
|
|
8
|
+
learned per group of one or two code columns when no single sum holds everywhere
|
|
9
|
+
reference a key column's values exist in a reference table's keys
|
|
10
|
+
domain a code column (<= 50 values) takes only values seen in history
|
|
11
|
+
order a <= b for two time columns, or two numeric columns
|
|
12
|
+
zero_when numeric b == 0 whenever code a == v
|
|
13
|
+
not_null a column is (almost) never empty
|
|
14
|
+
batch_day the date of a time column equals the batch's own day
|
|
15
|
+
unique a key column has no repeated values inside a batch
|
|
16
|
+
no_duplicate_rows no row is an exact copy of another row of the batch
|
|
17
|
+
determines each value of a goes with one value of b (store -> region), learned as a lookup
|
|
18
|
+
|
|
19
|
+
A rule is KEPT only if its violation rate stayed small (<= MAX_RATE) in EVERY history batch. Its tolerance is
|
|
20
|
+
frozen from history: new batches never move it.
|
|
21
|
+
"""
|
|
22
|
+
import itertools
|
|
23
|
+
|
|
24
|
+
import numpy as np
|
|
25
|
+
import pandas as pd
|
|
26
|
+
|
|
27
|
+
MAX_RATE = 0.02 # a rule must hold in >= 98% of rows of every history batch to be kept
|
|
28
|
+
MAX_PARTS = 12 # a sum target is searched over at most this many candidate part columns (2^12 subsets)
|
|
29
|
+
SUM_TOL = 0.011 # a sum holds on a row if it is within 1 cent (plus float rounding on large values)
|
|
30
|
+
KINDS = ("sum", "reference", "domain", "order", "zero_when", "not_null", "batch_day", "unique",
|
|
31
|
+
"no_duplicate_rows", "determines")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def is_text(s):
|
|
35
|
+
return s.dtype == object or pd.api.types.is_string_dtype(s)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _is_key(s):
|
|
39
|
+
"""Whole numbers or text: the types a key or code column has."""
|
|
40
|
+
return (pd.api.types.is_integer_dtype(s) or is_text(s)) and not pd.api.types.is_bool_dtype(s)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def kinds(df, overrides=None):
|
|
44
|
+
k = {}
|
|
45
|
+
for c in df.columns:
|
|
46
|
+
s = df[c]
|
|
47
|
+
if pd.api.types.is_datetime64_any_dtype(s):
|
|
48
|
+
k[c] = "time"
|
|
49
|
+
elif pd.api.types.is_bool_dtype(s):
|
|
50
|
+
k[c] = "code"
|
|
51
|
+
elif pd.api.types.is_float_dtype(s):
|
|
52
|
+
v = s.dropna()
|
|
53
|
+
# a float column holding a few whole numbers is a code (e.g. a rate code stored as 1.0, 2.0 ...)
|
|
54
|
+
k[c] = "code" if len(v) and v.nunique() <= 20 and bool((v == v.round()).all()) else "numeric"
|
|
55
|
+
elif _is_key(s):
|
|
56
|
+
k[c] = "code" if s.nunique(dropna=True) <= 300 else "other"
|
|
57
|
+
else:
|
|
58
|
+
k[c] = "other"
|
|
59
|
+
k.update({c: v for c, v in (overrides or {}).items() if c in k})
|
|
60
|
+
return k
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def norm_key(v):
|
|
64
|
+
"""One spelling for a key whatever its type: 7, 7.0 and '7' all become '7'."""
|
|
65
|
+
if isinstance(v, (bool, np.bool_)):
|
|
66
|
+
return str(bool(v))
|
|
67
|
+
if isinstance(v, (int, np.integer)):
|
|
68
|
+
return str(int(v))
|
|
69
|
+
if isinstance(v, (float, np.floating)):
|
|
70
|
+
return str(int(v)) if float(v).is_integer() else repr(float(v))
|
|
71
|
+
return str(v).strip()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _in_ref(s, keys):
|
|
75
|
+
"""Which values of s are keys of the reference table. If almost none match as they are, the two sides may just
|
|
76
|
+
be typed differently (numbers on one side, text on the other): compare them in one spelling."""
|
|
77
|
+
ok = s.isin(keys)
|
|
78
|
+
if len(s) and ok.mean() < 0.5:
|
|
79
|
+
ok2 = s.map(norm_key).isin({norm_key(x) for x in keys})
|
|
80
|
+
if ok2.mean() > ok.mean():
|
|
81
|
+
return ok2
|
|
82
|
+
return ok
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
# ---- violation rate of one rule on one batch: share of the rows it applies to that break it ----
|
|
86
|
+
def rate(idn, df, day=None, refs=None):
|
|
87
|
+
t, a = idn["type"], idn.get("a")
|
|
88
|
+
if t == "sum":
|
|
89
|
+
parts = df[idn["parts"]].fillna(0).sum(axis=1)
|
|
90
|
+
m = df[a].notna()
|
|
91
|
+
for c, v in idn.get("when", {}).items():
|
|
92
|
+
m &= df[c] == v
|
|
93
|
+
if not m.any():
|
|
94
|
+
return 0.0
|
|
95
|
+
tgt = df.loc[m, a]
|
|
96
|
+
return float(((tgt - parts[m]).abs() > SUM_TOL + 1e-9 * tgt.abs()).mean())
|
|
97
|
+
if t == "reference":
|
|
98
|
+
s = df[a].dropna()
|
|
99
|
+
return float((~_in_ref(s, refs[idn["ref"]])).mean()) if len(s) else 0.0
|
|
100
|
+
if t == "domain":
|
|
101
|
+
s = df[a].dropna()
|
|
102
|
+
return float((~s.isin(idn["values"])).mean()) if len(s) else 0.0
|
|
103
|
+
if t == "order":
|
|
104
|
+
m = df[a].notna() & df[idn["b"]].notna()
|
|
105
|
+
return float((df.loc[m, a] > df.loc[m, idn["b"]]).mean()) if m.any() else 0.0
|
|
106
|
+
if t == "zero_when":
|
|
107
|
+
m = df[a] == idn["v"]
|
|
108
|
+
return float((df.loc[m, idn["b"]].fillna(0).abs() > 0.0001).mean()) if m.sum() >= 30 else 0.0
|
|
109
|
+
if t == "not_null":
|
|
110
|
+
return float(df[a].isna().mean())
|
|
111
|
+
if t == "batch_day":
|
|
112
|
+
return float((df[a].dt.normalize() != pd.Timestamp(day)).mean())
|
|
113
|
+
if t == "unique":
|
|
114
|
+
s = df[a].dropna()
|
|
115
|
+
return float(s.duplicated().mean()) if len(s) else 0.0
|
|
116
|
+
if t == "no_duplicate_rows":
|
|
117
|
+
return float(df.duplicated().mean()) if len(df) else 0.0
|
|
118
|
+
if t == "determines":
|
|
119
|
+
if "_map" not in idn:
|
|
120
|
+
idn["_map"] = {x: y for x, y in idn["pairs"]}
|
|
121
|
+
exp = df[a].map(idn["_map"])
|
|
122
|
+
m = exp.notna() & df[idn["b"]].notna() # values of a not seen in history are left to other rules
|
|
123
|
+
return float((df.loc[m, idn["b"]].astype(object) != exp[m]).mean()) if m.any() else 0.0
|
|
124
|
+
raise ValueError(t)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _best_subset(X, ti, others, M):
|
|
128
|
+
"""Among all subsets of `others` (columns of M), the one whose row sums equal column ti most often.
|
|
129
|
+
-> (share of rows where it holds, list of column indices). Ties go to the larger subset."""
|
|
130
|
+
if len(X) == 0:
|
|
131
|
+
return 0.0, []
|
|
132
|
+
if len(X) > 2000: # a sample is enough here: every rule found is then
|
|
133
|
+
X = X[np.random.default_rng(0).choice(len(X), 2000, replace=False)] # checked on all rows of every batch
|
|
134
|
+
t, P = X[:, [ti]], X[:, others]
|
|
135
|
+
tol = SUM_TOL + 1e-9 * np.abs(t)
|
|
136
|
+
hold = np.empty(M.shape[1])
|
|
137
|
+
for s in range(0, M.shape[1], 256): # in slices, to keep memory small
|
|
138
|
+
hold[s:s + 256] = (np.abs(t - P @ M[:, s:s + 256]) <= tol).mean(axis=0)
|
|
139
|
+
j = int(np.lexsort((-np.arange(M.shape[1]), M.sum(axis=0), np.round(hold, 6)))[-1])
|
|
140
|
+
return float(hold[j]), [others[i] for i in np.nonzero(M[:, j])[0]]
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def sum_identities(pool, num, code, need=0.98, min_support=0.02):
|
|
144
|
+
"""total = sum of parts, either everywhere or within groups.
|
|
145
|
+
|
|
146
|
+
Real data often writes the same total differently in different groups (e.g. one sender folds a surcharge into
|
|
147
|
+
another column). So when no single sum holds everywhere, the rows are split by one code column, then by a pair
|
|
148
|
+
of code columns, and each group gets its own sum; the split that covers the most rows exactly is kept. Groups
|
|
149
|
+
under min_support of the rows are left without a rule."""
|
|
150
|
+
X = pool[num].fillna(0).to_numpy(dtype=np.float64)
|
|
151
|
+
quick = X[np.random.default_rng(1).choice(len(X), min(len(X), 400), replace=False)]
|
|
152
|
+
out, groups = [], {}
|
|
153
|
+
for ti, tgt in enumerate(num):
|
|
154
|
+
others = [j for j in range(len(num)) if j != ti]
|
|
155
|
+
if len(others) < 2:
|
|
156
|
+
continue
|
|
157
|
+
if len(others) > MAX_PARTS:
|
|
158
|
+
# too many columns to try every subset: keep the ones most related to the target (by |correlation|)
|
|
159
|
+
with np.errstate(invalid="ignore", divide="ignore"):
|
|
160
|
+
cor = np.nan_to_num(np.abs(np.corrcoef(X[:, [ti] + others].T)[0, 1:]))
|
|
161
|
+
others = [others[i] for i in np.argsort(-cor, kind="stable")[:MAX_PARTS]]
|
|
162
|
+
subs = [s for r in range(2, len(others) + 1) for s in itertools.combinations(range(len(others)), r)]
|
|
163
|
+
M = np.zeros((len(others), len(subs)), dtype=np.float64)
|
|
164
|
+
for c, s in enumerate(subs):
|
|
165
|
+
M[list(s), c] = 1
|
|
166
|
+
if _best_subset(quick, ti, others, M)[0] < 0.3: # a quick look on a few rows: clearly not a total
|
|
167
|
+
continue
|
|
168
|
+
hold, parts = _best_subset(X, ti, others, M)
|
|
169
|
+
if hold >= need:
|
|
170
|
+
out.append(dict(type="sum", a=tgt, parts=[num[j] for j in parts], when={}))
|
|
171
|
+
continue
|
|
172
|
+
if hold < 0.5: # no sum is even roughly there: this column is not a total
|
|
173
|
+
continue
|
|
174
|
+
best = (0.0, [])
|
|
175
|
+
splits = [(c,) for c in code if pool[c].nunique() <= 20]
|
|
176
|
+
splits += [p for p in itertools.combinations([s[0] for s in splits], 2)]
|
|
177
|
+
for cols in splits:
|
|
178
|
+
if len(cols) == 2 and best[0] >= 0.9:
|
|
179
|
+
break
|
|
180
|
+
if cols not in groups: # group number of every row; -1 where a key is empty
|
|
181
|
+
groups[cols] = pool.groupby(list(cols), observed=True, sort=False).ngroup().to_numpy()
|
|
182
|
+
gid = groups[cols]
|
|
183
|
+
ids, counts = np.unique(gid[gid >= 0], return_counts=True)
|
|
184
|
+
found, cover = [], 0.0
|
|
185
|
+
for g, n in sorted(zip(ids, counts), key=lambda x: -x[1]):
|
|
186
|
+
sup = n / len(pool)
|
|
187
|
+
if sup < min_support:
|
|
188
|
+
break
|
|
189
|
+
m = gid == g
|
|
190
|
+
h, p = _best_subset(X[m], ti, others, M)
|
|
191
|
+
if h >= need:
|
|
192
|
+
key = pool.iloc[int(np.argmax(m))]
|
|
193
|
+
found.append(dict(type="sum", a=tgt, parts=[num[j] for j in p],
|
|
194
|
+
when={c: (key[c].item() if hasattr(key[c], "item") else key[c]) for c in cols}))
|
|
195
|
+
cover += sup
|
|
196
|
+
if cover > best[0] + 0.05:
|
|
197
|
+
best = (cover, found)
|
|
198
|
+
out += best[1]
|
|
199
|
+
return out
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def candidates(hist, refs, skip=(), overrides=None):
|
|
203
|
+
"""Candidate rules from the pooled history (a sample of rows)."""
|
|
204
|
+
pool = pd.concat([df.sample(min(len(df), 3000), random_state=0) for _, df in hist], ignore_index=True)
|
|
205
|
+
last = hist[-1][1]
|
|
206
|
+
k = kinds(pool, overrides)
|
|
207
|
+
# float columns holding a few whole numbers count as codes AND as numbers (a fee of exactly 1.00 is both)
|
|
208
|
+
num = [c for c, v in k.items() if v == "numeric" or (v == "code" and pd.api.types.is_float_dtype(pool[c]))]
|
|
209
|
+
code = [c for c, v in k.items() if v == "code"]
|
|
210
|
+
time = [c for c, v in k.items() if v == "time"]
|
|
211
|
+
# key columns: codes, and whole-number or text columns with many values (e.g. thousands of airport ids)
|
|
212
|
+
keycols = code + [c for c, v in k.items() if v == "other" and _is_key(pool[c])]
|
|
213
|
+
out = []
|
|
214
|
+
if "sum" not in skip:
|
|
215
|
+
out += sum_identities(pool, num, code)
|
|
216
|
+
if "reference" not in skip:
|
|
217
|
+
for c in keycols:
|
|
218
|
+
for rn, keys in refs.items():
|
|
219
|
+
# a column refers to a table only if it holds most of its values AND uses many of its keys: a good
|
|
220
|
+
# share of a small table, or at least 100 keys of a big one (a 1-to-6 code would otherwise "refer"
|
|
221
|
+
# to any table whose keys start at 1; a real key column uses only part of a big national list)
|
|
222
|
+
if _in_ref(pool[c].dropna(), keys).mean() >= 0.95 and pool[c].nunique() >= min(0.3 * len(keys), 100):
|
|
223
|
+
out.append(dict(type="reference", a=c, ref=rn))
|
|
224
|
+
if "domain" not in skip:
|
|
225
|
+
for c in code:
|
|
226
|
+
if pool[c].nunique() <= 50:
|
|
227
|
+
out.append(dict(type="domain", a=c))
|
|
228
|
+
if "order" not in skip:
|
|
229
|
+
for a, b in itertools.permutations(time, 2):
|
|
230
|
+
out.append(dict(type="order", a=a, b=b))
|
|
231
|
+
P = pool[num].to_numpy(dtype=np.float64)
|
|
232
|
+
for i, j in itertools.permutations(range(len(num)), 2):
|
|
233
|
+
x, y = P[:, i], P[:, j]
|
|
234
|
+
with np.errstate(invalid="ignore"):
|
|
235
|
+
if ((x <= y) | np.isnan(x) | np.isnan(y)).mean() >= 0.99 and (x < y).mean() > 0.05:
|
|
236
|
+
out.append(dict(type="order", a=num[i], b=num[j]))
|
|
237
|
+
if "zero_when" not in skip:
|
|
238
|
+
for a in code:
|
|
239
|
+
vc = pool[a].value_counts(normalize=True)
|
|
240
|
+
for v in vc[(vc >= 0.01) & (vc.index.notna())].index:
|
|
241
|
+
m = pool[a] == v
|
|
242
|
+
for b in num:
|
|
243
|
+
if b == a:
|
|
244
|
+
continue
|
|
245
|
+
if (pool.loc[m, b].fillna(0).abs() <= 0.0001).mean() >= 0.99 and (pool.loc[~m, b].fillna(0).abs() > 0.0001).mean() > 0.2:
|
|
246
|
+
out.append(dict(type="zero_when", a=a, v=v.item() if hasattr(v, "item") else v, b=b))
|
|
247
|
+
if "not_null" not in skip:
|
|
248
|
+
for c in pool.columns:
|
|
249
|
+
if pool[c].isna().mean() <= 0.01:
|
|
250
|
+
out.append(dict(type="not_null", a=c))
|
|
251
|
+
if "batch_day" not in skip:
|
|
252
|
+
for c in time:
|
|
253
|
+
out.append(dict(type="batch_day", a=c))
|
|
254
|
+
if "unique" not in skip:
|
|
255
|
+
for c in last.columns:
|
|
256
|
+
s = last[c].dropna()
|
|
257
|
+
if _is_key(last[c]) and len(s) >= 30 and s.duplicated().mean() <= 0.001:
|
|
258
|
+
out.append(dict(type="unique", a=c))
|
|
259
|
+
if "no_duplicate_rows" not in skip:
|
|
260
|
+
out.append(dict(type="no_duplicate_rows"))
|
|
261
|
+
if "determines" not in skip:
|
|
262
|
+
deps = [c for c in code if 2 <= pool[c].nunique() <= 50]
|
|
263
|
+
for a in keycols:
|
|
264
|
+
na = pool[a].nunique()
|
|
265
|
+
if na < 2 or na > 20000 or na > len(pool) / 5: # a must repeat, or it "decides" everything
|
|
266
|
+
continue
|
|
267
|
+
for b in deps:
|
|
268
|
+
if a == b:
|
|
269
|
+
continue
|
|
270
|
+
sub = pool[[a, b]].dropna()
|
|
271
|
+
if len(sub) < 100 or 1 - sub[b].value_counts(normalize=True).iloc[0] < 0.05:
|
|
272
|
+
continue # b is almost one value: nothing to decide
|
|
273
|
+
cnt = sub.groupby([a, b], observed=True).size()
|
|
274
|
+
if cnt.groupby(level=0).max().sum() / len(sub) >= 0.99:
|
|
275
|
+
out.append(dict(type="determines", a=a, b=b))
|
|
276
|
+
return out
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _lookup(hist, a, b):
|
|
280
|
+
"""The value of b that goes with each value of a, over all of history."""
|
|
281
|
+
allh = pd.concat([df[[a, b]] for _, df in hist], ignore_index=True).dropna()
|
|
282
|
+
cnt = allh.groupby([a, b], observed=True).size().reset_index(name="n").sort_values("n")
|
|
283
|
+
top = cnt.drop_duplicates(a, keep="last")
|
|
284
|
+
return [[_plain(x), _plain(y)] for x, y in zip(top[a], top[b])]
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def mine(hist, refs, skip=(), overrides=None):
|
|
288
|
+
"""hist: list of (day, DataFrame). Returns the rules that held in every history batch, each with its worst
|
|
289
|
+
history violation rate (the frozen tolerance). skip: rule kinds to leave out. overrides: {column: kind}."""
|
|
290
|
+
kept = []
|
|
291
|
+
for idn in candidates(hist, refs, skip, overrides):
|
|
292
|
+
if idn["type"] == "domain":
|
|
293
|
+
idn["values"] = sorted(set(pd.concat([df[idn["a"]].dropna() for _, df in hist]).unique().tolist()))
|
|
294
|
+
if idn["type"] == "determines":
|
|
295
|
+
idn["pairs"] = _lookup(hist, idn["a"], idn["b"])
|
|
296
|
+
rates = [rate(idn, df, day, refs) for day, df in hist]
|
|
297
|
+
if max(rates) <= MAX_RATE:
|
|
298
|
+
idn["hist_max"] = max(rates)
|
|
299
|
+
kept.append(idn)
|
|
300
|
+
return kept
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def level(r, h):
|
|
304
|
+
"""How badly a rule with history tolerance h is broken at rate r: 'clear', 'slight' or None."""
|
|
305
|
+
if r > max(3 * h, h + 0.01):
|
|
306
|
+
return "clear"
|
|
307
|
+
if r > max(1.5 * h, h + 0.002):
|
|
308
|
+
return "slight"
|
|
309
|
+
return None
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def check(ids, df, day, refs):
|
|
313
|
+
"""-> list of (rule, rate, level) for rules broken in this batch. level 'clear' or 'slight'."""
|
|
314
|
+
out = []
|
|
315
|
+
for idn in ids:
|
|
316
|
+
r = rate(idn, df, day, refs)
|
|
317
|
+
lv = level(r, idn["hist_max"])
|
|
318
|
+
if lv:
|
|
319
|
+
out.append((idn, r, lv))
|
|
320
|
+
return out
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def columns(idn):
|
|
324
|
+
"""The columns a rule reads."""
|
|
325
|
+
cols = [idn.get("a")] + ([idn["b"]] if "b" in idn else []) + list(idn.get("parts", [])) + list(idn.get("when", {}))
|
|
326
|
+
return [c for c in cols if c is not None]
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def describe(idn):
|
|
330
|
+
t = idn["type"]
|
|
331
|
+
if t == "sum":
|
|
332
|
+
w = idn.get("when") or {}
|
|
333
|
+
return "%s = %s%s" % (idn["a"], " + ".join(idn["parts"]),
|
|
334
|
+
(" when " + ", ".join("%s=%s" % kv for kv in w.items())) if w else "")
|
|
335
|
+
if t == "reference":
|
|
336
|
+
return "%s in %s" % (idn["a"], idn["ref"])
|
|
337
|
+
if t == "domain":
|
|
338
|
+
return "%s in its %d known values" % (idn["a"], len(idn["values"]))
|
|
339
|
+
if t == "order":
|
|
340
|
+
return "%s <= %s" % (idn["a"], idn["b"])
|
|
341
|
+
if t == "zero_when":
|
|
342
|
+
return "%s = 0 when %s = %s" % (idn["b"], idn["a"], idn["v"])
|
|
343
|
+
if t == "not_null":
|
|
344
|
+
return "%s never empty" % idn["a"]
|
|
345
|
+
if t == "unique":
|
|
346
|
+
return "%s has no repeated values" % idn["a"]
|
|
347
|
+
if t == "no_duplicate_rows":
|
|
348
|
+
return "no fully duplicated rows"
|
|
349
|
+
if t == "determines":
|
|
350
|
+
return "each %s has one %s (%d known)" % (idn["a"], idn["b"], len(idn["pairs"]))
|
|
351
|
+
return "date(%s) = batch day" % idn["a"]
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _plain(v):
|
|
355
|
+
"""numpy / pandas scalars -> plain Python, so rules can be saved as JSON."""
|
|
356
|
+
if isinstance(v, dict):
|
|
357
|
+
return {str(a): _plain(b) for a, b in v.items()}
|
|
358
|
+
if isinstance(v, (list, tuple)):
|
|
359
|
+
return [_plain(x) for x in v]
|
|
360
|
+
if isinstance(v, pd.Timestamp):
|
|
361
|
+
return v.isoformat()
|
|
362
|
+
if hasattr(v, "item"):
|
|
363
|
+
return v.item()
|
|
364
|
+
return v
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def to_dict(idn):
|
|
368
|
+
return {k: _plain(v) for k, v in idn.items() if not k.startswith("_")}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: batchgate
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Block bad data batches on broken rules, not on ordinary change
|
|
5
|
+
Author: Muhammad Kashif Irshad
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/mkirshad/batchgate
|
|
8
|
+
Project-URL: Issues, https://github.com/mkirshad/batchgate/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/mkirshad/batchgate/blob/main/CHANGELOG.md
|
|
10
|
+
Keywords: data quality,data validation,data engineering,data pipelines,pandas,anomaly detection
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Database
|
|
15
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Requires-Dist: pandas>=1.5
|
|
20
|
+
Requires-Dist: numpy>=1.23
|
|
21
|
+
Provides-Extra: parquet
|
|
22
|
+
Requires-Dist: pyarrow; extra == "parquet"
|
|
23
|
+
Provides-Extra: test
|
|
24
|
+
Requires-Dist: pytest; extra == "test"
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# batchgate
|
|
28
|
+
|
|
29
|
+
[](https://github.com/mkirshad/batchgate/actions/workflows/tests.yml)
|
|
30
|
+
|
|
31
|
+
**Block bad data batches on broken rules, not on ordinary change.**
|
|
32
|
+
|
|
33
|
+
Daily data loads go wrong in quiet ways: a part of a total is dropped, codes fall outside the lookup table, a sign
|
|
34
|
+
flips, rows arrive twice, yesterday's file is delivered again. Drift monitors catch some of this, but they also fire
|
|
35
|
+
on every holiday, weekend and busy day, so teams learn to ignore them.
|
|
36
|
+
|
|
37
|
+
batchgate learns rules that held in **every** past batch (for example `total = net + tax + shipping`,
|
|
38
|
+
`store in stores table`, `tax = 0 when exempt = 1`, `each store has one region`), freezes them in a file, and blocks
|
|
39
|
+
a new batch only when one of those rules breaks. Ordinary drift is logged; only extreme drift blocks on its own.
|
|
40
|
+
Every alarm says which rule broke and on what share of rows.
|
|
41
|
+
|
|
42
|
+
```
|
|
43
|
+
BLOCK: 1 rule(s) clearly broken
|
|
44
|
+
clear total = net + tax + shipping (10.12% of rows, history at most 0.00%)
|
|
45
|
+
drift: largest z 2.1 on tax.mean
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Install
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
pip install git+https://github.com/mkirshad/batchgate # pandas + numpy; add pyarrow for .parquet files
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Use
|
|
55
|
+
|
|
56
|
+
From the command line:
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
# learn from history (one batch per day of a date column, or one file per batch)
|
|
60
|
+
batchgate fit history.parquet --split-by order_date -o rules.json --ref stores=stores.csv:store_id
|
|
61
|
+
batchgate show rules.json # numbered list of the rules
|
|
62
|
+
batchgate drop rules.json 12 # remove a rule you do not want
|
|
63
|
+
|
|
64
|
+
# check today's batch: exit code 1 = block, 0 = pass
|
|
65
|
+
batchgate check today.csv -r rules.json --ref stores=stores.csv:store_id --day 2024-04-01
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
From Python:
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from batchgate import Gate
|
|
72
|
+
|
|
73
|
+
gate = Gate.fit(past_batches, refs={"stores": set(store_ids)}) # list of (day, DataFrame), oldest first
|
|
74
|
+
gate.save("rules.json") # frozen: never re-learned from checked batches
|
|
75
|
+
|
|
76
|
+
verdict = Gate.load("rules.json").check(today_df, day=today, refs={"stores": set(store_ids)})
|
|
77
|
+
if verdict.block:
|
|
78
|
+
raise RuntimeError(str(verdict))
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Use at least 5 past batches; 30 or more, covering the seasons you will check, is better. Learning takes a minute or
|
|
82
|
+
two on tables with a few dozen columns and 100,000 rows per batch; checking a batch takes well under a second.
|
|
83
|
+
|
|
84
|
+
## Rules it looks for
|
|
85
|
+
|
|
86
|
+
| Kind | Example |
|
|
87
|
+
|---|---|
|
|
88
|
+
| `sum` (also per group of a small code column) | `total = net + tax + shipping when vendor = 2` |
|
|
89
|
+
| `reference` | `store in stores` |
|
|
90
|
+
| `domain` | `payment_type in its 6 known values` |
|
|
91
|
+
| `order` | `pickup_time <= dropoff_time`, `taxi_in <= elapsed_time` |
|
|
92
|
+
| `zero_when` | `tip = 0 when payment_type = 3` |
|
|
93
|
+
| `not_null` | `order_id never empty` |
|
|
94
|
+
| `batch_day` | `date(order_time) = batch day` |
|
|
95
|
+
| `unique` | `order_id has no repeated values` |
|
|
96
|
+
| `no_duplicate_rows` | `no fully duplicated rows` |
|
|
97
|
+
| `determines` | `each store has one region` |
|
|
98
|
+
|
|
99
|
+
A rule is kept only if it held in at least 98% of rows of every past batch; its tolerance is the worst rate seen in
|
|
100
|
+
history. A batch is blocked if a rule breaks clearly (above 3x its tolerance and at least 1 point more), or slightly
|
|
101
|
+
while drift is unusual, or if drift alone is extreme (z > 8). It is also blocked if it is empty, if a column the rules
|
|
102
|
+
read is missing, or if a column no longer holds its type (text where numbers were). These thresholds are fixed, not
|
|
103
|
+
tuned per dataset.
|
|
104
|
+
|
|
105
|
+
Controls:
|
|
106
|
+
|
|
107
|
+
- `Gate.fit(..., skip=["order"])` or `batchgate fit --skip order,unique` leaves rule kinds out.
|
|
108
|
+
- `gate.drop(12)` or `batchgate drop rules.json 12` removes single rules.
|
|
109
|
+
- `Gate.fit(..., kinds={"qty": "numeric"})` or `--numeric qty,units` lets whole-number amount columns take part in
|
|
110
|
+
sum and order rules (whole numbers are read as codes or keys by default).
|
|
111
|
+
- `Gate.fit(..., drift_block=None)` or `batchgate check --rules-only` never blocks on drift alone.
|
|
112
|
+
|
|
113
|
+
## How well it works
|
|
114
|
+
|
|
115
|
+
Three public datasets, January to March 2024 as history and every day of April to June 2024 as test, with 12 kinds of
|
|
116
|
+
fault injected into 30 test days at 10% and 100% of rows (720 bad batches and 91 clean ones per dataset). Each cell
|
|
117
|
+
is *false alarms on clean batches / faults caught*.
|
|
118
|
+
|
|
119
|
+
| Dataset | batchgate 0.2 | batchgate 0.2, rules only | Drift monitor, usual setting (k=3) | Drift monitor, threshold picked on the test |
|
|
120
|
+
|---|---|---|---|---|
|
|
121
|
+
| NYC yellow taxi trips (about 122,000 rows a day) | 8.8% / 83.9% | 2.2% / 75.8% | 75.8% / 90.3% | 2.2% / 31.1% |
|
|
122
|
+
| US airline on-time flights (about 20,000 a day) | 0.0% / 82.2% | 0.0% / 69.6% | 54.9% / 78.6% | 0.0% / 37.5% |
|
|
123
|
+
| US EIA-930 power grid, hourly (about 1,500 a day) | 4.4% / 95.8% | 4.4% / 71.7% | 74.7% / 89.0% | 0.0% / 54.2% |
|
|
124
|
+
|
|
125
|
+
How to read this honestly:
|
|
126
|
+
|
|
127
|
+
- The drift monitor is a re-implementation in the style of Deequ's anomaly checks, not Deequ itself.
|
|
128
|
+
- batchgate was built and improved on these three datasets. Version 0.1 was tested on the grid data before that data
|
|
129
|
+
had been looked at (3.3% / 87.8%); version 0.2 fixes and adds rules after seeing all three, so its numbers are not a
|
|
130
|
+
clean test. Expect less on your data.
|
|
131
|
+
- On the taxi data 6 of the 8 false alarms come from the extreme-drift block (a few very large fares on a day), not
|
|
132
|
+
from rules. `--rules-only` avoids them at the cost of some recall.
|
|
133
|
+
|
|
134
|
+
**Where it is weak.** Faults that keep every rule true are left to the drift log: a unit change on a column with no
|
|
135
|
+
rule, rows that are simply missing, a column emptied that already had gaps. Data whose rules are only nearly true
|
|
136
|
+
gives fewer rules (the grid's generation-by-fuel sum holds on 82% of rows). Rules learned in winter can break in
|
|
137
|
+
summer (all grid false alarms are of this kind): learn from history that covers the seasons you will check, and drop
|
|
138
|
+
rules that turn out to be seasonal. Order rules between unrelated columns (`delay <= distance`) are harmless noise;
|
|
139
|
+
`--skip order` removes them.
|
|
140
|
+
|
|
141
|
+
## Related work
|
|
142
|
+
|
|
143
|
+
batchgate combines known ideas; it does not claim a new method.
|
|
144
|
+
|
|
145
|
+
- Fariha, Tiwari, Radhakrishna, Gulwani, Meliou. *Conformance Constraint Discovery: Measuring Trust in Data-Driven
|
|
146
|
+
Systems.* SIGMOD 2021. Learned linear constraints among numeric columns, including per-partition constraints; the
|
|
147
|
+
basis of the sum rules here.
|
|
148
|
+
- Tu, He, Cui, et al. *Auto-Validate by-History: Auto-Program Data Quality Constraints to Validate Recurring Data
|
|
149
|
+
Pipelines.* KDD 2023. Automatic, history-based constraints with a target false-positive rate for recurring
|
|
150
|
+
pipelines (column statistics rather than row rules).
|
|
151
|
+
- Schelter et al. *Automating Large-Scale Data Quality Verification.* VLDB 2018 (Amazon Deequ). Breck et al. *Data
|
|
152
|
+
Validation for Machine Learning.* MLSys 2019 (TensorFlow Data Validation).
|
|
153
|
+
- Functional-dependency and denial-constraint discovery (TANE, 1999; Hydra, PVLDB 2017; DCFinder, PVLDB 2019) for
|
|
154
|
+
the lookup and order rules.
|
|
155
|
+
- The framing, block on damage rather than on difference, comes from danger theory in artificial immune systems
|
|
156
|
+
(Matzinger 1994; Aickelin and Cayzer 2002).
|
|
157
|
+
|
|
158
|
+
## License
|
|
159
|
+
|
|
160
|
+
MIT
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
batchgate/__init__.py,sha256=MsEo9srwsIo8zD9eVd0_SOzPfFA-pxSMN8QCxbog9ZU,182
|
|
2
|
+
batchgate/cli.py,sha256=bKVw4eFQyt1FlMtvFan3bsPyslZxELgoG7SWFYQ7V2s,4520
|
|
3
|
+
batchgate/drift.py,sha256=nfRGz2ZuALKv_YyQqrYbiFLN6JBNWvMs-H1YDWoG3x8,2075
|
|
4
|
+
batchgate/gate.py,sha256=iQIAj2GU1Sklbd-xplhDaCMDTIif1BoHx0tZ-FkiFw0,8023
|
|
5
|
+
batchgate/rules.py,sha256=VVm1m9Ni3XTDQJ27KgoJCPtJetAojLGuo8kZIqFMFno,17329
|
|
6
|
+
batchgate-0.2.0.dist-info/licenses/LICENSE,sha256=ezOhQ3u0_LE8NNOW0a098ccYn-3XaWya8Tf2NQMu0gE,1079
|
|
7
|
+
batchgate-0.2.0.dist-info/METADATA,sha256=j-o5vWgCLXRzy4LKsWNyklqvp4qmRRgVKEA9ynZ0ONQ,8088
|
|
8
|
+
batchgate-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
batchgate-0.2.0.dist-info/entry_points.txt,sha256=fXgmG_vewIgibfUc_kIXW_d-FtK8p1TK9quPEkPHpuk,49
|
|
10
|
+
batchgate-0.2.0.dist-info/top_level.txt,sha256=m0ZsWm7pkOoIDp5BgcXPLJSlytW8ihTBH33MFfozUTc,10
|
|
11
|
+
batchgate-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Muhammad Kashif Irshad
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
batchgate
|