proxyml-core 0.2.2__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/PKG-INFO +1 -1
  2. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/pyproject.toml +1 -1
  3. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/src/proxyml_core/__init__.py +5 -0
  4. proxyml_core-0.3.0/src/proxyml_core/drift.py +390 -0
  5. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/src/proxyml_core.egg-info/PKG-INFO +1 -1
  6. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/src/proxyml_core.egg-info/SOURCES.txt +2 -0
  7. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/tests/test_dependency_boundaries.py +1 -1
  8. proxyml_core-0.3.0/tests/test_drift.py +191 -0
  9. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/LICENSE +0 -0
  10. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/README.md +0 -0
  11. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/setup.cfg +0 -0
  12. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/src/proxyml_core/_version.py +0 -0
  13. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/src/proxyml_core/export.py +0 -0
  14. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/src/proxyml_core/fingerprint.py +0 -0
  15. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/src/proxyml_core/modeling/__init__.py +0 -0
  16. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/src/proxyml_core/modeling/estimators.py +0 -0
  17. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/src/proxyml_core/modeling/extract.py +0 -0
  18. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/src/proxyml_core/modeling/preprocess.py +0 -0
  19. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/src/proxyml_core/modeling/scoring.py +0 -0
  20. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/src/proxyml_core/schema.py +0 -0
  21. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/src/proxyml_core.egg-info/dependency_links.txt +0 -0
  22. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/src/proxyml_core.egg-info/requires.txt +0 -0
  23. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/src/proxyml_core.egg-info/top_level.txt +0 -0
  24. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/tests/test_export.py +0 -0
  25. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/tests/test_export_version_contract.py +0 -0
  26. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/tests/test_fingerprint.py +0 -0
  27. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/tests/test_modeling_estimators.py +0 -0
  28. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/tests/test_modeling_extract.py +0 -0
  29. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/tests/test_modeling_preprocess.py +0 -0
  30. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/tests/test_modeling_scoring.py +0 -0
  31. {proxyml_core-0.2.2 → proxyml_core-0.3.0}/tests/test_schema.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: proxyml-core
3
- Version: 0.2.2
3
+ Version: 0.3.0
4
4
  Summary: Shared schema types, export contract, and modeling code for proxyml and its backend.
5
5
  Author-email: ProxyML <contact@proxyml.ai>
6
6
  License: Apache License
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "proxyml-core"
3
- version = "0.2.2"
3
+ version = "0.3.0"
4
4
  description = "Shared schema types, export contract, and modeling code for proxyml and its backend."
5
5
  readme = "README.md"
6
6
  license = {file = "LICENSE"}
@@ -15,6 +15,7 @@ from proxyml_core.export import (
15
15
  predict_from_export,
16
16
  score_export,
17
17
  )
18
+ from proxyml_core.drift import DriftReport, DriftThresholds, FeatureDrift, compare_schemas
18
19
  from proxyml_core.fingerprint import FINGERPRINT_MISMATCH_MESSAGE, check_fingerprints
