batchgate 0.2.0__tar.gz

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.
@@ -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,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
+ [![tests](https://github.com/mkirshad/batchgate/actions/workflows/tests.yml/badge.svg)](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,134 @@
1
+ # batchgate
2
+
3
+ [![tests](https://github.com/mkirshad/batchgate/actions/workflows/tests.yml/badge.svg)](https://github.com/mkirshad/batchgate/actions/workflows/tests.yml)
4
+
5
+ **Block bad data batches on broken rules, not on ordinary change.**
6
+
7
+ Daily data loads go wrong in quiet ways: a part of a total is dropped, codes fall outside the lookup table, a sign
8
+ flips, rows arrive twice, yesterday's file is delivered again. Drift monitors catch some of this, but they also fire
9
+ on every holiday, weekend and busy day, so teams learn to ignore them.
10
+
11
+ batchgate learns rules that held in **every** past batch (for example `total = net + tax + shipping`,
12
+ `store in stores table`, `tax = 0 when exempt = 1`, `each store has one region`), freezes them in a file, and blocks
13
+ a new batch only when one of those rules breaks. Ordinary drift is logged; only extreme drift blocks on its own.
14
+ Every alarm says which rule broke and on what share of rows.
15
+
16
+ ```
17
+ BLOCK: 1 rule(s) clearly broken
18
+ clear total = net + tax + shipping (10.12% of rows, history at most 0.00%)
19
+ drift: largest z 2.1 on tax.mean
20
+ ```
21
+
22
+ ## Install
23
+
24
+ ```bash
25
+ pip install git+https://github.com/mkirshad/batchgate # pandas + numpy; add pyarrow for .parquet files
26
+ ```
27
+
28
+ ## Use
29
+
30
+ From the command line:
31
+
32
+ ```bash
33
+ # learn from history (one batch per day of a date column, or one file per batch)
34
+ batchgate fit history.parquet --split-by order_date -o rules.json --ref stores=stores.csv:store_id
35
+ batchgate show rules.json # numbered list of the rules
36
+ batchgate drop rules.json 12 # remove a rule you do not want
37
+
38
+ # check today's batch: exit code 1 = block, 0 = pass
39
+ batchgate check today.csv -r rules.json --ref stores=stores.csv:store_id --day 2024-04-01
40
+ ```
41
+
42
+ From Python:
43
+
44
+ ```python
45
+ from batchgate import Gate
46
+
47
+ gate = Gate.fit(past_batches, refs={"stores": set(store_ids)}) # list of (day, DataFrame), oldest first
48
+ gate.save("rules.json") # frozen: never re-learned from checked batches
49
+
50
+ verdict = Gate.load("rules.json").check(today_df, day=today, refs={"stores": set(store_ids)})
51
+ if verdict.block:
52
+ raise RuntimeError(str(verdict))
53
+ ```
54
+
55
+ Use at least 5 past batches; 30 or more, covering the seasons you will check, is better. Learning takes a minute or
56
+ two on tables with a few dozen columns and 100,000 rows per batch; checking a batch takes well under a second.
57
+
58
+ ## Rules it looks for
59
+
60
+ | Kind | Example |
61
+ |---|---|
62
+ | `sum` (also per group of a small code column) | `total = net + tax + shipping when vendor = 2` |
63
+ | `reference` | `store in stores` |
64
+ | `domain` | `payment_type in its 6 known values` |
65
+ | `order` | `pickup_time <= dropoff_time`, `taxi_in <= elapsed_time` |
66
+ | `zero_when` | `tip = 0 when payment_type = 3` |
67
+ | `not_null` | `order_id never empty` |
68
+ | `batch_day` | `date(order_time) = batch day` |
69
+ | `unique` | `order_id has no repeated values` |
70
+ | `no_duplicate_rows` | `no fully duplicated rows` |
71
+ | `determines` | `each store has one region` |
72
+
73
+ 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
74
+ history. A batch is blocked if a rule breaks clearly (above 3x its tolerance and at least 1 point more), or slightly
75
+ 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
76
+ read is missing, or if a column no longer holds its type (text where numbers were). These thresholds are fixed, not
77
+ tuned per dataset.
78
+
79
+ Controls:
80
+
81
+ - `Gate.fit(..., skip=["order"])` or `batchgate fit --skip order,unique` leaves rule kinds out.
82
+ - `gate.drop(12)` or `batchgate drop rules.json 12` removes single rules.
83
+ - `Gate.fit(..., kinds={"qty": "numeric"})` or `--numeric qty,units` lets whole-number amount columns take part in
84
+ sum and order rules (whole numbers are read as codes or keys by default).
85
+ - `Gate.fit(..., drift_block=None)` or `batchgate check --rules-only` never blocks on drift alone.
86
+
87
+ ## How well it works
88
+
89
+ Three public datasets, January to March 2024 as history and every day of April to June 2024 as test, with 12 kinds of
90
+ fault injected into 30 test days at 10% and 100% of rows (720 bad batches and 91 clean ones per dataset). Each cell
91
+ is *false alarms on clean batches / faults caught*.
92
+
93
+ | Dataset | batchgate 0.2 | batchgate 0.2, rules only | Drift monitor, usual setting (k=3) | Drift monitor, threshold picked on the test |
94
+ |---|---|---|---|---|
95
+ | 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% |
96
+ | 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% |
97
+ | 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% |
98
+
99
+ How to read this honestly:
100
+
101
+ - The drift monitor is a re-implementation in the style of Deequ's anomaly checks, not Deequ itself.
102
+ - batchgate was built and improved on these three datasets. Version 0.1 was tested on the grid data before that data
103
+ 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
104
+ clean test. Expect less on your data.
105
+ - 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
106
+ from rules. `--rules-only` avoids them at the cost of some recall.
107
+
108
+ **Where it is weak.** Faults that keep every rule true are left to the drift log: a unit change on a column with no
109
+ rule, rows that are simply missing, a column emptied that already had gaps. Data whose rules are only nearly true
110
+ gives fewer rules (the grid's generation-by-fuel sum holds on 82% of rows). Rules learned in winter can break in
111
+ summer (all grid false alarms are of this kind): learn from history that covers the seasons you will check, and drop
112
+ rules that turn out to be seasonal. Order rules between unrelated columns (`delay <= distance`) are harmless noise;
113
+ `--skip order` removes them.
114
+
115
+ ## Related work
116
+
117
+ batchgate combines known ideas; it does not claim a new method.
118
+
119
+ - Fariha, Tiwari, Radhakrishna, Gulwani, Meliou. *Conformance Constraint Discovery: Measuring Trust in Data-Driven
120
+ Systems.* SIGMOD 2021. Learned linear constraints among numeric columns, including per-partition constraints; the
121
+ basis of the sum rules here.
122
+ - Tu, He, Cui, et al. *Auto-Validate by-History: Auto-Program Data Quality Constraints to Validate Recurring Data
123
+ Pipelines.* KDD 2023. Automatic, history-based constraints with a target false-positive rate for recurring
124
+ pipelines (column statistics rather than row rules).
125
+ - Schelter et al. *Automating Large-Scale Data Quality Verification.* VLDB 2018 (Amazon Deequ). Breck et al. *Data
126
+ Validation for Machine Learning.* MLSys 2019 (TensorFlow Data Validation).
127
+ - Functional-dependency and denial-constraint discovery (TANE, 1999; Hydra, PVLDB 2017; DCFinder, PVLDB 2019) for
128
+ the lookup and order rules.
129
+ - The framing, block on damage rather than on difference, comes from danger theory in artificial immune systems
130
+ (Matzinger 1994; Aickelin and Cayzer 2002).
131
+
132
+ ## License
133
+
134
+ MIT
@@ -0,0 +1,5 @@
1
+ """batchgate: block bad data batches on broken rules, not on ordinary change."""
2
+ from .gate import Gate, Verdict, Break
3
+
4
+ __all__ = ["Gate", "Verdict", "Break"]
5
+ __version__ = "0.2.0"
@@ -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())
@@ -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())
@@ -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"))