normbeat 0.1.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.
normbeat-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 normbeat
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,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: normbeat
3
+ Version: 0.1.0
4
+ Summary: Alerts for jobs that succeed but do nothing: learns each job's normal row count by day of week.
5
+ Author-email: normbeat <hello@normbeat.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://normbeat.com
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Topic :: System :: Monitoring
10
+ Classifier: Topic :: Database
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Dynamic: license-file
15
+
16
+ # normbeat (Python)
17
+
18
+ Alerts for jobs that succeed but do nothing. `normbeat` learns each job's normal output count **by day of week** and tells you when a run loads zero, far too little, or suspiciously much, with no thresholds to set.
19
+
20
+ Zero dependencies. Python 3.9+. MIT licensed.
21
+
22
+ ## Offline mode (no account)
23
+
24
+ Keep history in a local SQLite file and check each run:
25
+
26
+ ```sh
27
+ normbeat local check --name orders --count 48211
28
+ # OK: Loaded 48,211. Normal for Tuesdays (39k–56k).
29
+
30
+ normbeat local check --name orders --count 0
31
+ # ZERO: Loaded 0. Tuesdays usually load 39k–56k. (exit code 2)
32
+ ```
33
+
34
+ - Exit code `0` = normal or still learning, `2` = anomaly (zero / low / high). Use it to fail a pipeline step or trigger your own alert.
35
+ - `--period hourly` (or seconds) for jobs that run more than twice a day; they're compared by weekday + hour, with fallbacks while history builds up.
36
+ - `--at 2026-11-20T02:00` to record a run with its real time (useful for backfilling history).
37
+ - Anomalies are recorded but **not learned from**, so a week-long outage can't teach normbeat that zero is normal. If volume really changed for good, pass `--accept` and it becomes the new normal.
38
+ - History lives in `~/.normbeat/history.db` (`--db` or `NORMBEAT_DB` to change).
39
+
40
+ ## Hosted service (coming soon)
41
+
42
+ ```python
43
+ import normbeat
44
+
45
+ with normbeat.run("YOUR_CHECK_KEY") as r: # sends "start"; sends "fail" if the block raises
46
+ rows = load_orders()
47
+ r.count(rows) # sends success with the count
48
+ ```
49
+
50
+ Or from a shell job: `normbeat ping YOUR_CHECK_KEY --count 48211`.
51
+
52
+ The client never breaks your job: network problems are logged and ignored, with a 10-second timeout. Join the waitlist at https://normbeat.com.
53
+
54
+ ## How the normal range works
55
+
56
+ For each run, normbeat looks at the last 8 runs on the **same weekday** (or same weekday and hour for frequent jobs), takes the median and a robust spread (median absolute deviation), and flags a run only if it is **both** a statistical outlier **and** a big practical change:
57
+
58
+ | Alert | When |
59
+ |---|---|
60
+ | zero | count is 0 and zero isn't normal for that day (works from the first run) |
61
+ | too low | below the range **and** under 50% of the usual count |
62
+ | too high | above the range **and** over 150% of the usual count |
63
+
64
+ While a weekday has fewer than 5 runs, it's stricter (under 40% / at least 2×), and it needs at least 3 runs before low/high alerts start.
65
+
66
+ **Measured on 200 simulated noisy jobs** (±5–30% daily noise, half-volume weekends): 0.03% false alarms over 16,800 runs. Caught: zero rows 100%, duplicate loads (2×) 94%, loads at 30% of normal 88%, at 45% of normal 68%. Partial loads at 60% of normal are deliberately **not** flagged (4%); that's the price of near-zero false alarms.
67
+
68
+ Not handled yet: month-end spikes and public holidays.
69
+
70
+ ## Development
71
+
72
+ ```sh
73
+ PYTHONPATH=src python -m unittest discover -s tests
74
+ ```
@@ -0,0 +1,59 @@
1
+ # normbeat (Python)
2
+
3
+ Alerts for jobs that succeed but do nothing. `normbeat` learns each job's normal output count **by day of week** and tells you when a run loads zero, far too little, or suspiciously much, with no thresholds to set.
4
+
5
+ Zero dependencies. Python 3.9+. MIT licensed.
6
+
7
+ ## Offline mode (no account)
8
+
9
+ Keep history in a local SQLite file and check each run:
10
+
11
+ ```sh
12
+ normbeat local check --name orders --count 48211
13
+ # OK: Loaded 48,211. Normal for Tuesdays (39k–56k).
14
+
15
+ normbeat local check --name orders --count 0
16
+ # ZERO: Loaded 0. Tuesdays usually load 39k–56k. (exit code 2)
17
+ ```
18
+
19
+ - Exit code `0` = normal or still learning, `2` = anomaly (zero / low / high). Use it to fail a pipeline step or trigger your own alert.
20
+ - `--period hourly` (or seconds) for jobs that run more than twice a day; they're compared by weekday + hour, with fallbacks while history builds up.
21
+ - `--at 2026-11-20T02:00` to record a run with its real time (useful for backfilling history).
22
+ - Anomalies are recorded but **not learned from**, so a week-long outage can't teach normbeat that zero is normal. If volume really changed for good, pass `--accept` and it becomes the new normal.
23
+ - History lives in `~/.normbeat/history.db` (`--db` or `NORMBEAT_DB` to change).
24
+
25
+ ## Hosted service (coming soon)
26
+
27
+ ```python
28
+ import normbeat
29
+
30
+ with normbeat.run("YOUR_CHECK_KEY") as r: # sends "start"; sends "fail" if the block raises
31
+ rows = load_orders()
32
+ r.count(rows) # sends success with the count
33
+ ```
34
+
35
+ Or from a shell job: `normbeat ping YOUR_CHECK_KEY --count 48211`.
36
+
37
+ The client never breaks your job: network problems are logged and ignored, with a 10-second timeout. Join the waitlist at https://normbeat.com.
38
+
39
+ ## How the normal range works
40
+
41
+ For each run, normbeat looks at the last 8 runs on the **same weekday** (or same weekday and hour for frequent jobs), takes the median and a robust spread (median absolute deviation), and flags a run only if it is **both** a statistical outlier **and** a big practical change:
42
+
43
+ | Alert | When |
44
+ |---|---|
45
+ | zero | count is 0 and zero isn't normal for that day (works from the first run) |
46
+ | too low | below the range **and** under 50% of the usual count |
47
+ | too high | above the range **and** over 150% of the usual count |
48
+
49
+ While a weekday has fewer than 5 runs, it's stricter (under 40% / at least 2×), and it needs at least 3 runs before low/high alerts start.
50
+
51
+ **Measured on 200 simulated noisy jobs** (±5–30% daily noise, half-volume weekends): 0.03% false alarms over 16,800 runs. Caught: zero rows 100%, duplicate loads (2×) 94%, loads at 30% of normal 88%, at 45% of normal 68%. Partial loads at 60% of normal are deliberately **not** flagged (4%); that's the price of near-zero false alarms.
52
+
53
+ Not handled yet: month-end spikes and public holidays.
54
+
55
+ ## Development
56
+
57
+ ```sh
58
+ PYTHONPATH=src python -m unittest discover -s tests
59
+ ```
@@ -0,0 +1,27 @@
1
+ [build-system]
2
+ requires = ["setuptools>=69"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "normbeat"
7
+ version = "0.1.0"
8
+ description = "Alerts for jobs that succeed but do nothing: learns each job's normal row count by day of week."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.9"
12
+ dependencies = []
13
+ authors = [{ name = "normbeat", email = "hello@normbeat.com" }]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Topic :: System :: Monitoring",
17
+ "Topic :: Database",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://normbeat.com"
22
+
23
+ [project.scripts]
24
+ normbeat = "normbeat.cli:main"
25
+
26
+ [tool.setuptools.packages.find]
27
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,7 @@
1
+ """normbeat: alerts for jobs that succeed but do nothing."""
2
+ __version__ = "0.1.0"
3
+
4
+ from .baseline import Verdict, evaluate # noqa: E402
5
+ from .client import ping, run # noqa: E402
6
+
7
+ __all__ = ["ping", "run", "evaluate", "Verdict", "__version__"]
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,156 @@
1
+ """Learned normal range for a job's output count.
2
+
3
+ The reference implementation of the algorithm in docs/PRODUCT-DESIGN.md §6.
4
+ The hosted Go service is tested against this module's outputs, so keep the
5
+ two in sync: change the design doc, this file and its tests together.
6
+
7
+ Pure functions, standard library only, no I/O.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+ from datetime import datetime, timedelta
13
+ from statistics import median
14
+ from typing import Iterable, Optional, Sequence, Tuple
15
+
16
+ # All tuning constants in one place (design §6).
17
+ WINDOW = 8 # use the last N matching runs
18
+ MIN_SAMPLES = 3 # below this a bucket is still "learning"
19
+ K = 4.0 # spread multiplier for low/high bounds
20
+ MAD_SCALE = 1.4826 # makes MAD comparable to a standard deviation
21
+ REL_FLOOR = 0.05 # spread is at least 5% of the median ...
22
+ ABS_FLOOR = 1.0 # ... and at least 1
23
+ LOW_RATIO = 0.5 # "too low" also needs x < 50% of median
24
+ HIGH_RATIO = 1.5 # "too high" also needs x > 150% of median
25
+ FEW_SAMPLES = 5 # with fewer runs than this the range is uncertain, so ...
26
+ LOW_RATIO_FEW = 0.4 # ... "too low" needs x < 40% of median
27
+ HIGH_RATIO_FEW = 2.0 # ... and "too high" needs x >= 2x the median
28
+ DAILY_PERIOD_S = 12 * 3600 # jobs this slow or slower use day-of-week buckets
29
+ RECENT_DAYS = 7 # last-resort fallback window for frequent jobs
30
+
31
+ NORMAL = "normal"
32
+ ZERO = "zero"
33
+ LOW = "low"
34
+ HIGH = "high"
35
+ LEARNING = "learning"
36
+ ANOMALIES = frozenset({ZERO, LOW, HIGH})
37
+
38
+ Sample = Tuple[datetime, int]
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class Verdict:
43
+ verdict: str # normal | zero | low | high | learning
44
+ bucket: str # e.g. "dow:5" or "dow:5|h:02" or "h:02" or "recent"
45
+ samples: int # how many past runs the range is based on
46
+ median: Optional[float] = None
47
+ low: Optional[float] = None
48
+ high: Optional[float] = None
49
+
50
+ @property
51
+ def is_anomaly(self) -> bool:
52
+ return self.verdict in ANOMALIES
53
+
54
+ def explain(self, count: int) -> str:
55
+ """One human sentence, as used in alerts."""
56
+ if self.verdict == LEARNING:
57
+ if count == 0:
58
+ return "Loaded 0. Still learning this job's normal range."
59
+ return f"Loaded {count:,}. Still learning ({self.samples} of {MIN_SAMPLES} runs for {self._where()})."
60
+ rng = f"{_fmt(max(self.low, 0))}–{_fmt(self.high)}" if self.low is not None else "n/a"
61
+ where = self._where()
62
+ if self.verdict == ZERO:
63
+ return f"Loaded 0. {where.capitalize()} usually load {rng}." if self.low is not None else "Loaded 0."
64
+ if self.verdict == LOW:
65
+ return f"Loaded {count:,}, far below normal. {where.capitalize()} usually load {rng}."
66
+ if self.verdict == HIGH:
67
+ return f"Loaded {count:,}, far above normal. {where.capitalize()} usually load {rng}."
68
+ return f"Loaded {count:,}. Normal for {where} ({rng})."
69
+
70
+ def _where(self) -> str:
71
+ days = ["Mondays", "Tuesdays", "Wednesdays", "Thursdays", "Fridays", "Saturdays", "Sundays"]
72
+ parts = dict(p.split(":") for p in self.bucket.split("|")) if ":" in self.bucket else {}
73
+ if "dow" in parts and "h" in parts:
74
+ return f"{days[int(parts['dow'])]} at {parts['h']}:00"
75
+ if "dow" in parts:
76
+ return days[int(parts["dow"])]
77
+ if "h" in parts:
78
+ return f"runs at {parts['h']}:00"
79
+ return "recent runs"
80
+
81
+
82
+ def _fmt(v: float) -> str:
83
+ v = round(v)
84
+ if v >= 1_000_000:
85
+ return f"{v / 1_000_000:.1f}M"
86
+ if v >= 10_000:
87
+ return f"{v / 1000:.0f}k"
88
+ return f"{v:,}"
89
+
90
+
91
+ def _dow(ts: datetime) -> int:
92
+ return ts.weekday() # Monday = 0
93
+
94
+
95
+ def _pick_bucket(history: Sequence[Sample], ts: datetime, period_s: Optional[float]) -> Tuple[str, list]:
96
+ """Return (bucket label, matching past counts, newest last)."""
97
+ if period_s is None or period_s >= DAILY_PERIOD_S:
98
+ d = _dow(ts)
99
+ return f"dow:{d}", [c for t, c in history if _dow(t) == d]
100
+ d, h = _dow(ts), ts.hour
101
+ exact = [c for t, c in history if _dow(t) == d and t.hour == h]
102
+ if len(exact) >= MIN_SAMPLES:
103
+ return f"dow:{d}|h:{h:02d}", exact
104
+ same_hour = [c for t, c in history if t.hour == h]
105
+ if len(same_hour) >= MIN_SAMPLES:
106
+ return f"h:{h:02d}", same_hour
107
+ cutoff = ts - timedelta(days=RECENT_DAYS)
108
+ return "recent", [c for t, c in history if cutoff <= t < ts]
109
+
110
+
111
+ def evaluate(history: Iterable[Sample], ts: datetime, count: int,
112
+ period_s: Optional[float] = None) -> Verdict:
113
+ """Judge a new run's count against the job's own past.
114
+
115
+ history: past *accepted* runs as (timestamp, count); anomalies the user
116
+ didn't accept should be left out so an outage can't teach the
117
+ model that zero is normal.
118
+ ts: when the new run finished, in the job's local time zone.
119
+ count: the new run's count (>= 0).
120
+ period_s: how often the job runs, in seconds (None = treat as daily).
121
+ """
122
+ if count < 0:
123
+ raise ValueError("count must be >= 0")
124
+ past = sorted((t, c) for t, c in history if t < ts)
125
+ bucket, counts = _pick_bucket(past, ts, period_s)
126
+ recent = counts[-WINDOW:]
127
+ n = len(recent)
128
+
129
+ if n < MIN_SAMPLES:
130
+ if count == 0 and not (n and sum(1 for c in recent if c == 0) * 2 >= n):
131
+ return Verdict(ZERO, bucket, n)
132
+ return Verdict(LEARNING, bucket, n)
133
+
134
+ m = float(median(recent))
135
+ mad = float(median(abs(c - m) for c in recent))
136
+ s = max(MAD_SCALE * mad, REL_FLOOR * m, ABS_FLOOR)
137
+ low, high = m - K * s, m + K * s
138
+ zeros_normal = sum(1 for c in recent if c == 0) * 2 >= n
139
+
140
+ few = n < FEW_SAMPLES
141
+ low_ok = count < (LOW_RATIO_FEW if few else LOW_RATIO) * m
142
+ high_ok = count >= HIGH_RATIO_FEW * m if few else count > HIGH_RATIO * m
143
+
144
+ if count == 0 and not zeros_normal:
145
+ v = ZERO
146
+ elif count < low and low_ok:
147
+ v = LOW
148
+ elif count > high and high_ok:
149
+ v = HIGH
150
+ else:
151
+ v = NORMAL
152
+ # Report the effective alert boundaries (statistical AND practical), so
153
+ # "normal range" in messages and charts matches what actually alerts.
154
+ eff_low = max(min(low, (LOW_RATIO_FEW if few else LOW_RATIO) * m), 0.0)
155
+ eff_high = max(high, (HIGH_RATIO_FEW if few else HIGH_RATIO) * m)
156
+ return Verdict(v, bucket, n, m, eff_low, eff_high)
@@ -0,0 +1,84 @@
1
+ """normbeat command line.
2
+
3
+ normbeat ping KEY [--count N | --start | --fail]
4
+ normbeat local check --name NAME --count N [--period daily|hourly|SECONDS] [--at ISO] [--accept] [--db PATH]
5
+
6
+ Exit codes for `local check`: 0 normal/learning, 2 anomaly (zero/low/high), 1 usage error.
7
+ `ping` always exits 0 unless the arguments are wrong, so it can't fail a job.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import sys
13
+ from datetime import datetime
14
+ from pathlib import Path
15
+ from typing import List, Optional
16
+
17
+ from . import __version__
18
+ from .client import ping
19
+ from .local import PERIODS, check, connect
20
+
21
+
22
+ def _period(v: str) -> float:
23
+ if v in PERIODS:
24
+ return PERIODS[v]
25
+ try:
26
+ p = float(v)
27
+ except ValueError:
28
+ raise argparse.ArgumentTypeError("use daily, hourly or a number of seconds")
29
+ if p <= 0:
30
+ raise argparse.ArgumentTypeError("period must be positive")
31
+ return p
32
+
33
+
34
+ def _count(v: str) -> int:
35
+ try:
36
+ n = int(v)
37
+ except ValueError:
38
+ raise argparse.ArgumentTypeError("count must be a whole number")
39
+ if n < 0:
40
+ raise argparse.ArgumentTypeError("count must be >= 0")
41
+ return n
42
+
43
+
44
+ def main(argv: Optional[List[str]] = None) -> int:
45
+ p = argparse.ArgumentParser(prog="normbeat", description="Alerts for jobs that succeed but do nothing.")
46
+ p.add_argument("--version", action="version", version=f"normbeat {__version__}")
47
+ sub = p.add_subparsers(dest="cmd", required=True)
48
+
49
+ pp = sub.add_parser("ping", help="send a ping to the hosted service")
50
+ pp.add_argument("key")
51
+ g = pp.add_mutually_exclusive_group()
52
+ g.add_argument("--count", type=_count)
53
+ g.add_argument("--start", action="store_true")
54
+ g.add_argument("--fail", action="store_true")
55
+
56
+ lp = sub.add_parser("local", help="offline mode (no account)")
57
+ lsub = lp.add_subparsers(dest="lcmd", required=True)
58
+ lc = lsub.add_parser("check", help="judge a run's count against this job's history")
59
+ lc.add_argument("--name", required=True)
60
+ lc.add_argument("--count", required=True, type=_count)
61
+ lc.add_argument("--period", type=_period, default=None, help="daily (default), hourly, or seconds")
62
+ lc.add_argument("--at", type=datetime.fromisoformat, default=None, help="run time, ISO-8601 (default: now)")
63
+ lc.add_argument("--accept", action="store_true", help="treat this run as normal and learn from it")
64
+ lc.add_argument("--db", type=Path, default=None)
65
+
66
+ a = p.parse_args(argv)
67
+
68
+ if a.cmd == "ping":
69
+ kind = "start" if a.start else "fail" if a.fail else "success"
70
+ ping(a.key, count=a.count, kind=kind)
71
+ return 0
72
+
73
+ con = connect(a.db)
74
+ try:
75
+ v = check(con, a.name, a.count, ts=a.at, period_s=a.period, accept=a.accept)
76
+ finally:
77
+ con.close()
78
+ label = "OK" if not v.is_anomaly else v.verdict.upper()
79
+ print(f"{label}: {v.explain(a.count)}")
80
+ return 2 if v.is_anomaly else 0
81
+
82
+
83
+ if __name__ == "__main__":
84
+ sys.exit(main())
@@ -0,0 +1,84 @@
1
+ """Tiny client for the hosted normbeat ping API.
2
+
3
+ Design rule: monitoring must never break the job it monitors. Every call has a
4
+ short timeout and swallows network errors (they're logged, not raised).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import logging
9
+ import os
10
+ import urllib.error
11
+ import urllib.parse
12
+ import urllib.request
13
+ from typing import Optional
14
+
15
+ log = logging.getLogger("normbeat")
16
+
17
+ DEFAULT_URL = "https://ping.normbeat.com"
18
+ TIMEOUT_S = 10.0
19
+
20
+
21
+ def _base_url() -> str:
22
+ return os.environ.get("NORMBEAT_URL", DEFAULT_URL).rstrip("/")
23
+
24
+
25
+ def ping(key: str, count: Optional[int] = None, kind: str = "success",
26
+ timeout: float = TIMEOUT_S) -> bool:
27
+ """Send one ping. kind is "success", "start" or "fail".
28
+
29
+ Returns True if the server answered 2xx, False otherwise. Never raises
30
+ for network or server problems; raises ValueError only for programming
31
+ mistakes (bad kind, negative count, empty key) so they surface in tests.
32
+ """
33
+ if not key or "/" in key:
34
+ raise ValueError("invalid check key")
35
+ if kind not in ("success", "start", "fail"):
36
+ raise ValueError("kind must be 'success', 'start' or 'fail'")
37
+ if count is not None:
38
+ count = int(count)
39
+ if count < 0:
40
+ raise ValueError("count must be >= 0")
41
+
42
+ path = "/p/" + urllib.parse.quote(key, safe="")
43
+ if kind != "success":
44
+ path += "/" + kind
45
+ if count is not None and kind == "success":
46
+ path += "?" + urllib.parse.urlencode({"count": count})
47
+ req = urllib.request.Request(_base_url() + path, method="POST", data=b"",
48
+ headers={"User-Agent": "normbeat-python/0.1"})
49
+ try:
50
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
51
+ return 200 <= resp.status < 300
52
+ except (urllib.error.URLError, OSError, ValueError) as e: # ValueError: bad URL in env
53
+ log.warning("normbeat ping failed (%s): %s", kind, e)
54
+ return False
55
+
56
+
57
+ class run:
58
+ """Context manager: sends start, then success-with-count or fail.
59
+
60
+ with normbeat.run("KEY") as r:
61
+ rows = load()
62
+ r.count(rows)
63
+
64
+ An exception inside the block sends "fail" and is re-raised unchanged.
65
+ """
66
+
67
+ def __init__(self, key: str, timeout: float = TIMEOUT_S):
68
+ self.key = key
69
+ self.timeout = timeout
70
+ self._count: Optional[int] = None
71
+
72
+ def count(self, n: int) -> None:
73
+ self._count = int(n)
74
+
75
+ def __enter__(self) -> "run":
76
+ ping(self.key, kind="start", timeout=self.timeout)
77
+ return self
78
+
79
+ def __exit__(self, exc_type, exc, tb) -> bool:
80
+ if exc_type is None:
81
+ ping(self.key, count=self._count, timeout=self.timeout)
82
+ else:
83
+ ping(self.key, kind="fail", timeout=self.timeout)
84
+ return False # never swallow the job's own exception
@@ -0,0 +1,55 @@
1
+ """Offline mode: keep a job's history in a local SQLite file and judge each
2
+ new count with the same algorithm the hosted service uses. No account, no
3
+ network.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ import sqlite3
9
+ from datetime import datetime
10
+ from pathlib import Path
11
+ from typing import Optional
12
+
13
+ from .baseline import ANOMALIES, Verdict, evaluate
14
+
15
+ SCHEMA = """
16
+ CREATE TABLE IF NOT EXISTS runs (
17
+ name TEXT NOT NULL,
18
+ ts TEXT NOT NULL, -- ISO-8601 local time of the job
19
+ count INTEGER NOT NULL CHECK (count >= 0),
20
+ verdict TEXT NOT NULL,
21
+ accepted INTEGER NOT NULL -- 1 = part of the baseline
22
+ );
23
+ CREATE INDEX IF NOT EXISTS runs_name_ts ON runs (name, ts);
24
+ """
25
+
26
+ PERIODS = {"daily": 86400.0, "hourly": 3600.0}
27
+
28
+
29
+ def default_db() -> Path:
30
+ return Path(os.environ.get("NORMBEAT_DB", Path.home() / ".normbeat" / "history.db"))
31
+
32
+
33
+ def connect(path: Optional[Path] = None) -> sqlite3.Connection:
34
+ path = Path(path or default_db())
35
+ path.parent.mkdir(parents=True, exist_ok=True)
36
+ con = sqlite3.connect(str(path))
37
+ con.executescript(SCHEMA)
38
+ return con
39
+
40
+
41
+ def check(con: sqlite3.Connection, name: str, count: int, ts: Optional[datetime] = None,
42
+ period_s: Optional[float] = None, accept: bool = False) -> Verdict:
43
+ """Evaluate and record one run. Anomalies are recorded but kept out of the
44
+ baseline unless accept=True (the user says "this is normal now")."""
45
+ if not name:
46
+ raise ValueError("name is required")
47
+ ts = ts or datetime.now()
48
+ rows = con.execute("SELECT ts, count FROM runs WHERE name = ? AND accepted = 1", (name,)).fetchall()
49
+ history = [(datetime.fromisoformat(t), c) for t, c in rows]
50
+ v = evaluate(history, ts, count, period_s)
51
+ accepted = 1 if (accept or v.verdict not in ANOMALIES) else 0
52
+ with con:
53
+ con.execute("INSERT INTO runs (name, ts, count, verdict, accepted) VALUES (?, ?, ?, ?, ?)",
54
+ (name, ts.isoformat(timespec="seconds"), int(count), v.verdict, accepted))
55
+ return v
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: normbeat
3
+ Version: 0.1.0
4
+ Summary: Alerts for jobs that succeed but do nothing: learns each job's normal row count by day of week.
5
+ Author-email: normbeat <hello@normbeat.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://normbeat.com
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Topic :: System :: Monitoring
10
+ Classifier: Topic :: Database
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Dynamic: license-file
15
+
16
+ # normbeat (Python)
17
+
18
+ Alerts for jobs that succeed but do nothing. `normbeat` learns each job's normal output count **by day of week** and tells you when a run loads zero, far too little, or suspiciously much, with no thresholds to set.
19
+
20
+ Zero dependencies. Python 3.9+. MIT licensed.
21
+
22
+ ## Offline mode (no account)
23
+
24
+ Keep history in a local SQLite file and check each run:
25
+
26
+ ```sh
27
+ normbeat local check --name orders --count 48211
28
+ # OK: Loaded 48,211. Normal for Tuesdays (39k–56k).
29
+
30
+ normbeat local check --name orders --count 0
31
+ # ZERO: Loaded 0. Tuesdays usually load 39k–56k. (exit code 2)
32
+ ```
33
+
34
+ - Exit code `0` = normal or still learning, `2` = anomaly (zero / low / high). Use it to fail a pipeline step or trigger your own alert.
35
+ - `--period hourly` (or seconds) for jobs that run more than twice a day; they're compared by weekday + hour, with fallbacks while history builds up.
36
+ - `--at 2026-11-20T02:00` to record a run with its real time (useful for backfilling history).
37
+ - Anomalies are recorded but **not learned from**, so a week-long outage can't teach normbeat that zero is normal. If volume really changed for good, pass `--accept` and it becomes the new normal.
38
+ - History lives in `~/.normbeat/history.db` (`--db` or `NORMBEAT_DB` to change).
39
+
40
+ ## Hosted service (coming soon)
41
+
42
+ ```python
43
+ import normbeat
44
+
45
+ with normbeat.run("YOUR_CHECK_KEY") as r: # sends "start"; sends "fail" if the block raises
46
+ rows = load_orders()
47
+ r.count(rows) # sends success with the count
48
+ ```
49
+
50
+ Or from a shell job: `normbeat ping YOUR_CHECK_KEY --count 48211`.
51
+
52
+ The client never breaks your job: network problems are logged and ignored, with a 10-second timeout. Join the waitlist at https://normbeat.com.
53
+
54
+ ## How the normal range works
55
+
56
+ For each run, normbeat looks at the last 8 runs on the **same weekday** (or same weekday and hour for frequent jobs), takes the median and a robust spread (median absolute deviation), and flags a run only if it is **both** a statistical outlier **and** a big practical change:
57
+
58
+ | Alert | When |
59
+ |---|---|
60
+ | zero | count is 0 and zero isn't normal for that day (works from the first run) |
61
+ | too low | below the range **and** under 50% of the usual count |
62
+ | too high | above the range **and** over 150% of the usual count |
63
+
64
+ While a weekday has fewer than 5 runs, it's stricter (under 40% / at least 2×), and it needs at least 3 runs before low/high alerts start.
65
+
66
+ **Measured on 200 simulated noisy jobs** (±5–30% daily noise, half-volume weekends): 0.03% false alarms over 16,800 runs. Caught: zero rows 100%, duplicate loads (2×) 94%, loads at 30% of normal 88%, at 45% of normal 68%. Partial loads at 60% of normal are deliberately **not** flagged (4%); that's the price of near-zero false alarms.
67
+
68
+ Not handled yet: month-end spikes and public holidays.
69
+
70
+ ## Development
71
+
72
+ ```sh
73
+ PYTHONPATH=src python -m unittest discover -s tests
74
+ ```
@@ -0,0 +1,16 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/normbeat/__init__.py
5
+ src/normbeat/__main__.py
6
+ src/normbeat/baseline.py
7
+ src/normbeat/cli.py
8
+ src/normbeat/client.py
9
+ src/normbeat/local.py
10
+ src/normbeat.egg-info/PKG-INFO
11
+ src/normbeat.egg-info/SOURCES.txt
12
+ src/normbeat.egg-info/dependency_links.txt
13
+ src/normbeat.egg-info/entry_points.txt
14
+ src/normbeat.egg-info/top_level.txt
15
+ tests/test_baseline.py
16
+ tests/test_client_and_cli.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ normbeat = normbeat.cli:main
@@ -0,0 +1 @@
1
+ normbeat
@@ -0,0 +1,150 @@
1
+ """Algorithm tests: synthetic job histories modelled on the failure patterns
2
+ found in the 40 public incidents collected during validation."""
3
+ import random
4
+ import unittest
5
+ from datetime import datetime, timedelta
6
+
7
+ from normbeat.baseline import HIGH, LEARNING, LOW, NORMAL, ZERO, evaluate
8
+
9
+ MON = datetime(2026, 9, 7, 2, 0) # a Monday, 02:00
10
+
11
+
12
+ def daily(weeks, value_for_day, start=MON):
13
+ """History of a daily job: value_for_day(date) -> count."""
14
+ return [(start + timedelta(days=i), value_for_day(start + timedelta(days=i))) for i in range(weeks * 7)]
15
+
16
+
17
+ def weekday_weekend(rng=None):
18
+ rng = rng or random.Random(1)
19
+ def f(d):
20
+ if d.weekday() >= 5:
21
+ return rng.randint(20_000, 30_000)
22
+ return rng.randint(40_000, 54_000)
23
+ return f
24
+
25
+
26
+ class DailyJob(unittest.TestCase):
27
+ def setUp(self):
28
+ self.hist = daily(6, weekday_weekend())
29
+ self.next_sat = MON + timedelta(days=6 * 7 + 5) # Saturday after history
30
+ self.next_tue = MON + timedelta(days=6 * 7 + 1)
31
+
32
+ def test_quiet_saturday_is_normal_where_a_fixed_threshold_would_page(self):
33
+ v = evaluate(self.hist, self.next_sat, 24_000)
34
+ self.assertEqual(v.verdict, NORMAL)
35
+ self.assertEqual(v.bucket, "dow:5")
36
+ self.assertLess(24_000, 100_000) # the "alert if < 100k" rule from the research would fire
37
+
38
+ def test_empty_api_page_zero_rows(self):
39
+ self.assertEqual(evaluate(self.hist, self.next_tue, 0).verdict, ZERO)
40
+
41
+ def test_partial_file_far_too_low(self):
42
+ self.assertEqual(evaluate(self.hist, self.next_tue, 12_000).verdict, LOW)
43
+
44
+ def test_duplicate_load_suspiciously_high(self):
45
+ self.assertEqual(evaluate(self.hist, self.next_tue, 110_000).verdict, HIGH)
46
+
47
+ def test_weekday_volume_on_saturday_is_flagged_high(self):
48
+ # ~1.8x a normal Saturday: possibly a duplicate or a mis-scheduled run, worth a look
49
+ self.assertEqual(evaluate(self.hist, self.next_sat, 45_000).verdict, HIGH)
50
+
51
+ def test_exact_duplicate_flagged_even_with_few_samples(self):
52
+ hist = daily(3, lambda d: 1000)
53
+ self.assertEqual(evaluate(hist, MON + timedelta(days=21), 2000).verdict, HIGH)
54
+
55
+ def test_reported_range_matches_alerting(self):
56
+ for x in range(0, 120_000, 500):
57
+ v = evaluate(self.hist, self.next_tue, x)
58
+ inside = v.low <= x <= v.high
59
+ self.assertEqual(v.is_anomaly, not inside, (x, v))
60
+
61
+ def test_explanation_mentions_day_and_range(self):
62
+ v = evaluate(self.hist, self.next_sat, 0)
63
+ text = v.explain(0)
64
+ self.assertIn("Saturdays", text)
65
+ self.assertIn("Loaded 0", text)
66
+
67
+
68
+ class Learning(unittest.TestCase):
69
+ def test_first_runs_are_learning(self):
70
+ hist = daily(1, lambda d: 1000)[:5] # Mon..Fri once each
71
+ v = evaluate(hist, MON + timedelta(days=7), 1000)
72
+ self.assertEqual(v.verdict, LEARNING)
73
+
74
+ def test_zero_alerts_from_day_one(self):
75
+ self.assertEqual(evaluate([], MON, 0).verdict, ZERO)
76
+
77
+ def test_low_needs_three_samples(self):
78
+ hist = daily(2, lambda d: 1000) # 2 Mondays
79
+ self.assertEqual(evaluate(hist, MON + timedelta(days=14), 10).verdict, LEARNING)
80
+ hist = daily(3, lambda d: 1000) # 3 Mondays
81
+ self.assertEqual(evaluate(hist, MON + timedelta(days=21), 10).verdict, LOW)
82
+
83
+
84
+ class Edges(unittest.TestCase):
85
+ def test_steady_job_small_wobble_is_normal(self):
86
+ hist = daily(4, lambda d: 1000)
87
+ self.assertEqual(evaluate(hist, MON + timedelta(days=28), 1003).verdict, NORMAL)
88
+ self.assertEqual(evaluate(hist, MON + timedelta(days=28), 960).verdict, NORMAL)
89
+
90
+ def test_zeros_normal_bucket(self):
91
+ # job that loads nothing on Sundays by design
92
+ hist = daily(4, lambda d: 0 if d.weekday() == 6 else 5000)
93
+ sunday = MON + timedelta(days=28 + 6)
94
+ self.assertEqual(evaluate(hist, sunday, 0).verdict, NORMAL)
95
+ monday = MON + timedelta(days=28)
96
+ self.assertEqual(evaluate(hist, monday, 0).verdict, ZERO)
97
+
98
+ def test_growth_trend_no_alert(self):
99
+ hist = daily(8, lambda d: int(10_000 * (1.03 ** ((d - MON).days / 7))))
100
+ nxt = MON + timedelta(days=56)
101
+ v = evaluate(hist, nxt, int(10_000 * 1.03 ** 8))
102
+ self.assertEqual(v.verdict, NORMAL)
103
+
104
+ def test_noisy_job_few_false_alarms(self):
105
+ rng = random.Random(7)
106
+ hist, alarms, runs = [], 0, 0
107
+ for i in range(12 * 7):
108
+ ts = MON + timedelta(days=i)
109
+ c = int(20_000 * rng.uniform(0.7, 1.3))
110
+ v = evaluate(hist, ts, c)
111
+ if v.verdict in (LOW, HIGH, ZERO):
112
+ alarms += 1
113
+ runs += 1
114
+ hist.append((ts, c))
115
+ self.assertEqual(alarms, 0, f"{alarms} false alarms in {runs} runs")
116
+
117
+ def test_future_history_ignored(self):
118
+ hist = daily(4, lambda d: 1000)
119
+ v = evaluate(hist, MON + timedelta(days=1), 1000) # only 1 past Tuesday... and 0 future ones counted
120
+ self.assertEqual(v.verdict, LEARNING)
121
+
122
+ def test_negative_count_rejected(self):
123
+ with self.assertRaises(ValueError):
124
+ evaluate([], MON, -1)
125
+
126
+
127
+ class FrequentJob(unittest.TestCase):
128
+ START = MON.replace(hour=0)
129
+
130
+ def hourly(self, days, f):
131
+ return [(self.START + timedelta(hours=i), f(self.START + timedelta(hours=i))) for i in range(days * 24)]
132
+
133
+ def test_hourly_uses_hour_bucket_with_fallback(self):
134
+ # night hours quiet, day hours busy
135
+ f = lambda t: 50 if t.hour < 6 else 800
136
+ hist = self.hourly(10, f) # 10 days: <3 same-weekday-hour samples except dow 0..2
137
+ ts = self.START + timedelta(days=10, hours=3) # Thursday 03:00 -> only 1 Thu sample -> fallback to hour
138
+ v = evaluate(hist, ts, 50, period_s=3600)
139
+ self.assertEqual(v.bucket, "h:03")
140
+ self.assertEqual(v.verdict, NORMAL)
141
+ self.assertEqual(evaluate(hist, ts.replace(hour=14), 30, period_s=3600).verdict, LOW)
142
+
143
+ def test_hourly_exact_bucket_after_three_weeks(self):
144
+ hist = self.hourly(22, lambda t: 100)
145
+ ts = self.START + timedelta(days=21, hours=5) # 4th Monday 05:00
146
+ self.assertEqual(evaluate(hist, ts, 100, period_s=3600).bucket, "dow:0|h:05")
147
+
148
+
149
+ if __name__ == "__main__":
150
+ unittest.main()
@@ -0,0 +1,132 @@
1
+ import io
2
+ import os
3
+ import tempfile
4
+ import threading
5
+ import unittest
6
+ from contextlib import redirect_stdout
7
+ from datetime import datetime, timedelta
8
+ from http.server import BaseHTTPRequestHandler, HTTPServer
9
+ from pathlib import Path
10
+
11
+ import normbeat
12
+ from normbeat.cli import main
13
+
14
+
15
+ class Recorder(BaseHTTPRequestHandler):
16
+ paths = []
17
+
18
+ def do_POST(self):
19
+ Recorder.paths.append(self.path)
20
+ self.send_response(200)
21
+ self.end_headers()
22
+ self.wfile.write(b"OK")
23
+
24
+ def log_message(self, *a):
25
+ pass
26
+
27
+
28
+ class Client(unittest.TestCase):
29
+ @classmethod
30
+ def setUpClass(cls):
31
+ cls.srv = HTTPServer(("127.0.0.1", 0), Recorder)
32
+ threading.Thread(target=cls.srv.serve_forever, daemon=True).start()
33
+ os.environ["NORMBEAT_URL"] = f"http://127.0.0.1:{cls.srv.server_port}"
34
+
35
+ @classmethod
36
+ def tearDownClass(cls):
37
+ cls.srv.shutdown()
38
+ os.environ.pop("NORMBEAT_URL", None)
39
+
40
+ def setUp(self):
41
+ Recorder.paths.clear()
42
+
43
+ def test_ping_paths(self):
44
+ self.assertTrue(normbeat.ping("abc", count=42))
45
+ normbeat.ping("abc", kind="start")
46
+ normbeat.ping("abc", kind="fail")
47
+ normbeat.ping("abc")
48
+ self.assertEqual(Recorder.paths, ["/p/abc?count=42", "/p/abc/start", "/p/abc/fail", "/p/abc"])
49
+
50
+ def test_run_context_success_and_fail(self):
51
+ with normbeat.run("k1") as r:
52
+ r.count(7)
53
+ with self.assertRaises(RuntimeError):
54
+ with normbeat.run("k2"):
55
+ raise RuntimeError("job broke")
56
+ self.assertEqual(Recorder.paths, ["/p/k1/start", "/p/k1?count=7", "/p/k2/start", "/p/k2/fail"])
57
+
58
+ def test_key_is_escaped(self):
59
+ with self.assertRaises(ValueError):
60
+ normbeat.ping("../admin")
61
+ normbeat.ping("a b?c")
62
+ self.assertEqual(Recorder.paths, ["/p/a%20b%3Fc"])
63
+
64
+ def test_never_raises_when_server_down(self):
65
+ os.environ["NORMBEAT_URL"] = "http://127.0.0.1:9" # nothing listens
66
+ try:
67
+ self.assertFalse(normbeat.ping("abc", count=1, timeout=1))
68
+ with normbeat.run("abc", timeout=1) as r:
69
+ r.count(1)
70
+ finally:
71
+ os.environ["NORMBEAT_URL"] = f"http://127.0.0.1:{self.srv.server_port}"
72
+
73
+ def test_bad_arguments_raise(self):
74
+ with self.assertRaises(ValueError):
75
+ normbeat.ping("abc", count=-1)
76
+ with self.assertRaises(ValueError):
77
+ normbeat.ping("abc", kind="nope")
78
+
79
+
80
+ class LocalCli(unittest.TestCase):
81
+ def setUp(self):
82
+ self.tmp = tempfile.TemporaryDirectory()
83
+ self.db = str(Path(self.tmp.name) / "h.db")
84
+
85
+ def tearDown(self):
86
+ self.tmp.cleanup()
87
+
88
+ def run_cli(self, *args):
89
+ buf = io.StringIO()
90
+ with redirect_stdout(buf):
91
+ code = main(["local", "check", "--db", self.db, *args])
92
+ return code, buf.getvalue().strip()
93
+
94
+ def test_learns_then_flags_and_outage_does_not_become_normal(self):
95
+ mon = datetime(2026, 9, 7, 2, 0)
96
+ for w in range(4):
97
+ code, _ = self.run_cli("--name", "orders", "--count", "50000", "--at", (mon + timedelta(weeks=w)).isoformat())
98
+ self.assertEqual(code, 0)
99
+ # four Mondays of outage in a row: each must still alert
100
+ for w in range(4, 8):
101
+ code, out = self.run_cli("--name", "orders", "--count", "0", "--at", (mon + timedelta(weeks=w)).isoformat())
102
+ self.assertEqual(code, 2, out)
103
+ self.assertTrue(out.startswith("ZERO"), out)
104
+ code, out = self.run_cli("--name", "orders", "--count", "49000", "--at", (mon + timedelta(weeks=8)).isoformat())
105
+ self.assertEqual(code, 0, out)
106
+
107
+ def test_accept_teaches_new_level(self):
108
+ mon = datetime(2026, 9, 7, 2, 0)
109
+ for w in range(3):
110
+ self.run_cli("--name", "j", "--count", "1000", "--at", (mon + timedelta(weeks=w)).isoformat())
111
+ for w in range(3, 6): # business changed: user accepts the new level
112
+ self.run_cli("--name", "j", "--count", "100", "--accept", "--at", (mon + timedelta(weeks=w)).isoformat())
113
+ for w in range(6, 9):
114
+ self.run_cli("--name", "j", "--count", "100", "--accept", "--at", (mon + timedelta(weeks=w)).isoformat())
115
+ code, out = self.run_cli("--name", "j", "--count", "100", "--at", (mon + timedelta(weeks=9)).isoformat())
116
+ self.assertEqual(code, 0, out)
117
+
118
+ def test_rejects_bad_count(self):
119
+ with self.assertRaises(SystemExit):
120
+ with redirect_stdout(io.StringIO()):
121
+ main(["local", "check", "--db", self.db, "--name", "x", "--count", "-5"])
122
+
123
+ def test_ping_command_exits_zero_even_if_down(self):
124
+ os.environ["NORMBEAT_URL"] = "http://127.0.0.1:9"
125
+ try:
126
+ self.assertEqual(main(["ping", "abc", "--count", "3"]), 0)
127
+ finally:
128
+ os.environ.pop("NORMBEAT_URL", None)
129
+
130
+
131
+ if __name__ == "__main__":
132
+ unittest.main()