prompts.chatprompts.chatprompts.chat
TeamsBotsSkillsPromptsPromptmasters
BookFor KidsDevelopers
Login
CC0 2026 prompts.chat
DeepWikiHow to...DocsAPIPrivacyTermsSupportAboutGitHub
All Tags

Metrics Prompts

5 prompts
Git Bus Factor and Knowledge Risk Analyzer
Skill

Finds knowledge concentration risk in a Git repo from its history: per-module bus factor, who holds the knowledge, modules nobody active still knows, single-knower hot spots, the repo truck factor and duplicate identities, with a handover plan template. Offline stdlib Python.

---
name: git-bus-factor-and-knowledge-risk-analyzer
description: Finds knowledge concentration risk in a Git repo from its history: per-module bus factor, who holds the knowledge, modules nobody active still knows, single-knower hot spots, the repo truck factor and duplicate identities, with a handover plan template. Offline stdlib Python.
---

# Git Bus Factor and Knowledge Risk Analyzer

You help engineering managers, tech leads, CTOs of small companies and open-source maintainers see where knowledge of their codebase sits with just one or two people, and where nobody who still works on the project knows the code at all. That risk usually shows up at the worst moment: someone goes on leave, changes teams or leaves, and an outage or a security fix lands in code nobody else has touched. You turn the Git history into a short, factual picture and a practical plan to spread knowledge before it is needed.

You work only on the repository or log the user gives you, on their machine. You never judge or rank people by their commit counts: history shows who changed code, not who understands it, how good the work was or how much invisible work (reviews, design, support) someone did. You present findings as risks in the system, not as performance data, and you suggest confirming them with the team.

## Files in this skill

- `scripts/bus_factor.py` - reads `git log --numstat` history (a saved log or `--repo PATH`), merges aliases, skips bots, lockfiles and vendored code, weights changes by size and recency, and reports per-module bus factor, active knowers and coverage, the repository truck factor, people and findings BF01-BF06; `--json` for tooling, `--self-test` runs 22 checks (Python 3.8+ standard library only; git only for `--repo`)
- `references/metrics-explained.md` - how weights, "knows a file", module bus factor, active coverage and truck factor are computed, which settings to change, and the known limits
- `references/reducing-knowledge-risk.md` - what each finding usually means and the concrete practices that fix it (pairing, review rotation, runbooks, ownership, handover)
- `templates/knowledge-risk-report.md` - the report and 90-day plan you hand back
- `examples/git-history.log`, `examples/aliases.csv` - history of a fictional shop API with five people and a bot: a payments module written by someone who left, a frontend only one person changes, an author with two emails

## Workflow

### 1. Agree the scope
Ask which repository (or monorepo folders) matter, what counts as "active" (default: committed in the last 120 days), how old history should count (default half-life 365 days), and who has left or is about to go on long leave. Ask whether a CODEOWNERS file or team map exists to compare with afterwards.

### 2. Get the history
Inside the repository:
```
git log --no-merges --numstat --date=short --format='@@%H%x09%an%x09%ae%x09%ad' > history.log
```
or let the script run git with `--repo PATH`. Build `aliases.csv` (`alias,canonical`) for people with several emails or names; the first run lists likely duplicates as BF05.

### 3. Run the analysis
```
python3 scripts/bus_factor.py examples/git-history.log --aliases examples/aliases.csv
python3 scripts/bus_factor.py --repo . --aliases aliases.csv --depth 2 --since 2024-01-01
python3 scripts/bus_factor.py history.log --aliases aliases.csv --json > knowledge.json
python3 scripts/bus_factor.py --self-test
```
Use `--depth 2` for monorepos (`services/payments`), `--exclude 'docs/*'` for folders that do not matter, `--as-of` to reproduce a past date. Exit 0 = no high findings, 1 = high findings, 2 = bad input.

### 4. Interpret with the team
- High: BF01 repository truck factor 1-2 (losing one or two people orphans most files), BF02 a module where most files have no active person who knows them.
- Medium: BF03 module bus factor 1, BF04 a hot spot that changed a lot in the last 90 days and is known by one person.
- Low: BF05 duplicate identities (fix aliases and re-run), BF06 only one person ever changed the module.
Before reporting, check each high finding with the team lead: generated code, a recent rewrite or pair-programmed work can make history misleading. Map modules to business impact (payments, auth and data pipelines first).

### 5. Report and plan
Fill `templates/knowledge-risk-report.md`: the module table, the top 3-5 risks ranked by business impact, and a 90-day plan from `references/reducing-knowledge-risk.md` with an owner and a check for each action. Re-run the script monthly or quarterly and compare coverage.

## Rules
- Never present the people table as a productivity ranking or share it outside the team leads; it is there to find single points of failure.
- Treat findings as questions; confirm with the people involved before reassigning work.
- Work locally; do not upload the repository or its history anywhere.

FILE:references/metrics-explained.md
# How bus_factor.py measures knowledge