19
20
  from proxyml_core.schema import (
20
21
  CategoricalFeature,
@@ -52,4 +53,8 @@ __all__ = [
52
53
  "check_compatible",
53
54
  "check_fingerprints",
54
55
  "FINGERPRINT_MISMATCH_MESSAGE",
56
+ "compare_schemas",
57
+ "DriftThresholds",
58
+ "DriftReport",
59
+ "FeatureDrift",
55
60
  ]
@@ -0,0 +1,390 @@
1
+ """Data-drift comparison between two feature schemas.
2
+
3
+ A ``FeatureSchema`` carries only per-feature marginal summaries (mean/std for
4
+ continuous and numeric-ordinal features, category frequencies for categorical
5
+ ones, lambda for counts), so drift can be checked from those summaries alone —
6
+ no raw rows ever have to leave the machine that computed them.
7
+
8
+ ``compare_schemas(baseline, current, n_samples)`` is pure (stdlib only): the
9
+ SDK, the backend and the MCP server can all share this one implementation.
10
+
11
+ What this can and cannot see
12
+ ----------------------------
13
+ * Marginal shifts only. Changes in correlations or joint structure are
14
+ invisible to per-feature summaries.
15
+ * Continuous / numeric-ordinal features are compared through mean and std
16
+ (min/max are ignored; they are too noisy to be useful).
17
+ * Every metric must clear BOTH its threshold and a sample-size noise floor
18
+ (``noise_sigmas`` standard errors, derived from ``n_samples``), so a small
19
+ production sample cannot trip a strict threshold by chance. The floors are
20
+ tail-aware: the schema's min/max bound a feature's variance and kurtosis
21
+ (Bhatia-Davis), so heavy-tailed or zero-inflated features get wider floors
22
+ instead of firing on a handful of outlier rows. The baseline's own sample
23
+ count is not recorded; pass ``baseline_n_samples`` when it is known, otherwise
24
+ the baseline is treated as noise-free.
25
+ * Thresholds are policy, not statistics. The defaults are a starting point;
26
+ callers are expected to tune them for their own tolerance. The noise floors,
27
+ not the thresholds, set the false-alarm rate, so lowering a threshold is
28
+ cheap, while lowering ``noise_sigmas`` is what makes alerts noisy.
29
+ ``scripts/calibrate_drift.py`` reproduces the false-alarm and detection rates
30
+ the defaults were chosen from.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import math
36
+ from statistics import NormalDist
37
+ from dataclasses import asdict, dataclass, field
38
+ from typing import Any
39
+
40
+ from proxyml_core.schema import (
41
+ CategoricalFeature,
42
+ CategoricalOrdinalFeature,
43
+ ContinuousFeature,
44
+ CountFeature,
45
+ Feature,
46
+ FeatureSchema,
47
+ NumericOrdinalFeature,
48
+ )
49
+
50
+ # Per-feature statuses.
51
+ OK = "ok"
52
+ DRIFT = "drift"
53
+ ADDED = "added"
54
+ REMOVED = "removed"
55
+ TYPE_CHANGED = "type_changed"
56
+
57
+ # Overall statuses.
58
+ PASS = "pass"
59
+ INSUFFICIENT_SAMPLE = "insufficient_sample"
60
+
61
+ # A category absent from the baseline must also appear at least this many times
62
+ # in the current sample before it counts as "new" (guards tiny-sample noise).
63
+ _NEW_CATEGORY_MIN_COUNT = 10
64
+
65
+ # A baseline category is reported as "vanished" only if its absence from the
66
+ # current sample would happen by chance less than this often: (1 - p) ** n.
67
+ _VANISHED_CHANCE = 1e-3
68
+
69
+ # A shift in a mean (or lambda) that could be produced by fewer than this many
70
+ # extreme rows is not reported: one outlier landing in the sample is not drift.
71
+ _MIN_ROWS_FOR_SHIFT = 3
72
+
73
+ # Family-wise false-alarm target per snapshot used when noise_sigmas is automatic.
74
+ _FAMILY_ALPHA = 0.05
75
+ _AUTO_SIGMAS_FLOOR = 3.0
76
+
77
+ # Features whose min or max sits further than this many std from the mean are
78
+ # too heavy-tailed for a std comparison to mean anything (a handful of rows set
79
+ # the std), so only their mean is compared. A Gaussian sample of 20,000 rarely
80
+ # exceeds 4.
81
+ _HEAVY_TAIL_RATIO = 10.0
82
+
83
+
84
+ @dataclass(frozen=True, kw_only=True)
85
+ class DriftThresholds:
86
+ """Tunable alerting policy. All values are per-feature.
87
+
88
+ mean_shift |mean_current - mean_baseline| / std_baseline
89
+ std_ratio max(std_c, std_b) / min(std_c, std_b)
90
+ category_tvd total variation distance between category frequencies
91
+ count_rel_change |lambda_c - lambda_b| / lambda_b
92
+ new_category_mass minimum share for an unseen (or vanished) category to be reported
93
+ noise_sigmas standard errors a metric must exceed, given n_samples, to count.
94
+ None (default) = automatic: a Bonferroni-style value that keeps the
95
+ chance of any false alarm per snapshot near 5% however many
96
+ features the schema has, but never below 3. A number is used as-is.
97
+ min_samples below this the check is refused (status "insufficient_sample")
98
+ """
99
+
100
+ mean_shift: float = 0.2
101
+ std_ratio: float = 1.4
102
+ category_tvd: float = 0.08
103
+ count_rel_change: float = 0.2
104
+ new_category_mass: float = 0.02
105
+ noise_sigmas: float | None = None
106
+ min_samples: int = 100
107
+
108
+ def to_dict(self) -> dict[str, Any]:
109
+ return asdict(self)
110
+
111
+ @classmethod
112
+ def from_dict(cls, d: dict[str, Any] | None) -> "DriftThresholds":
113
+ """Build from a (possibly partial) dict; unknown keys raise ValueError."""
114
+ if not d:
115
+ return cls()
116
+ known = set(cls.__dataclass_fields__)
117
+ unknown = set(d) - known
118
+ if unknown:
119
+ raise ValueError(f"Unknown drift threshold(s): {sorted(unknown)}")
120
+ t = cls(**d)
121
+ for name in ("mean_shift", "category_tvd", "count_rel_change", "new_category_mass"):
122
+ if getattr(t, name) < 0:
123
+ raise ValueError(f"{name} must be >= 0")
124
+ if t.noise_sigmas is not None and t.noise_sigmas < 0:
125
+ raise ValueError("noise_sigmas must be >= 0")
126
+ if t.std_ratio < 1:
127
+ raise ValueError("std_ratio must be >= 1")
128
+ if t.min_samples < 1:
129
+ raise ValueError("min_samples must be >= 1")
130
+ return t
131
+
132
+
133
+ @dataclass
134
+ class FeatureDrift:
135
+ name: str
136
+ type: str
137
+ status: str
138
+ metrics: dict[str, float] = field(default_factory=dict)
139
+ noise_floors: dict[str, float] = field(default_factory=dict)
140
+ reasons: list[str] = field(default_factory=list)
141
+
142
+ def to_dict(self) -> dict[str, Any]:
143
+ """JSON-safe: non-finite metrics/floors (e.g. a zero baseline std, or a
144
+ comparison that was skipped) become None rather than Infinity/NaN."""
145
+ d = asdict(self)
146
+ for key in ("metrics", "noise_floors"):
147
+ d[key] = {k: (v if math.isfinite(v) else None) for k, v in d[key].items()}
148
+ return d
149
+
150
+
151
+ @dataclass
152
+ class DriftReport:
153
+ status: str # "pass" | "drift" | "insufficient_sample"
154
+ passed: bool
155
+ n_samples: int
156
+ thresholds: DriftThresholds
157
+ features: list[FeatureDrift]
158
+ noise_sigmas_used: float | None = None
159
+
160
+ @property
161
+ def summary(self) -> dict[str, int]:
162
+ count = lambda s: sum(1 for f in self.features if f.status == s) # noqa: E731
163
+ return {
164
+ "checked": len(self.features),
165
+ "drifted": count(DRIFT),
166
+ "added": count(ADDED),
167
+ "removed": count(REMOVED),
168
+ "type_changed": count(TYPE_CHANGED),
169
+ }
170
+
171
+ def to_dict(self) -> dict[str, Any]:
172
+ return {
173
+ "status": self.status,
174
+ "passed": self.passed,
175
+ "n_samples": self.n_samples,
176
+ "thresholds": self.thresholds.to_dict(),
177
+ "noise_sigmas_used": self.noise_sigmas_used,
178
+ "summary": self.summary,
179
+ "features": [f.to_dict() for f in self.features],
180
+ }
181
+
182
+
183
+ # ── metric helpers ───────────────────────────────────────────────────────────
184
+
185
+
186
+ def _mean_shift(mean_b: float, std_b: float, mean_c: float) -> float:
187
+ delta = abs(mean_c - mean_b)
188
+ if std_b <= 0:
189
+ return 0.0 if delta == 0 else math.inf
190
+ return delta / std_b
191
+
192
+
193
+ def _std_ratio(std_b: float, std_c: float) -> float:
194
+ lo, hi = sorted((std_b, std_c))
195
+ if hi == 0:
196
+ return 1.0
197
+ if lo <= 0:
198
+ return math.inf
199
+ return hi / lo
200
+
201
+
202
+ def _tail_ratio(*features: Feature) -> float | None:
203
+ """Largest deviation from the mean, in std units, over the given continuous
204
+ features (None if any lacks min/max or has zero std). Bounds kurtosis:
205
+ kappa <= tail_ratio**2."""
206
+ ratios = []
207
+ for f in features:
208
+ if not isinstance(f, ContinuousFeature) or f.std <= 0:
209
+ return None
210
+ ratios.append(max(f.max - f.mean, f.mean - f.min) / f.std)
211
+ return max(ratios)
212
+
213
+
214
+ def _distribution(feature: Feature) -> dict[str, float]:
215
+ if isinstance(feature, CategoricalFeature):
216
+ return {str(k): float(v) for k, v in feature.valid_categories.items()}
217
+ assert isinstance(feature, CategoricalOrdinalFeature)
218
+ return {str(c): float(p) for c, p in zip(feature.categories, feature.probabilities)}
219
+
220
+
221
+ def _tvd(p: dict[str, float], q: dict[str, float]) -> float:
222
+ return 0.5 * sum(abs(p.get(k, 0.0) - q.get(k, 0.0)) for k in p.keys() | q.keys())
223
+
224
+
225
+ def _fmt(x: float) -> str:
226
+ return "inf" if math.isinf(x) else f"{x:.3g}"
227
+
228
+
229
+ # ── per-type comparisons ─────────────────────────────────────────────────────
230
+
231
+
232
+ def _compare_mean_std(
233
+ name: str, ftype: str, mean_b: float, std_b: float, mean_c: float, std_c: float,
234
+ n: float, t: DriftThresholds, sig: float, tail_ratio: float | None = None, n_rows: int = 0,
235
+ ) -> FeatureDrift:
236
+ shift = _mean_shift(mean_b, std_b, mean_c)
237
+ ratio = _std_ratio(std_b, std_c)
238
+ # SE of the mean, in baseline-std units (a wider current std widens it).
239
+ spread = max(1.0, std_c / std_b) if std_b > 0 else 1.0
240
+ shift_floor = sig * spread / math.sqrt(n)
241
+ if tail_ratio is not None and n_rows:
242
+ # Fewer than _MIN_ROWS_FOR_SHIFT extreme rows can move the mean this far.
243
+ shift_floor = max(shift_floor, _MIN_ROWS_FOR_SHIFT * tail_ratio / n_rows)
244
+ # SE of log(std) is sqrt((kappa - 1) / (4n)); kappa = 3 for a Gaussian. With
245
+ # min/max available, kappa <= tail_ratio**2 bounds it for heavy tails.
246
+ kappa = max(3.0, tail_ratio**2) if tail_ratio is not None else 3.0
247
+ ratio_floor = math.exp(sig * math.sqrt((kappa - 1) / (4 * n)))
248
+ heavy_tailed = tail_ratio is not None and tail_ratio > _HEAVY_TAIL_RATIO
249
+ if heavy_tailed:
250
+ ratio_floor = math.inf # std not comparable; see _HEAVY_TAIL_RATIO
251
+
252
+ reasons: list[str] = []
253
+ if shift > t.mean_shift and shift > shift_floor:
254
+ reasons.append(f"mean_shift {_fmt(shift)} > {_fmt(max(t.mean_shift, shift_floor))}")
255
+ if not heavy_tailed and ratio > t.std_ratio and ratio > ratio_floor:
256
+ reasons.append(f"std_ratio {_fmt(ratio)} > {_fmt(max(t.std_ratio, ratio_floor))}")
257
+ return FeatureDrift(
258
+ name=name, type=ftype, status=DRIFT if reasons else OK,
259
+ metrics={"mean_shift": shift, "std_ratio": ratio},
260
+ noise_floors={"mean_shift": shift_floor, "std_ratio": ratio_floor},
261
+ reasons=reasons,
262
+ )
263
+
264
+
265
+ def _compare_categorical(base: Feature, cur: Feature, n: float, t: DriftThresholds, sig: float, n_current: int) -> FeatureDrift:
266
+ p, q = _distribution(base), _distribution(cur)
267
+ tvd = _tvd(p, q)
268
+ # Expected TVD from sampling noise alone is ~0.4 * sum(sqrt(p(1-p)/n));
269
+ # scale to noise_sigmas for a conservative floor.
270
+ tvd_floor = sig * 0.5 * sum(math.sqrt(v * (1 - v) / n) for v in p.values())
271
+
272
+ reasons: list[str] = []
273
+ if tvd > t.category_tvd and tvd > tvd_floor:
274
+ reasons.append(f"category_tvd {_fmt(tvd)} > {_fmt(max(t.category_tvd, tvd_floor))}")
275
+ for k in sorted(q.keys() - p.keys()):
276
+ if q[k] >= t.new_category_mass and q[k] * n_current >= _NEW_CATEGORY_MIN_COUNT:
277
+ reasons.append(f"new category {k!r} ({q[k]:.1%} of sample)")
278
+ for k in sorted(p.keys() - q.keys()):
279
+ if p[k] >= t.new_category_mass and (1 - p[k]) ** n_current < _VANISHED_CHANCE:
280
+ reasons.append(f"category {k!r} vanished (was {p[k]:.1%})")
281
+ return FeatureDrift(
282
+ name=base.name, type=base.type, status=DRIFT if reasons else OK,
283
+ metrics={"category_tvd": tvd}, noise_floors={"category_tvd": tvd_floor}, reasons=reasons,
284
+ )
285
+
286
+
287
+ def _compare_count(base: CountFeature, cur: CountFeature, n: float, t: DriftThresholds, sig: float, n_rows: int) -> FeatureDrift:
288
+ lam_b, lam_c = base.lambda_, cur.lambda_
289
+ if lam_b <= 0:
290
+ rel = 0.0 if lam_c == 0 else math.inf
291
+ floor = 0.0
292
+ else:
293
+ rel = abs(lam_c - lam_b) / lam_b
294
+ # Poisson variance is lambda, but real "counts" are often overdispersed
295
+ # or zero-inflated (a few large values drive the mean). Bhatia-Davis
296
+ # bounds the variance of a [0, max] variable by lambda * (max - lambda);
297
+ # use the larger of the two so such features get an honest, wider floor.
298
+ top = max(base.max, cur.max) if base.max is not None and cur.max is not None else None
299
+ variance = lam_b if top is None else max(lam_b, lam_b * (top - lam_b))
300
+ floor = sig * math.sqrt(variance / n) / lam_b
301
+ if top is not None:
302
+ floor = max(floor, _MIN_ROWS_FOR_SHIFT * top / (n_rows * lam_b))
303
+ reasons = []
304
+ if rel > t.count_rel_change and rel > floor:
305
+ reasons.append(f"count_rel_change {_fmt(rel)} > {_fmt(max(t.count_rel_change, floor))}")
306
+ return FeatureDrift(
307
+ name=base.name, type=base.type, status=DRIFT if reasons else OK,
308
+ metrics={"count_rel_change": rel}, noise_floors={"count_rel_change": floor}, reasons=reasons,
309
+ )
310
+
311
+
312
+ def _compare_feature(base: Feature, cur: Feature, n: float, t: DriftThresholds, sig: float, n_current: int) -> FeatureDrift:
313
+ if base.type != cur.type:
314
+ return FeatureDrift(
315
+ name=base.name, type=cur.type, status=TYPE_CHANGED,
316
+ reasons=[f"type changed from {base.type} to {cur.type}"],
317
+ )
318
+ if isinstance(base, (ContinuousFeature, NumericOrdinalFeature)):
319
+ result = _compare_mean_std(
320
+ base.name, base.type, base.mean, base.std, cur.mean, cur.std, n, t, sig, # type: ignore[union-attr]
321
+ tail_ratio=_tail_ratio(base, cur), n_rows=n_current,
322
+ )
323
+ if isinstance(base, NumericOrdinalFeature) and set(base.categories) != set(cur.categories): # type: ignore[union-attr]
324
+ result.status = DRIFT
325
+ result.reasons.append("ordinal category set changed")
326
+ return result
327
+ if isinstance(base, (CategoricalFeature, CategoricalOrdinalFeature)):
328
+ return _compare_categorical(base, cur, n, t, sig, n_current)
329
+ assert isinstance(base, CountFeature) and isinstance(cur, CountFeature)
330
+ return _compare_count(base, cur, n, t, sig, n_current)
331
+
332
+
333
+ # ── public entry point ───────────────────────────────────────────────────────
334
+
335
+
336
+ def _auto_sigmas(n_features: int) -> float:
337
+ """Per-metric sigma giving ~_FAMILY_ALPHA chance of any false alarm per snapshot
338
+ (two-sided Bonferroni over ~2 metrics per feature), never below 3."""
339
+ tests = max(1, 2 * n_features)
340
+ return max(_AUTO_SIGMAS_FLOOR, NormalDist().inv_cdf(1 - _FAMILY_ALPHA / (2 * tests)))
341
+
342
+
343
+ def compare_schemas(
344
+ baseline: FeatureSchema,
345
+ current: FeatureSchema,
346
+ n_samples: int,
347
+ thresholds: DriftThresholds | None = None,
348
+ baseline_n_samples: int | None = None,
349
+ ) -> DriftReport:
350
+ """Compare a current-data schema against a baseline schema.
351
+
352
+ Returns a ``DriftReport``. Added/removed features and type changes are
353
+ findings (and fail the check), never exceptions. If ``n_samples`` is below
354
+ ``thresholds.min_samples`` nothing is evaluated and the status is
355
+ ``"insufficient_sample"`` (``passed`` is False: no conclusion was reached).
356
+
357
+ ``baseline_n_samples``, when known, makes the noise floors account for the
358
+ baseline's own sampling error (effective n = 1 / (1/n_current + 1/n_baseline)).
359
+ """
360
+ if n_samples < 1:
361
+ raise ValueError("n_samples must be >= 1")
362
+ t = thresholds or DriftThresholds()
363
+ if n_samples < t.min_samples:
364
+ return DriftReport(
365
+ status=INSUFFICIENT_SAMPLE, passed=False, n_samples=n_samples, thresholds=t, features=[],
366
+ )
367
+
368
+ sig = t.noise_sigmas if t.noise_sigmas is not None else _auto_sigmas(len(baseline.features))
369
+ n_eff = float(n_samples)
370
+ if baseline_n_samples:
371
+ n_eff = 1.0 / (1.0 / n_samples + 1.0 / baseline_n_samples)
372
+
373
+ base = {f.name: f for f in baseline.features}
374
+ cur = {f.name: f for f in current.features}
375
+ findings: list[FeatureDrift] = []
376
+ for name, bf in base.items():
377
+ cf = cur.get(name)
378
+ if cf is None:
379
+ findings.append(FeatureDrift(name=name, type=bf.type, status=REMOVED, reasons=["feature missing from current data"]))
380
+ else:
381
+ findings.append(_compare_feature(bf, cf, n_eff, t, sig, n_samples))
382
+ for name, cf in cur.items():
383
+ if name not in base:
384
+ findings.append(FeatureDrift(name=name, type=cf.type, status=ADDED, reasons=["feature not in baseline"]))
385
+
386
+ passed = all(f.status == OK for f in findings)
387
+ return DriftReport(
388
+ status=PASS if passed else DRIFT, passed=passed, n_samples=n_samples, thresholds=t, features=findings,
389
+ noise_sigmas_used=sig,
390
+ )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: proxyml-core
3
- Version: 0.2.2
3
+ Version: 0.3.0
4
4
  Summary: Shared schema types, export contract, and modeling code for proxyml and its backend.
5
5
  Author-email: ProxyML <contact@proxyml.ai>
6
6
  License: Apache License
@@ -3,6 +3,7 @@ README.md
3
3
  pyproject.toml
4
4
  src/proxyml_core/__init__.py
5
5
  src/proxyml_core/_version.py
6
+ src/proxyml_core/drift.py
6
7
  src/proxyml_core/export.py
7
8
  src/proxyml_core/fingerprint.py
8
9
  src/proxyml_core/schema.py
@@ -17,6 +18,7 @@ src/proxyml_core/modeling/extract.py
17
18
  src/proxyml_core/modeling/preprocess.py
18
19
  src/proxyml_core/modeling/scoring.py
19
20
  tests/test_dependency_boundaries.py
21
+ tests/test_drift.py
20
22
  tests/test_export.py
21
23
  tests/test_export_version_contract.py
22
24
  tests/test_fingerprint.py
@@ -12,7 +12,7 @@ from pathlib import Path
12
12
 
13
13
  import proxyml_core
14
14
 
15
- _PURE_MODULES = ["schema.py", "export.py", "_version.py", "fingerprint.py"]
15
+ _PURE_MODULES = ["schema.py", "export.py", "_version.py", "fingerprint.py", "drift.py"]
16
16
  _ALLOWED_PURE_TOP_LEVEL = {"numpy"} | set(sys.stdlib_module_names)
17
17
  _ALLOWED_MODELING_TOP_LEVEL = _ALLOWED_PURE_TOP_LEVEL | {"sklearn", "scipy"}
18
18
 
@@ -0,0 +1,191 @@
1
+ import json
2
+ import math
3
+
4
+ import pytest
5
+
6
+ from proxyml_core import (
7
+ CategoricalFeature,
8
+ ContinuousFeature,
9
+ CountFeature,
10
+ DriftThresholds,
11
+ FeatureSchema,
12
+ NumericOrdinalFeature,
13
+ compare_schemas,
14
+ )
15
+
16
+
17
+ def cont(name="x", mean=0.0, std=1.0, lo=-4.0, hi=4.0):
18
+ return ContinuousFeature(name=name, mean=mean, std=std, min=lo, max=hi)
19
+
20
+
21
+ def cat(name="c", **probs):
22
+ return CategoricalFeature(name=name, valid_categories=probs or {"a": 0.5, "b": 0.5})
23
+
24
+
25
+ def count(name="k", lam=5.0, mx=15):
26
+ return CountFeature(name=name, lambda_=lam, max=mx)
27
+
28
+
29
+ def schema(*features):
30
+ return FeatureSchema(features=list(features))
31
+
32
+
33
+ def one(report, name):
34
+ return next(f for f in report.features if f.name == name)
35
+
36
+
37
+ def test_identical_schemas_pass():
38
+ s = schema(cont(), cat(), count())
39
+ r = compare_schemas(s, s, 1000)
40
+ assert r.passed and r.status == "pass"
41
+ assert r.summary == {"checked": 3, "drifted": 0, "added": 0, "removed": 0, "type_changed": 0}
42
+
43
+
44
+ def test_mean_shift_flagged_above_threshold_and_floor():
45
+ r = compare_schemas(schema(cont()), schema(cont(mean=0.6)), 2000)
46
+ f = one(r, "x")
47
+ assert f.status == "drift" and not r.passed
48
+ assert f.metrics["mean_shift"] == pytest.approx(0.6)
49
+ assert "mean_shift" in f.reasons[0]
50
+
51
+
52
+ def test_small_shift_below_threshold_is_ignored():
53
+ r = compare_schemas(schema(cont()), schema(cont(mean=0.1)), 100_000)
54
+ assert r.passed
55
+
56
+
57
+ def test_noise_floor_suppresses_small_sample_shift():
58
+ # 0.3 sigma exceeds the 0.2 threshold, but with n=100 it is within noise.
59
+ small = compare_schemas(schema(cont()), schema(cont(mean=0.3)), 100)
60
+ large = compare_schemas(schema(cont()), schema(cont(mean=0.3)), 5000)
61
+ assert small.passed
62
+ assert not large.passed
63
+
64
+
65
+ def test_std_ratio_flagged():
66
+ r = compare_schemas(schema(cont()), schema(cont(std=2.5, lo=-10, hi=10)), 2000)
67
+ assert one(r, "x").status == "drift"
68
+ assert one(r, "x").metrics["std_ratio"] == pytest.approx(2.5)
69
+
70
+
71
+ def test_heavy_tailed_feature_skips_std_comparison():
72
+ base = cont(std=1.0, lo=-50, hi=50) # 50 sigma tail
73
+ cur = cont(std=5.0, lo=-50, hi=50)
74
+ r = compare_schemas(schema(base), schema(cur), 5000)
75
+ f = one(r, "x")
76
+ assert f.status == "ok"
77
+ assert f.noise_floors["std_ratio"] == math.inf
78
+
79
+
80
+ def test_extreme_rows_cannot_trigger_mean_shift():
81
+ # Mean moved 0.5 sigma, but only ~1 row of a 100-sample at the 50-sigma tail could do that.
82
+ base = cont(lo=-50, hi=50)
83
+ cur = cont(mean=0.5, lo=-50, hi=50)
84
+ assert compare_schemas(schema(base), schema(cur), 100).passed
85
+
86
+
87
+ def test_categorical_tvd_flagged():
88
+ base = schema(cat(a=0.5, b=0.5))
89
+ cur = schema(cat(a=0.8, b=0.2))
90
+ r = compare_schemas(base, cur, 2000)
91
+ assert one(r, "c").status == "drift"
92
+ assert one(r, "c").metrics["category_tvd"] == pytest.approx(0.3)
93
+
94
+
95
+ def test_new_category_needs_enough_rows():
96
+ base = schema(cat(a=0.5, b=0.5))
97
+ # 3% of 200 rows = 6 rows: below the minimum count, not reported.
98
+ assert compare_schemas(base, schema(cat(a=0.485, b=0.485, z=0.03)), 200).passed
99
+ # 3% of 2000 rows = 60 rows: reported.
100
+ r = compare_schemas(base, schema(cat(a=0.485, b=0.485, z=0.03)), 2000)
101
+ assert any("new category 'z'" in x for x in one(r, "c").reasons)
102
+
103
+
104
+ def test_vanished_category_only_when_absence_is_unlikely_by_chance():
105
+ base = schema(cat(a=0.5, b=0.47, rare=0.03))
106
+ cur = schema(cat(a=0.515, b=0.485))
107
+ # A 3% category missing from 100 rows happens ~5% of the time: not drift.
108
+ assert compare_schemas(base, cur, 100).passed
109
+ r = compare_schemas(base, cur, 5000)
110
+ assert any("vanished" in x for x in one(r, "c").reasons)
111
+
112
+
113
+ def test_count_lambda_shift_flagged():
114
+ r = compare_schemas(schema(count()), schema(count(lam=8.0, mx=25)), 3000)
115
+ assert one(r, "k").status == "drift"
116
+ assert one(r, "k").metrics["count_rel_change"] == pytest.approx(0.6)
117
+
118
+
119
+ def test_zero_inflated_count_not_flagged_by_a_few_rows():
120
+ base = schema(CountFeature(name="pool", lambda_=0.01, max=738))
121
+ cur = schema(CountFeature(name="pool", lambda_=0.05, max=738))
122
+ assert compare_schemas(base, cur, 200).passed
123
+
124
+
125
+ def test_numeric_ordinal_category_set_change():
126
+ base = schema(NumericOrdinalFeature(name="r", categories=[1, 2, 3], mean=2.0, std=0.8))
127
+ cur = schema(NumericOrdinalFeature(name="r", categories=[1, 2, 3, 4], mean=2.0, std=0.8))
128
+ assert one(compare_schemas(base, cur, 1000), "r").status == "drift"
129
+
130
+
131
+ def test_structural_changes_are_findings_not_errors():
132
+ base = schema(cont("a"), cont("b"), cat("c"))
133
+ cur = schema(cont("a"), count("b"), cont("d"))
134
+ r = compare_schemas(base, cur, 1000)
135
+ assert not r.passed
136
+ assert one(r, "b").status == "type_changed"
137
+ assert one(r, "c").status == "removed"
138
+ assert one(r, "d").status == "added"
139
+ assert r.summary["added"] == r.summary["removed"] == r.summary["type_changed"] == 1
140
+
141
+
142
+ def test_insufficient_sample_is_not_evaluated():
143
+ s = schema(cont())
144
+ r = compare_schemas(s, s, 50)
145
+ assert r.status == "insufficient_sample" and not r.passed and r.features == []
146
+ assert compare_schemas(s, s, 50, DriftThresholds(min_samples=10)).passed
147
+
148
+
149
+ def test_invalid_n_samples():
150
+ with pytest.raises(ValueError):
151
+ compare_schemas(schema(cont()), schema(cont()), 0)
152
+
153
+
154
+ def test_thresholds_are_tunable():
155
+ base, cur = schema(cont()), schema(cont(mean=0.3))
156
+ assert compare_schemas(base, cur, 20_000, DriftThresholds(mean_shift=0.5)).passed
157
+ assert not compare_schemas(base, cur, 20_000, DriftThresholds(mean_shift=0.1)).passed
158
+
159
+
160
+ def test_thresholds_from_dict_validation():
161
+ assert DriftThresholds.from_dict(None) == DriftThresholds()
162
+ assert DriftThresholds.from_dict({"mean_shift": 0.4}).mean_shift == 0.4
163
+ with pytest.raises(ValueError, match="Unknown"):
164
+ DriftThresholds.from_dict({"nope": 1})
165
+ with pytest.raises(ValueError):
166
+ DriftThresholds.from_dict({"std_ratio": 0.5})
167
+ with pytest.raises(ValueError):
168
+ DriftThresholds.from_dict({"mean_shift": -1})
169
+
170
+
171
+ def test_auto_noise_sigmas_grows_with_schema_width():
172
+ narrow = compare_schemas(schema(cont()), schema(cont()), 1000)
173
+ wide_s = schema(*[cont(f"f{i}") for i in range(200)])
174
+ wide = compare_schemas(wide_s, wide_s, 1000)
175
+ assert narrow.noise_sigmas_used == 3.0
176
+ assert wide.noise_sigmas_used > narrow.noise_sigmas_used
177
+ fixed = compare_schemas(wide_s, wide_s, 1000, DriftThresholds(noise_sigmas=2.0))
178
+ assert fixed.noise_sigmas_used == 2.0
179
+
180
+
181
+ def test_baseline_n_samples_widens_floors():
182
+ base, cur = schema(cont()), schema(cont(mean=0.3))
183
+ assert not compare_schemas(base, cur, 1000).passed
184
+ assert compare_schemas(base, cur, 1000, baseline_n_samples=50).passed
185
+
186
+
187
+ def test_report_is_strict_json_serializable():
188
+ base = schema(ContinuousFeature(name="z", mean=1.0, std=0.0, min=1.0, max=1.0), cont(lo=-50, hi=50))
189
+ cur = schema(ContinuousFeature(name="z", mean=2.0, std=0.0, min=2.0, max=2.0), cont(lo=-50, hi=50))
190
+ text = json.dumps(compare_schemas(base, cur, 1000).to_dict(), allow_nan=False)
191
+ assert "Infinity" not in text and "NaN" not in text
File without changes
File without changes
File without changes