Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(signals): add KS change-detection lens to anomaly scout (#62351)

Andrew Maguireb4fe49d88851
diff --git a/products/signals/skills/signals-scout-anomaly-detection/SKILL.md b/products/signals/skills/signals-scout-anomaly-detection/SKILL.md
index ddfd8dd06872..561b43ac7cb2 100644
--- a/products/signals/skills/signals-scout-anomaly-detection/SKILL.md
+++ b/products/signals/skills/signals-scout-anomaly-detection/SKILL.md
@@ -108,6 +108,17 @@ and will always look like a drop (see the partial-bucket guard in `anomaly-metho
When a metric moves, **attribute it before deciding** — re-run the insight with its own breakdown (or add a `GROUP BY` in SQL) to find which segment drove the move. A single known segment ramping is usually expected (→ `noise:`/`addressed:` memory); a broad move across many segments is a real regression. See [`references/anomaly-methods.md`](references/anomaly-methods.md).
+**Change-detection lens (optional).** Point/level scoring catches an outlier _bucket_; it
+misses a metric whose mean holds but whose **distribution shifts shape** (variance, tail, mix)
+and it won't tell you _where_ a drift began. For that, run a two-sample Kolmogorov-Smirnov test
+in `Bash` + `python3` — inline as a self-contained heredoc, or fetch the bundled
+`scripts/ks2.py` via `llma-skill-file-get` and write it to `/tmp` first (it is **not** on disk
+in a scheduled run). Compare two seasonality-matched windows, or sweep an ordered series for
+the changepoint. Pull **histograms** (`GROUP BY` a value bucket), not raw rows, to stay cheap
+and under the `execute-sql` cap. Full recipe, calibration (incl. the changepoint multiple-
+comparisons caveat), and the seasonality caveat in
+[`references/anomaly-methods.md`](references/anomaly-methods.md).
+
### Explore — discover new high-value insights/dashboards to add
Spend a slice of each run widening coverage so the watchlist tracks what the team currently
@@ -211,6 +222,10 @@ Direct (read-only):
- `read-data-schema` — confirm events/properties before any SQL.
- `inbox-reports-list` — check whether the move is already reported before emitting.
+Local: `Bash` + `python3` — the distribution-shift lens: run a pure-stdlib two-sample KS /
+changepoint inline, or fetch the bundled `scripts/ks2.py` via `llma-skill-file-get` and write
+it to `/tmp` first (not on disk in a scheduled run). Feed it histograms from `execute-sql`.
+
Write (user-facing, gated on `notebook:write`):
- `notebooks-create` — the durable write-up that backs an emitted finding. Build it _before_
diff --git a/products/signals/skills/signals-scout-anomaly-detection/references/anomaly-methods.md b/products/signals/skills/signals-scout-anomaly-detection/references/anomaly-methods.md
index bafb8713f145..82bad8388501 100644
--- a/products/signals/skills/signals-scout-anomaly-detection/references/anomaly-methods.md
+++ b/products/signals/skills/signals-scout-anomaly-detection/references/anomaly-methods.md
@@ -218,6 +218,85 @@ an internal product dialing up usage — is usually expected and belongs in a
`noise:`/`addressed:` memory, whereas a move spread across many unrelated segments is a real
broad regression. Put the driving segment and its share of the move in the evidence.
+## Distribution shift & changepoint (KS two-sample)
+
+A different lens from everything above. The simulator and the z-score answer _"is the **latest
+bucket** an outlier?"_ — point/level detection. They miss a metric whose **mean barely moves
+but whose distribution changes shape** (variance widens, a tail appears, a bimodal split, a
+mix shift), and they don't tell you _where_ a drift started. A two-sample
+**Kolmogorov-Smirnov** test does both: it compares two samples' whole empirical distributions
+(`D = max|F_a(x) − F_b(x)|`, with a p-value) and, swept across an ordered series, locates the
+**changepoint** that best separates it into two differently-distributed halves. Reach for it
+in the explore phase when a watched series looks fine on the mean but you suspect a shape/mix
+change, or to pin the onset of a drift a level detector already flagged.
+
+**Running it.** A scheduled run has `Bash` + `python3` but **no repo and no bundled file on
+disk** — skill files arrive via `llma-skill-file-get`, not the filesystem — so don't assume
+`scripts/ks2.py` is on a path. Two ways to run KS (no numpy/scipy needed; neither is in the
+sandbox):
+
+- **Inline** (zero dependencies) — paste a self-contained heredoc for a quick two-sample check:
+
+ ```bash
+ python3 - <<'PY'
+ import json, math
+ def ks(a, b):
+ a = sorted(a); b = sorted(b); n, m = len(a), len(b)
+ i = j = 0; d = 0.0
+ while i < n and j < m:
+ x = a[i] if a[i] <= b[j] else b[j]
+ while i < n and a[i] <= x: i += 1
+ while j < m and b[j] <= x: j += 1
+ d = max(d, abs(i/n - j/m))
+ en = math.sqrt(n*m/(n+m)); t = (en + 0.12 + 0.11/en)*d
+ p = sum(2*(-1)**(k-1)*math.exp(-2*k*k*t*t) for k in range(1, 101))
+ return d, max(0.0, min(1.0, p))
+ a = [] # window A (seasonality-matched to B)
+ b = [] # window B
+ d, p = ks(a, b); print(json.dumps({"d": round(d, 4), "p": p}))
+ PY
+ ```
+
+- **Full helper** — the tested implementation (raw + binned two-sample, and the changepoint
+ sweep with a multiple-comparisons `p_adj`) is bundled at `scripts/ks2.py`. Fetch it with
+ `llma-skill-file-get` (`file_path: scripts/ks2.py`), write it to `/tmp/ks2.py`, then pipe
+ JSON in: `echo '{"mode":"changepoint","series":[...]}' | python3 /tmp/ks2.py`. Request
+ shapes: `{"a": [...], "b": [...]}`; `{"a_hist": [[value, count], ...], "b_hist": [...]}`
+ (the cheap path); `{"mode": "changepoint", "series": [...ordered...], "min_seg": 24}`.
+
+**Pull histograms, not raw rows.** `execute-sql` caps at 500 rows, and raw samples are
+token-heavy. Instead `GROUP BY` a value-bucket expression (e.g.
+`round(rate, 4)` or `floor(value/10)*10`) so a whole window comes back as a few dozen
+`(value, count)` rows, and feed `a_hist`/`b_hist`. Binned KS reproduces the raw verdict
+closely (validated: D 0.76 raw vs 0.77 binned on the same windows) at a fraction of the
+payload. For a changepoint you do need the ordered series, but a daily series — or ≤ 500
+hourly buckets (~20 days) — fits under the cap.
+
+**Compare like with like — KS is not seasonality-aware.** Fed a weekend window against a
+weekday-heavy baseline, KS will correctly report the distributions differ — but that's the
+weekly rhythm, not an anomaly. Use seasonality-matched windows: same-day-of-week, full-week
+vs full-week (a whole week cancels its own diurnal+weekly shape), or difference the series
+first. The same discipline as the rest of this file; KS just makes the trap easy to fall into
+because it's so sensitive.
+
+**Calibration.** Emit only when **all three** hold: a small p (≲ ~0.01), a **meaningful effect
+size** `D` (the max CDF gap — a real separation, not a hair), and a move not explained by
+seasonality or a pipeline gap. On large samples p goes tiny on trivial differences, so `D` and
+the windows compared are the real evidence — put both in the finding, plus the changepoint
+timestamp when you have one. For a **changepoint**, the returned `p` is a **scan minimum**: the
+sweep picked the split that maximized `D` over many candidates, so `p` is biased low by
+multiple comparisons. Use `p_adj` (the Bonferroni-corrected value the helper returns), and
+confirm the chosen split with a direct two-sample KS on seasonality-matched windows before
+treating it as emit evidence — never emit on the raw scan `p` alone.
+
+**Worked example.** A high-volume hourly rate metric (~480 hourly buckets) with a genuine level
+shift partway through the window: the changepoint sweep located the break at the shift hour
+(`D ≈ 0.86`, corrected `p_adj` tiny); a clean prior week vs the shifted day gave `D ≈ 0.76`;
+two ordinary like-for-like weeks compared against each other gave `D ≈ 0.06`, `p ≈ 0.92`
+(silent — no false positive). The level detectors saw the drop in magnitude; KS additionally
+pinned _when_ it broke and confirmed a genuine distribution shift, not noise — while staying
+quiet on seasonality-matched windows.
+
## Per-insight-type recipes (all insight types are in scope)
Most dashboard tiles are trends-style numeric series and the method above applies directly.
diff --git a/products/signals/skills/signals-scout-anomaly-detection/scripts/ks2.py b/products/signals/skills/signals-scout-anomaly-detection/scripts/ks2.py
new file mode 100644
index 000000000000..b522515d08bd
--- /dev/null
+++ b/products/signals/skills/signals-scout-anomaly-detection/scripts/ks2.py
@@ -0,0 +1,130 @@
+#!/usr/bin/env python3
+"""Two-sample Kolmogorov-Smirnov change/distribution-shift detector — pure stdlib.
+
+No numpy/scipy needed (neither is preinstalled in the scout sandbox). Reads a JSON
+request on stdin and prints a JSON verdict, so the scout can pull samples via
+execute-sql and pipe them straight in.
+
+Modes (request `mode`):
+ - "two_sample": compare two samples `a` and `b` (raw value lists, or binned
+ [[value, count], ...] via `a_hist`/`b_hist`). Detects whether two windows'
+ distributions differ — the thing point/level detectors miss.
+ - "changepoint": scan an ordered `series` for the split that best separates it into
+ two differently-distributed halves (KS on left vs right at each candidate point).
+ This is the "where did it change" detector, not "is the latest point an outlier".
+
+The KS statistic D = max|F_a(x) - F_b(x)|; the p-value is the asymptotic Kolmogorov
+distribution with the Stephens small-sample correction (matches scipy's ks_2samp
+asymptotic mode closely for n,m >~ 30).
+"""
+
+from __future__ import annotations
+
+import sys
+import json
+import math
+
+
+def _ks_pvalue(d: float, n: float, m: float) -> float:
+ if n <= 0 or m <= 0 or d <= 0:
+ return 1.0
+ en = math.sqrt(n * m / (n + m))
+ t = (en + 0.12 + 0.11 / en) * d # Stephens correction
+ if t < 1e-12:
+ return 1.0
+ s = 0.0
+ for k in range(1, 101):
+ term = 2.0 * (-1) ** (k - 1) * math.exp(-2.0 * k * k * t * t)
+ s += term
+ if abs(term) < 1e-10:
+ break
+ return max(0.0, min(1.0, s))
+
+
+def ks_2samp(a: list[float], b: list[float]) -> tuple[float, float]:
+ a = sorted(a)
+ b = sorted(b)
+ n, m = len(a), len(b)
+ if n == 0 or m == 0:
+ return 0.0, 1.0
+ i = j = 0
+ d = 0.0
+ while i < n and j < m:
+ x = a[i] if a[i] <= b[j] else b[j]
+ while i < n and a[i] <= x:
+ i += 1
+ while j < m and b[j] <= x:
+ j += 1
+ d = max(d, abs(i / n - j / m))
+ return d, _ks_pvalue(d, n, m)
+
+
+def ks_2samp_binned(a_hist: list[list[float]], b_hist: list[list[float]]) -> tuple[float, float]:
+ """KS on two empirical CDFs given as (value, count) bins — the cheap-payload path."""
+ ca: dict[float, float] = {}
+ cb: dict[float, float] = {}
+ for v, c in a_hist:
+ ca[v] = ca.get(v, 0.0) + c
+ for v, c in b_hist:
+ cb[v] = cb.get(v, 0.0) + c
+ na = sum(ca.values())
+ nb = sum(cb.values())
+ if na == 0 or nb == 0:
+ return 0.0, 1.0
+ fa = fb = d = 0.0
+ for v in sorted(set(ca) | set(cb)):
+ fa += ca.get(v, 0.0) / na
+ fb += cb.get(v, 0.0) / nb
+ d = max(d, abs(fa - fb))
+ return d, _ks_pvalue(d, na, nb)
+
+
+def changepoint(series: list[float], min_seg: int = 8) -> dict:
+ """Find the split index whose left/right value distributions differ most (max D).
+
+ The sweep picks the split that maximizes D over many candidates, so the winning
+ `p` is a **scan minimum** — biased low by multiple comparisons and NOT a
+ single-hypothesis p-value. Use `p_adj` (Bonferroni over `tests`) as the calibrated
+ figure, and confirm the chosen split with a direct two-sample KS on
+ seasonality-matched windows before treating it as emit evidence.
+ """
+ n = len(series)
+ if n < 2 * min_seg:
+ return {"changepoint": None, "reason": f"need >= {2 * min_seg} points, got {n}"}
+ best = {"index": None, "d": 0.0, "p": 1.0}
+ tests = 0
+ for c in range(min_seg, n - min_seg + 1):
+ tests += 1
+ d, p = ks_2samp(series[:c], series[c:])
+ if d > best["d"]:
+ best = {"index": c, "d": d, "p": p}
+ return {
+ "changepoint": best["index"],
+ "d": round(best["d"], 4),
+ "p": best["p"], # scan minimum — uncorrected; see p_adj
+ "p_adj": min(1.0, best["p"] * tests), # Bonferroni over the scan
+ "tests": tests,
+ "n": n,
+ }
+
+
+def main() -> None:
+ req = json.load(sys.stdin)
+ mode = req.get("mode", "two_sample")
+ if mode == "changepoint":
+ out = changepoint(req["series"], min_seg=req.get("min_seg", 8))
+ elif "a_hist" in req or "b_hist" in req:
+ if "a_hist" not in req or "b_hist" not in req:
+ out = {"error": "binned mode needs both a_hist and b_hist"}
+ else:
+ d, p = ks_2samp_binned(req["a_hist"], req["b_hist"])
+ out = {"d": round(d, 4), "p": p, "na": sum(c for _, c in req["a_hist"]), "nb": sum(c for _, c in req["b_hist"])}
+ else:
+ d, p = ks_2samp(req["a"], req["b"])
+ out = {"d": round(d, 4), "p": p, "n": len(req["a"]), "m": len(req["b"])}
+ json.dump(out, sys.stdout)
+ sys.stdout.write("\n")
+
+
+if __name__ == "__main__":
+ main()