evalradar 0.2.1__py3-none-any.whl

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.
evalradar/compile.py ADDED
@@ -0,0 +1,139 @@
1
+ """Compiled monitors at run time: what to capture and how to turn it into features (the compiler that chooses sites
2
+ and fits directions is part of the EvalRadar server, `evalradar_server.compile`).
3
+
4
+ A compiled monitor is (1) a MonitorSpec that says exactly what to capture and how to turn it into
5
+ features, and (2) a calibrated `core.Artifact` that scores those features. Loading it needs neither
6
+ a coding agent nor the diagnosis package: only capture hooks and NumPy.
7
+
8
+ Strategies
9
+ single_site_probe one site, full vector
10
+ multi_site_probe k sites, concatenated vectors
11
+ direction_projection k sites, each projected on a direction fitted on train (one scalar per site)
12
+ Site selection (who chooses the sites)
13
+ label_screen sites ranked by a supervised screen on train/dev labels (ordinary probe baseline)
14
+ attribution writer nodes ranked by |attribution| on contrast pairs (no failure labels)
15
+ circuit writer nodes of a verified circuit, ranked by their total edge weight
16
+ random uniformly random sites (control)
17
+ explicit caller-supplied
18
+
19
+ The compiler never claims that a mechanism-informed monitor is better; that is measured
20
+ separately, under matched budgets.
21
+ """
22
+ from __future__ import annotations
23
+ from dataclasses import asdict, dataclass, field
24
+ from typing import Mapping, Sequence
25
+ import json
26
+ import time
27
+
28
+ import numpy as np
29
+
30
+ from .contracts import CaptureSpec, UnsupportedError, digest
31
+ from .core import Artifact, Fingerprint
32
+
33
+ STRATEGIES = ("single_site_probe", "multi_site_probe", "direction_projection")
34
+ SELECTIONS = ("label_screen", "attribution", "circuit", "random", "explicit")
35
+ NODE_TAP = {"mixer": "mixer_out", "mlp": "mlp_out"}
36
+
37
+
38
+ def node_to_site(node: str) -> tuple[int, str]:
39
+ """'L17.mlp' -> (17, 'mlp_out'); 'resid.L5' -> (5, 'resid_post')."""
40
+ if node.startswith("resid.L"):
41
+ return int(node.split("L", 1)[1]), "resid_post"
42
+ layer, kind = node.split(".")
43
+ if not layer.startswith("L") or kind not in NODE_TAP:
44
+ raise ValueError(f"not a site: {node!r}")
45
+ return int(layer[1:]), NODE_TAP[kind]
46
+
47
+
48
+ def site_feature_id(layer: int, tap: str) -> str:
49
+ return f"{tap}.L{layer}.last_prefill"
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class MonitorSpec:
54
+ monitor_id: str
55
+ version: str
56
+ strategy: str
57
+ selection: str
58
+ sites: tuple[str, ...]
59
+ capture_specs: tuple[Mapping, ...]
60
+ position_policy: str
61
+ preprocessing: Mapping # {"kind": "concat"} or {"kind": "projection", "directions": {...}}
62
+ artifact_id: str
63
+ model_fingerprint: Mapping
64
+ failure_categories: tuple[str, ...]
65
+ validated_conditions: Mapping # task, execution mode, dtype, split sizes, metrics
66
+ evidence_refs: tuple[str, ...] = ()
67
+ benchmarks: Mapping = field(default_factory=dict)
68
+ created_unix: float = field(default_factory=time.time)
69
+
70
+ def __post_init__(self):
71
+ if self.strategy not in STRATEGIES or self.selection not in SELECTIONS:
72
+ raise ValueError("invalid strategy or selection")
73
+ if self.strategy == "single_site_probe" and len(self.sites) != 1:
74
+ raise ValueError("single_site_probe needs exactly one site")
75
+
76
+ @property
77
+ def digest(self) -> str:
78
+ d = asdict(self)
79
+ d.pop("created_unix")
80
+ d.pop("benchmarks")
81
+ return digest(d)
82
+
83
+ def specs(self) -> list[CaptureSpec]:
84
+ return [CaptureSpec(**s) for s in self.capture_specs]
85
+
86
+ def to_json(self) -> dict:
87
+ return asdict(self) | {"digest": self.digest}
88
+
89
+
90
+ def capture_specs_for(sites: Sequence[str], dtype: str, position_policy: str = "last_prefill") -> list[CaptureSpec]:
91
+ out = []
92
+ for s in sites:
93
+ layer, tap = node_to_site(s)
94
+ out.append(CaptureSpec(layer=layer, module_path=None, tap=tap, position_policy=position_policy, dtype=dtype,
95
+ reduction="none", feature_id=site_feature_id(layer, tap)))
96
+ return out
97
+
98
+
99
+ def featurize(spec_or_strategy, site_vectors: Mapping[str, Sequence[float]], directions: Mapping | None = None) -> list[float]:
100
+ """The one feature function used both when fitting and at runtime."""
101
+ if isinstance(spec_or_strategy, MonitorSpec):
102
+ strategy, sites = spec_or_strategy.strategy, spec_or_strategy.sites
103
+ directions = spec_or_strategy.preprocessing.get("directions") if directions is None else directions
104
+ else:
105
+ strategy, sites = spec_or_strategy, tuple(site_vectors)
106
+ if strategy == "direction_projection":
107
+ vals = []
108
+ for s in sites:
109
+ p = directions[s]
110
+ z = (np.asarray(site_vectors[s], float) - np.asarray(p["mean"])) / np.asarray(p["scale"])
111
+ vals.append(float(z @ np.asarray(p["direction"])))
112
+ return vals
113
+ return [float(v) for s in sites for v in site_vectors[s]]
114
+
115
+
116
+ def compatibility(spec: MonitorSpec, fingerprint: Fingerprint) -> tuple[bool, list[str]]:
117
+ """Check a monitor against the deployment before attaching it. Any difference is a refusal."""
118
+ fp = asdict(fingerprint)
119
+ diffs = [k for k, v in spec.model_fingerprint.items() if fp.get(k) != v]
120
+ return (not diffs, diffs)
121
+
122
+
123
+ def load_monitor(spec_path, artifact_path, fingerprint: Fingerprint):
124
+ """Load a compiled monitor for a deployment, refusing it if the deployment differs from the
125
+ validated fingerprint or if the spec and the artifact do not belong together."""
126
+ from .core import load_artifact
127
+ d = json.loads(open(spec_path).read())
128
+ stored = d.pop("digest")
129
+ spec = MonitorSpec(**{**d, "sites": tuple(d["sites"]), "capture_specs": tuple(d["capture_specs"]),
130
+ "failure_categories": tuple(d["failure_categories"]), "evidence_refs": tuple(d["evidence_refs"])})
131
+ if spec.digest != stored:
132
+ raise ValueError("monitor spec digest mismatch")
133
+ art: Artifact = load_artifact(artifact_path)
134
+ if art.artifact_id != spec.artifact_id:
135
+ raise ValueError("artifact does not belong to this monitor spec")
136
+ ok, diffs = compatibility(spec, fingerprint)
137
+ if not ok:
138
+ raise UnsupportedError(f"monitor not validated for this deployment; fingerprint fields differ: {diffs}")
139
+ return spec, art
evalradar/contracts.py ADDED
@@ -0,0 +1,232 @@
1
+ """Versioned capture / readout / detector contracts (Phase 1).
2
+
3
+ CPU-only: this module must not import torch or transformers.
4
+
5
+ Separation enforced here:
6
+ capture -> what was observed, where, and when (CaptureSpec, Capture)
7
+ readout -> what a method surfaces from a capture (ReadoutResult); not a risk score
8
+ detector -> a task-defined score for a declared risk (SignalResult); not a causal claim
9
+ """
10
+ from __future__ import annotations
11
+ from dataclasses import dataclass, asdict, field
12
+ from typing import Mapping, Protocol, Sequence, runtime_checkable
13
+ import hashlib
14
+ import json
15
+ import math
16
+
17
+ CONTRACT_VERSION = 1
18
+
19
+ # resid_post: residual stream after a decoder block. mixer_out / mlp_out: the output a block's
20
+ # attention (or linear-attention) mixer / MLP writes into the residual stream, before the add.
21
+ # Taps are added only with a tested adapter layout.
22
+ TAPS = ("resid_post", "mixer_out", "mlp_out")
23
+ # last_prefill: the final prompt position, i.e. the last state available before any output token.
24
+ # decode: one state per generated-token forward pass (input = previously generated token).
25
+ POSITION_POLICIES = ("last_prefill", "decode", "prefill_last_and_decode")
26
+ REDUCTIONS = ("none",)
27
+ PHASES = ("prefill", "decode")
28
+
29
+ SIGNAL_STATES = ("ok", "unavailable", "unsupported", "stale", "error", "timeout", "not_sampled")
30
+ METHOD_STATUSES = ("planned", "blocked", "implemented", "validated_offline", "runtime_validated")
31
+ IMPLEMENTATION_TYPES = ("native_baseline", "upstream_adapter", "independent_reproduction", "none")
32
+
33
+
34
+ class EvalRadarError(Exception):
35
+ """Base class. `state` is the SignalResult/ReadoutResult state this error maps to."""
36
+ state = "error"
37
+
38
+
39
+ class UnsupportedError(EvalRadarError):
40
+ """The requested method, architecture or capture mode is not supported by this build."""
41
+ state = "unsupported"
42
+
43
+
44
+ class UnavailableError(EvalRadarError):
45
+ """A required input (capture, feature, artifact) is missing for this request."""
46
+ state = "unavailable"
47
+
48
+
49
+ class CaptureError(EvalRadarError):
50
+ """Capture semantics were violated (unexpected shape, batch, or call order)."""
51
+ state = "error"
52
+
53
+
54
+ def digest(value) -> str:
55
+ return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest()
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class CaptureSpec:
60
+ """Where and when an activation is captured. Data-only; safe to serialize."""
61
+ layer: int | None
62
+ module_path: str | None
63
+ tap: str
64
+ position_policy: str
65
+ dtype: str
66
+ reduction: str
67
+ feature_id: str
68
+
69
+ def __post_init__(self):
70
+ if self.tap not in TAPS:
71
+ raise UnsupportedError(f"unsupported tap: {self.tap}")
72
+ if self.position_policy not in POSITION_POLICIES:
73
+ raise UnsupportedError(f"unsupported position policy: {self.position_policy}")
74
+ if self.reduction not in REDUCTIONS:
75
+ raise UnsupportedError(f"unsupported reduction: {self.reduction}")
76
+ if self.layer is None and not self.module_path:
77
+ raise ValueError("layer or module_path required")
78
+ if self.layer is not None and (not isinstance(self.layer, int) or self.layer < 0):
79
+ raise ValueError("layer must be a non-negative integer")
80
+ if not self.feature_id.strip() or not self.dtype.strip():
81
+ raise ValueError("feature_id and dtype required")
82
+
83
+ @property
84
+ def digest(self) -> str:
85
+ return digest({"contract": CONTRACT_VERSION, **asdict(self)})
86
+
87
+
88
+ @dataclass(frozen=True)
89
+ class Capture:
90
+ """One request's captured states for one CaptureSpec.
91
+
92
+ `data` is backend-owned (e.g. a device tensor of shape [n_positions, d]) and is never
93
+ serialized by the SDK. `positions` are absolute token positions in the request's sequence;
94
+ position p holds the state computed while reading input token p.
95
+ """
96
+ request_id: str
97
+ spec: CaptureSpec
98
+ fingerprint_digest: str
99
+ prompt_len: int
100
+ positions: tuple[int, ...]
101
+ phases: tuple[str, ...]
102
+ data: object = field(repr=False, compare=False)
103
+
104
+ def __post_init__(self):
105
+ if len(self.positions) != len(self.phases) or any(p not in PHASES for p in self.phases):
106
+ raise CaptureError("positions and phases must align")
107
+ if any(b <= a for a, b in zip(self.positions, self.positions[1:])):
108
+ raise CaptureError("positions must be strictly increasing")
109
+ for pos, phase in zip(self.positions, self.phases):
110
+ if (pos < self.prompt_len) != (phase == "prefill"):
111
+ raise CaptureError("phase does not match position relative to prompt length")
112
+
113
+
114
+ @dataclass(frozen=True)
115
+ class MethodManifest:
116
+ method_id: str
117
+ version: str
118
+ implementation_type: str
119
+ status: str
120
+ output_semantics: str
121
+ runtime_tier: str = "offline"
122
+ upstream_url: str = ""
123
+ upstream_revision: str = ""
124
+ license: str = "unreviewed"
125
+ notes: str = ""
126
+
127
+ def __post_init__(self):
128
+ if self.status not in METHOD_STATUSES:
129
+ raise ValueError(f"invalid status: {self.status}")
130
+ if self.implementation_type not in IMPLEMENTATION_TYPES:
131
+ raise ValueError(f"invalid implementation type: {self.implementation_type}")
132
+
133
+ @property
134
+ def digest(self) -> str:
135
+ return digest({"contract": CONTRACT_VERSION, **asdict(self)})
136
+
137
+
138
+ @dataclass(frozen=True)
139
+ class Compatibility:
140
+ supported: bool
141
+ state: str = "ok"
142
+ reason: str | None = None
143
+
144
+ def __post_init__(self):
145
+ if self.state not in SIGNAL_STATES or self.supported != (self.state == "ok"):
146
+ raise ValueError("supported must be true exactly when state is ok")
147
+
148
+
149
+ @dataclass(frozen=True)
150
+ class ReadoutResult:
151
+ """What a readout surfaced. Values are method-specific and are NOT calibrated probabilities."""
152
+ request_id: str
153
+ method_id: str
154
+ method_digest: str
155
+ state: str
156
+ layer: int | None = None
157
+ positions: tuple[int, ...] = ()
158
+ phases: tuple[str, ...] = ()
159
+ token_ids: tuple[tuple[int, ...], ...] = ()
160
+ values: tuple[tuple[float, ...], ...] = ()
161
+ value_kind: str = ""
162
+ summary: Mapping[str, tuple[float, ...]] = field(default_factory=dict)
163
+ fitted_position_status: str = "not_applicable"
164
+ position_status: tuple[str, ...] = () # per position, for fitted lenses; empty when not applicable
165
+ duration_ms: float = 0.0
166
+ reason: str | None = None
167
+
168
+ def __post_init__(self):
169
+ if self.state not in SIGNAL_STATES:
170
+ raise ValueError(f"invalid state: {self.state}")
171
+ if self.state != "ok" and (self.token_ids or self.values or self.summary):
172
+ raise ValueError("a non-ok readout must not carry values")
173
+ n = len(self.positions)
174
+ if len(self.phases) != n or (self.token_ids and len(self.token_ids) != n) or (self.values and len(self.values) != n):
175
+ raise ValueError("readout rows must align with positions")
176
+ if any(len(v) != n for v in self.summary.values()):
177
+ raise ValueError("summary rows must align with positions")
178
+ if self.position_status and len(self.position_status) != n:
179
+ raise ValueError("position_status must align with positions")
180
+
181
+
182
+ @dataclass(frozen=True)
183
+ class SignalResult:
184
+ """One detector's result for one event. `not_sampled` (by policy) differs from `unavailable`."""
185
+ event_id_hash: str
186
+ risk_id: str
187
+ detector: str
188
+ artifact_digest: str
189
+ state: str
190
+ score: float | None = None
191
+ reason: str | None = None
192
+ source_readouts: tuple[str, ...] = ()
193
+ elapsed_ms: float = 0.0
194
+
195
+ def __post_init__(self):
196
+ if self.state not in SIGNAL_STATES:
197
+ raise ValueError(f"invalid state: {self.state}")
198
+ if (self.state == "ok") != (self.score is not None):
199
+ raise ValueError("score must be present exactly when state is ok")
200
+ if self.score is not None and not (math.isfinite(self.score) and 0.0 <= self.score <= 1.0):
201
+ raise ValueError("score must be a finite value in [0, 1]")
202
+ if self.state != "ok" and not self.reason:
203
+ raise ValueError("a non-ok signal requires a reason")
204
+
205
+ def to_json(self) -> dict:
206
+ d = asdict(self)
207
+ d["source_readouts"] = list(self.source_readouts)
208
+ d["contract_version"] = CONTRACT_VERSION
209
+ return d
210
+
211
+
212
+ @runtime_checkable
213
+ class ReadoutPlugin(Protocol):
214
+ def manifest(self) -> MethodManifest: ...
215
+ def supports(self, fingerprint, capture_spec: CaptureSpec) -> Compatibility: ...
216
+ def required_captures(self) -> tuple[CaptureSpec, ...]: ...
217
+ def read(self, capture: Capture, context: Mapping | None = None) -> ReadoutResult: ...
218
+
219
+
220
+ @runtime_checkable
221
+ class Detector(Protocol):
222
+ """Runtime side of a detector. Fitting is a classmethod on concrete detectors (`train`)."""
223
+ name: str
224
+ def raw(self, event) -> float | None: ...
225
+ def spec(self) -> dict: ...
226
+
227
+
228
+ def available_feature_ids(specs: Sequence[CaptureSpec]) -> tuple[str, ...]:
229
+ ids = tuple(s.feature_id for s in specs)
230
+ if len(set(ids)) != len(ids):
231
+ raise ValueError("duplicate feature_id in capture specs")
232
+ return ids
evalradar/core.py ADDED
@@ -0,0 +1,277 @@
1
+ """Small, fail-closed-for-assurance (not fail-closed-for-generation) monitoring core.
2
+
3
+ Scores are detector scores, not calibrated probabilities or causal evidence.
4
+ No raw text or activations are included in exported evidence.
5
+ """
6
+ from __future__ import annotations
7
+ from dataclasses import dataclass, asdict, field
8
+ from typing import Mapping, Protocol, Sequence
9
+ from types import MappingProxyType
10
+ from pathlib import Path
11
+ from functools import cached_property
12
+ import hashlib
13
+ import json
14
+ import math
15
+ import time
16
+ import numpy as np
17
+
18
+ SCHEMA_VERSION = 1
19
+
20
+
21
+ def _freeze(value):
22
+ if isinstance(value, Mapping):
23
+ return MappingProxyType({k: _freeze(v) for k, v in value.items()})
24
+ if isinstance(value, (list, tuple)):
25
+ return tuple(_freeze(v) for v in value)
26
+ return value
27
+
28
+
29
+ def _thaw(value):
30
+ if isinstance(value, Mapping):
31
+ return {k: _thaw(v) for k, v in value.items()}
32
+ if isinstance(value, (list, tuple)):
33
+ return [_thaw(v) for v in value]
34
+ return value
35
+
36
+
37
+ def _digest(value) -> str:
38
+ return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest()
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class Fingerprint:
43
+ model: str
44
+ checkpoint: str
45
+ tokenizer: str
46
+ backend: str
47
+ quantization: str = "none"
48
+ adapter: str = "none"
49
+ config: str = "unspecified"
50
+ feature_spec: str = "unspecified" # layer, pooling, tap point, preprocessing
51
+
52
+ def __post_init__(self):
53
+ if any(not isinstance(v, str) or not v.strip() for v in asdict(self).values()):
54
+ raise ValueError("fingerprint fields must be nonempty strings")
55
+
56
+ @cached_property
57
+ def digest(self) -> str:
58
+ return _digest(asdict(self))
59
+
60
+
61
+ @dataclass(frozen=True)
62
+ class Event:
63
+ event_id: str
64
+ fingerprint: Fingerprint
65
+ text: str | None = None
66
+ features: Mapping[str, Sequence[float]] = field(default_factory=dict)
67
+ step: int = 0
68
+
69
+
70
+ @dataclass(frozen=True)
71
+ class Example:
72
+ event: Event
73
+ label: int
74
+ group: str # e.g. source prompt, task family instance, or conversation ID
75
+
76
+ def __post_init__(self):
77
+ if self.label not in (0, 1) or not self.group or not self.event.event_id:
78
+ raise ValueError("binary label and nonempty group/event ID required")
79
+
80
+
81
+ class Monitor(Protocol):
82
+ name: str
83
+ def raw(self, event: Event) -> float | None: ...
84
+ def spec(self) -> dict: ...
85
+
86
+
87
+ @dataclass(frozen=True)
88
+ class PatternMonitor:
89
+ """Illustrative behavioral baseline, not a production safety classifier."""
90
+ patterns: tuple[str, ...]
91
+ name: str = "behavioral"
92
+
93
+ def __post_init__(self):
94
+ if not self.patterns or any(not p.strip() for p in self.patterns):
95
+ raise ValueError("nonempty patterns required")
96
+
97
+ def raw(self, event: Event) -> float | None:
98
+ if event.text is None:
99
+ return None
100
+ text = event.text.casefold()
101
+ return float(any(p.casefold() in text for p in self.patterns))
102
+
103
+ def spec(self) -> dict:
104
+ return {"kind": "pattern", "name": self.name, "patterns": list(self.patterns)}
105
+
106
+
107
+ @dataclass(frozen=True)
108
+ class LinearProbe:
109
+ """Ridge least-squares linear classifier + sigmoid; score is not a probability."""
110
+ feature: str
111
+ weight: tuple[float, ...]
112
+ bias: float
113
+ mean: tuple[float, ...]
114
+ scale: tuple[float, ...]
115
+ name: str = "mechanistic"
116
+
117
+ @classmethod
118
+ def train(cls, rows: Sequence[Example], feature: str, ridge: float = 1.0) -> LinearProbe:
119
+ if ridge <= 0 or not math.isfinite(ridge):
120
+ raise ValueError("ridge must be positive")
121
+ y = np.asarray([r.label for r in rows], dtype=float)
122
+ if len(set(y)) != 2:
123
+ raise ValueError("training requires both classes")
124
+ try:
125
+ x = np.asarray([r.event.features[feature] for r in rows], dtype=float)
126
+ except (KeyError, ValueError, TypeError) as exc:
127
+ raise ValueError("complete, rectangular training features required") from exc
128
+ if x.ndim != 2 or not x.shape[1] or not np.isfinite(x).all():
129
+ raise ValueError("finite nonempty 2D features required")
130
+ mean = x.mean(axis=0)
131
+ scale = x.std(axis=0)
132
+ scale[scale < 1e-8] = 1.0
133
+ z = (x - mean) / scale
134
+ target = 2*y - 1
135
+ # Centered design; solve primal or dual to avoid d*d for wide layers.
136
+ centered = target - target.mean()
137
+ n, d = z.shape
138
+ if d <= n:
139
+ w = np.linalg.solve(z.T @ z + ridge*np.eye(d), z.T @ centered)
140
+ else:
141
+ w = z.T @ np.linalg.solve(z @ z.T + ridge*np.eye(n), centered)
142
+ return cls(feature, tuple(w.tolist()), float(target.mean()), tuple(mean.tolist()), tuple(scale.tolist()))
143
+
144
+ def raw(self, event: Event) -> float | None:
145
+ try:
146
+ x = np.asarray(event.features[self.feature], dtype=float)
147
+ if x.shape != (len(self.weight),) or not np.isfinite(x).all():
148
+ return None
149
+ z = float(np.dot((x - self.mean) / self.scale, self.weight) + self.bias)
150
+ if not math.isfinite(z):
151
+ return None
152
+ return 1.0 / (1.0 + math.exp(-max(-60., min(60., z))))
153
+ except (KeyError, ValueError, TypeError, OverflowError):
154
+ return None
155
+
156
+ def spec(self) -> dict:
157
+ return {"kind": "linear_probe", **asdict(self)}
158
+
159
+
160
+ def _from_spec(spec: dict) -> Monitor:
161
+ d = dict(spec)
162
+ kind = d.pop("kind")
163
+ if kind == "pattern":
164
+ d["patterns"] = tuple(d["patterns"])
165
+ return PatternMonitor(**d)
166
+ if kind == "linear_probe":
167
+ for key in ("weight", "mean", "scale"):
168
+ d[key] = tuple(d[key])
169
+ p = LinearProbe(**d)
170
+ if not p.weight or not (len(p.weight) == len(p.mean) == len(p.scale)) or any(v <= 0 for v in p.scale):
171
+ raise ValueError("invalid probe parameters")
172
+ if not all(math.isfinite(v) for v in (*p.weight, *p.mean, *p.scale, p.bias)):
173
+ raise ValueError("nonfinite probe parameters")
174
+ return p
175
+ if kind == "logistic_probe": # allowlisted built-in; no dynamic import by name
176
+ from .detectors import logistic_from_spec
177
+ return logistic_from_spec(d)
178
+ raise ValueError(f"unsupported monitor kind: {kind}")
179
+
180
+
181
+ def _raw(monitors: Sequence[Monitor], event: Event) -> dict[str, float | None]:
182
+ out = {}
183
+ for m in monitors:
184
+ try:
185
+ s = m.raw(event)
186
+ out[m.name] = float(s) if s is not None and math.isfinite(s) and 0 <= s <= 1 else None
187
+ except Exception: # a plugin failure is unavailable, not a safe prediction
188
+ out[m.name] = None
189
+ return out
190
+
191
+
192
+ def _fuse(raw: Mapping[str, float | None]) -> float | None:
193
+ # Predeclared max rule; calibrated jointly, not OR of individually calibrated alerts.
194
+ if not raw or any(v is None for v in raw.values()):
195
+ return None
196
+ return max(raw.values())
197
+
198
+
199
+ @dataclass(frozen=True)
200
+ class Artifact:
201
+ fingerprint: Fingerprint
202
+ behavior: str
203
+ monitors: tuple[Monitor, ...]
204
+ thresholds: Mapping[str, float]
205
+ alpha: float
206
+ calibration_alpha: float
207
+ min_recall: float
208
+ min_coverage: float
209
+ split_keys: tuple[str, ...]
210
+ calibration_counts: Mapping[str, int]
211
+ validation: Mapping[str, object]
212
+ approved: bool
213
+ schema_version: int = SCHEMA_VERSION
214
+
215
+ def __post_init__(self):
216
+ for name in ("thresholds", "calibration_counts", "validation"):
217
+ object.__setattr__(self, name, _freeze(getattr(self, name)))
218
+
219
+ def body(self) -> dict:
220
+ return {"schema_version": self.schema_version, "fingerprint": asdict(self.fingerprint),
221
+ "behavior": self.behavior, "monitors": [m.spec() for m in self.monitors],
222
+ "thresholds": dict(self.thresholds), "alpha": self.alpha, "calibration_alpha": self.calibration_alpha, "min_recall": self.min_recall,
223
+ "min_coverage": self.min_coverage, "split_keys": list(self.split_keys),
224
+ "calibration_counts": dict(self.calibration_counts), "validation": _thaw(self.validation),
225
+ "approved": self.approved}
226
+
227
+ @cached_property
228
+ def artifact_id(self) -> str:
229
+ return _digest(self.body())
230
+
231
+
232
+ def score(artifact: Artifact, event: Event) -> dict:
233
+ """Score a single runtime event; return a privacy-minimized evidence record."""
234
+ start = time.perf_counter_ns()
235
+ evidence = {"schema_version": SCHEMA_VERSION, "artifact_id": artifact.artifact_id,
236
+ "model_fingerprint": event.fingerprint.digest, "event_id_hash": _digest(event.event_id),
237
+ "step": event.step, "behavior": artifact.behavior, "signals": {}, "fusion": None,
238
+ "status": "abstain", "reason": None, "causal_claim": False}
239
+ if event.fingerprint != artifact.fingerprint:
240
+ evidence["reason"] = "stale_monitor_fingerprint_mismatch"
241
+ elif not artifact.approved:
242
+ evidence["reason"] = "artifact_not_approved"
243
+ else:
244
+ raw = _raw(artifact.monitors, event)
245
+ evidence["signals"] = {k: {"score": v, "threshold": artifact.thresholds[k],
246
+ "state": "unavailable" if v is None else ("alert" if v > artifact.thresholds[k] else "no_alert")}
247
+ for k, v in raw.items()}
248
+ f = _fuse(raw)
249
+ if f is None:
250
+ evidence["reason"] = "required_signal_unavailable"
251
+ else:
252
+ evidence["fusion"] = {"score": f, "threshold": artifact.thresholds["fusion"]}
253
+ evidence["status"] = "alert" if f > artifact.thresholds["fusion"] else "no_alert"
254
+ evidence["scoring_ms"] = (time.perf_counter_ns() - start)/1e6
255
+ return evidence
256
+
257
+
258
+ def save_artifact(artifact: Artifact, path: str | Path):
259
+ Path(path).write_text(json.dumps({"artifact_id": artifact.artifact_id, **artifact.body()}, indent=2, allow_nan=False)+"\n")
260
+
261
+
262
+ def load_artifact(path: str | Path) -> Artifact:
263
+ d = json.loads(Path(path).read_text())
264
+ d.pop("signature", None) # checked by evalradar.signing; the digest covers the content only
265
+ expected = d.pop("artifact_id")
266
+ if d.get("schema_version") != SCHEMA_VERSION or _digest(d) != expected:
267
+ raise ValueError("artifact schema or content digest mismatch")
268
+ d["fingerprint"] = Fingerprint(**d["fingerprint"])
269
+ d["monitors"] = tuple(_from_spec(s) for s in d["monitors"])
270
+ d["split_keys"] = tuple(d["split_keys"])
271
+ a = Artifact(**d)
272
+ names = [m.name for m in a.monitors]
273
+ if len(set(names)) != len(names) or "fusion" in names or set(a.thresholds) != set(names) | {"fusion"}:
274
+ raise ValueError("invalid monitor names or thresholds")
275
+ if any(not 0 <= v <= 1 for v in a.thresholds.values()) or a.artifact_id != expected:
276
+ raise ValueError("invalid thresholds or artifact canonical form")
277
+ return a