|
Última actualización: 2026-12-02
DAY 023 OF 1600 · 2026-10-23 Day 023 — Watch the inputs, because the labels are late; and one parameter that means two thingsA student's private learning log · one concept at a time. Date: 2026-10-23 · Day: 23 of 1600 Log: a student's private learning log · one concept at a time. --- Concept #23 — Drift belongs on the input side, and the KS statistic measures the distanceYesterday I wrote down that a served model is a service with a contract. Today I opened the next part of MA03 (AI-Ops): monitoring. The requirement is the boring one everybody signs and nobody implements — *monitor the model in production and detect when its behaviour degrades*. Here is the problem with the obvious reading of that sentence. "Degradation" is measured by accuracy, and accuracy needs labels, and labels arrive after the fact — next week, next month, whenever a human finally checks the outcomes. So a model that broke this morning gets discovered by an accuracy dashboard three weeks from now, after every decision it made in between. The inputs, on the other hand, are available the instant the request arrives. So the operational question is not "is this model still accurate?" but *"is this traffic still the traffic I trained on?"* — and that is a question about two distributions, which is machinery I already have. The statistic. The two-sample Kolmogorov–Smirnov distance is the largest gap between the two empirical cumulative distribution functions: D = max over x of | F_baseline(x) - F_live(x) | Two properties matter more than the formula. First, it is distribution-free : no assumption that the feature is normal, so it works on the odd feature I actually have. Second, it is a distance , not only a test: D = 0.09 is a small disagreement between two curves, D = 0.30 is a different population, whatever the sample size. That second property is the one I did not appreciate until I ran it. What I tried today: a pure-stdlib implementation of D, its p-value through the Kolmogorov distribution (with Stephens' small-sample correction) and — so the p-value is not taken on faith — a permutation test on the same samples, which uses no formula at all. Then four scenarios against one baseline of 400 draws: nothing changed, the mean moved, the mean stayed and the spread widened, and a tiny shift with 5000 rows. # ks.py - drift on the INPUTS, because the labels arrive too late to be an alarm. # MA03 (AI-Ops): monitoring. The Kolmogorov-Smirnov two-sample statistic is a # distribution-free measure of "how far apart are these two samples", and it # answers a question accuracy cannot answer on the day the traffic changes. import math, random def ks_two_sample(a, b): """Return (D, n1, n2). D = max distance between the two empirical CDFs.""" xs = sorted(a) ys = sorted(b) n1, n2 = len(xs), len(ys) i = j = 0 d = 0.0 while i < n1 and j < n2: if xs[i] <= ys[j]: i += 1 else: j += 1 d = max(d, abs(i / n1 - j / n2)) return d, n1, n2 def ks_p_asymptotic(d, n1, n2): """Kolmogorov distribution, Stephens' correction for small samples.""" ne = n1 * n2 / (n1 + n2) lam = (math.sqrt(ne) + 0.12 + 0.11 / math.sqrt(ne)) * d if lam < 0.2: return 1.0 total = 0.0 for k in range(1, 101): term = 2.0 * (-1) ** (k - 1) * math.exp(-2.0 * k * k * lam * lam) total += term if abs(term) < 1e-12: break return min(1.0, max(0.0, total)) def ks_p_permutation(a, b, reps=1000, rng=None): """The same p-value without trusting the asymptotic formula at all.""" rng = rng or random.Random(7) observed, _, _ = ks_two_sample(a, b) pool = list(a) + list(b) n1 = len(a) hits = 0 for _ in range(reps): rng.shuffle(pool) d, _, _ = ks_two_sample(pool[:n1], pool[n1:]) if d >= observed - 1e-12: hits += 1 return (hits + 1) / (reps + 1) def mean(v): return sum(v) / len(v) def sd(v): m = mean(v) return math.sqrt(sum((x - m) ** 2 for x in v) / (len(v) - 1)) rng = random.Random(20261023) BASE = [rng.gauss(0.0, 1.0) for _ in range(400)] CASES = [ ("same process, nothing changed", [rng.gauss(0.0, 1.0) for _ in range(400)]), ("mean moved +0.6", [rng.gauss(0.6, 1.0) for _ in range(400)]), ("same mean, sd 1.0 -> 1.8", [rng.gauss(0.0, 1.8) for _ in range(400)]), ("same mean, n=5000, +0.08 shift", [rng.gauss(0.08, 1.0) for _ in range(5000)]), ] Real output (Python 3, this session): baseline: 400 samples, mean -0.062, sd 0.948 case mean sd D p(asym) p(perm) alarm same process, nothing changed 0.094 1.041 0.093 6.13e-02 0.0709 quiet mean moved +0.6 0.579 1.011 0.298 4.43e-16 0.0010 DRIFT same mean, sd 1.0 -> 1.8 0.008 1.817 0.185 1.77e-06 0.0010 DRIFT same mean, n=5000, +0.08 shift 0.083 1.013 0.090 4.40e-03 n/a watch why the input side: on the day traffic changes, the labels for that traffic do not exist yet. Accuracy is a lagging measure; a feature distribution is not. row 1 is two draws from the SAME process and still lands at p=0.06: near the line means nothing. D is the size of the difference; p only says it exists. row 4: 5000 rows turn a 0.08 shift into p=0.004 while D stays at 0.09 -- significant, and too small to act on. So a drift alarm reports D, not just p. What I understood from it: three things I did not have yesterday. The row that taught me most is the third. The mean is 0.008 — a mean monitor, the dashboard everybody builds first, would have reported nothing wrong on the day the spread widened from 1.0 to 1.8. A model trained on tight data and then fed a wide version of the same data is a model being asked questions it was never taught to answer, and no average shows it. D caught it at 0.185, p = 1.8e-06. The monitor has to compare the whole curve, not one number off it. Second: the pair of p-values. Asymptotic 6.1e-02 against permutation 7.1e-02 on the same data — the formula is not magic, it is an approximation that agrees with resampling here, and the permutation floor is 1/(reps+1) = 0.001, which is exactly why rows 2 and 3 both print 0.0010 and cannot be told apart. If I ever need to separate two real drifts by p-value, I need more permutations, not a better formula. Third, and least comfortable: with 5000 rows a shift of 0.08 in the mean is "significant" (p = 0.004) and completely uninteresting, because D stayed at 0.09. Significance scales with sample size; the distance does not. An alarm that fires on p alone pages somebody every week forever, and the person paged learns to ignore it. Report D, threshold on D, and use p only to know whether D is bigger than sampling noise. Honest limit: KS on one feature says nothing about the joint distribution. Ten features that are each individually fine can still make a combination the model has never seen. This is a smoke detector, not a fire inspection. --- Security #23 — HTTP parameter pollution: one query string, two parsers, two answers (CWE-235)Twenty-two classes so far, and most were one component trusting its input. This one is different: the bug needs **two components that both read the same input correctly**. Neither is broken. They disagree about what a duplicated key means. ?action=view&action=delete is not malformed. It is a legal query string with no single correct reading: first occurrence wins — several WAFs, and ASP.NET's Request.QueryString last occurrence wins — PHP's $_GET , and most dict(...) -style parsers all of them, as a list — Node's qs , and parse_qs in Python So a check that reads action[0] and a handler that reads action[-1] are looking at the same request and describing two different requests. The guard approves a read; the handler performs the delete. The pattern I studied — the vulnerable shape, loopback only: def first_value(pairs, key): # what the guard inspects for k, v in pairs: if k == key: return v return "" def last_value(pairs, key): # what the handler executes out = "" for k, v in pairs: if k == key: out = v return out ALLOWED = {"view", "list", "export"} pairs = parse_qsl(urlsplit(self.path).query, keep_blank_values=True) guard = first_value(pairs, "action") # "view" -> allowed executed = last_value(pairs, "action") # "delete" -> ORDER DELETED if guard not in ALLOWED: return 403 # ... then dispatch on `executed` The same bug in the other direction is why guessing at hardening is useless: ?action=delete&action=view is blocked by that same guard, because now the first value is the bad one. The attacker controls the order, so whichever parser the guard uses, the order can be arranged for the guard to see the harmless value. What I understood about preventing it: the fix is not a better regex and not "sanitize the input". The fix is that there must be exactly one interpretation of a request, decided once at the edge and passed forward as a data structure — and duplicate keys must be refused, not resolved. def duplicate_keys(pairs): seen, dup = set(), [] for k, _ in pairs: if k in seen and k not in dup: dup.append(k) seen.add(k) return dup pairs = parse_qsl(urlsplit(self.path).query, keep_blank_values=True) if duplicate_keys(pairs): # ambiguity is an error, not a choice return 400 action = first_value(pairs, "action") # now there is only one value if action not in ALLOWED: return 403 Sandbox check (two local servers, 127.0.0.1, real HTTP requests, ports closed after the run): [VULNERABLE] service on 127.0.0.1:8731 clean read GET /orders?action=view -> 200 check saw action='view' -> 200 allow | handler executed action='view' -> read only padded read GET /orders?action=view&action=delete -> 200 check saw action='view' -> 200 allow | handler executed action='delete' -> ORDER DELETED reversed order GET /orders?action=delete&action=view -> 403 blocked by check (saw action='delete') [FIXED] service on 127.0.0.1:8732 clean read GET /orders?action=view -> 200 one value, checked once: action='view' -> read only padded read GET /orders?action=view&action=delete -> 400 rejected: duplicate parameter(s) ['action'] reversed order GET /orders?action=delete&action=view -> 400 rejected: duplicate parameter(s) ['action'] What I understood: this is the same shape as the request smuggling day — two parsers, one buffer — moved up a layer, from the byte framing into the query string. Anywhere a request crosses a component boundary and gets parsed twice, "what does this request say?" has to be answered once, before the first parser, and the answer has to travel with the request. A WAF that re-parses the raw URI it was handed can only ever hold an opinion about a request the application is free to read differently. Honest part: my demo keeps both parsers in one file on purpose — clearest way to show the disagreement, least realistic deployment. In the field the guard is a different process, written by a different team, in a different language, which is exactly why nobody notices the disagreement until it is used. --- Day 23 notesConcept #23: code ran, output above. ✔ Security #23: understood the idea, sandbox only, both servers shut down. ✔ 1577 days left. One at a time. Written by my own daily machine, checked by me. · Day 023 of 1600 · Matías Rathgeb [ inicio ] [ proyectos ] [ posts ] [ daylog ] Página estática. Sin cookies, sin javascript, sin fuentes externas. Contacto: ver inicio. |