## Inputs and filters
- History comes from `git log --no-merges --numstat`. Each commit gives author name, email, date and lines added and deleted per file. Binary files (`-`) are skipped; renames keep the new path.
- Bots are skipped unless `--include-bots` (name or email containing `[bot]`, `bot@`, or a name ending in " bot").
- Default excludes: lockfiles (`package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `poetry.lock`, `Cargo.lock`, `go.sum`, `composer.lock`, `Gemfile.lock`), `vendor/`, `node_modules/`, `dist/`, `build/`, minified files and images. Add more with `--exclude GLOB`.
- Aliases: `aliases.csv` maps an email or a name to one canonical person. Without it, the same person with two emails counts as two people and looks less concentrated than reality.

## Weight of a change
    weight = ln(1 + lines added + lines deleted) * 0.5 ^ (age_days / half_life_days)

- The logarithm stops one huge generated diff from outweighing years of small careful changes.
- The half-life (default 365 days) makes old work count less; people forget code they have not touched.

## Knows a file
An author knows a file when they hold at least `--knows-share` (default 0.25) of the file's total weight. A file can have several knowers.

## Active
An author is active if their last commit is within `--active-days` (default 120) of `--as-of` (default: the newest commit). Tell the script about people who left recently by moving `--as-of` or shortening `--active-days`; history cannot know about resignations.

## Module metrics
- **Module**: the first `--depth` folders of the path (default 1); files at the root form "(root)".
- **Top author / top share**: the person with the largest share of the module's total weight.
- **Bus factor**: the smallest number of people who together hold more than half of the module's weight. 1 means one person holds most of it.
- **Active knowers**: active people who know at least one file in the module.
- **Active coverage**: the share of the module's files with at least one active knower.

## Repository truck factor
A greedy estimate in the spirit of published truck factor research: repeatedly remove the active person who knows the most still-covered files, until more than half of all files have no active knower. The number of people removed is the truck factor. 0 means more than half of the files already have no active knower.

## Findings
| code | severity | rule |
|---|---|---|
| BF01 | high | truck factor is 0, 1 or 2 |
| BF02 | high | active coverage of a module is under 50% |
| BF03 | medium | module bus factor 1 and the module has 3 or more files |
| BF04 | medium | bus factor 1 and the module's line changes in the last 90 days are in the top quarter of modules (needs 4+ modules) |
| BF05 | low | one name appears with several emails and no alias |
| BF06 | low | only one person ever changed the module |

## Limits
- Commits show authorship, not understanding: reviewers, pair partners and people who designed or operate the code are invisible.
- Squash merges credit one author for a team's work; large refactors and formatting commits inflate one person's share (exclude them with `--since` or by filtering the log).
- Co-authored-by trailers are not counted.
- Small repositories and modules with few files give noisy numbers; read them with the team.

FILE:references/reducing-knowledge-risk.md
# Reducing knowledge risk

## By finding
| finding | usual meaning | first actions |
|---|---|---|
| BF01 truck factor 1-2 | most of the codebase depends on one or two people | pick the 2-3 most business-critical modules and start the actions below there; make it a quarterly goal, not extra work on top |
| BF02 orphaned module | the people who wrote it left or moved on | name an owner now; schedule a code walkthrough with anyone who remembers it; write a short runbook; add tests around the risky paths before the next change |
| BF03 bus factor 1 | one person does almost all changes | rotate reviews so a second person reviews every change; pair on the next feature; the main author writes a one-page architecture note |
| BF04 single-knower hot spot | the busiest code is known by one person | highest priority after orphaned modules: pair every second change, add a second reviewer as required, keep a changelog of decisions |
| BF05 duplicate identity | one person with several emails | add alias lines and re-run; ask people to set `user.email` per repository |
| BF06 one person ever | nobody else has touched it at all | give a small, real task in that module to a second person with the author as reviewer |

## Practices that work
- **Review rotation**: the second reviewer for a module comes from outside its usual authors; track it for a month.
- **Pairing or mob sessions** on the next real change, not on toy tasks; 60-90 minutes per week per risky module is often enough.
- **Runbooks** for operating the module: how to deploy, roll back, read its dashboards and handle its common alerts.
- **Architecture notes**: one page per module (purpose, data flow, sharp edges, why decisions were made), kept next to the code.
- **Ownership**: a team (not one person) as owner in CODEOWNERS, with at least two people able to approve.
- **On-call shadowing** for modules that page people.
- **Handover plans** when someone gives notice or goes on long leave: list their modules from this report, schedule walkthroughs, and pair on open work in their last weeks.

## Measuring progress
Re-run monthly with the same settings and compare: active coverage per critical module (target 100% with at least two active knowers), module bus factor (target 2+), and the repository truck factor (target 3+ for a small team).

FILE:templates/knowledge-risk-report.md
# Knowledge risk report: {{repository}} - {{date}}

Settings: active = committed in the last {{active_days}} days; half-life {{half_life_days}} days; knows-share {{knows_share}}; module depth {{depth}}. History since {{since}}.

## Summary
- Repository truck factor: {{truck_factor}} ({{people}})
- Modules with low active coverage: {{bf02_modules}}
- Single-knower modules: {{bf03_modules}}
- Hot spots known by one person: {{bf04_modules}}

## Module table
(paste the module table from bus_factor.py)

## Top risks (ranked by business impact)
| # | module | why it matters | finding | confirmed with |
|---|---|---|---|---|
| 1 | {{module}} | {{impact, e.g. checkout payments}} | {{code}} | {{lead}} |

## 90-day plan
| action | module | owner | by | done when |
|---|---|---|---|---|
| {{e.g. pair on next two changes}} | {{module}} | {{name}} | {{date}} | {{second person merged a change alone}} |

## Caveats
- History shows who changed code, not who understands it; reviewers, pair partners and operators are not counted.
- {{anything specific: squash merges, a big refactor, generated code}}

## Next check
{{date}} with the same settings.

FILE:examples/git-history.log
@@58f5d4cce18a5ce4e3f9aa12d9767dcfd74b25ee	Ben Okafor	ben@shop.example	2026-11-14

5	0	web/src/api.ts
32	0	web/src/checkout.tsx
@@4cbab3078c9e5e9fac0a6d3627c6e022739f96e1	Eli Novak	eli@shop.example	2026-11-12

12	0	core/config.py
40	0	core/db.py
@@a0d3945429639f6c562a88444476839744d9453e	Ana Silva	ana.silva@shop.example	2026-11-10

10	0	core/db.py
29	0	orders/api.py
@@faa0aacf2cd46c8e74c9bd98cf5921fb50dd6c6b	Ana Silva	ana.silva@shop.example	2026-10-20

15	0	payments/webhooks.py
@@b579089fdf73b4d2bc6598a4ee680b3839743088	Ben Okafor	ben@shop.example	2026-10-11

9	0	web/src/cart.tsx
6	0	web/src/checkout.tsx
@@50b03245d12d83ddb1e9ae1c66a2d45178051021	Eli Novak	eli@shop.example	2026-10-10

15	0	core/config.py
11	0	search/query.py
@@7214f7c5b6154585c695eaf02e978b3464b8dc02	dependabot[bot]	49699333+dependabot[bot]@users.noreply.github.com	2026-10-01

150	0	web/package-lock.json
150	0	web/package.json
@@16652d4b388444019ca413263b86cbfd87baed7a	Ana Silva	ana.silva@shop.example	2026-09-24

37	0	orders/api.py
7	0	orders/service.py
@@8290901896c8e9f9611cff8466cf7966b25eb76d	Ben Okafor	ben@shop.example	2026-09-15

5	0	README.md
@@fffb9688a48be4a6e95b08b16cba70e17e9f4b9b	Eli Novak	eli@shop.example	2026-09-07

15	0	orders/api.py
31	0	search/query.py
@@e841c7d0bbed56f4725d681b6587a1808123c893	Ben Okafor	ben@shop.example	2026-09-07

24	0	web/src/api.ts
25	0	web/src/cart.tsx
@@88ccae50a361536da22fe6b5e96cc008385ccccb	Ana Silva	ana.silva@shop.example	2026-08-09

25	0	orders/models.py
14	0	orders/service.py
@@000ed52a381b54ba901092d2050c6165b8441de8	Eli Novak	eli@shop.example	2026-08-06

37	0	core/db.py
27	0	orders/api.py
@@c548efcb90ebc04644b4f9d761bb0a96bc9be56d	Ben Okafor	ben@shop.example	2026-08-04

4	0	web/src/api.ts
13	0	web/src/checkout.tsx
@@b9a4d1e4e28cda2113d8ac51cdff3389910dc14e	Eli Novak	eli@shop.example	2026-07-04

32	0	core/config.py
15	0	core/db.py
@@a003bffd397e386e00c745b4393ca3c509859e35	Ben O.	ben.okafor@gmail.example	2026-07-01

3	0	web/src/cart.tsx
9	0	web/src/checkout.tsx
@@10e0e7b09f2d37b0c7055c4a7a17af09dc945e91	Ana Silva	ana.silva@shop.example	2026-06-24

18	0	core/db.py
28	0	orders/models.py
@@d0076f938d1899cc368d2cc627220682762e6516	Eli Novak	eli@shop.example	2026-06-02

35	0	core/config.py
15	0	search/query.py
@@b70911cb2b187c324a78b2af770bff9c354ed222	Ben Okafor	ben@shop.example	2026-05-29

28	0	web/src/api.ts
6	0	web/src/cart.tsx
@@c77843f7c87f8d6ad35d107e4ad625e4559cf306	Chen Wei	chen@shop.example	2026-05-15

30	0	core/config.py
9	0	search/query.py
@@faeb60ed9f9ec1faaf33e8393463027d45666e4a	Ana Silva	ana.silva@shop.example	2026-05-09

25	0	core/db.py
31	0	orders/api.py
@@09c4044f954ffd84dc15713518cc1532a6c5cc6f	Ben Okafor	ben@shop.example	2026-04-25

8	0	web/src/api.ts
8	0	web/src/checkout.tsx
@@efcdcc32cc592412a5a7dd1796fa0149aff7094a	dependabot[bot]	49699333+dependabot[bot]@users.noreply.github.com	2026-04-01

150	0	web/package-lock.json
150	0	web/package.json
@@ae3fc07a50e237c4a8b98c1df55da1f5e8155aa6	Ana Silva	ana.silva@shop.example	2026-03-24

30	0	orders/api.py
36	0	orders/service.py
@@eb7130d2a61f5f297762462e5ea807f5c601b827	Ben Okafor	ben@shop.example	2026-03-22

36	0	web/src/cart.tsx
30	0	web/src/checkout.tsx
@@bdadf66c0528166414b20facd6e0bc6490dc50c4	Chen Wei	chen@shop.example	2026-03-14

38	0	search/index.py
37	0	search/query.py
@@9dd045964286f69e2630aa8d2492d9cb8b126f45	Ben Okafor	ben@shop.example	2026-02-16

22	0	web/src/api.ts
39	0	web/src/cart.tsx
@@e5b16b9f4a0600bb1303545da56d8ec5b775a71d	Ana Silva	ana.silva@shop.example	2026-02-06

40	0	orders/models.py
4	0	orders/service.py
@@9f3ce69e27b7d9c169f07879450c79faffb917e9	Ben Okafor	ben@shop.example	2026-01-14

28	0	web/src/api.ts
26	0	web/src/checkout.tsx
@@87c36c4896129acc5b4dacb88498e10394a0dfaf	Chen Wei	chen@shop.example	2026-01-11

22	0	core/config.py
39	0	search/index.py
@@8ef82e501b1097d202e79c324d4a6118e855f852	Ana Silva	ana.silva@shop.example	2025-12-22

28	0	core/db.py
14	0	orders/models.py
@@3433f75f61d9493c5cb9d48d7a5fb86ef241bea0	Ben Okafor	ben@shop.example	2025-12-11

36	0	web/src/cart.tsx
29	0	web/src/checkout.tsx
@@304e9fd851a7b0cdd05780fe452310a5d3d86abc	Chen Wei	chen@shop.example	2025-11-11

21	0	core/config.py
35	0	search/query.py
@@98d8c4bbb5f3b6604cfd38bc5dda9f08736c64ed	Ben Okafor	ben@shop.example	2025-11-07

29	0	web/src/api.ts
19	0	web/src/cart.tsx
@@03290d9ed4de0c842c7b378220f9a385b4135a4d	Ana Silva	ana@personal.example	2025-11-06

5	0	core/db.py
37	0	orders/api.py
@@f1e157a039fbe041730b8f1137c684027f0e7c32	Ben Okafor	ben@shop.example	2025-10-04

24	0	web/src/api.ts
6	0	web/src/checkout.tsx
@@5622224adaa507aa5490d234b1840d20477c3575	dependabot[bot]	49699333+dependabot[bot]@users.noreply.github.com	2025-09-30

150	0	web/package-lock.json
150	0	web/package.json
@@f658dbaddfcc5963b8e27a6f36a1903d4b3db6e6	Ana Silva	ana.silva@shop.example	2025-09-21

30	0	orders/api.py
14	0	orders/service.py
@@bac00f633bef75ed05866ccc8d6d31fb9e071e3e	Chen Wei	chen@shop.example	2025-09-10

20	0	search/index.py
20	0	search/query.py
@@c460c69d03be963f77b2524616dfde637254e72f	Ben Okafor	ben@shop.example	2025-09-01

35	0	web/src/cart.tsx
12	0	web/src/checkout.tsx
@@65153a48d22bf9b981f3680e6f9917b64a43ec35	Ana Silva	ana.silva@shop.example	2025-08-06

28	0	orders/models.py
22	0	orders/service.py
@@bc8cbd6bf9daee0d05449afbbaccb64f56bfb29a	Chen Wei	chen@shop.example	2025-07-11

19	0	core/config.py
14	0	search/index.py
@@6a34d862b912eb393cf7f8ca55c028b9010173be	Ana Silva	ana.silva@shop.example	2025-06-21

23	0	core/db.py
24	0	orders/models.py
@@6059e786b3ab3482031920657fecf929a4a58bd4	Dana Kim	dana@shop.example	2025-05-20

6	0	payments/stripe_client.py
39	0	payments/webhooks.py
@@e7cb62d4ed5198d9ce0a3fe0b1c938113a67ad97	Chen Wei	chen@shop.example	2025-05-10

36	0	core/config.py
40	0	search/query.py
@@9fd0749dd73e35beb76f65b7e3657463d44c7e54	Ana Silva	ana.silva@shop.example	2025-05-06

10	0	core/db.py
14	0	orders/api.py
@@a0c736ff9075a594896ca5bf024440a12c35c115	Dana Kim	dana@shop.example	2025-05-03

29	0	payments/refunds.py
15	0	payments/webhooks.py
@@1e40d5f4b152a88dbd317ede961bf06ae2a0a742	Dana Kim	dana@shop.example	2025-04-17

22	0	payments/refunds.py
19	0	payments/stripe_client.py
@@ab3f7a3a2d1bea59b43fc959a0b3e1116dcf247f	dependabot[bot]	49699333+dependabot[bot]@users.noreply.github.com	2025-04-01

150	0	web/package-lock.json
150	0	web/package.json
@@fb0a311f7267f495367425518ef25dbf365f5ae1	Dana Kim	dana@shop.example	2025-03-31

40	0	payments/stripe_client.py
4	0	payments/webhooks.py
@@cd493d2263836828dcb0be8e4c4140125c965850	Ana Silva	ana.silva@shop.example	2025-03-21

39	0	orders/api.py
6	0	orders/service.py
@@3c743484d0dd4bca3905f9686bba1f48b22de580	Dana Kim	dana@shop.example	2025-03-15

38	0	payments/refunds.py
30	0	payments/webhooks.py
@@981e4f06309729c1da359503aed2ba7acd1a8e8b	Chen Wei	chen@shop.example	2025-03-10

23	0	search/index.py
14	0	search/query.py
@@c9168c14828d2c382e334aa604064471d5d0cd63	Dana Kim	dana@shop.example	2025-02-26

6	0	payments/refunds.py
20	0	payments/stripe_client.py
@@4e20074f7f1b7bddfda1949cc23b0852c36ec61a	Dana Kim	dana@shop.example	2025-02-10

17	0	payments/stripe_client.py
8	0	payments/webhooks.py
@@d53da3ddd6680b9335a63352e7b365c79f62c028	Ana Silva	ana.silva@shop.example	2025-02-03

10	0	orders/models.py
25	0	orders/service.py
@@3e657197ddd176ccb02ab859abd3f8416459b665	Dana Kim	dana@shop.example	2025-01-24

31	0	payments/refunds.py
14	0	payments/webhooks.py
@@8590bef42bccc66937a1dcbc79275ed93099cef7	Dana Kim	dana@shop.example	2025-01-08

4	0	payments/refunds.py
18	0	payments/stripe_client.py
@@f67141a910fd0594c02e23adbc41e740d373506c	Ana Silva	ana.silva@shop.example	2025-01-06

11	0	README.md

FILE:examples/aliases.csv
alias,canonical
ben.okafor@gmail.example,Ben Okafor
Ben O.,Ben Okafor

FILE:scripts/bus_factor.py
#!/usr/bin/env python3
"""bus_factor.py - find knowledge concentration ("bus factor") risk in a Git repository from its history.

Reads `git log --numstat` history (from a saved log file or by running git on a repo), merges author
aliases, skips bots, lockfiles and vendored code, and weights each change by lines touched and how
recent it is. Per module (top-level folder by default) it reports who holds the knowledge, the module
bus factor (fewest people holding more than half of it), whether any active person still knows it,
and the repository truck factor (how many people would have to leave before more than half of the
files have no active person who knows them). Standard library only.

Usage:
  python3 bus_factor.py LOGFILE [options]
  python3 bus_factor.py --repo PATH [options]          (runs git log for you)
  python3 bus_factor.py --self-test
Make LOGFILE with:
  git log --no-merges --numstat --date=short --format='@@%H%x09%an%x09%ae%x09%ad' > history.log
Options:
  --aliases FILE       CSV alias,canonical  (alias = an email or a name; canonical = the person's name)
  --depth N            module = first N folders of the path (default 1; root files = "(root)")
  --since YYYY-MM-DD   ignore older commits
  --as-of YYYY-MM-DD   reference date (default: newest commit in the log)
  --active-days N      an author is active if they committed within N days of --as-of (default 120)
  --half-life-days N   a change loses half its weight after N days (default 365)
  --knows-share X      an author "knows" a file when they hold at least X of its weight (default 0.25)
  --exclude GLOB       extra path pattern to skip (repeatable); defaults skip lockfiles, vendor, dist, minified
  --include-bots       keep authors whose name or email contains [bot] or "bot@"
  --json               machine-readable output
Exit codes: 0 no high findings, 1 high findings, 2 bad input.
"""
import csv, datetime as dt, fnmatch, json, math, os, subprocess, sys
from collections import defaultdict

DEFAULT_EXCLUDES = ["*package-lock.json", "*yarn.lock", "*pnpm-lock.yaml", "*poetry.lock", "*Cargo.lock", "*go.sum",
                    "*composer.lock", "*Gemfile.lock", "vendor/*", "*/vendor/*", "node_modules/*", "dist/*",
                    "build/*", "*.min.js", "*.min.css", "*.svg", "*.png", "*.jpg", "*.pdf"]
SEV = {"BF01": "high", "BF02": "high", "BF03": "medium", "BF04": "medium", "BF05": "low", "BF06": "low"}
NAMES = {"BF01": "repository truck factor is 1 or 2",
         "BF02": "orphaned module: most files have no active person who knows them",
         "BF03": "module bus factor 1: one person holds most of the knowledge",
         "BF04": "hot spot with a single knower (busy recently, one person)",
         "BF05": "possible duplicate identity (same name, different emails)",
         "BF06": "only one person has ever changed this module"}


class InputError(Exception):
    pass


def parse_date(s, what):
    try:
        return dt.date.fromisoformat(s.strip()[:10])
    except (ValueError, AttributeError):
        raise InputError("bad %s date: %r" % (what, s))


def parse_log(lines):
    """Return list of commits: dict(sha, name, email, date, files=[(path, added, deleted)])."""
    commits, cur = [], None
    for n, raw in enumerate(lines, 1):
        line = raw.rstrip("\n")
        if line.startswith("@@"):
            parts = line[2:].split("\t")
            if len(parts) < 4:
                raise InputError("line %d: header needs sha, name, email, date separated by tabs" % n)
            cur = {"sha": parts[0], "name": parts[1].strip(), "email": parts[2].strip().lower(),
                   "date": parse_date(parts[3], "commit"), "files": []}
            commits.append(cur)
        elif line.strip():
            if cur is None:
                raise InputError("line %d: numstat line before any @@ commit header (wrong --format?)" % n)
            parts = line.split("\t")
            if len(parts) != 3:
                raise InputError("line %d: expected 'added<TAB>deleted<TAB>path'" % n)
            a, d, path = parts
            if a == "-" or d == "-":      # binary file
                continue
            path = path.strip()
            if " => " in path:            # rename: keep the new path
                if "{" in path:
                    pre, rest = path.split("{", 1)
                    mid, post = rest.split("}", 1)
                    path = (pre + mid.split(" => ")[1] + post).replace("//", "/")
                else:
                    path = path.split(" => ")[1]
            try:
                cur["files"].append((path, int(a), int(d)))
            except ValueError:
                raise InputError("line %d: added/deleted must be numbers" % n)
    if not commits:
        raise InputError("no commits found (expected lines starting with @@)")
    return commits


def git_log(repo, since=None):
    cmd = ["git", "-C", repo, "log", "--no-merges", "--numstat", "--date=short", "--format=@@%H%x09%an%x09%ae%x09%ad"]
    if since:
        cmd.append("--since=" + since)
    try:
        out = subprocess.run(cmd, capture_output=True, text=True, check=True).stdout
    except (OSError, subprocess.CalledProcessError) as e:
        raise InputError("git log failed: %s" % (getattr(e, "stderr", "") or e))
    return out.splitlines()


def load_aliases(path):
    m = {}
    if not path:
        return m
    try:
        for row in csv.DictReader(open(path, encoding="utf-8", newline="")):
            a, c = (row.get("alias") or "").strip(), (row.get("canonical") or "").strip()
            if a and c:
                m[a.lower()] = c
    except OSError as e:
        raise InputError("cannot read aliases: %s" % e)
    return m


def module_of(path, depth):
    parts = path.split("/")
    if len(parts) == 1:
        return "(root)"
    return "/".join(parts[:min(depth, len(parts) - 1)])


def analyse(commits, aliases=None, depth=1, since=None, as_of=None, active_days=120, half_life=365,
            knows_share=0.25, excludes=None, include_bots=False):
    aliases = aliases or {}
    pats = DEFAULT_EXCLUDES + list(excludes or [])
    since_d = parse_date(since, "--since") if since else None
    as_of_d = parse_date(as_of, "--as-of") if as_of else max(c["date"] for c in commits)
    emails_by_name = defaultdict(set)
    last_seen = {}
    fw = defaultdict(lambda: defaultdict(float))       # file -> author -> weight
    f_last = {}
    f_recent = defaultdict(float)                       # lines in last 90 days
    commits_per_module = defaultdict(set)
    authors_ever = defaultdict(set)                     # module -> authors (unweighted)
    used = 0
    for c in commits:
        if since_d and c["date"] < since_d:
            continue
        if c["date"] > as_of_d:
            continue
        if not include_bots and ("[bot]" in c["name"].lower() or "bot@" in c["email"] or c["name"].lower().endswith(" bot")):
            continue
        who = aliases.get(c["email"]) or aliases.get(c["name"].lower()) or c["name"]
        if who == c["name"] and not aliases.get(c["email"]):
            emails_by_name[c["name"]].add(c["email"])
        last_seen[who] = max(last_seen.get(who, c["date"]), c["date"])
        age = (as_of_d - c["date"]).days
        w = 0.5 ** (age / float(half_life)) if half_life > 0 else 1.0
        touched = False
        for path, a, d in c["files"]:
            if any(fnmatch.fnmatch(path, p) for p in pats):
                continue
            lines = a + d
            if lines == 0:
                continue
            touched = True
            fw[path][who] += math.log1p(lines) * w     # log damps huge generated diffs
            f_last[path] = max(f_last.get(path, c["date"]), c["date"])
            if age <= 90:
                f_recent[path] += lines
            mod = module_of(path, depth)
            commits_per_module[mod].add(c["sha"])
            authors_ever[mod].add(who)
        used += touched
    if not fw:
        raise InputError("no usable file changes after filters")
    active = {a for a, d in last_seen.items() if (as_of_d - d).days <= active_days}

    def knowers(path):
        tot = sum(fw[path].values())
        return {a for a, v in fw[path].items() if v / tot >= knows_share}

    files = sorted(fw)
    mods = defaultdict(list)
    for p in files:
        mods[module_of(p, depth)].append(p)
    recent_by_mod = {m: sum(f_recent[p] for p in ps) for m, ps in mods.items()}
    hot_cut = sorted(recent_by_mod.values())[int(len(recent_by_mod) * 0.75)] if recent_by_mod else 0
    out_mods, findings = [], []
    for m in sorted(mods):
        ps = mods[m]
        aw = defaultdict(float)
        for p in ps:
            for a, v in fw[p].items():
                aw[a] += v
        tot = sum(aw.values())
        ranked = sorted(aw.items(), key=lambda x: -x[1])
        acc, bf = 0.0, 0
        for a, v in ranked:
            acc += v; bf += 1
            if acc > tot / 2:
                break
        kn = set().union(*(knowers(p) for p in ps))
        act_kn = sorted(kn & active)
        covered = sum(1 for p in ps if knowers(p) & active)
        top, share = ranked[0][0], ranked[0][1] / tot
        row = {"module": m, "files": len(ps), "commits": len(commits_per_module[m]), "authors": len(aw),
               "top_author": top, "top_share": round(share, 3), "bus_factor": bf,
               "active_knowers": act_kn, "active_coverage": round(covered / len(ps), 3),
               "last_change": max(f_last[p] for p in ps).isoformat(), "recent_lines_90d": int(recent_by_mod[m]),
               "top_author_active": top in active, "findings": []}
        if covered / len(ps) < 0.5:
            row["findings"].append("BF02")
        if bf == 1 and len(ps) >= 3:
            row["findings"].append("BF03")
        if bf == 1 and recent_by_mod[m] > 0 and recent_by_mod[m] >= hot_cut and len(mods) >= 4:
            row["findings"].append("BF04")
        if len(authors_ever[m]) == 1:
            row["findings"].append("BF06")
        out_mods.append(row)
    # repository truck factor: greedily remove the author who knows most still-covered files
    file_kn = {p: knowers(p) & active for p in files}
    removed, tf = [], 0
    remaining = {p: set(k) for p, k in file_kn.items()}
    def orphaned():
        return sum(1 for k in remaining.values() if not k)
    if orphaned() > len(files) / 2:
        tf = 0
    else:
        while orphaned() <= len(files) / 2:
            cnt = defaultdict(int)
            for k in remaining.values():
                for a in k:
                    cnt[a] += 1
            if not cnt:
                break
            a = sorted(cnt.items(), key=lambda x: (-x[1], x[0]))[0][0]
            removed.append(a); tf += 1
            for k in remaining.values():
                k.discard(a)
    if tf <= 2:
        findings.append({"code": "BF01", "detail": "truck factor %d (%s)" % (tf, ", ".join(removed) or "already orphaned")})
    for name, em in sorted(emails_by_name.items()):
        if len(em) > 1:
            findings.append({"code": "BF05", "detail": "%s uses %s; add an alias line" % (name, ", ".join(sorted(em)))})
    for r in out_mods:
        for code in r["findings"]:
            findings.append({"code": code, "module": r["module"], "detail": "top %s %.0f%%, active knowers: %s" % (
                r["top_author"], r["top_share"] * 100, ", ".join(r["active_knowers"]) or "none")})
    people = sorted(({"author": a, "last_commit": d.isoformat(), "active": a in active,
                      "files_known": sum(1 for p in files if a in knowers(p))} for a, d in last_seen.items()),
                    key=lambda x: -x["files_known"])
    return {"as_of": as_of_d.isoformat(), "commits_used": used, "files": len(files), "modules": out_mods,
            "truck_factor": tf, "truck_factor_people": removed, "people": people,
            "settings": {"depth": depth, "active_days": active_days, "half_life_days": half_life, "knows_share": knows_share},
            "findings": findings}


def render(a):
    L = ["# Knowledge risk report (as of %s)" % a["as_of"], "",
         "Commits used: %d | files: %d | repository truck factor: %d (%s)" % (
             a["commits_used"], a["files"], a["truck_factor"], ", ".join(a["truck_factor_people"]) or "-"), "",
         "| module | files | commits | authors | top author | top share | bus factor | active knowers | active coverage | last change |",
         "|---|---|---|---|---|---|---|---|---|---|"]
    for r in a["modules"]:
        L.append("| %s | %d | %d | %d | %s%s | %.0f%% | %d | %s | %.0f%% | %s |" % (
            r["module"], r["files"], r["commits"], r["authors"], r["top_author"], "" if r["top_author_active"] else " (inactive)",
            r["top_share"] * 100, r["bus_factor"], ", ".join(r["active_knowers"]) or "none", r["active_coverage"] * 100,
            r["last_change"]))
    L += ["", "## People", "", "| author | last commit | active | files known |", "|---|---|---|---|"]
    for p in a["people"]:
        L.append("| %s | %s | %s | %d |" % (p["author"], p["last_commit"], "yes" if p["active"] else "no", p["files_known"]))
    L += ["", "## Findings"]
    order = {"high": 0, "medium": 1, "low": 2}
    for f in sorted(a["findings"], key=lambda f: (order[SEV[f["code"]]], f["code"], f.get("module", ""))):
        L.append("- [%s] %s %s%s: %s" % (SEV[f["code"]], f["code"], NAMES[f["code"]],
                                         (" - " + f["module"]) if f.get("module") else "", f["detail"]))
    if not a["findings"]:
        L.append("- none")
    L += ["", "History shows who changed code, not who understands it; confirm with the team before acting."]
    return "\n".join(L)


def self_test():
    T = []
    def check(name, cond):
        T.append((name, bool(cond)))
    log = """@@a1\tAna\tana@x.io\t2026-01-10
10\t2\tapi/orders.py
5\t0\tapi/users.py
@@a2\tBen\tben@x.io\t2026-03-01
20\t5\tweb/app.js
3\t1\tapi/orders.py
@@a3\tAna\tana@home.io\t2026-06-01
4\t4\tapi/users.py
-\t-\tweb/logo.png
@@a4\tdependabot[bot]\t49699333+dependabot[bot]@users.noreply.github.com\t2026-06-02
200\t180\tpackage-lock.json
1\t1\tweb/package.json
@@a5\tCara\tcara@x.io\t2025-01-05
50\t0\tbilling/{old => new}/invoice.py
@@a6\tBen\tben@x.io\t2026-06-10
2\t2\tREADME.md
""".splitlines()
    c = parse_log(log)
    check("parses 6 commits", len(c) == 6)
    check("binary numstat rows skipped", all(f[0] != "web/logo.png" for x in c for f in x["files"]))
    check("brace rename resolved to new path", c[4]["files"][0][0] == "billing/new/invoice.py")
    check("module of root file is (root)", module_of("README.md", 1) == "(root)")
    check("module depth 2", module_of("src/api/x/y.py", 2) == "src/api")
    a = analyse(c, as_of="2026-06-10")
    mods = {m["module"]: m for m in a["modules"]}
    check("bot commits skipped", "web" in mods and mods["web"]["authors"] == 1)
    check("lockfile excluded", all(m["module"] != "(root)" or m["files"] == 1 for m in a["modules"]))
    check("duplicate identity flagged BF05", any(f["code"] == "BF05" and "Ana" in f["detail"] for f in a["findings"]))
    a2 = analyse(c, aliases={"ana@home.io": "Ana"}, as_of="2026-06-10")
    check("alias removes BF05", not any(f["code"] == "BF05" for f in a2["findings"]))
    check("inactive author makes billing orphaned BF02", "BF02" in mods["billing"]["findings"])
    check("single-author module flagged BF06", "BF06" in mods["web"]["findings"])
    check("api bus factor is 1 (Ana holds most)", mods["api"]["bus_factor"] == 1 and mods["api"]["top_author"] == "Ana")
    check("truck factor small -> BF01", any(f["code"] == "BF01" for f in a["findings"]))
    a3 = analyse(c, as_of="2026-06-10", since="2026-02-01")
    check("--since drops older commits", a3["commits_used"] == 3)
    a4 = analyse(c, as_of="2026-06-10", active_days=600)
    check("long active window: billing has an active knower", "BF02" not in {m["module"]: m for m in a4["modules"]}["billing"]["findings"])
    check("BF02 uses active coverage under 50%", all(("BF02" in m["findings"]) == (m["active_coverage"] < 0.5) for m in a["modules"]))
    check("recency weight halves after half-life", abs(0.5 ** (365 / 365.0) - 0.5) < 1e-9)
    for bad, label in [(["10\t2\tx.py"], "numstat before header rejected"), (["@@x\tA\ta@b\tnot-a-date"], "bad date rejected"),
                       (["@@x\tA\ta@b\t2026-01-01", "ten\t2\tx.py"], "non-numeric counts rejected"), ([], "empty log rejected")]:
        try:
            parse_log(bad); check(label, False)
        except InputError:
            check(label, True)
    try:
        analyse(parse_log(["@@x\tA\ta@b\t2026-01-01", "3\t1\tyarn.lock"])); check("only excluded files rejected", False)
    except InputError:
        check("only excluded files rejected", True)
    for name, ok in T:
        print(("PASS  " if ok else "FAIL  ") + name)
    good = all(ok for _, ok in T)
    print("ALL PASS" if good else "SOME FAILED", "(%d/%d)" % (sum(ok for _, ok in T), len(T)))
    return 0 if good else 1


def main(argv):
    if "--self-test" in argv:
        return self_test()
    opts = {"aliases": None, "depth": "1", "since": None, "as-of": None, "active-days": "120", "half-life-days": "365",
            "knows-share": "0.25", "repo": None}
    excludes, pos, i = [], [], 0
    while i < len(argv):
        x = argv[i]
        if x in ("--json", "--include-bots"):
            i += 1; continue
        if x.startswith("--"):
            k = x[2:]
            if i + 1 >= len(argv) or (k not in opts and k != "exclude"):
                print("error: unknown or incomplete option %s" % x, file=sys.stderr); return 2
            if k == "exclude":
                excludes.append(argv[i + 1])
            else:
                opts[k] = argv[i + 1]
            i += 2; continue
        pos.append(x); i += 1
    try:
        if opts["repo"]:
            lines = git_log(opts["repo"], opts["since"])
        elif len(pos) == 1:
            try:
                lines = open(pos[0], encoding="utf-8", errors="replace").read().splitlines()
            except OSError as e:
                raise InputError("cannot read %s: %s" % (pos[0], e))
        else:
            print(__doc__, file=sys.stderr); return 2
        try:
            depth, ad, hl, ks = int(opts["depth"]), int(opts["active-days"]), int(opts["half-life-days"]), float(opts["knows-share"])
        except ValueError:
            raise InputError("--depth, --active-days and --half-life-days need whole numbers, --knows-share a decimal")
        if depth < 1 or not 0 < ks <= 1:
            raise InputError("--depth must be >= 1 and --knows-share between 0 and 1")
        a = analyse(parse_log(lines), load_aliases(opts["aliases"]), depth, opts["since"], opts["as-of"], ad, hl, ks,
                    excludes, "--include-bots" in argv)
    except InputError as e:
        print("error: %s" % e, file=sys.stderr); return 2
    print(json.dumps(a, indent=2) if "--json" in argv else render(a))
    return 1 if any(SEV[f["code"]] == "high" for f in a["findings"]) else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
RiskEngineeringGit+3
F@f
0
SaaS MRR and Churn Metrics Calculator
Skill

Turns a subscription events CSV into a monthly MRR bridge (new, expansion, contraction, churn, reactivation) with logo churn, GRR, NRR, ARPA, quick ratio and cohort retention. Normalizes annual and quarterly billing to MRR and flags data errors, shrinking months, high churn and customer concentration. Offline stdlib Python calculator.

---
name: saas-mrr-and-churn-metrics-calculator
description: Turns a subscription events CSV into a monthly MRR bridge (new, expansion, contraction, churn, reactivation) with logo churn, GRR, NRR, ARPA, quick ratio and cohort retention. Normalizes annual and quarterly billing to MRR and flags data errors (annual typed as monthly, mislabeled upgrades, churn of unknown customers), shrinking months, high churn and customer concentration. Offline stdlib Python calculator.
---

# SaaS MRR and Churn Metrics Calculator

You help founders, finance leads and product managers of subscription businesses get honest recurring-revenue numbers. Spreadsheet MRR usually goes wrong in the same places: an annual contract typed in as a monthly price inflates MRR twelvefold, downgrades get logged as upgrades, churn is counted on customers who already left, and one big account hides the fact that everyone else is leaving. You take a plain events export, rebuild MRR month by month so every movement is explained, and say what the numbers mean for the business.

You do not connect to billing systems, change data or give investment or accounting advice. Work only from the CSV the user provides, show every assumption, and remind them that MRR is a management metric, not recognized revenue.

## Files in this skill

- `scripts/mrr_metrics.py` - reads the events CSV and prints the MRR bridge, retention, cohorts, top customers and findings SM01-SM10; `--from/--to` to pick the reporting window, `--json` for further analysis, `--self-test` runs 17 checks (Python 3.8+ standard library only)
- `references/metric-definitions.md` - exact formulas for every metric and how the script classifies each event
- `references/data-prep-and-pitfalls.md` - how to export events from common billing tools, what counts as MRR, and the classic mistakes
- `templates/metrics-report.md` - the monthly metrics report you hand back
- `examples/subscription_events.csv` - ten months of events for a fictional scheduling SaaS with planted errors

## Workflow

### 1. Get the events
Ask for one row per subscription change: `date` (YYYY-MM-DD), `customer`, `event` (`new`, `upgrade`, `downgrade`, `price_change`, `churn`, `reactivate`), `amount` (the recurring price after the change, per billing period, excluding tax and one-off fees), `billing` (`monthly`, `quarterly`, `annual`) and optional `plan`. Use one currency (convert first). See `references/data-prep-and-pitfalls.md` for exports from Stripe, Paddle, Chargebee or a spreadsheet.

### 2. Run the calculator
```
python3 scripts/mrr_metrics.py examples/subscription_events.csv
python3 scripts/mrr_metrics.py events.csv --from 2026-07 --to 2026-10
python3 scripts/mrr_metrics.py events.csv --json --top-share 0.15 --churn-alert 0.03
python3 scripts/mrr_metrics.py --self-test
```
Pass `--from` to get period retention (NRR and logo retention of the customers active just before the window). Exit 0 = no high findings, 1 = high findings, 2 = bad input. Without a shell, build the bridge by hand with `references/metric-definitions.md`; it is just bookkeeping per customer.

### 3. Fix the data, then read the metrics
- Data findings first: SM01 unreadable row, SM02 event that doesn't fit the customer's state (churn of an unknown customer, `new` for an active one), SM03 zero-MRR new customer (free or trial), SM04 monthly amount 8x or more the median (an annual price typed as monthly?), SM05 `upgrade` that lowers MRR or `downgrade` that raises it, SM08 negative amount. Correct the CSV and re-run before drawing conclusions.
- Business findings: SM07 quick ratio below 1 (the business shrank that month, high), SM06 monthly logo churn above the alert level, SM09 period NRR below 100%, SM10 one customer above the concentration threshold.

### 4. Deliver
Fill `templates/metrics-report.md`: headline MRR and growth, the bridge table, retention and cohorts, what changed and why, data fixes made, and three concrete actions (for example: call the customers who downgraded, fix onboarding for the cohort that churns in month 2, diversify away from the largest account). Keep the language plain; define GRR and NRR once.

## Example result
On the sample file, ending MRR in October shows 6,435.40 across 14 paying customers, but 4,788 of it is A09, whose annual Business contract was typed as monthly (SM04); with `billing=annual` it is 399 MRR and the business is about a third of the size it appears. The data also has an "upgrade" from 399 to 149 (SM05), a churn row for unknown customer A99 and a `new` row for already-active A01 (SM02). Business signals: May, June and August lost more MRR than they gained (quick ratio 0.16, 0.75, 0.43), logo churn hit 22% in May and 25% in August, and July to October NRR is 92%. Result: 3 high, 8 medium, 1 low.

## Rules

- Never mix one-off charges, setup fees, usage overages or taxes into MRR unless the user explicitly defines MRR that way; say which definition you used.
- Divide annual and quarterly prices by 12 and 3; do not book the whole contract in the signing month.
- Fix data findings before interpreting trends, and state every correction you made.
- Small numbers lie: with fewer than ~20 customers, one churn moves rates a lot; say so instead of over-reading percentages.
- These are management metrics, not GAAP/IFRS revenue; refer accounting questions to an accountant.

FILE:references/metric-definitions.md
# Metric definitions (as implemented in mrr_metrics.py)

## Normalizing to MRR
`MRR = amount / months in billing period` (monthly 1, quarterly 3, annual 12). The amount is the recurring price after the change, net of recurring discounts, without tax or one-off fees.

## Classifying each event per customer
| Event | Condition | Bridge bucket |
|---|---|---|
| `new` | customer never paid before | New MRR (+ new customer) |
| `new` | customer already active | treated as price change, flagged SM02 |
| `new` / `reactivate` | customer paid before, now at 0 | Reactivation MRR |
| `upgrade` / `downgrade` / `price_change` | active customer | Expansion if MRR rises, Contraction if it falls (label mismatch flagged SM05) |
| change to 0 | active customer | counted as Churn, flagged SM05 |
| `churn` | active customer | Churn MRR = the customer's MRR before churning (+ churned customer) |
| any change / churn | no active subscription | ignored, flagged SM02 |

Bridge identity (checked every month): `start MRR + new + expansion + reactivation - contraction - churn = end MRR`.

## Monthly metrics
- **Net new MRR** = end MRR - start MRR
- **Logo churn rate** = churned customers / paying customers at start of month
- **MRR churn rate (gross)** = (churn + contraction) / start MRR
- **GRR (gross revenue retention)** = (start MRR - churn - contraction) / start MRR, never above 100%
- **NRR (net revenue retention)** = (start MRR - churn - contraction + expansion) / start MRR; reactivation and new are excluded
- **Quick ratio** = (new + expansion + reactivation) / (churn + contraction); above 4 is excellent, 1-2 means growth is fragile, below 1 means shrinking
- **ARPA** = end MRR / paying customers at end of month

## Period and cohort metrics
- **Period NRR** (`--from`): customers paying at the end of the month before the window; their MRR at the end of the window divided by their MRR at the start. New customers acquired in the window are excluded.
- **Logo retention**: share of that base still paying at the end of the window.
- **Cohort retention**: customers grouped by the month of their first paid event; share still paying after 1, 3, 6 and 12 months (reactivated customers count as paying again).
- **Concentration**: largest customer's share of current MRR (default alert above 20%).

## Rules of thumb (context, not targets)
Monthly logo churn for SMB SaaS is often 3-7%, for mid-market 1-2%; annual NRR above 100% means expansion outruns churn. Compare with your own history before comparing with benchmarks.

FILE:references/data-prep-and-pitfalls.md
# Data preparation and pitfalls

## Getting an events file
- **Stripe**: export subscriptions and subscription item changes (or invoice line items for `subscription` items); one row per change with the new recurring price. Use `plan.interval` (month/year) and `interval_count` for `billing`.
- **Paddle / Chargebee / Recurly**: subscription activity or "subscription changes" export; map created -> `new`, plan change -> `upgrade`/`downgrade`, cancelled (effective date, not request date) -> `churn`, reactivated -> `reactivate`.
- **Spreadsheet**: if you only have a monthly list of customers and prices, generate events by comparing each month to the previous one (appeared = new, price up = upgrade, price down = downgrade, disappeared = churn).

## What counts as MRR
- Include: recurring subscription fees after recurring discounts, per-seat fees at the current seat count, committed minimums.
- Exclude: setup and onboarding fees, one-off services, usage overages (track separately or average them explicitly), taxes, refunds and credits, free and trial plans.
- Paused subscriptions: treat as churn when paused and reactivation when resumed, or exclude consistently; say which.
- Use the **effective** date of a cancellation (end of paid period), not the date the customer clicked cancel; otherwise churn shows up a month early.

## Classic mistakes the script catches
1. Annual price typed as monthly (SM04): MRR jumps by the full contract value. Set `billing=annual`.
2. Wrong event labels (SM05): an "upgrade" to a cheaper plan. The script trusts the amounts, not the label, and flags the row.
3. Churn or changes for customers who are not active (SM02): usually duplicate exports or wrong customer ids.
4. Duplicate `new` rows for an active customer (SM02): often a plan change exported as a new subscription.
5. Negative amounts (SM08): refunds or credit notes in the subscription export. Remove them.

## Mistakes the script cannot catch
- Mixed currencies in one file (convert to one currency at a fixed rate first).
- Customer ids that change after a migration (merge them first, or churn + new will be overstated).
- Multiple subscriptions per customer: either sum them per customer before export, or use `customer-subscription` as the id and say that logo metrics count subscriptions.

FILE:templates/metrics-report.md
# Subscription metrics report: [Company], [reporting window]

**Ending MRR:** [x] ([+/- y%] vs previous month, [+/- z%] vs start of window)  **ARR run-rate:** [MRR x 12]
**Paying customers:** [n]  **ARPA:** [x]
**Data status:** [clean / corrected: list of fixes]  (`mrr_metrics.py` output attached)

## MRR bridge
| Month | Start | New | Expansion | Contraction | Churn | Reactivation | End | Logo churn | NRR | Quick ratio |
|---|---|---|---|---|---|---|---|---|---|---|
| [YYYY-MM] | | | | | | | | | | |

## Retention
- Period NRR [x%], GRR trend [..], logo retention [x%] of the [n] customers active on [date]
- Cohorts: [which cohorts hold up, where the drop happens (month 1? month 3?)]

## What changed and why
1. [Biggest movement and its drivers, with customer names if useful]
2. [...]

## Risks
- Concentration: [largest customer share]
- [Churn spike / shrinking months / small-sample caveat]

## Data corrections made
| Row | Problem | Fix |
|---|---|---|
| [line 12, A09] | [annual typed as monthly] | [billing=annual] |

## Recommended actions (next 30 days)
1. [...]
2. [...]
3. [...]

_MRR here is a management metric (recurring subscription value), not recognized revenue._

FILE:examples/subscription_events.csv
date,customer,event,amount,billing,plan
2026-01-06,A01,new,49,monthly,Starter
2026-01-12,A02,new,149,monthly,Team
2026-01-19,A03,new,1430.40,annual,Team
2026-01-27,A04,new,49,monthly,Starter
2026-02-03,A05,new,149,monthly,Team
2026-02-11,A06,new,49,monthly,Starter
2026-02-20,A01,upgrade,149,monthly,Team
2026-03-02,A07,new,399,monthly,Business
2026-03-16,A08,new,49,monthly,Starter
2026-03-30,A04,churn,0,monthly,Starter
2026-04-07,A09,new,4788,monthly,Business
2026-04-15,A10,new,149,monthly,Team
2026-04-22,A06,upgrade,149,monthly,Team
2026-05-05,A11,new,49,monthly,Starter
2026-05-13,A02,downgrade,49,monthly,Starter
2026-05-21,A05,churn,0,monthly,Team
2026-05-28,A08,churn,0,monthly,Starter
2026-06-04,A12,new,149,monthly,Team
2026-06-10,A13,new,470.40,annual,Starter
2026-06-24,A07,upgrade,149,monthly,Team
2026-07-01,A14,new,49,monthly,Starter
2026-07-09,A04,reactivate,149,monthly,Team
2026-07-15,A15,new,0,monthly,Free
2026-07-23,A99,churn,0,monthly,Team
2026-08-04,A16,new,149,monthly,Team
2026-08-12,A10,churn,0,monthly,Team
2026-08-19,A11,churn,0,monthly,Starter
2026-08-26,A12,churn,0,monthly,Team
2026-09-02,A17,new,399,monthly,Business
2026-09-09,A18,new,49,monthly,Starter
2026-09-17,A14,upgrade,149,monthly,Team
2026-10-06,A19,new,149,monthly,Team
2026-10-14,A20,new,49,monthly,Starter
2026-10-20,A06,downgrade,49,monthly,Starter
2026-10-27,A01,new,149,monthly,Team

FILE:scripts/mrr_metrics.py
#!/usr/bin/env python3
"""SaaS MRR and churn metrics calculator (offline, Python 3.8+ standard library only).

Reads a subscription events CSV (date, customer, event, amount, billing, plan), normalizes
annual and quarterly amounts to MRR, builds a month-by-month MRR bridge (new, expansion,
contraction, churn, reactivation), computes logo churn, GRR, NRR, ARPA and quick ratio, and
flags data problems and business warning signs.

Usage:
  mrr_metrics.py events.csv [--from 2026-01] [--to 2026-10] [--json] [--top-share 0.2]
  mrr_metrics.py --self-test
Exit codes: 0 = no high findings, 1 = high findings, 2 = bad input.
"""
import argparse, csv, json, statistics, sys
from collections import Counter, OrderedDict
from datetime import date

EVENTS = {"new", "upgrade", "downgrade", "churn", "reactivate", "price_change"}
BILLING_MONTHS = {"monthly": 1, "quarterly": 3, "annual": 12, "yearly": 12}
SEV = {"high": 0, "medium": 1, "low": 2}


def month_key(s):
    y, m = int(s[:4]), int(s[5:7])
    if not (1 <= m <= 12):
        raise ValueError("bad month in %r" % s)
    return "%04d-%02d" % (y, m)


def next_month(k):
    y, m = int(k[:4]), int(k[5:7])
    return "%04d-%02d" % (y + (m == 12), 1 if m == 12 else m + 1)


def month_range(a, b):
    out = [a]
    while out[-1] < b:
        out.append(next_month(out[-1]))
    return out


def load(path):
    with open(path, newline="", encoding="utf-8-sig") as fh:
        rows = list(csv.DictReader(fh))
    need = {"date", "customer", "event", "amount"}
    if not rows or not need <= set(k.strip() for k in rows[0].keys()):
        raise ValueError("CSV needs columns: date, customer, event, amount (optional: billing, plan)")
    return [{k.strip(): (v or "").strip() for k, v in r.items()} for r in rows]


def compute(rows, start=None, end=None, top_share=0.2, churn_alert=0.05):
    findings = []
    def add(code, sev, msg, month=None, customer=None):
        findings.append({"code": code, "severity": sev, "month": month, "customer": customer, "message": msg})
    events = []
    for i, r in enumerate(rows, start=2):
        try:
            d = date.fromisoformat(r["date"][:10])
        except ValueError:
            add("SM01", "high", "line %d: bad date %r" % (i, r["date"])); continue
        ev = r["event"].lower()
        if ev not in EVENTS:
            add("SM01", "high", "line %d: unknown event %r (use %s)" % (i, r["event"], ", ".join(sorted(EVENTS)))); continue
        billing = (r.get("billing") or "monthly").lower()
        if billing not in BILLING_MONTHS:
            add("SM01", "high", "line %d: unknown billing %r" % (i, billing)); continue
        try:
            amount = float(r["amount"] or 0)
        except ValueError:
            add("SM01", "high", "line %d: amount %r is not a number" % (i, r["amount"])); continue
        if amount < 0:
            add("SM08", "high", "line %d: negative amount %.2f (refunds and credits are not MRR)" % (i, amount), customer=r["customer"]); continue
        events.append({"line": i, "date": d, "month": d.strftime("%Y-%m"), "customer": r["customer"], "event": ev,
                       "mrr": round(amount / BILLING_MONTHS[billing], 2), "billing": billing, "amount": amount, "plan": r.get("plan", "")})
    if not events:
        raise ValueError("no usable events")
    events.sort(key=lambda e: (e["date"], e["line"]))
    # SM04: monthly-billed amounts that look like annual totals typed as monthly
    monthly_amounts = [e["mrr"] for e in events if e["billing"] == "monthly" and e["mrr"] > 0]
    med = statistics.median(monthly_amounts) if monthly_amounts else 0
    for e in events:
        if med and e["billing"] == "monthly" and e["mrr"] >= 8 * med and e["mrr"] > 0:
            add("SM04", "medium", "line %d: monthly amount %.2f is %.0fx the median monthly price: an annual contract entered as monthly? (set billing=annual)" % (e["line"], e["mrr"], e["mrr"] / med), e["month"], e["customer"])
    first = start or events[0]["month"]
    last = end or events[-1]["month"]
    months = month_range(min(first, events[0]["month"]), last)
    state = {}            # customer -> current MRR (0 = churned)
    ever = set()
    bridge = OrderedDict()
    by_month = {}
    for e in events:
        by_month.setdefault(e["month"], []).append(e)
    cohort_start = {}
    active_by_month = {}
    snaps = {}
    for m in months:
        start_mrr = round(sum(state.values()), 2)
        start_logos = sum(1 for v in state.values() if v > 0)
        b = {"month": m, "start_mrr": start_mrr, "new": 0.0, "expansion": 0.0, "contraction": 0.0, "churn": 0.0, "reactivation": 0.0,
             "start_customers": start_logos, "new_customers": 0, "churned_customers": 0, "reactivated_customers": 0}
        for e in by_month.get(m, []):
            c, ev, new = e["customer"], e["event"], e["mrr"]
            cur = state.get(c)
            if ev == "new":
                if cur is not None and cur > 0:
                    add("SM02", "medium", "line %d: 'new' for a customer who is already active (%.2f MRR); treated as a price change" % (e["line"], cur), m, c)
                    ev = "price_change"
                elif cur is not None and cur == 0 and c in ever:
                    add("SM02", "low", "line %d: 'new' for a returning customer; counted as reactivation" % e["line"], m, c)
                    ev = "reactivate"
            if ev == "new":
                state[c] = new; b["new"] += new
                if new == 0:
                    add("SM03", "low", "line %d: new customer with 0 MRR (free plan or trial?) not counted in paid metrics" % e["line"], m, c)
                else:
                    b["new_customers"] += 1; cohort_start[c] = m; ever.add(c)
            elif ev == "churn":
                if not cur:
                    add("SM02", "medium", "line %d: churn for a customer who is not active; ignored" % e["line"], m, c); continue
                b["churn"] += cur; b["churned_customers"] += 1; state[c] = 0.0
            elif ev == "reactivate":
                if cur:
                    add("SM02", "medium", "line %d: reactivate for an active customer; treated as a price change" % e["line"], m, c)
                    ev = "price_change"
                else:
                    if c not in ever:
                        add("SM02", "low", "line %d: reactivate for an unknown customer; counted as new" % e["line"], m, c)
                        b["new"] += new; b["new_customers"] += 1; ever.add(c); cohort_start[c] = m
                    else:
                        b["reactivation"] += new; b["reactivated_customers"] += 1
                    state[c] = new
            if ev in ("upgrade", "downgrade", "price_change"):
                if cur is None or cur == 0:
                    add("SM02", "medium", "line %d: %s for a customer with no active subscription; ignored" % (e["line"], e["event"]), m, c); continue
                delta = round(new - cur, 2)
                if e["event"] == "upgrade" and delta < 0:
                    add("SM05", "medium", "line %d: 'upgrade' lowers MRR %.2f -> %.2f; check the event type" % (e["line"], cur, new), m, c)
                if e["event"] == "downgrade" and delta > 0:
                    add("SM05", "medium", "line %d: 'downgrade' raises MRR %.2f -> %.2f; check the event type" % (e["line"], cur, new), m, c)
                if new == 0:
                    add("SM05", "medium", "line %d: change to 0 MRR; record it as churn instead" % e["line"], m, c)
                    b["churn"] += cur; b["churned_customers"] += 1; state[c] = 0.0; continue
                if delta > 0: b["expansion"] += delta
                else: b["contraction"] += -delta
                state[c] = new
        end_mrr = round(sum(state.values()), 2)
        for k in ("new", "expansion", "contraction", "churn", "reactivation"):
            b[k] = round(b[k], 2)
        b["end_mrr"] = end_mrr
        b["net_new_mrr"] = round(end_mrr - start_mrr, 2)
        b["end_customers"] = sum(1 for v in state.values() if v > 0)
        b["arpa"] = round(end_mrr / b["end_customers"], 2) if b["end_customers"] else 0.0
        if start_mrr:
            b["grr"] = round((start_mrr - b["churn"] - b["contraction"]) / start_mrr, 4)
            b["nrr"] = round((start_mrr - b["churn"] - b["contraction"] + b["expansion"]) / start_mrr, 4)
            b["mrr_churn_rate"] = round((b["churn"] + b["contraction"]) / start_mrr, 4)
        else:
            b["grr"] = b["nrr"] = b["mrr_churn_rate"] = None
        b["logo_churn_rate"] = round(b["churned_customers"] / start_logos, 4) if start_logos else None
        lost = b["churn"] + b["contraction"]
        b["quick_ratio"] = round((b["new"] + b["expansion"] + b["reactivation"]) / lost, 2) if lost else None
        assert abs(start_mrr + b["new"] + b["expansion"] + b["reactivation"] - b["contraction"] - b["churn"] - end_mrr) < 0.05, m
        active_by_month[m] = {c for c, v in state.items() if v > 0}
        snaps[m] = dict(state)
        bridge[m] = b
    report_months = [m for m in months if m >= first]
    rows_out = [bridge[m] for m in report_months]
    for b in rows_out:
        m = b["month"]
        if b["logo_churn_rate"] is not None and b["logo_churn_rate"] > churn_alert and b["start_customers"] >= 5:
            add("SM06", "medium", "logo churn %.1f%% in %s (alert above %.1f%%)" % (100 * b["logo_churn_rate"], m, 100 * churn_alert), m)
        if b["quick_ratio"] is not None and b["quick_ratio"] < 1:
            add("SM07", "high", "quick ratio %.2f in %s: lost MRR exceeded gained MRR (shrinking)" % (b["quick_ratio"], m), m)
    # trailing NRR over the reported period (cohort of customers active at period start)
    base_month = report_months[0]
    prev = None
    for m in months:
        if m == base_month: break
        prev = m
    period = {}
    if prev and snaps[prev]:
        base = {c: v for c, v in snaps[prev].items() if v > 0}
        now = snaps[report_months[-1]]
        start_sum = sum(base.values()); end_sum = sum(now.get(c, 0) for c in base)
        kept = sum(1 for c in base if now.get(c, 0) > 0)
        period = {"base_month": prev, "base_customers": len(base), "base_mrr": round(start_sum, 2),
                  "same_customers_mrr_now": round(end_sum, 2), "period_nrr": round(end_sum / start_sum, 4) if start_sum else None,
                  "logo_retention": round(kept / len(base), 4) if base else None}
        if period["period_nrr"] is not None and period["period_nrr"] < 1:
            add("SM09", "medium", "net revenue retention over %s..%s is %.1f%% (<100%%): existing customers shrink" % (report_months[0], report_months[-1], 100 * period["period_nrr"]))
    final = {c: v for c, v in state.items() if v > 0}
    total = sum(final.values())
    if total:
        top = sorted(final.items(), key=lambda x: -x[1])[:3]
        if top[0][1] / total > top_share:
            add("SM10", "medium", "largest customer %s is %.0f%% of MRR (threshold %.0f%%): concentration risk" % (top[0][0], 100 * top[0][1] / total, 100 * top_share), customer=top[0][0])
    # cohorts: logo retention by start month
    cohorts = OrderedDict()
    for c, m in sorted(cohort_start.items(), key=lambda x: x[1]):
        cohorts.setdefault(m, []).append(c)
    cohort_table = []
    for m, cs in cohorts.items():
        row = {"cohort": m, "customers": len(cs)}
        k = m
        for i in range(0, 13):
            if k > last: break
            if i in (1, 3, 6, 12):
                row["m%d" % i] = round(sum(1 for c in cs if c in active_by_month[k]) / len(cs), 2)
            k = next_month(k)
        cohort_table.append(row)
    findings.sort(key=lambda f: (SEV[f["severity"]], f["code"], f["month"] or ""))
    s = Counter(f["severity"] for f in findings)
    return {"months": rows_out, "period": period, "cohorts": cohort_table,
            "top_customers": [{"customer": c, "mrr": v, "share": round(v / total, 3)} for c, v in sorted(final.items(), key=lambda x: -x[1])[:5]] if total else [],
            "findings": findings, "summary": {k: s.get(k, 0) for k in ("high", "medium", "low")}}


def pct(x):
    return "   -  " if x is None else "%5.1f%%" % (100 * x)


def print_text(rep):
    print("MRR bridge")
    print("month    start_mrr      new  expans  contr    churn  react   end_mrr  cust  logo_ch   GRR     NRR    QR    ARPA")
    for b in rep["months"]:
        print("%s %10.2f %8.2f %7.2f %6.2f %8.2f %6.2f %9.2f %5d %s %s %s %5s %7.2f" % (
            b["month"], b["start_mrr"], b["new"], b["expansion"], b["contraction"], b["churn"], b["reactivation"],
            b["end_mrr"], b["end_customers"], pct(b["logo_churn_rate"]), pct(b["grr"]), pct(b["nrr"]),
            "-" if b["quick_ratio"] is None else "%.2f" % b["quick_ratio"], b["arpa"]))
    p = rep["period"]
    if p:
        print("\nPeriod retention (customers active at end of %s: %d, %.2f MRR): NRR %s, logo retention %s" % (
            p["base_month"], p["base_customers"], p["base_mrr"], pct(p["period_nrr"]), pct(p["logo_retention"])))
    if rep["cohorts"]:
        print("\nCohort logo retention (share still paying after N months)")
        for c in rep["cohorts"]:
            print("  %s  n=%-3d m1=%s m3=%s m6=%s" % (c["cohort"], c["customers"], c.get("m1", "-"), c.get("m3", "-"), c.get("m6", "-")))
    print("\nTop customers: " + ", ".join("%s %.2f (%.0f%%)" % (t["customer"], t["mrr"], 100 * t["share"]) for t in rep["top_customers"]))
    print("\nFindings: %(high)d high, %(medium)d medium, %(low)d low" % rep["summary"])
    for f in rep["findings"]:
        print("  [%s] %s %s%s: %s" % (f["severity"].upper(), f["code"], f["month"] or "", (" " + f["customer"]) if f["customer"] else "", f["message"]))


def self_test():
    ok = total = 0
    def t(name, cond):
        nonlocal ok, total
        total += 1; ok += bool(cond)
        print(("PASS  " if cond else "FAIL  ") + name)
    def R(*lines):
        return [dict(zip(["date", "customer", "event", "amount", "billing"], l.split(","))) for l in lines]
    r = compute(R("2026-01-05,a,new,100,monthly", "2026-01-09,b,new,1200,annual", "2026-02-03,a,upgrade,150,monthly",
                  "2026-02-10,b,churn,0,annual", "2026-03-01,b,reactivate,50,monthly", "2026-03-15,c,new,200,monthly"))
    m = {b["month"]: b for b in r["months"]}
    t("annual normalized to MRR", m["2026-01"]["end_mrr"] == 200)
    t("expansion counted", m["2026-02"]["expansion"] == 50)
    t("churn counted at prior MRR", m["2026-02"]["churn"] == 100 and m["2026-02"]["churned_customers"] == 1)
    t("reactivation separate from new", m["2026-03"]["reactivation"] == 50 and m["2026-03"]["new"] == 200)
    t("bridge closes", all(abs(b["start_mrr"] + b["new"] + b["expansion"] + b["reactivation"] - b["contraction"] - b["churn"] - b["end_mrr"]) < 0.01 for b in r["months"]))
    t("NRR feb = (200-100+50)/200", m["2026-02"]["nrr"] == 0.75 and m["2026-02"]["grr"] == 0.5)
    t("SM07 quick ratio < 1 in feb", any(f["code"] == "SM07" and f["month"] == "2026-02" for f in r["findings"]))
    r = compute(R("2026-01-01,a,new,50,monthly", "2026-01-01,b,new,50,monthly", "2026-01-01,c,new,55,monthly", "2026-01-02,d,new,1200,monthly"))
    t("SM04 annual typed as monthly", any(f["code"] == "SM04" and f["customer"] == "d" for f in r["findings"]))
    t("SM10 concentration", any(f["code"] == "SM10" for f in r["findings"]))
    r = compute(R("2026-01-01,a,new,50,monthly", "2026-02-01,a,upgrade,40,monthly", "2026-02-02,z,churn,0,monthly", "2026-02-03,a,new,60,monthly"))
    codes = Counter(f["code"] for f in r["findings"])
    t("SM05 upgrade lowering MRR", codes["SM05"] == 1)
    t("SM02 churn of unknown + new for active", codes["SM02"] == 2)
    t("contraction from mislabeled upgrade", r["months"][1]["contraction"] == 10 and r["months"][1]["expansion"] == 20)
    rows = R(*["2026-01-0%d,c%d,new,100,monthly" % (1 + i % 9, i) for i in range(20)] + ["2026-02-05,c%d,churn,0,monthly" % i for i in range(3)])
    r = compute(rows)
    t("SM06 logo churn alert (15%)", any(f["code"] == "SM06" for f in r["findings"]) and r["months"][1]["logo_churn_rate"] == 0.15)
    r = compute(R("2026-01-01,a,new,100,monthly", "2026-01-01,b,new,100,monthly", "2026-02-01,a,downgrade,60,monthly", "2026-03-01,c,new,500,monthly"), start="2026-02")
    t("period NRR for base cohort excludes new logos", r["period"]["period_nrr"] == 0.8 and r["period"]["base_customers"] == 2)
    t("SM09 NRR < 100%", any(f["code"] == "SM09" for f in r["findings"]))
    r = compute(R("2026-01-01,f,new,0,monthly", "2026-02-01,f,new,49,monthly"))
    t("free-to-paid conversion counted as new", r["months"][1]["new"] == 49 and r["months"][1]["new_customers"] == 1 and r["months"][0]["new_customers"] == 0)
    try:
        compute(R("2026-13-01,a,new,1,monthly")); t("bad date reported", False)
    except ValueError:
        t("bad date -> no usable events error", True)
    print("%d/%d passed" % (ok, total))
    return 0 if ok == total else 1


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("file", nargs="?"); ap.add_argument("--from", dest="start"); ap.add_argument("--to", dest="end")
    ap.add_argument("--json", action="store_true"); ap.add_argument("--top-share", type=float, default=0.2)
    ap.add_argument("--churn-alert", type=float, default=0.05); ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args()
    if a.self_test:
        return self_test()
    if not a.file:
        ap.print_help(); return 2
    try:
        rep = compute(load(a.file), a.start and month_key(a.start), a.end and month_key(a.end), a.top_share, a.churn_alert)
    except (OSError, ValueError) as e:
        print("bad input: %s" % e, file=sys.stderr); return 2
    if a.json:
        print(json.dumps(rep, indent=2))
    else:
        print_text(rep)
    return 1 if rep["summary"]["high"] else 0


if __name__ == "__main__":
    sys.exit(main())
SaaSRevenueData Analysis+3
F@f
0
SLO Error Budget and Burn Rate Calculator
Skill

Turns request counts into SLO answers: SLI, error budget for a 28d or 30d window, budget consumed and remaining, burn rates over 5m to 3d, multiwindow burn-rate alerts (page at 14.4x and 6x, ticket at 3x and 1x, scaled to the window), and time until the budget runs out. Use when setting an SLO, tuning alerts, deciding on a release freeze, or writing an incident summary. Includes a stdlib Python calculator with --self-test.

---
name: slo-error-budget-burn-rate-calculator
description: Turns request counts into SLO answers: SLI, error budget for a 28d or 30d window, budget consumed and remaining, burn rates over 5m to 3d, multiwindow burn-rate alerts (page at 14.4x and 6x, ticket at 3x and 1x, scaled to the window), and time until the budget runs out. Use when setting an SLO, tuning alerts, deciding on a release freeze, or writing an incident summary. Includes a stdlib Python calculator with --self-test.
---

# SLO Error Budget and Burn Rate Calculator

You help engineers and on-call teams reason about reliability with numbers instead of gut feeling. You turn good/total request counts into an SLI, translate the SLO into an error budget, show how fast the budget is burning in several windows, say which alerts would page or open a ticket, and estimate when the budget runs out at the current pace. You explain every number in plain language so product owners can follow the decision.

## Files in this skill

- `scripts/slo_budget.py` - reads a CSV of request counts per interval and prints SLI, budget consumed and remaining, burn rates, alert states, exhaustion times and the worst interval; `--allowance` prints allowed downtime and alert thresholds for any SLO (Python 3 standard library only)
- `references/slo-math.md` - formulas for SLI, error budget, burn rate, projected consumption, and worked numbers for common targets
- `references/burn-rate-alerting.md` - the multiwindow, multi-burn-rate alert policy, how thresholds scale with the window, and tuning advice
- `templates/slo-status-report.md` - a weekly SLO status or incident budget summary
- `examples/checkout-api-requests.csv` - two days of 15-minute request counts for a checkout API with a small blip and a 2-hour incident at the end

## Workflow

### 1. Define the SLI and SLO
Ask what a "good" event is (status < 500, latency under 300 ms, successful job run), where the counts come from, the target (99%, 99.5%, 99.9%, 99.95%), and the window (rolling 28 or 30 days). Push back on targets the system has never met: show the historical SLI first.

### 2. Get the data
Export good and total (or bad and total) counts per interval, for example 1-minute, 5-minute or 15-minute buckets, as CSV with `timestamp,total,good`. The timestamp marks the start of each interval. Use UTC.

### 3. Run the calculator
```
python3 scripts/slo_budget.py examples/checkout-api-requests.csv --slo 99.9 --window 30d
python3 scripts/slo_budget.py requests.csv --slo 99.5 --window 28d --json > slo.json
python3 scripts/slo_budget.py requests.csv --now 2026-10-19T22:00:00Z
python3 scripts/slo_budget.py --allowance --slo 99.95 --window 30d
python3 scripts/slo_budget.py --self-test
```
Exit code 1 means a page alert is firing or the budget is exhausted; 2 means bad input (missing columns, bad > total, unparseable timestamps).

### 4. Interpret
- Burn rate 1.0 spends exactly the budget over the window; 14.4 for an hour spends 2% of a 30-day budget.
- Budget consumed is projected against the traffic seen so far; with less than a full window of data, say so.
- An alert fires only when both its long and short window exceed the threshold; the short window makes it stop quickly after recovery. See `references/burn-rate-alerting.md`.
- Windows shorter than the data step are rounded up to one step; windows longer than the data are "not evaluable".

### 5. Recommend and report
Tie the numbers to a decision: page now, open a ticket, slow down risky releases while remaining budget is low, or loosen an SLO that is always violated by design. Fill `templates/slo-status-report.md`.

## Example result
For `examples/checkout-api-requests.csv` at 99.9% over 30d: SLI 99.8768%, 8.2% of the budget consumed, 1h burn 26.46 and 5m burn 28.06 so the fast page fires, 6h burn 5.83 just under 6.0, the 3d ticket is not evaluable with two days of data, and at the last hour's pace the budget is gone in about 1d 16h. Exit code 1.

## Rules

- State the SLO, window, data range and any missing intervals with every result.
- Do not mix good-event definitions in one SLI; compute separate SLOs for availability and latency.
- An SLO is a decision tool, not a blame tool: describe impact on users, not on people.
- Do not invent traffic numbers; if counts are missing, ask for them or say which result cannot be computed.
FILE:references/slo-math.md
# SLO Math

## Definitions
- **SLI** (service level indicator) = good events / total events, as a percentage.
- **SLO** (objective) = target SLI over a window, e.g. 99.9% of requests succeed over a rolling 30 days.
- **Error budget** = 1 - SLO = the share of events allowed to fail. 99.9% -> 0.1%.
- **Budget in events** = (1 - SLO) x total events in the window.
- **Error rate** over a window = bad / total in that window.
- **Burn rate** = error rate / (1 - SLO). 1.0 means the budget would be exactly used up at the end of the window.

## Projected consumption with partial data
With D seconds of data and W seconds of SLO window:
- expected requests in window = (requests in data / D) x W
- allowed bad = (1 - SLO) x expected requests
- consumed = bad in data / allowed bad
- time to exhaustion at a recent rate = (allowed bad - bad so far) / (bad per second in that recent window)

## Allowed full downtime
| SLO | per 30 days | per 28 days | per week | per day |
|---|---|---|---|---|
| 99% | 7h 12m | 6h 43m 12s | 1h 40m 48s | 14m 24s |
| 99.5% | 3h 36m | 3h 21m 36s | 50m 24s | 7m 12s |
| 99.9% | 43m 12s | 40m 19s | 10m 5s | 1m 26s |
| 99.95% | 21m 36s | 20m 10s | 5m 2s | 43s |
| 99.99% | 4m 19s | 4m 2s | 1m 0s | 9s |

Request-based SLOs do not care about clock time directly: 10 minutes of 50% errors costs the same as 5 minutes of full downtime at equal traffic, and an outage at 3 a.m. costs less budget than one at peak.

## Worked example
SLO 99.9%, 30d window, 1,000,000 requests per day.
- Budget: 0.001 x 30,000,000 = 30,000 failed requests.
- A 2% error rate for one hour at 41,667 req/h burns 833 failures = 2.8% of the budget, burn rate 20.
- At burn rate 20 the whole budget lasts 30d / 20 = 36 hours.

## Pitfalls
- Counting retries as separate good events hides user-facing failures.
- Very low traffic (night, new region) makes error rates noisy; use a minimum request count or a longer short window.
- Synthetic probes measure the probe, not users; label them separately.
- Changing the SLO mid-window: recompute the whole window with the new target and say so.
FILE:references/burn-rate-alerting.md
# Burn-Rate Alerting

## Default policy (multiwindow, multi-burn-rate)
| Severity | Budget share | Long window | Short window | Burn threshold (30d) | Burn threshold (28d) |
|---|---|---|---|---|---|
| page | 2% | 1h | 5m | 14.4 | 13.44 |
| page | 5% | 6h | 30m | 6.0 | 5.6 |
| ticket | 10% | 1d | 2h | 3.0 | 2.8 |
| ticket | 10% | 3d | 6h | 1.0 | 0.93 |

Threshold = budget share x SLO window / long window. Example: 0.02 x 720h / 1h = 14.4.

## Why two windows
- The **long window** proves the problem is significant (enough budget spent).
- The **short window** (about 1/12 of the long one) proves it is still happening, so the alert resets within minutes after recovery instead of staying red for an hour.
- Fire only when both exceed the threshold.

## Example alert rule (Prometheus style)
```
(
  sum(rate(http_requests_errors_total[1h])) / sum(rate(http_requests_total[1h])) > (14.4 * 0.001)
and
  sum(rate(http_requests_errors_total[5m])) / sum(rate(http_requests_total[5m])) > (14.4 * 0.001)
)
```

## Tuning
- Low-traffic services: require a minimum number of requests in the short window, or page on 6h only.
- Too many pages: check whether the SLO is stricter than users need before raising thresholds.
- Missed incidents: slow burns below 1.0 never alert by design; review the budget weekly.
- Data step coarser than the short window (e.g. 15-minute buckets): the short window becomes one bucket and recovery detection is slower.

## Budget policy ideas
- Over 50% consumed: review risky changes, prefer canaries.
- Over 75%: release freeze for non-fixes, reliability work first.
- Exhausted: postmortem required; freeze until the rolling window recovers.
FILE:templates/slo-status-report.md
# SLO Status - <service> - <period or incident>

**SLI:** <what counts as good>  **SLO:** <target>% over rolling <28d/30d>
**Data:** <start> to <end> UTC, step <interval>, <n> missing intervals
**Calculator:** `slo_budget.py --slo <target> --window <window>` (exit <code>)

## Budget
| Metric | Value |
|---|---|
| SLI in period | |
| Budget consumed | |
| Budget remaining | |
| Allowed full downtime per window | |

## Burn rates
| 5m | 30m | 1h | 2h | 6h | 1d | 3d |
|---|---|---|---|---|---|---|
| | | | | | | |

## Alerts
| Policy | Status | Long / short burn |
|---|---|---|
| page 1h/5m | | |
| page 6h/30m | | |
| ticket 1d/2h | | |
| ticket 3d/6h | | |

## What happened
<worst interval, user impact, cause if known>

## Decision
- [ ] Page / incident open
- [ ] Release policy: <normal / caution / freeze> because <remaining budget>
- [ ] SLO or alert tuning: <change and reason>

## Summary for stakeholders
> <service> met <SLI>% against a <target>% target. <x>% of this window's error budget is used; at the current pace it lasts <time>. Next step: <decision>.
FILE:examples/checkout-api-requests.csv
timestamp,total,good
2026-10-18T00:00:00Z,4757,4755
2026-10-18T00:15:00Z,4525,4523
2026-10-18T00:30:00Z,4313,4311
2026-10-18T00:45:00Z,4122,4120
2026-10-18T01:00:00Z,3951,3949
2026-10-18T01:15:00Z,3803,3801
2026-10-18T01:30:00Z,3678,3676
2026-10-18T01:45:00Z,3577,3576
2026-10-18T02:00:00Z,3500,3498
2026-10-18T02:15:00Z,3448,3446
2026-10-18T02:30:00Z,3421,3419
2026-10-18T02:45:00Z,3019,3018
2026-10-18T03:00:00Z,3044,3043
2026-10-18T03:15:00Z,3093,3092
2026-10-18T03:30:00Z,3169,3168
2026-10-18T03:45:00Z,3270,3268
2026-10-18T04:00:00Z,3396,3394
2026-10-18T04:15:00Z,3547,3545
2026-10-18T04:30:00Z,3722,3720
2026-10-18T04:45:00Z,3921,3919
2026-10-18T05:00:00Z,4143,4141
2026-10-18T05:15:00Z,4388,4386
2026-10-18T05:30:00Z,4253,4251
2026-10-18T05:45:00Z,4539,4537
2026-10-18T06:00:00Z,4845,4843
2026-10-18T06:15:00Z,5168,5166
2026-10-18T06:30:00Z,5509,5507
2026-10-18T06:45:00Z,5865,5863
2026-10-18T07:00:00Z,6236,6234
2026-10-18T07:15:00Z,6619,6616
2026-10-18T07:30:00Z,7013,7009
2026-10-18T07:45:00Z,7418,7414
2026-10-18T08:00:00Z,7831,7827
2026-10-18T08:15:00Z,7850,7847
2026-10-18T08:30:00Z,8274,8271
2026-10-18T08:45:00Z,8702,8699
2026-10-18T09:00:00Z,9132,9127
2026-10-18T09:15:00Z,9561,9556
2026-10-18T09:30:00Z,9989,9984
2026-10-18T09:45:00Z,10413,10408
2026-10-18T10:00:00Z,10832,10827
2026-10-18T10:15:00Z,11245,11240
2026-10-18T10:30:00Z,11650,11645
2026-10-18T10:45:00Z,12044,12038
2026-10-18T11:00:00Z,12028,12022
2026-10-18T11:15:00Z,12398,12392
2026-10-18T11:30:00Z,12754,12748
2026-10-18T11:45:00Z,13095,13089
2026-10-18T12:00:00Z,13418,13412
2026-10-18T12:15:00Z,13724,13719
2026-10-18T12:30:00Z,14010,14003
2026-10-18T12:45:00Z,14275,14268
2026-10-18T13:00:00Z,14520,14513
2026-10-18T13:15:00Z,14742,14735
2026-10-18T13:30:00Z,14941,14934
2026-10-18T13:45:00Z,14716,14710
2026-10-18T14:00:00Z,14867,14861
2026-10-18T14:15:00Z,14993,14985
2026-10-18T14:30:00Z,15094,15086
2026-10-18T14:45:00Z,15170,15163
2026-10-18T15:00:00Z,15220,15213
2026-10-18T15:15:00Z,15244,15237
2026-10-18T15:30:00Z,15242,15236
2026-10-18T15:45:00Z,15215,15209
2026-10-18T16:00:00Z,15163,15155
2026-10-18T16:15:00Z,14686,14679
2026-10-18T16:30:00Z,14585,14578
2026-10-18T16:45:00Z,14460,14453
2026-10-18T17:00:00Z,14312,14306
2026-10-18T17:15:00Z,14141,14135
2026-10-18T17:30:00Z,13950,13866
2026-10-18T17:45:00Z,13738,13656
2026-10-18T18:00:00Z,13506,13499
2026-10-18T18:15:00Z,13257,13251
2026-10-18T18:30:00Z,12990,12984
2026-10-18T18:45:00Z,12708,12702
2026-10-18T19:00:00Z,12012,12007
2026-10-18T19:15:00Z,11702,11697
2026-10-18T19:30:00Z,11382,11376
2026-10-18T19:45:00Z,11051,11045
2026-10-18T20:00:00Z,10712,10707
2026-10-18T20:15:00Z,10367,10362
2026-10-18T20:30:00Z,10017,10013
2026-10-18T20:45:00Z,9663,9659
2026-10-18T21:00:00Z,9308,9304
2026-10-18T21:15:00Z,8952,8947
2026-10-18T21:30:00Z,8598,8594
2026-10-18T21:45:00Z,7848,7844
2026-10-18T22:00:00Z,7503,7500
2026-10-18T22:15:00Z,7164,7161
2026-10-18T22:30:00Z,6833,6830
2026-10-18T22:45:00Z,6513,6510
2026-10-18T23:00:00Z,6204,6201
2026-10-18T23:15:00Z,5907,5904
2026-10-18T23:30:00Z,5625,5622
2026-10-18T23:45:00Z,5358,5356
2026-10-19T00:00:00Z,5109,5107
2026-10-19T00:15:00Z,4877,4875
2026-10-19T00:30:00Z,4265,4263
2026-10-19T00:45:00Z,4074,4072
2026-10-19T01:00:00Z,3903,3901
2026-10-19T01:15:00Z,3755,3753
2026-10-19T01:30:00Z,3630,3628
2026-10-19T01:45:00Z,3529,3527
2026-10-19T02:00:00Z,3452,3451
2026-10-19T02:15:00Z,3400,3399
2026-10-19T02:30:00Z,3373,3371
2026-10-19T02:45:00Z,3371,3369
2026-10-19T03:00:00Z,3396,3394
2026-10-19T03:15:00Z,3045,3044
2026-10-19T03:30:00Z,3121,3120
2026-10-19T03:45:00Z,3222,3221
2026-10-19T04:00:00Z,3348,3347
2026-10-19T04:15:00Z,3499,3497
2026-10-19T04:30:00Z,3674,3672
2026-10-19T04:45:00Z,3873,3871
2026-10-19T05:00:00Z,4095,4093
2026-10-19T05:15:00Z,4340,4338
2026-10-19T05:30:00Z,4605,4603
2026-10-19T05:45:00Z,4491,4489
2026-10-19T06:00:00Z,4797,4795
2026-10-19T06:15:00Z,5120,5117
2026-10-19T06:30:00Z,5461,5458
2026-10-19T06:45:00Z,5817,5814
2026-10-19T07:00:00Z,6188,6185
2026-10-19T07:15:00Z,6571,6568
2026-10-19T07:30:00Z,6965,6962
2026-10-19T07:45:00Z,7370,7366
2026-10-19T08:00:00Z,7783,7779
2026-10-19T08:15:00Z,8202,8198
2026-10-19T08:30:00Z,8226,8222
2026-10-19T08:45:00Z,8654,8650
2026-10-19T09:00:00Z,9084,9080
2026-10-19T09:15:00Z,9513,9509
2026-10-19T09:30:00Z,9941,9936
2026-10-19T09:45:00Z,10365,10360
2026-10-19T10:00:00Z,10784,10779
2026-10-19T10:15:00Z,11197,11192
2026-10-19T10:30:00Z,11602,11597
2026-10-19T10:45:00Z,11996,11991
2026-10-19T11:00:00Z,12380,12375
2026-10-19T11:15:00Z,12350,12344
2026-10-19T11:30:00Z,12706,12700
2026-10-19T11:45:00Z,13047,13041
2026-10-19T12:00:00Z,13370,13364
2026-10-19T12:15:00Z,13676,13670
2026-10-19T12:30:00Z,13962,13956
2026-10-19T12:45:00Z,14227,14221
2026-10-19T13:00:00Z,14472,14464
2026-10-19T13:15:00Z,14694,14687
2026-10-19T13:30:00Z,14893,14886
2026-10-19T13:45:00Z,15068,15061
2026-10-19T14:00:00Z,14819,14812
2026-10-19T14:15:00Z,14945,14939
2026-10-19T14:30:00Z,15046,15040
2026-10-19T14:45:00Z,15122,15114
2026-10-19T15:00:00Z,15172,15164
2026-10-19T15:15:00Z,15196,15189
2026-10-19T15:30:00Z,15194,15187
2026-10-19T15:45:00Z,15167,15160
2026-10-19T16:00:00Z,15115,15109
2026-10-19T16:15:00Z,15038,15032
2026-10-19T16:30:00Z,14937,14929
2026-10-19T16:45:00Z,14412,14405
2026-10-19T17:00:00Z,14264,14257
2026-10-19T17:15:00Z,14093,14087
2026-10-19T17:30:00Z,13902,13896
2026-10-19T17:45:00Z,13690,13684
2026-10-19T18:00:00Z,13458,13453
2026-10-19T18:15:00Z,13209,13202
2026-10-19T18:30:00Z,12942,12936
2026-10-19T18:45:00Z,12660,12654
2026-10-19T19:00:00Z,12364,12358
2026-10-19T19:15:00Z,11654,11649
2026-10-19T19:30:00Z,11334,11329
2026-10-19T19:45:00Z,11003,10999
2026-10-19T20:00:00Z,10664,10658
2026-10-19T20:15:00Z,10319,10314
2026-10-19T20:30:00Z,9969,9964
2026-10-19T20:45:00Z,9615,9611
2026-10-19T21:00:00Z,9260,9256
2026-10-19T21:15:00Z,8904,8900
2026-10-19T21:30:00Z,8550,8547
2026-10-19T21:45:00Z,8200,8196
2026-10-19T22:00:00Z,7455,7298
2026-10-19T22:15:00Z,7116,6959
2026-10-19T22:30:00Z,6785,6629
2026-10-19T22:45:00Z,6465,6310
2026-10-19T23:00:00Z,6156,6002
2026-10-19T23:15:00Z,5859,5707
2026-10-19T23:30:00Z,5577,5426
2026-10-19T23:45:00Z,5310,5161
FILE:scripts/slo_budget.py
#!/usr/bin/env python3
"""SLO error budget and burn rate calculator (Python 3 standard library only).

Input: CSV with one row per interval, the timestamp marking the START of the interval, and request
counts. Accepted columns (case-insensitive): timestamp|time|ts, total|requests|count, and either
good|success|ok or bad|errors|failed. Timestamps: ISO 8601 (Z or offset) or Unix seconds.

Math (see references/slo-math.md):
  error budget (fraction)  = 1 - SLO                          e.g. 99.9% -> 0.001
  error rate over window   = sum(bad) / sum(total)
  burn rate                = error rate / (1 - SLO)           1.0 = spends exactly the budget over the SLO window
  budget consumed so far   = sum(bad) / ((1 - SLO) * expected requests in the SLO window)
  alert threshold          = budget share * window hours / long window hours   (14.4 = 2% of 30d in 1h)

Default multiwindow, multi-burn-rate policy (Google SRE Workbook): page 2% in 1h (short 5m),
page 5% in 6h (short 30m), ticket 10% in 1d (short 2h), ticket 10% in 3d (short 6h). An alert fires
only when BOTH the long and the short window burn faster than the threshold. Windows shorter than
the data step are rounded up to one step; windows longer than the data are reported as not evaluable.

Usage:
  python3 slo_budget.py requests.csv --slo 99.9 --window 30d
  python3 slo_budget.py requests.csv --slo 99.5 --window 28d --json
  python3 slo_budget.py --allowance --slo 99.95 --window 30d     # downtime allowed, no CSV needed
  python3 slo_budget.py --self-test
Exit code: 0 OK, 1 a page alert fires or the budget is exhausted, 2 bad input.
"""
import argparse
import csv
import datetime as dt
import json
import re
import statistics
import sys

POLICY = [
    # (severity, long window, short window, budget share)
    ("page", "1h", "5m", 0.02),
    ("page", "6h", "30m", 0.05),
    ("ticket", "1d", "2h", 0.10),
    ("ticket", "3d", "6h", 0.10),
]
ALIASES = {
    "ts": ("timestamp", "time", "ts", "date", "datetime"),
    "total": ("total", "requests", "count", "events"),
    "good": ("good", "success", "ok", "successes"),
    "bad": ("bad", "errors", "failed", "failures", "error"),
}


class SLOError(ValueError):
    pass


def parse_duration(s):
    m = re.fullmatch(r"\s*(\d+(?:\.\d+)?)\s*([smhdw])\s*", str(s).lower())
    if not m:
        raise SLOError(f"bad duration {s!r} (use e.g. 5m, 1h, 28d)")
    return float(m.group(1)) * {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800}[m.group(2)]


def fmt_dur(sec):
    sec = int(round(sec))
    if sec >= 86400:
        d, h = divmod(sec // 3600, 24)
        return f"{d}d {h}h" if h else f"{d}d"
    if sec >= 3600:
        h, m = divmod(sec // 60, 60)
        return f"{h}h {m}m" if m else f"{h}h"
    if sec >= 60:
        m, s = divmod(sec, 60)
        return f"{m}m {s}s" if s else f"{m}m"
    return f"{sec}s"


def parse_ts(v):
    v = v.strip()
    if re.fullmatch(r"\d+(\.\d+)?", v):
        return dt.datetime.fromtimestamp(float(v), dt.timezone.utc)
    t = dt.datetime.fromisoformat(v.replace("Z", "+00:00").replace(" ", "T"))
    if t.tzinfo is None:
        t = t.replace(tzinfo=dt.timezone.utc)
    return t.astimezone(dt.timezone.utc)


def load_rows(lines):
    rd = csv.DictReader(lines)
    if not rd.fieldnames:
        raise SLOError("empty CSV")
    cols = {}
    lower = {f.strip().lower(): f for f in rd.fieldnames}
    for key, names in ALIASES.items():
        for n in names:
            if n in lower:
                cols[key] = lower[n]
                break
    if "ts" not in cols or "total" not in cols or not ({"good", "bad"} & cols.keys()):
        raise SLOError(f"need timestamp, total and good or bad columns; got {rd.fieldnames}")
    rows = []
    for i, r in enumerate(rd, 2):
        try:
            ts = parse_ts(r[cols["ts"]])
            total = int(float(r[cols["total"]]))
            bad = int(float(r[cols["bad"]])) if "bad" in cols else total - int(float(r[cols["good"]]))
        except (ValueError, TypeError) as e:
            raise SLOError(f"line {i}: {e}")
        if total < 0 or bad < 0 or bad > total:
            raise SLOError(f"line {i}: counts must satisfy 0 <= bad <= total (total={total}, bad={bad})")
        rows.append((ts, total, bad))
    if len(rows) < 2:
        raise SLOError("need at least two rows")
    rows.sort(key=lambda r: r[0])
    return rows


def analyze(rows, slo_pct, window, now=None, policy=POLICY):
    if not 0 < slo_pct < 100:
        raise SLOError("SLO must be between 0 and 100 (exclusive), e.g. 99.9")
    budget = 1 - slo_pct / 100
    win = parse_duration(window)
    diffs = [(b[0] - a[0]).total_seconds() for a, b in zip(rows, rows[1:])]
    step = statistics.median(diffs)
    if step <= 0:
        raise SLOError("duplicate timestamps")
    first = rows[0][0]
    end = (now or rows[-1][0] + dt.timedelta(seconds=step))
    covered = (end - first).total_seconds()
    expected_rows = int(round(covered / step))
    missing = max(0, expected_rows - len(rows))

    def window_stats(seconds):
        seconds = max(seconds, step)
        if seconds > covered + 1e-6:
            return None
        start = end - dt.timedelta(seconds=seconds)
        tot = sum(t for ts, t, b in rows if start <= ts < end)
        bad = sum(b for ts, t, b in rows if start <= ts < end)
        rate = bad / tot if tot else 0.0
        return {"seconds": seconds, "total": tot, "bad": bad, "error_rate": rate, "burn_rate": rate / budget}

    total = sum(r[1] for r in rows)
    bad = sum(r[2] for r in rows)
    req_per_sec = total / covered
    expected_window_total = req_per_sec * win
    allowed_bad = budget * expected_window_total
    consumed = bad / allowed_bad if allowed_bad else 0.0
    alerts = []
    for sev, lw, sw, share in policy:
        thr = share * win / parse_duration(lw)
        L, S = window_stats(parse_duration(lw)), window_stats(parse_duration(sw))
        if L is None or S is None:
            alerts.append({"severity": sev, "long": lw, "short": sw, "threshold": thr, "status": "not evaluable",
                           "long_burn": None, "short_burn": None})
            continue
        fires = L["burn_rate"] >= thr and S["burn_rate"] >= thr
        alerts.append({"severity": sev, "long": lw, "short": sw, "threshold": thr,
                       "status": "FIRING" if fires else "ok",
                       "long_burn": L["burn_rate"], "short_burn": S["burn_rate"]})
    burn = {}
    for w in ("5m", "30m", "1h", "2h", "6h", "1d", "3d"):
        s = window_stats(parse_duration(w))
        burn[w] = None if s is None else s["burn_rate"]
    remaining_bad = allowed_bad - bad
    exhaust = {}
    for w in ("1h", "6h", "1d"):
        s = window_stats(parse_duration(w))
        if s and s["bad"] > 0 and remaining_bad > 0:
            exhaust[w] = remaining_bad / (s["bad"] / s["seconds"])
        elif s:
            exhaust[w] = 0.0 if remaining_bad <= 0 else None
    worst = max(rows, key=lambda r: (r[2] / r[1] if r[1] else 0, r[0]))
    return {
        "slo_percent": slo_pct, "window": window, "window_seconds": win, "step_seconds": step,
        "data_start": first.strftime("%Y-%m-%dT%H:%M:%SZ"), "data_end": end.strftime("%Y-%m-%dT%H:%M:%SZ"),
        "rows": len(rows), "missing_intervals": missing,
        "total": total, "bad": bad, "sli_percent": 100 * (1 - bad / total) if total else 100.0,
        "allowed_bad_in_window": allowed_bad, "budget_consumed": consumed, "budget_remaining": 1 - consumed,
        "allowed_downtime_seconds": budget * win,
        "burn_rates": burn, "alerts": alerts, "exhaustion_seconds": exhaust,
        "worst_interval": {"start": worst[0].strftime("%Y-%m-%dT%H:%M:%SZ"), "total": worst[1], "bad": worst[2],
                           "error_rate": worst[2] / worst[1] if worst[1] else 0.0},
    }


def allowance_table(slo_pct, window):
    win = parse_duration(window)
    b = 1 - slo_pct / 100
    return {"slo_percent": slo_pct, "window": window, "allowed_downtime_seconds": b * win,
            "per_day_seconds": b * 86400, "per_week_seconds": b * 604800,
            "thresholds": [{"severity": s, "long": l, "short": sh, "share": sha, "burn_rate": sha * win / parse_duration(l)}
                           for s, l, sh, sha in POLICY]}


def to_markdown(r):
    pct = lambda x: f"{100 * x:.1f}%"
    out = [f"# SLO error budget report", "",
           f"**SLO:** {r['slo_percent']}% over {r['window']}  **Data:** {r['data_start']} to {r['data_end']} "
           f"({r['rows']} rows, step {fmt_dur(r['step_seconds'])}, {r['missing_intervals']} missing)",
           f"**SLI over data:** {r['sli_percent']:.4f}%  ({r['bad']:,} bad of {r['total']:,})",
           f"**Error budget:** {r['allowed_bad_in_window']:,.0f} bad requests per {r['window']} at current traffic "
           f"(= {fmt_dur(r['allowed_downtime_seconds'])} of full downtime)",
           f"**Consumed so far:** {pct(r['budget_consumed'])}  **Remaining:** {pct(r['budget_remaining'])}", "",
           "## Burn rates (1.0 = on budget)", "", "| Window | Burn rate |", "|---|---|"]
    for w, v in r["burn_rates"].items():
        out.append(f"| {w} | {'n/a' if v is None else f'{v:.2f}'} |")
    out += ["", "## Alert policy", "", "| Severity | Long / short window | Threshold | Long burn | Short burn | Status |",
            "|---|---|---|---|---|---|"]
    for a in r["alerts"]:
        lb = "n/a" if a["long_burn"] is None else f"{a['long_burn']:.2f}"
        sb = "n/a" if a["short_burn"] is None else f"{a['short_burn']:.2f}"
        out.append(f"| {a['severity']} | {a['long']} / {a['short']} | {a['threshold']:.1f} | {lb} | {sb} | {a['status']} |")
    out += ["", "## Time to exhaustion at recent burn"]
    for w, s in r["exhaustion_seconds"].items():
        out.append(f"- at last {w} rate: " + ("budget already exhausted" if s == 0 else ("no errors in window" if s is None else fmt_dur(s))))
    wi = r["worst_interval"]
    out += ["", f"Worst interval: {wi['start']} with {wi['bad']:,} bad of {wi['total']:,} ({100 * wi['error_rate']:.2f}%)"]
    return "\n".join(out)


def self_test():
    cases = []

    def ok(name, cond):
        cases.append((name, bool(cond)))

    t0 = dt.datetime(2026, 1, 1, tzinfo=dt.timezone.utc)

    def series(n, step_min, total, bad_fn):
        return [(t0 + dt.timedelta(minutes=step_min * i), total, bad_fn(i)) for i in range(n)]

    ok("duration parse", parse_duration("28d") == 28 * 86400 and parse_duration("5m") == 300)
    ok("duration format", fmt_dur(43.2 * 60) == "43m 12s" and fmt_dur(86400 * 3) == "3d")
    a = allowance_table(99.9, "30d")
    ok("99.9% of 30d allows 43m 12s", round(a["allowed_downtime_seconds"]) == 2592)
    ok("page threshold 14.4 for 30d", abs(a["thresholds"][0]["burn_rate"] - 14.4) < 1e-9)
    ok("28d threshold scales to 13.44", abs(allowance_table(99.9, "28d")["thresholds"][0]["burn_rate"] - 13.44) < 1e-9)
    flat = series(4 * 24 * 4, 15, 10000, lambda i: 10)          # 0.1% errors at 99.9 -> burn 1.0
    r = analyze(flat, 99.9, "30d")
    ok("steady burn rate is 1.0", abs(r["burn_rates"]["1h"] - 1.0) < 1e-9 and abs(r["burn_rates"]["1d"] - 1.0) < 1e-9)
    ok("no alert at burn 1.0", all(x["status"] != "FIRING" for x in r["alerts"][:3]))
    ok("burn 1.0 over 4 of 30 days consumes 4/30", abs(r["budget_consumed"] - 4 / 30) < 1e-9)
    ok("SLI computed", abs(r["sli_percent"] - 99.9) < 1e-9)
    spike = series(4 * 24 * 4, 15, 10000, lambda i: 200 if i >= 4 * 24 * 4 - 4 else 5)   # last hour 2% errors
    r = analyze(spike, 99.9, "30d")
    ok("fast burn pages (1h/5m)", r["alerts"][0]["status"] == "FIRING")
    ok("short window rounded up to step", abs(r["burn_rates"]["5m"] - 20.0) < 1e-9)
    ok("6h page not firing for 1h spike", r["alerts"][1]["status"] == "ok")
    recovered = spike[:-2] + [(spike[-2][0], 10000, 5), (spike[-1][0], 10000, 5)]
    r = analyze(recovered, 99.9, "30d")
    ok("short window resets page after recovery", r["alerts"][0]["status"] == "ok")
    short = series(8, 15, 1000, lambda i: 0)
    r = analyze(short, 99.9, "30d")
    ok("long windows not evaluable on 2h of data", r["alerts"][3]["status"] == "not evaluable" and r["burn_rates"]["3d"] is None)
    gap = flat[:10] + flat[12:]
    ok("missing intervals counted", analyze(gap, 99.9, "30d")["missing_intervals"] == 2)
    ok("exhaustion time at burn 1", abs(analyze(flat, 99.9, "30d")["exhaustion_seconds"]["1d"] - 26 * 86400) < 1)
    rows = load_rows(["time,requests,errors", "2026-01-01T00:00:00Z,100,1", "2026-01-01T00:05:00Z,100,0"])
    ok("aliases requests/errors", rows[0][1] == 100 and rows[0][2] == 1)
    rows = load_rows(["ts,total,good", "1767225600,50,49", "1767225900,50,50"])
    ok("unix timestamps and good column", rows[0][2] == 1 and rows[0][0] == t0)
    for data, label in [(["ts,total", "x,1"], "missing good/bad rejected"),
                        (["ts,total,bad", "2026-01-01T00:00:00Z,10,11", "2026-01-01T00:05:00Z,10,0"], "bad > total rejected"),
                        (["ts,total,bad", "nope,10,1", "2026-01-01T00:05:00Z,10,0"], "bad timestamp rejected")]:
        try:
            load_rows(data)
            ok(label, False)
        except SLOError:
            ok(label, True)
    try:
        analyze(flat, 100, "30d")
        ok("SLO 100 rejected", False)
    except SLOError:
        ok("SLO 100 rejected", True)
    ok("markdown has alert table", "## Alert policy" in to_markdown(analyze(flat, 99.9, "30d")))
    passed = sum(c for _, c in cases)
    for name, c in cases:
        print(("PASS " if c else "FAIL ") + name)
    print(f"{passed}/{len(cases)} passed")
    return 0 if passed == len(cases) else 1


def main(argv=None):
    ap = argparse.ArgumentParser(description="Compute SLO error budget consumption and multiwindow burn-rate alerts.")
    ap.add_argument("file", nargs="?", help="CSV of request counts per interval ('-' for stdin)")
    ap.add_argument("--slo", type=float, default=99.9, help="target in percent (default 99.9)")
    ap.add_argument("--window", default="30d", help="SLO window, e.g. 28d or 30d (default 30d)")
    ap.add_argument("--now", help="evaluate as of this ISO time (default: end of the last interval)")
    ap.add_argument("--allowance", action="store_true", help="print allowed downtime and alert thresholds only")
    ap.add_argument("--json", action="store_true")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args(argv)
    if a.self_test:
        return self_test()
    try:
        if a.allowance:
            t = allowance_table(a.slo, a.window)
            if a.json:
                print(json.dumps(t, indent=2))
            else:
                print(f"SLO {a.slo}% over {a.window}: {fmt_dur(t['allowed_downtime_seconds'])} of full downtime "
                      f"({fmt_dur(t['per_day_seconds'])}/day, {fmt_dur(t['per_week_seconds'])}/week)")
                for x in t["thresholds"]:
                    print(f"  {x['severity']:6} {x['share'] * 100:.0f}% of budget in {x['long']} (short {x['short']}): burn rate >= {x['burn_rate']:.2f}")
            return 0
        if not a.file:
            ap.error("CSV file required (or --allowance / --self-test)")
        lines = sys.stdin.read().splitlines() if a.file == "-" else open(a.file, encoding="utf-8").read().splitlines()
        r = analyze(load_rows(lines), a.slo, a.window, parse_ts(a.now) if a.now else None)
    except (OSError, SLOError, ValueError) as e:
        print(f"error: {e}", file=sys.stderr)
        return 2
    print(json.dumps(r, indent=2) if a.json else to_markdown(r))
    paging = any(x["severity"] == "page" and x["status"] == "FIRING" for x in r["alerts"])
    return 1 if paging or r["budget_remaining"] <= 0 else 0


if __name__ == "__main__":
    sys.exit(main())
MonitoringSREDevOps+2
F@f
0
Time Series Gap and Anomaly Checker
Skill

Checks CSV time series (metrics, sensor readings, sales by hour) for data problems before you chart or alert on them: missing intervals, duplicate or out-of-order timestamps, empty values, flatlines from stuck exporters, robust median/MAD spikes, and counter resets. Use when a dashboard looks wrong, before training a forecast, or when asking "is this data complete?". Includes a stdlib Python checker with --self-test.

---
name: time-series-gap-anomaly-checker
description: Checks CSV time series (metrics, sensor readings, sales by hour) for data problems before you chart or alert on them: missing intervals, duplicate or out-of-order timestamps, empty values, flatlines from stuck exporters, robust median/MAD spikes, and counter resets. Use when a dashboard looks wrong, before training a forecast, or when asking "is this data complete?". Includes a stdlib Python checker with --self-test.
---

# Time Series Gap and Anomaly Checker

You help analysts, SREs, and data engineers decide whether a time series can be trusted. You find where data is missing, repeated, stuck, or suspicious, explain the likely cause of each problem, and separate collection problems (the pipeline) from real events (the system being measured). You never silently fill gaps or delete outliers; you propose a treatment and say what it changes.

## Files in this skill

- `scripts/ts_check.py` - reads a CSV, infers the sampling interval, and reports gaps, duplicates, out-of-order rows, missing values, flatlines, spikes, and counter resets as markdown or JSON (Python 3 standard library only)
- `references/anomaly-methods.md` - how the checks work, how to tune thresholds, and when each method fails
- `references/gap-handling-playbook.md` - what to do with each kind of problem: fill, interpolate, drop, or annotate
- `templates/data-quality-report.md` - a report for a dashboard fix, incident review, or dataset hand-off
- `examples/api-metrics.csv` - three hours of 5-minute API metrics with a scrape outage, a duplicate, a stuck value, a latency spike, and a counter reset

## Workflow

### 1. Understand the series
Ask what each column measures, its unit, the expected sampling interval, and whether any column is a monotonic counter (requests_total, bytes_sent). Ask which time zone naive timestamps use; the script treats them as UTC.

### 2. Run the checker
```
python3 scripts/ts_check.py examples/api-metrics.csv --counter requests_total
python3 scripts/ts_check.py data.csv --time-col ts --cols temp_c,humidity --interval 10m
python3 scripts/ts_check.py data.csv --z 5 --window 12 --flatline-points 12 --json > report.json
python3 scripts/ts_check.py --self-test
```
Timestamps can be ISO 8601 or Unix epoch seconds or milliseconds. Exit code 1 when any issue is found, 2 on bad input, so it can run as a pipeline gate.

### 3. Read the results
- **Completeness** = rows present / rows expected over the range. Below 95% usually means aggregates and averages are biased.
- **gap**: spacing over 1.5x the interval. Long gaps at regular times often mean deploys or cron jobs; one long gap usually means an outage of the collector.
- **duplicate / out_of_order**: double scrapes, retries, or merged files.
- **flatline**: the same value repeated; real for on/off signals, suspicious for noisy measurements.
- **spike**: robust z-score against a rolling median. Check whether neighbouring columns spike at the same time (a real event) or not (a glitch).
- **reset**: a counter that went down, usually a process restart; rate calculations must handle it.

### 4. Recommend treatment
Use `references/gap-handling-playbook.md`. Tune thresholds with `references/anomaly-methods.md` if the data is seasonal, bursty, or very sparse.

### 5. Report
Fill `templates/data-quality-report.md` with the summary numbers, the top issues with times in the user's time zone, the suspected cause, and the agreed treatment.

## Rules

- Report problems; do not alter the source data. Write cleaned data to a new file and document every change.
- Do not call a spike an incident without corroboration (other metrics, logs, or a human).
- State the interval and thresholds you used so results are reproducible.
- Convert UTC times to the user's time zone when presenting them.
FILE:references/anomaly-methods.md
# Anomaly Methods and Tuning

## Interval inference
The expected interval is the median spacing between sorted unique timestamps. This survives a few gaps and jitter. Pass `--interval` when the series is mostly gaps (sparse events) or when you know the scrape interval.

A gap is any spacing above 1.5x the interval, so 5-minute data with a 7-minute spacing is not a gap but a 10-minute spacing is (1 missing point).

## Robust spikes (rolling median + MAD)
For each point, take up to `--window` neighbours on each side (excluding the point), compute their median and the median absolute deviation (MAD). The robust z-score is:

    z = |value - median| / (1.4826 * MAD)

1.4826 makes MAD comparable to a standard deviation for normal data. Default threshold 4 is roughly a 1-in-15,000 event for normal noise. When more than half the neighbours are identical (MAD = 0), the mean absolute deviation is used, and for a perfectly flat neighbourhood 1% of the level.

Why not mean and standard deviation? One large spike inflates the standard deviation and hides itself. The median and MAD ignore it.

## Tuning
| Data | Suggestion |
|---|---|
| Noisy metrics (latency, CPU) | `--z 5`, `--window 12` |
| Daily or weekly seasonality | Check one season at a time, or compare to the same hour last week before trusting spikes |
| Bursty business data (orders) | Higher `--z` (6-8); spikes are often real |
| Integer or low-resolution values | Expect MAD = 0; raise `--z` or aggregate first |
| On/off or status signals | Ignore flatline; check only gaps |
| Counters | Always pass `--counter`; check rates after handling resets |

## Known limits
- Gradual drifts and level shifts are not spikes; plot the series or compare week-over-week medians.
- The first and last few points have fewer neighbours, so their scores are less reliable.
- Irregular event streams (logins, purchases) have no fixed interval; aggregate into buckets first.
FILE:references/gap-handling-playbook.md
# Gap and Anomaly Handling Playbook

| Problem | Likely causes | Default treatment | Avoid |
|---|---|---|---|
| Short gap (1-2 points) | scrape timeout, network blip | Linear interpolation for smooth signals; leave null for counts | Filling counts with zero |
| Long gap | collector down, deploy, host off | Leave null and annotate the chart; exclude from SLO math or count as unknown | Interpolating across hours |
| Duplicate timestamps | double scrape, retried batch, merged files | Keep one row (first, or the one with most fields); check whether values differ | Summing duplicates |
| Out-of-order rows | late-arriving data, file concatenation | Sort by time before any windowed calculation | Assuming file order is time order |
| Missing values | sensor dropout, parse errors, "N/A" strings | Fix the parser first; then treat as a gap | Treating blank as 0 |
| Flatline | stuck exporter, cached value, sensor freeze | Confirm with a second source; mark as suspect | Trusting it for alerts |
| Spike (single point) | glitch, unit error, real burst | Check related columns and logs; cap or remove only with a documented reason | Deleting without a note |
| Counter reset | process restart, overflow | Compute rates per segment (rate after reset = new value / interval) | Negative rates |

## Before modeling or forecasting
1. Sort, de-duplicate, and regularize to the expected interval (insert nulls for missing slots).
2. Decide gap policy per column and record it.
3. Keep a mask column (`is_imputed`) so models and readers know what was filled.
4. Re-run the checker on the cleaned file and attach both reports.

## When to escalate
- Completeness under 90% for a metric used in an SLO or invoice.
- Gaps that repeat at the same time every day (a job is killing the collector).
- Spikes that appear in all hosts at once (a real incident, not a data issue).
FILE:templates/data-quality-report.md
# Time Series Data Quality - <dataset or dashboard>

**Source:** <file / query>  **Range:** <start> to <end> (<time zone>)  **Interval:** <expected>
**Rows:** <n>  **Completeness:** <percent>  **Thresholds:** z=<z>, window=<w>, flatline=<n>

## Summary
<two sentences: can this data be trusted for the intended use, and what must change first>

## Issues
| Kind | When (<time zone>) | Column | Detail | Suspected cause | Treatment |
|---|---|---|---|---|---|
| | | | | | |

## Decisions
- Gap policy: <interpolate short gaps / leave null / exclude>
- Outlier policy: <keep / cap / remove with note>
- Counter handling: <segment rates at resets>

## Follow-ups
- [ ] <fix collector / parser / alert> - owner <name> - due <date>

Generated with scripts/ts_check.py. Source data was not modified.
FILE:examples/api-metrics.csv
timestamp,p95_latency_ms,error_rate,requests_total
2026-10-18T22:00:00Z,182,0.4,1200
2026-10-18T22:05:00Z,176,0.3,2435
2026-10-18T22:10:00Z,190,0.5,3705
2026-10-18T22:15:00Z,185,0.4,5010
2026-10-18T22:20:00Z,179,0.3,6210
2026-10-18T22:25:00Z,188,0.4,7445
2026-10-18T22:30:00Z,181,0.5,8715
2026-10-18T22:35:00Z,193,0.4,10020
2026-10-18T22:35:00Z,193,0.4,10020
2026-10-18T22:40:00Z,177,0.3,11220
2026-10-18T22:45:00Z,184,0.4,12455
2026-10-18T22:50:00Z,186,0.4,13725
2026-10-18T22:55:00Z,180,0.4,15030
2026-10-18T23:00:00Z,191,0.4,16230
2026-10-18T23:05:00Z,,0.4,17465
2026-10-18T23:10:00Z,178,0.4,18735
2026-10-18T23:15:00Z,187,0.4,20040
2026-10-18T23:20:00Z,182,0.4,21240
2026-10-18T23:25:00Z,189,0.4,22475
2026-10-18T23:30:00Z,612,2.1,23745
2026-10-18T23:35:00Z,185,0.5,25050
2026-10-18T23:40:00Z,180,0.3,26250
2026-10-18T23:45:00Z,184,0.4,27485
2026-10-19T00:10:00Z,188,0.5,28755
2026-10-19T00:15:00Z,183,0.4,30060
2026-10-19T00:20:00Z,177,0.3,31260
2026-10-19T00:25:00Z,185,0.4,32495
2026-10-19T00:30:00Z,182,0.5,1180
2026-10-19T00:35:00Z,189,0.4,2485
2026-10-19T00:40:00Z,184,0.3,3685
2026-10-19T00:45:00Z,180,0.4,4920
2026-10-19T00:50:00Z,186,0.5,6190
2026-10-19T00:55:00Z,183,0.4,7495
FILE:scripts/ts_check.py
#!/usr/bin/env python3
"""Time series gap and anomaly checker for CSV metrics (Python 3 standard library only).

Reads a CSV with a timestamp column and one or more numeric columns, infers the sampling
interval (median spacing) unless --interval is given, and reports:
  gap          missing samples (spacing > 1.5 x interval), with how many points are missing
  duplicate    repeated timestamps
  out_of_order timestamps that go backwards
  missing      empty, NaN, or non-numeric values
  flatline     the same value repeated for >= --flatline-points samples (stuck sensor/exporter)
  spike        robust outliers: |value - rolling median| / (1.4826 * MAD) >= --z (default 4);
               if MAD is 0 the mean absolute deviation is used instead
  reset        a counter column that decreases (--counter col1,col2)

Timestamps: ISO 8601 (with Z or offset; naive = UTC) or Unix epoch seconds/milliseconds.

Usage:
  python3 ts_check.py metrics.csv
  python3 ts_check.py metrics.csv --time-col ts --cols cpu,latency_ms --interval 5m --z 5
  python3 ts_check.py metrics.csv --counter requests_total --json
  python3 ts_check.py --self-test
Exit code: 0 clean, 1 issues found, 2 bad input.
"""
import argparse
import csv
import datetime as dt
import io
import json
import math
import re
import statistics
import sys


class InputError(ValueError):
    pass


def parse_ts(raw):
    s = (raw or "").strip()
    if not s:
        raise InputError("empty timestamp")
    if re.fullmatch(r"-?\d+(\.\d+)?", s):
        v = float(s)
        return v / 1000.0 if v > 1e11 else v
    try:
        t = dt.datetime.fromisoformat(s.replace("Z", "+00:00").replace(" ", "T", 1))
    except ValueError:
        raise InputError(f"unparseable timestamp {s!r}")
    if t.tzinfo is None:
        t = t.replace(tzinfo=dt.timezone.utc)
    return t.timestamp()


def parse_interval(s):
    m = re.fullmatch(r"(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)?", s.strip())
    if not m:
        raise InputError(f"bad interval {s!r}; use e.g. 30s, 5m, 1h")
    mult = {"ms": 0.001, "s": 1, None: 1, "m": 60, "h": 3600, "d": 86400}[m.group(2)]
    return float(m.group(1)) * mult


def fmt_ts(ts):
    return dt.datetime.fromtimestamp(ts, dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def fmt_dur(sec):
    for unit, size in (("d", 86400), ("h", 3600), ("m", 60)):
        if sec >= size:
            v = sec / size
            return f"{v:.0f}{unit}" if v == int(v) else f"{v:.1f}{unit}"
    return f"{sec:g}s"


def to_float(raw):
    s = (raw or "").strip()
    if s == "" or s.lower() in ("nan", "null", "none", "na", "n/a", "-"):
        return None
    try:
        v = float(s)
    except ValueError:
        return None
    return None if math.isnan(v) or math.isinf(v) else v


def load(text, time_col=None, cols=None):
    reader = csv.DictReader(io.StringIO(text))
    if not reader.fieldnames:
        raise InputError("CSV has no header row")
    fields = [f.strip() for f in reader.fieldnames]
    reader.fieldnames = fields
    if time_col is None:
        cands = [f for f in fields if f.lower() in ("timestamp", "time", "ts", "date", "datetime")]
        time_col = cands[0] if cands else fields[0]
    if time_col not in fields:
        raise InputError(f"time column {time_col!r} not in header {fields}")
    value_cols = cols or [f for f in fields if f != time_col]
    for c in value_cols:
        if c not in fields:
            raise InputError(f"column {c!r} not in header {fields}")
    rows = []
    for i, r in enumerate(reader, start=2):
        rows.append({"line": i, "ts": parse_ts(r.get(time_col)),
                     "raw": {c: r.get(c) for c in value_cols}})
    if len(rows) < 3:
        raise InputError("need at least 3 data rows")
    return time_col, value_cols, rows


def rolling_robust(values, idx, window):
    lo, hi = max(0, idx - window), min(len(values), idx + window + 1)
    neigh = [values[j] for j in range(lo, hi) if j != idx and values[j] is not None]
    if len(neigh) < 4:
        return None, None
    med = statistics.median(neigh)
    mad = statistics.median(abs(v - med) for v in neigh)
    scale = 1.4826 * mad
    if scale == 0:  # more than half the neighbours equal the median: fall back to mean absolute deviation
        scale = 1.2533 * statistics.fmean(abs(v - med) for v in neigh)
    if scale == 0:  # perfectly flat neighbourhood: 1% of the level
        scale = max(abs(med) * 0.01, 1e-9)
    return med, scale


def check(text, time_col=None, cols=None, interval=None, z=4.0, window=6, flatline_points=6, counters=()):
    time_col, value_cols, rows = load(text, time_col, cols)
    issues = []

    def add(kind, line, ts, col, detail):
        issues.append({"kind": kind, "line": line, "time": fmt_ts(ts), "column": col, "detail": detail})

    # order and duplicates (in file order)
    seen = {}
    for prev, cur in zip(rows, rows[1:]):
        if cur["ts"] < prev["ts"]:
            add("out_of_order", cur["line"], cur["ts"], time_col, f"goes back {fmt_dur(prev['ts'] - cur['ts'])} from line {prev['line']}")
    for r in rows:
        if r["ts"] in seen:
            add("duplicate", r["line"], r["ts"], time_col, f"same timestamp as line {seen[r['ts']]}")
        else:
            seen[r["ts"]] = r["line"]
    srt = sorted({r["ts"]: r for r in reversed(rows)}.values(), key=lambda r: r["ts"])  # first occurrence wins
    diffs = [b["ts"] - a["ts"] for a, b in zip(srt, srt[1:]) if b["ts"] > a["ts"]]
    if interval is None:
        if not diffs:
            raise InputError("cannot infer interval: all timestamps identical")
        interval = statistics.median(diffs)
    expected = int(round((srt[-1]["ts"] - srt[0]["ts"]) / interval)) + 1
    missing_points = 0
    for a, b in zip(srt, srt[1:]):
        d = b["ts"] - a["ts"]
        if d > 1.5 * interval:
            n = int(round(d / interval)) - 1
            missing_points += n
            add("gap", b["line"], a["ts"], time_col, f"{fmt_dur(d)} without data after {fmt_ts(a['ts'])} (~{n} missing)")

    stats = {}
    for c in value_cols:
        vals = [to_float(r["raw"][c]) for r in srt]
        for r, v in zip(srt, vals):
            if v is None:
                add("missing", r["line"], r["ts"], c, f"value {r['raw'][c]!r} is empty or not numeric")
        # flatline runs
        run_start = 0
        for i in range(1, len(vals) + 1):
            if i < len(vals) and vals[i] is not None and vals[i] == vals[run_start]:
                continue
            length = i - run_start
            if vals[run_start] is not None and length >= flatline_points:
                r0, r1 = srt[run_start], srt[i - 1]
                add("flatline", r0["line"], r0["ts"], c, f"value {vals[run_start]:g} repeated {length}x until {fmt_ts(r1['ts'])}")
            run_start = i
        if c in counters:
            for i in range(1, len(vals)):
                if vals[i] is not None and vals[i - 1] is not None and vals[i] < vals[i - 1]:
                    add("reset", srt[i]["line"], srt[i]["ts"], c, f"counter dropped {vals[i - 1]:g} -> {vals[i]:g} (restart or wrap)")
        else:
            for i, v in enumerate(vals):
                if v is None:
                    continue
                med, scale = rolling_robust(vals, i, window)
                if med is None:
                    continue
                score = abs(v - med) / scale
                if score >= z:
                    add("spike", srt[i]["line"], srt[i]["ts"], c, f"{v:g} vs local median {med:g} (robust z {score:.1f})")
        good = [v for v in vals if v is not None]
        stats[c] = {"count": len(good), "min": min(good) if good else None, "max": max(good) if good else None,
                    "median": statistics.median(good) if good else None}

    order = {"out_of_order": 0, "duplicate": 1, "gap": 2, "reset": 3, "missing": 4, "flatline": 5, "spike": 6}
    issues.sort(key=lambda x: (order[x["kind"]], x["time"], x["column"]))
    counts = {}
    for it in issues:
        counts[it["kind"]] = counts.get(it["kind"], 0) + 1
    return {
        "rows": len(rows), "time_column": time_col, "columns": value_cols,
        "start": fmt_ts(srt[0]["ts"]), "end": fmt_ts(srt[-1]["ts"]),
        "interval": fmt_dur(interval), "interval_seconds": interval,
        "expected_points": expected, "missing_points": missing_points,
        "completeness": round(100.0 * len(srt) / expected, 1) if expected else 100.0,
        "stats": stats, "counts": counts, "issues": issues,
    }


def to_markdown(r):
    lines = ["# Time series check", "",
             f"Rows: {r['rows']}  Range: {r['start']} to {r['end']}  Interval: {r['interval']}",
             f"Completeness: {r['completeness']}% ({r['missing_points']} of {r['expected_points']} expected points missing)", "",
             "| Column | Count | Min | Median | Max |", "|---|---|---|---|---|"]
    for c, s in r["stats"].items():
        f = lambda v: "-" if v is None else f"{v:g}"
        lines.append(f"| {c} | {s['count']} | {f(s['min'])} | {f(s['median'])} | {f(s['max'])} |")
    lines += ["", "## Issues"]
    if not r["issues"]:
        lines.append("No issues found.")
    else:
        lines.append("Totals: " + ", ".join(f"{k} {v}" for k, v in r["counts"].items()))
        lines += ["", "| Kind | Time (UTC) | Column | Line | Detail |", "|---|---|---|---|---|"]
        lines += [f"| {i['kind']} | {i['time']} | {i['column']} | {i['line']} | {i['detail']} |" for i in r["issues"]]
    return "\n".join(lines)


def self_test():
    cases = []

    def ok(name, cond):
        cases.append((name, bool(cond)))

    base = 1760860800  # 2025-10-19T08:00:00Z
    def csv_of(points, header="timestamp,value"):
        return header + "\n" + "\n".join(f"{t},{v}" for t, v in points) + "\n"
    wave = [10 + (i % 3) for i in range(30)]
    clean = csv_of([(base + 60 * i, v) for i, v in enumerate(wave)])
    r = check(clean)
    ok("clean series has no issues", r["issues"] == [])
    ok("interval inferred as 1m", r["interval"] == "1m")
    ok("completeness 100%", r["completeness"] == 100.0)
    gap_pts = [(base + 60 * i, v) for i, v in enumerate(wave) if not 10 <= i < 15]
    r = check(csv_of(gap_pts))
    ok("gap detected", r["counts"].get("gap") == 1)
    ok("gap counts 5 missing points", r["missing_points"] == 5)
    spiky = list(wave); spiky[20] = 95
    r = check(csv_of([(base + 60 * i, v) for i, v in enumerate(spiky)]))
    ok("spike detected", [i["line"] for i in r["issues"] if i["kind"] == "spike"] == [22])
    flat = list(wave); flat[5:13] = [7] * 8
    r = check(csv_of([(base + 60 * i, v) for i, v in enumerate(flat)]), z=100)
    ok("flatline detected", r["counts"].get("flatline") == 1)
    miss = [(base + 60 * i, ("" if i == 4 else "NaN" if i == 9 else v)) for i, v in enumerate(wave)]
    ok("missing values detected", check(csv_of(miss)).get("counts").get("missing") == 2)
    dup = [(base + 60 * i, v) for i, v in enumerate(wave)]
    dup.insert(6, dup[5])
    ok("duplicate detected", check(csv_of(dup))["counts"].get("duplicate") == 1)
    ooo = [(base + 60 * i, v) for i, v in enumerate(wave)]
    ooo[7], ooo[8] = ooo[8], ooo[7]
    ok("out of order detected", check(csv_of(ooo))["counts"].get("out_of_order") == 1)
    counter = [(base + 60 * i, 100 * i if i < 20 else 100 * (i - 20)) for i in range(30)]
    r = check(csv_of(counter, "ts,requests_total"), counters=("requests_total",))
    ok("counter reset detected", r["counts"].get("reset") == 1 and "spike" not in r["counts"])
    iso_rows = "time,cpu\n" + "\n".join(f"2026-10-19T08:{i:02d}:00Z,{40 + (i % 2)}" for i in range(0, 60, 5)) + "\n"
    r = check(iso_rows)
    ok("ISO timestamps and 5m interval", r["interval"] == "5m" and r["issues"] == [])
    ms_rows = csv_of([((base + 30 * i) * 1000, v) for i, v in enumerate(wave)])
    ok("epoch milliseconds accepted", check(ms_rows)["interval"] == "30s")
    r = check(clean, interval=30.0)
    ok("explicit 30s interval flags every 1m step as a gap", r["counts"].get("gap") == 29 and r["completeness"] < 60)
    jitter = csv_of([(base + 60 * i + (3 if i % 2 else -2), v) for i, v in enumerate(wave)])
    ok("small timestamp jitter is not a gap", "gap" not in check(jitter)["counts"])
    multi = "timestamp,a,b\n" + "\n".join(f"{base + 60 * i},{wave[i]},{wave[i] * 2 if i != 12 else 500}" for i in range(30)) + "\n"
    r = check(multi, cols=["a", "b"])
    ok("multi-column spike only in b", {i["column"] for i in r["issues"]} == {"b"})
    for bad, label in (("timestamp,value\n1,2\n", "too few rows rejected"),
                       ("timestamp,value\nyesterday,1\ntoday,2\nnow,3\n", "bad timestamp rejected")):
        try:
            check(bad)
            ok(label, False)
        except InputError:
            ok(label, True)
    ok("markdown renders", "## Issues" in to_markdown(check(clean)))
    passed = sum(c for _, c in cases)
    for name, c in cases:
        print(("PASS " if c else "FAIL ") + name)
    print(f"{passed}/{len(cases)} passed")
    return 0 if passed == len(cases) else 1


def main(argv=None):
    ap = argparse.ArgumentParser(description="Find gaps, duplicates, flatlines, spikes, and counter resets in CSV metrics.")
    ap.add_argument("csv", nargs="?", help="CSV file, or '-' for stdin")
    ap.add_argument("--time-col")
    ap.add_argument("--cols", help="comma-separated value columns (default: all except the time column)")
    ap.add_argument("--interval", help="expected spacing, e.g. 30s, 5m, 1h (default: median spacing)")
    ap.add_argument("--z", type=float, default=4.0, help="robust z-score threshold for spikes (default 4)")
    ap.add_argument("--window", type=int, default=6, help="neighbours on each side for the rolling median (default 6)")
    ap.add_argument("--flatline-points", type=int, default=6)
    ap.add_argument("--counter", default="", help="comma-separated monotonic counter columns (checked for resets, not spikes)")
    ap.add_argument("--json", action="store_true")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args(argv)
    if a.self_test:
        return self_test()
    if not a.csv:
        ap.error("csv path required (or --self-test)")
    try:
        text = sys.stdin.read() if a.csv == "-" else open(a.csv, encoding="utf-8-sig").read()
        r = check(text, a.time_col, [c.strip() for c in a.cols.split(",")] if a.cols else None,
                  parse_interval(a.interval) if a.interval else None, a.z, a.window, a.flatline_points,
                  tuple(c.strip() for c in a.counter.split(",") if c.strip()))
    except (OSError, InputError) as e:
        print(f"error: {e}", file=sys.stderr)
        return 2
    print(json.dumps(r, indent=2) if a.json else to_markdown(r))
    return 1 if r["issues"] else 0


if __name__ == "__main__":
    sys.exit(main())
MonitoringData QualitySRE+3
F@f
1
Impact Metrics
Text

Spotlighting Your Project

Create a compelling data-driven section showing the impact of [project name]: downloads, users helped, issues resolved, and community growth statistics.
ImpactMetricsProject
F@f
0