Skip to content

recall_guard.harness.guarded_decision

recall_guard.harness.guarded_decision

Ensemble-first guarded decision: draw, estimate per draw, reduce, adjust.

An adopter asks a model for a decision (named numbers, see :class:~recall_guard.core.decision.DecisionDefinition) and wants it adjusted for memorization without wiring the guard by hand. :func:guarded_decide draws the same prompt :attr:GuardConfig.draws times on the same model and settings, records every draw as a :class:~recall_guard.core.distribution.RecordedDraw, computes a per-draw memorization estimate from the configured evidence source, and returns one :class:GuardedDecision: the consensus decision, the mean estimate, the distribution summary, the adjusted decision and a status.

This is the package's one ensemble-first surface. A single draw is returned only when the configuration asks for :attr:DrawMode.SINGLE; such a result is labelled, carries no distribution, and its estimate never withholds or zeroes the decision. :class:~recall_guard.harness.scorer.MemoryGuardedScorer keeps its single-draw score and score_many unchanged.

Estimates come from the response's own token evidence, top-k logprobs or full-distribution evidence (:mod:recall_guard.mia.estimate_source), never from the evaluator's direction parser. A calibrator is bound to the model, source and settings it was fitted on; that identity is checked before any request, with settings compared without seed keys, because a seed selects a sample and does not change the calibrated distribution.

Every result is a pure function of its recorded draws, the configuration and the identity, so :func:decide_from_draws recomputes it from stored draws without a request. :meth:GuardedRun.to_dict and :meth:GuardedRun.from_dict (with the same pair on :class:GuardedDecision and :class:GuardIdentity) are the supported serialisation of a result; dataclasses.asdict is not, because the decision vectors are read-only mappings. :func:guarded_run takes the draws an interrupted run already recorded (recorded) and issues only the others.

DrawMode

Bases: Enum

Ensemble by default; a single draw only on explicit request.

Source code in recall_guard/harness/guarded_decision.py
158
159
160
161
162
class DrawMode(Enum):
    """Ensemble by default; a single draw only on explicit request."""

    ENSEMBLE = "ensemble"
    SINGLE = "single"

GuardConfig dataclass

How one guarded decision is drawn and reduced; validated when built, before any request.

draws requests of the same prompt form the ensemble and at least min_parsed of them must parse. mode is :attr:DrawMode.ENSEMBLE unless a single draw is requested explicitly, which needs draws == 1 and therefore min_parsed == 1. temperature None keeps the client's configured setting. seed_base sets the seed of draw i to seed_base + i; None sends no seed override.

Source code in recall_guard/harness/guarded_decision.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
@dataclass(frozen=True)
class GuardConfig:
    """How one guarded decision is drawn and reduced; validated when built, before any request.

    ``draws`` requests of the same prompt form the ensemble and at least
    ``min_parsed`` of them must parse. ``mode`` is :attr:`DrawMode.ENSEMBLE`
    unless a single draw is requested explicitly, which needs ``draws == 1``
    and therefore ``min_parsed == 1``. ``temperature`` None keeps the client's
    configured setting. ``seed_base`` sets the seed of draw ``i`` to
    ``seed_base + i``; None sends no seed override.
    """

    definition: DecisionDefinition
    source: SourceLabel
    draws: int = 32
    min_parsed: int = 24
    mode: DrawMode = DrawMode.ENSEMBLE
    temperature: float | None = None
    seed_base: int | None = None

    def __post_init__(self) -> None:
        if not isinstance(self.definition, DecisionDefinition):
            raise TypeError("definition must be a DecisionDefinition")
        if not isinstance(self.source, SourceLabel):
            raise TypeError("source must be a SourceLabel")
        mode, temperature = _draw_settings(self.draws, self.min_parsed, self.mode, self.temperature, self.seed_base)
        object.__setattr__(self, "mode", mode)
        object.__setattr__(self, "temperature", temperature)

GuardIdentity dataclass

What one guarded decision was computed with (Requirement 1.7).

settings_json is the canonical JSON of the client's generation settings with the configured temperature applied and seed keys left out (:func:~recall_guard.harness.scorer_client.identity_settings). temperature is the temperature those settings give every draw, None when the client configures none. calibrator_fingerprint is the scorer's calibration_fingerprint; calibrator_is_weak is the calibrator's weak flag, which the fingerprint also covers, recorded so that :func:decide_from_draws reproduces the status without the calibrator. prompt_sha256 is the SHA-256 of the prompt text.

Source code in recall_guard/harness/guarded_decision.py
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
@dataclass(frozen=True)
class GuardIdentity:
    """What one guarded decision was computed with (Requirement 1.7).

    ``settings_json`` is the canonical JSON of the client's generation settings
    with the configured temperature applied and seed keys left out
    (:func:`~recall_guard.harness.scorer_client.identity_settings`).
    ``temperature`` is the temperature those settings give every draw, None when
    the client configures none. ``calibrator_fingerprint`` is the scorer's
    ``calibration_fingerprint``; ``calibrator_is_weak`` is the calibrator's weak
    flag, which the fingerprint also covers, recorded so that
    :func:`decide_from_draws` reproduces the status without the calibrator.
    ``prompt_sha256`` is the SHA-256 of the prompt text.
    """

    model: str
    protocol: str
    endpoint: str | None
    response_mapping: str
    source: SourceLabel
    settings_json: str
    temperature: float | None
    draws: int
    calibrator_fingerprint: str
    calibrator_is_weak: bool
    prompt_sha256: str

    def __post_init__(self) -> None:
        if not isinstance(self.source, SourceLabel):
            raise TypeError("source must be a SourceLabel")
        if not _is_int(self.draws) or self.draws < 1:
            raise ValueError(f"draws must be a positive integer; got {self.draws!r}")
        if not isinstance(self.calibrator_is_weak, bool):
            raise TypeError("calibrator_is_weak must be a boolean")

    def to_dict(self) -> dict[str, Any]:
        """JSON-compatible dict; the source is written as ``{"source": ..., "k": ...}``."""
        return {
            "model": self.model, "protocol": self.protocol, "endpoint": self.endpoint,
            "response_mapping": self.response_mapping,
            "source": {"source": self.source.source.value, "k": self.source.k},
            "settings_json": self.settings_json, "temperature": self.temperature, "draws": self.draws,
            "calibrator_fingerprint": self.calibrator_fingerprint, "calibrator_is_weak": self.calibrator_is_weak,
            "prompt_sha256": self.prompt_sha256,
        }

    @classmethod
    def from_dict(cls, data: Mapping[str, Any]) -> GuardIdentity:
        """Inverse of :meth:`to_dict`; unknown, missing or invalid fields are refused."""
        values = dict(_exact_fields(data, _IDENTITY_FIELDS, "guard identity"))
        source = _exact_fields(values["source"], ("source", "k"), "guard identity source")
        try:
            kind = EstimateSource(source["source"])
        except ValueError:
            raise ValueError(f"source must be one of {[item.value for item in EstimateSource]}; "
                             f"got {source['source']!r}") from None
        k = source["k"]
        if k is not None and (not _is_int(k) or k < 1):
            raise ValueError(f"source k must be a positive integer or None; got {k!r}")
        for name in ("model", "protocol", "response_mapping", "settings_json", "calibrator_fingerprint",
                     "prompt_sha256"):
            _text_field(values[name], name)
        _text_field(values["endpoint"], "endpoint", optional=True)
        values["source"] = SourceLabel(kind, k)
        values["temperature"] = _real_field(values["temperature"], "temperature")
        return cls(**values)

to_dict

to_dict()

JSON-compatible dict; the source is written as {"source": ..., "k": ...}.

Source code in recall_guard/harness/guarded_decision.py
258
259
260
261
262
263
264
265
266
267
def to_dict(self) -> dict[str, Any]:
    """JSON-compatible dict; the source is written as ``{"source": ..., "k": ...}``."""
    return {
        "model": self.model, "protocol": self.protocol, "endpoint": self.endpoint,
        "response_mapping": self.response_mapping,
        "source": {"source": self.source.source.value, "k": self.source.k},
        "settings_json": self.settings_json, "temperature": self.temperature, "draws": self.draws,
        "calibrator_fingerprint": self.calibrator_fingerprint, "calibrator_is_weak": self.calibrator_is_weak,
        "prompt_sha256": self.prompt_sha256,
    }

from_dict classmethod

from_dict(data)

Inverse of :meth:to_dict; unknown, missing or invalid fields are refused.

Source code in recall_guard/harness/guarded_decision.py
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> GuardIdentity:
    """Inverse of :meth:`to_dict`; unknown, missing or invalid fields are refused."""
    values = dict(_exact_fields(data, _IDENTITY_FIELDS, "guard identity"))
    source = _exact_fields(values["source"], ("source", "k"), "guard identity source")
    try:
        kind = EstimateSource(source["source"])
    except ValueError:
        raise ValueError(f"source must be one of {[item.value for item in EstimateSource]}; "
                         f"got {source['source']!r}") from None
    k = source["k"]
    if k is not None and (not _is_int(k) or k < 1):
        raise ValueError(f"source k must be a positive integer or None; got {k!r}")
    for name in ("model", "protocol", "response_mapping", "settings_json", "calibrator_fingerprint",
                 "prompt_sha256"):
        _text_field(values[name], name)
    _text_field(values["endpoint"], "endpoint", optional=True)
    values["source"] = SourceLabel(kind, k)
    values["temperature"] = _real_field(values["temperature"], "temperature")
    return cls(**values)

GuardedDecision dataclass

One guarded decision with the evidence behind it.

decision is the consensus of the parsed draws, or the one draw in :attr:DrawMode.SINGLE, as a read-only mapping in declared component order. A component split into separated clusters is None there and stays None in adjusted (Requirement 5.7). not_assessed names the components whose split check could not run (no grid, too few parsed draws, or a single draw): their values are kept but are never presented as resolved. category is the definition's decide applied to decision when every component is present, else None.

p_memorized is the mean of the per-draw estimates over the parsed draws that carry one, the set the distribution summary uses, or the single draw's estimate. distribution is None for a single draw and on failure.

Statuses:

  • ok: adjusted scales every present component by 1 - clip(p_memorized); reason states the counts when only some parsed draws carry an estimate.
  • estimate_unavailable: no parsed draw carries an estimate; the decision passes through unchanged (adjusted == decision) and p_memorized is None.
  • adjustment_skipped_weak_calibrator: the calibrator is weak; the decision and p_memorized are reported and adjusted == decision.
  • failed: fewer parsed draws than min_parsed; no decision, adjustment, estimate or distribution, and reason gives the counts.

draws are the recorded draws; :func:decide_from_draws recomputes this result from them. draws_sha256 is :func:~recall_guard.core.ensemble.canonical_draw_hash over the parsed draws' response hashes, None when no draw parsed.

Source code in recall_guard/harness/guarded_decision.py
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
@dataclass(frozen=True)
class GuardedDecision:
    """One guarded decision with the evidence behind it.

    ``decision`` is the consensus of the parsed draws, or the one draw in
    :attr:`DrawMode.SINGLE`, as a read-only mapping in declared component
    order. A component split into separated clusters is None there and stays
    None in ``adjusted`` (Requirement 5.7). ``not_assessed`` names the
    components whose split check could not run (no grid, too few parsed draws,
    or a single draw): their values are kept but are never presented as
    resolved. ``category`` is the definition's ``decide`` applied to
    ``decision`` when every component is present, else None.

    ``p_memorized`` is the mean of the per-draw estimates over the parsed draws
    that carry one, the set the distribution summary uses, or the single draw's
    estimate. ``distribution`` is None for a single draw and on failure.

    Statuses:

    - ``ok``: ``adjusted`` scales every present component by
      ``1 - clip(p_memorized)``; ``reason`` states the counts when only some
      parsed draws carry an estimate.
    - ``estimate_unavailable``: no parsed draw carries an estimate; the decision
      passes through unchanged (``adjusted == decision``) and ``p_memorized`` is None.
    - ``adjustment_skipped_weak_calibrator``: the calibrator is weak; the
      decision and ``p_memorized`` are reported and ``adjusted == decision``.
    - ``failed``: fewer parsed draws than ``min_parsed``; no decision,
      adjustment, estimate or distribution, and ``reason`` gives the counts.

    ``draws`` are the recorded draws; :func:`decide_from_draws` recomputes this
    result from them. ``draws_sha256`` is
    :func:`~recall_guard.core.ensemble.canonical_draw_hash` over the parsed
    draws' response hashes, None when no draw parsed.
    """

    status: GuardStatus
    mode: DrawMode
    decision: Mapping[str, float | None] | None
    adjusted: Mapping[str, float | None] | None
    p_memorized: float | None
    distribution: DistributionSummary | None
    reason: str | None
    identity: GuardIdentity
    draws_sha256: str | None
    category: Hashable | None
    not_assessed: tuple[str, ...]
    draws: tuple[RecordedDraw, ...]

    def to_dict(self) -> dict[str, Any]:
        """JSON-compatible dict, as the study recording stores it.

        The decision vectors become plain dicts in component order, the draws
        :meth:`RecordedDraw.to_dict` records. Raises ``ValueError`` for a
        ``category`` that would not read back from JSON unchanged (only None,
        bool, int, str or a finite float can be recorded).
        """
        return {
            "status": self.status, "mode": self.mode.value, "decision": _vector_to_dict(self.decision),
            "adjusted": _vector_to_dict(self.adjusted), "p_memorized": self.p_memorized,
            "distribution": None if self.distribution is None else self.distribution.to_dict(),
            "reason": self.reason, "identity": self.identity.to_dict(), "draws_sha256": self.draws_sha256,
            "category": _json_scalar(self.category, "category"), "not_assessed": list(self.not_assessed),
            "draws": [draw.to_dict() for draw in self.draws],
        }

    @classmethod
    def from_dict(cls, data: Mapping[str, Any]) -> GuardedDecision:
        """Inverse of :meth:`to_dict`; unknown, missing or invalid fields are refused.

        Loading does not recompute the decision; :func:`decide_from_draws` on the
        loaded draws and identity does, without a request.
        """
        values = _exact_fields(data, _DECISION_FIELDS, "guarded decision")
        if values["status"] not in _STATUSES:
            raise ValueError(f"status must be one of {list(_STATUSES)}; got {values['status']!r}")
        try:
            mode = DrawMode(values["mode"])
        except ValueError:
            raise ValueError(f"mode must be ensemble or single; got {values['mode']!r}") from None
        draws, not_assessed = values["draws"], values["not_assessed"]
        if not isinstance(draws, list | tuple):
            raise ValueError("draws must be a list of recorded draws")
        if not isinstance(not_assessed, list | tuple) or not all(isinstance(name, str) for name in not_assessed):
            raise ValueError(f"not_assessed must be a list of component names; got {not_assessed!r}")
        distribution = values["distribution"]
        return cls(
            status=values["status"], mode=mode,
            decision=_vector_from_dict(values["decision"], "decision"),
            adjusted=_vector_from_dict(values["adjusted"], "adjusted"),
            p_memorized=_real_field(values["p_memorized"], "p_memorized"),
            distribution=None if distribution is None else DistributionSummary.from_dict(distribution),
            reason=_text_field(values["reason"], "reason", optional=True),
            identity=GuardIdentity.from_dict(values["identity"]),
            draws_sha256=_text_field(values["draws_sha256"], "draws_sha256", optional=True),
            category=_json_scalar(values["category"], "category"),
            not_assessed=tuple(not_assessed),
            draws=tuple(RecordedDraw.from_dict(draw) for draw in draws),
        )

to_dict

to_dict()

JSON-compatible dict, as the study recording stores it.

The decision vectors become plain dicts in component order, the draws :meth:RecordedDraw.to_dict records. Raises ValueError for a category that would not read back from JSON unchanged (only None, bool, int, str or a finite float can be recorded).

Source code in recall_guard/harness/guarded_decision.py
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
def to_dict(self) -> dict[str, Any]:
    """JSON-compatible dict, as the study recording stores it.

    The decision vectors become plain dicts in component order, the draws
    :meth:`RecordedDraw.to_dict` records. Raises ``ValueError`` for a
    ``category`` that would not read back from JSON unchanged (only None,
    bool, int, str or a finite float can be recorded).
    """
    return {
        "status": self.status, "mode": self.mode.value, "decision": _vector_to_dict(self.decision),
        "adjusted": _vector_to_dict(self.adjusted), "p_memorized": self.p_memorized,
        "distribution": None if self.distribution is None else self.distribution.to_dict(),
        "reason": self.reason, "identity": self.identity.to_dict(), "draws_sha256": self.draws_sha256,
        "category": _json_scalar(self.category, "category"), "not_assessed": list(self.not_assessed),
        "draws": [draw.to_dict() for draw in self.draws],
    }

from_dict classmethod

from_dict(data)

Inverse of :meth:to_dict; unknown, missing or invalid fields are refused.

Loading does not recompute the decision; :func:decide_from_draws on the loaded draws and identity does, without a request.

Source code in recall_guard/harness/guarded_decision.py
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> GuardedDecision:
    """Inverse of :meth:`to_dict`; unknown, missing or invalid fields are refused.

    Loading does not recompute the decision; :func:`decide_from_draws` on the
    loaded draws and identity does, without a request.
    """
    values = _exact_fields(data, _DECISION_FIELDS, "guarded decision")
    if values["status"] not in _STATUSES:
        raise ValueError(f"status must be one of {list(_STATUSES)}; got {values['status']!r}")
    try:
        mode = DrawMode(values["mode"])
    except ValueError:
        raise ValueError(f"mode must be ensemble or single; got {values['mode']!r}") from None
    draws, not_assessed = values["draws"], values["not_assessed"]
    if not isinstance(draws, list | tuple):
        raise ValueError("draws must be a list of recorded draws")
    if not isinstance(not_assessed, list | tuple) or not all(isinstance(name, str) for name in not_assessed):
        raise ValueError(f"not_assessed must be a list of component names; got {not_assessed!r}")
    distribution = values["distribution"]
    return cls(
        status=values["status"], mode=mode,
        decision=_vector_from_dict(values["decision"], "decision"),
        adjusted=_vector_from_dict(values["adjusted"], "adjusted"),
        p_memorized=_real_field(values["p_memorized"], "p_memorized"),
        distribution=None if distribution is None else DistributionSummary.from_dict(distribution),
        reason=_text_field(values["reason"], "reason", optional=True),
        identity=GuardIdentity.from_dict(values["identity"]),
        draws_sha256=_text_field(values["draws_sha256"], "draws_sha256", optional=True),
        category=_json_scalar(values["category"], "category"),
        not_assessed=tuple(not_assessed),
        draws=tuple(RecordedDraw.from_dict(draw) for draw in draws),
    )

GuardedRun dataclass

A guarded decision with the replies and evidence it was computed from, by draw index.

responses holds None for a request that returned no reply, and for a draw that :func:guarded_run took from recorded (its reply is in the caller's recording). evidence holds full-distribution evidence for the FULL_DISTRIBUTION source and None elsewhere.

Source code in recall_guard/harness/guarded_decision.py
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
@dataclass(frozen=True)
class GuardedRun:
    """A guarded decision with the replies and evidence it was computed from, by draw index.

    ``responses`` holds None for a request that returned no reply, and for a
    draw that :func:`guarded_run` took from ``recorded`` (its reply is in the
    caller's recording). ``evidence`` holds full-distribution evidence for the
    ``FULL_DISTRIBUTION`` source and None elsewhere.
    """

    decision: GuardedDecision
    responses: tuple[ModelResponse | None, ...]
    evidence: tuple[FullDistributionEvidence | None, ...]

    def to_dict(self) -> dict[str, Any]:
        """JSON-compatible dict: the decision, and per draw index the reply and the full evidence or None."""
        return {
            "decision": self.decision.to_dict(),
            "responses": [None if response is None else response.to_dict() for response in self.responses],
            "evidence": [None if item is None else item.to_dict() for item in self.evidence],
        }

    @classmethod
    def from_dict(cls, data: Mapping[str, Any]) -> GuardedRun:
        """Inverse of :meth:`to_dict`; ``responses`` and ``evidence`` must hold one entry per draw."""
        values = _exact_fields(data, _RUN_FIELDS, "guarded run")
        decision = GuardedDecision.from_dict(values["decision"])
        for name in ("responses", "evidence"):
            entries = values[name]
            if not isinstance(entries, list | tuple) or len(entries) != len(decision.draws):
                raise ValueError(f"{name} must hold one entry per draw ({len(decision.draws)}); got "
                                 f"{len(entries) if isinstance(entries, list | tuple) else entries!r}")
        return cls(
            decision,
            tuple(None if item is None else ModelResponse.from_dict(item) for item in values["responses"]),
            tuple(None if item is None else FullDistributionEvidence.from_dict(item) for item in values["evidence"]),
        )

to_dict

to_dict()

JSON-compatible dict: the decision, and per draw index the reply and the full evidence or None.

Source code in recall_guard/harness/guarded_decision.py
405
406
407
408
409
410
411
def to_dict(self) -> dict[str, Any]:
    """JSON-compatible dict: the decision, and per draw index the reply and the full evidence or None."""
    return {
        "decision": self.decision.to_dict(),
        "responses": [None if response is None else response.to_dict() for response in self.responses],
        "evidence": [None if item is None else item.to_dict() for item in self.evidence],
    }

from_dict classmethod

from_dict(data)

Inverse of :meth:to_dict; responses and evidence must hold one entry per draw.

Source code in recall_guard/harness/guarded_decision.py
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> GuardedRun:
    """Inverse of :meth:`to_dict`; ``responses`` and ``evidence`` must hold one entry per draw."""
    values = _exact_fields(data, _RUN_FIELDS, "guarded run")
    decision = GuardedDecision.from_dict(values["decision"])
    for name in ("responses", "evidence"):
        entries = values[name]
        if not isinstance(entries, list | tuple) or len(entries) != len(decision.draws):
            raise ValueError(f"{name} must hold one entry per draw ({len(decision.draws)}); got "
                             f"{len(entries) if isinstance(entries, list | tuple) else entries!r}")
    return cls(
        decision,
        tuple(None if item is None else ModelResponse.from_dict(item) for item in values["responses"]),
        tuple(None if item is None else FullDistributionEvidence.from_dict(item) for item in values["evidence"]),
    )

SourceCalibrator dataclass

The existing MCS calibrator bound to its evidence source and calibration identity.

identity is the extended calibration identity (model, settings, estimate source, corpus hash) and fingerprint the scorer's calibration_fingerprint.

Source code in recall_guard/harness/guarded_decision.py
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
@dataclass(frozen=True)
class SourceCalibrator:
    """The existing MCS calibrator bound to its evidence source and calibration identity.

    ``identity`` is the extended calibration identity (model, settings,
    estimate source, corpus hash) and ``fingerprint`` the scorer's
    ``calibration_fingerprint``.
    """

    mcs: MCSCalibrator
    baseline: ControlBaseline
    identity: CalibrationIdentity
    fingerprint: str

    def __post_init__(self) -> None:
        if not isinstance(self.mcs, MCSCalibrator):
            raise TypeError("mcs must be an MCSCalibrator")
        if not isinstance(self.baseline, ControlBaseline):
            raise TypeError("baseline must be a ControlBaseline")
        if not isinstance(self.identity, CalibrationIdentity):
            raise TypeError("identity must be a CalibrationIdentity")
        if not isinstance(self.fingerprint, str) or not self.fingerprint:
            raise ValueError("fingerprint must be a nonempty string")

    def estimate(self, features: MiaFeatures) -> float:
        """Calibrated ``p(memorized | features)``: the fitted classifier on the standardised features.

        Raises ``ValueError`` when a core feature cannot be standardised.
        """
        return float(self.mcs.predict_proba(features, self.baseline))

    @property
    def is_weak(self) -> bool:
        """True when the held-out AUC is below the calibration threshold."""
        return bool(self.mcs.is_weak)

    def holdout_auc_interval(self) -> dict | None:
        """Held-out AUC with its seeded stratified bootstrap interval; None without a retained holdout."""
        labels, probabilities = self.mcs.holdout_labels, self.mcs.holdout_probabilities
        if labels is None or probabilities is None:
            return None
        # Import at use: local_reporting imports local_execution, which imports the scorer.
        from recall_guard.harness.local_reporting import held_out_discrimination

        return held_out_discrimination(probabilities, labels)

    @classmethod
    def from_scorer(
        cls, scorer: MemoryGuardedScorer, *, source: EstimateSource, corpus_sha256: str | None
    ) -> SourceCalibrator:
        """Bind a configured-client calibration to ``source`` and the calibration corpus hash.

        Raises ``ValueError`` for a legacy calibration, which has no calibration identity.
        """
        identity = scorer.calibration_identity
        if identity is None:
            raise ValueError(
                "SourceCalibrator.from_scorer needs a configured-client calibration (calibrate_client or "
                "from_profile); a legacy calibration has no calibration identity"
            )
        bound = replace(identity, estimate_source=EstimateSource(source).value, corpus_sha256=corpus_sha256)
        return cls(scorer.mcs, scorer.control_baseline, bound, scorer.calibration_fingerprint)

is_weak property

is_weak

True when the held-out AUC is below the calibration threshold.

estimate

estimate(features)

Calibrated p(memorized | features): the fitted classifier on the standardised features.

Raises ValueError when a core feature cannot be standardised.

Source code in recall_guard/harness/guarded_decision.py
454
455
456
457
458
459
def estimate(self, features: MiaFeatures) -> float:
    """Calibrated ``p(memorized | features)``: the fitted classifier on the standardised features.

    Raises ``ValueError`` when a core feature cannot be standardised.
    """
    return float(self.mcs.predict_proba(features, self.baseline))

holdout_auc_interval

holdout_auc_interval()

Held-out AUC with its seeded stratified bootstrap interval; None without a retained holdout.

Source code in recall_guard/harness/guarded_decision.py
466
467
468
469
470
471
472
473
474
def holdout_auc_interval(self) -> dict | None:
    """Held-out AUC with its seeded stratified bootstrap interval; None without a retained holdout."""
    labels, probabilities = self.mcs.holdout_labels, self.mcs.holdout_probabilities
    if labels is None or probabilities is None:
        return None
    # Import at use: local_reporting imports local_execution, which imports the scorer.
    from recall_guard.harness.local_reporting import held_out_discrimination

    return held_out_discrimination(probabilities, labels)

from_scorer classmethod

from_scorer(scorer, *, source, corpus_sha256)

Bind a configured-client calibration to source and the calibration corpus hash.

Raises ValueError for a legacy calibration, which has no calibration identity.

Source code in recall_guard/harness/guarded_decision.py
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
@classmethod
def from_scorer(
    cls, scorer: MemoryGuardedScorer, *, source: EstimateSource, corpus_sha256: str | None
) -> SourceCalibrator:
    """Bind a configured-client calibration to ``source`` and the calibration corpus hash.

    Raises ``ValueError`` for a legacy calibration, which has no calibration identity.
    """
    identity = scorer.calibration_identity
    if identity is None:
        raise ValueError(
            "SourceCalibrator.from_scorer needs a configured-client calibration (calibrate_client or "
            "from_profile); a legacy calibration has no calibration identity"
        )
    bound = replace(identity, estimate_source=EstimateSource(source).value, corpus_sha256=corpus_sha256)
    return cls(scorer.mcs, scorer.control_baseline, bound, scorer.calibration_fingerprint)

UnestimatedDecision dataclass

The decision of an ensemble drawn and reduced without a calibrator and without a recall estimate.

decision is the consensus of the parsed draws as :class:GuardedDecision defines it (a component split into separated clusters is None), or None when fewer draws parsed than min_parsed; reason then gives the counts and is None otherwise. n_replies is the number of requests that returned a reply and n_parsed the number of replies that parsed into the definition. distribution is None for a single draw and without a decision. draws_sha256 is :func:~recall_guard.core.ensemble.canonical_draw_hash over the parsed draws' response hashes, None when no draw parsed.

Source code in recall_guard/harness/guarded_decision.py
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
@dataclass(frozen=True)
class UnestimatedDecision:
    """The decision of an ensemble drawn and reduced without a calibrator and without a recall estimate.

    ``decision`` is the consensus of the parsed draws as
    :class:`GuardedDecision` defines it (a component split into separated
    clusters is None), or None when fewer draws parsed than ``min_parsed``;
    ``reason`` then gives the counts and is None otherwise. ``n_replies`` is
    the number of requests that returned a reply and ``n_parsed`` the number
    of replies that parsed into the definition. ``distribution`` is None for a
    single draw and without a decision. ``draws_sha256`` is
    :func:`~recall_guard.core.ensemble.canonical_draw_hash` over the parsed
    draws' response hashes, None when no draw parsed.
    """

    decision: Mapping[str, float | None] | None
    reason: str | None
    n_replies: int
    n_parsed: int
    distribution: DistributionSummary | None
    draws_sha256: str | None

guarded_run

guarded_run(
    prompt,
    config,
    *,
    client,
    calibrator,
    full_distribution=None,
    recorded=(),
    on_request=None,
    on_draw=None,
)

Draw prompt config.draws times, estimate per draw and return the guarded decision.

Before any request: a FULL_DISTRIBUTION source without a full-distribution client is refused (ValueError) and the client's identity is checked against the calibrator's (:class:~recall_guard.harness.scorer_client.CalibrationMismatchError). The loop then issues at most config.draws requests, each with the configured temperature and per-draw seed as overrides, never a retry. A rejected credential or an exhausted budget stops the loop and is raised; any other failure is recorded on its draw. Estimates are computed for parsed draws only, so a FULL_DISTRIBUTION source requests evidence once per parsed draw and never for a reply that did not parse.

recorded holds draws an earlier, interrupted run of the same prompt and configuration already recorded (the study recording, task 7.4). Those draw indices are filled from it and never requested; only the missing indices are issued, each with its deterministic seed, and the result reduces the union exactly as a run without interruption would. A recorded draw outside 0..draws-1, a repeated index, or a seed or temperature other than the run's is refused (ValueError) before any request. The recorded estimates must come from this calibrator; the caller's recording checks that. Their replies and evidence stay in that recording, so responses and evidence hold None at those indices.

on_request(index, seed) is called before each issued request and on_draw(draw, response, evidence) after it is recorded, so a caller can persist each attempt as it happens. An exception from either stops the loop; one from on_request stops it before that request is sent.

Source code in recall_guard/harness/guarded_decision.py
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
def guarded_run(
    prompt: str, config: GuardConfig, *, client: CompletionClient, calibrator: SourceCalibrator,
    full_distribution: FullDistributionClient | None = None, recorded: Sequence[RecordedDraw] = (),
    on_request: RequestHook | None = None, on_draw: DrawHook | None = None,
) -> GuardedRun:
    """Draw ``prompt`` ``config.draws`` times, estimate per draw and return the guarded decision.

    Before any request: a ``FULL_DISTRIBUTION`` source without a
    full-distribution client is refused (``ValueError``) and the client's
    identity is checked against the calibrator's
    (:class:`~recall_guard.harness.scorer_client.CalibrationMismatchError`).
    The loop then issues at most ``config.draws`` requests, each with the
    configured temperature and per-draw seed as overrides, never a retry. A
    rejected credential or an exhausted budget stops the loop and is raised;
    any other failure is recorded on its draw. Estimates are computed for
    parsed draws only, so a ``FULL_DISTRIBUTION`` source requests evidence
    once per parsed draw and never for a reply that did not parse.

    ``recorded`` holds draws an earlier, interrupted run of the same prompt
    and configuration already recorded (the study recording, task 7.4). Those
    draw indices are filled from it and never requested; only the missing
    indices are issued, each with its deterministic seed, and the result
    reduces the union exactly as a run without interruption would. A recorded
    draw outside ``0..draws-1``, a repeated index, or a seed or temperature
    other than the run's is refused (``ValueError``) before any request. The
    recorded estimates must come from this calibrator; the caller's recording
    checks that. Their replies and evidence stay in that recording, so
    ``responses`` and ``evidence`` hold None at those indices.

    ``on_request(index, seed)`` is called before each issued request and
    ``on_draw(draw, response, evidence)`` after it is recorded, so a caller can
    persist each attempt as it happens. An exception from either stops the
    loop; one from ``on_request`` stops it before that request is sent.
    """
    if not isinstance(prompt, str):
        raise TypeError("prompt must be a string")
    if not isinstance(config, GuardConfig):
        raise TypeError("config must be a GuardConfig")
    if config.source.source is EstimateSource.FULL_DISTRIBUTION and full_distribution is None:
        raise ValueError("A full_distribution estimate source needs a full-distribution client "
                         "(full_distribution=...); nothing was sent")
    identity = _guard_identity(prompt, config, client, calibrator)
    seed_of = _seeds(client, config.seed_base)

    def estimate_of(response: ModelResponse) -> tuple[float | None, str | None, FullDistributionEvidence | None]:
        return _estimate(prompt, response, config, calibrator, full_distribution)

    prefilled = _prefilled(recorded, config, identity, seed_of)
    draws: list[RecordedDraw] = []
    responses: list[ModelResponse | None] = []
    evidence: list[FullDistributionEvidence | None] = []
    for index in range(config.draws):
        if index in prefilled:
            draws.append(prefilled[index])
            responses.append(None)
            evidence.append(None)
            continue
        seed = seed_of(index)
        if on_request is not None:
            on_request(index, seed)
        response, failure = _request(client, prompt, _overrides(config.temperature, config.seed_base, seed))
        draw, full = _record(index, config.definition, identity.temperature, seed, response, failure, estimate_of)
        if on_draw is not None:
            on_draw(draw, response, full)
        draws.append(draw)
        responses.append(response)
        evidence.append(full)
    return GuardedRun(decide_from_draws(draws, config, identity), tuple(responses), tuple(evidence))

guarded_decide

guarded_decide(
    prompt,
    config,
    *,
    client,
    calibrator,
    full_distribution=None,
)

The guarded decision of :func:guarded_run, without the replies and evidence.

Source code in recall_guard/harness/guarded_decision.py
755
756
757
758
759
760
761
def guarded_decide(
    prompt: str, config: GuardConfig, *, client: CompletionClient, calibrator: SourceCalibrator,
    full_distribution: FullDistributionClient | None = None,
) -> GuardedDecision:
    """The guarded decision of :func:`guarded_run`, without the replies and evidence."""
    return guarded_run(prompt, config, client=client, calibrator=calibrator,
                       full_distribution=full_distribution).decision

decide_without_estimate

decide_without_estimate(
    prompt,
    definition,
    *,
    client,
    draws=32,
    min_parsed=24,
    mode=DrawMode.ENSEMBLE,
    temperature=None,
    seed_base=None,
)

Draw prompt draws times and reduce the replies; no calibrator, no recall estimate.

The requests and the reduction are those of :func:guarded_run: each draw is one request with the same overrides (temperature, and seed_base + index as its seed), never retried; a rejected credential or an exhausted budget stops the loop and is raised, any other failure counts as a missing reply. The decision is the one :func:guarded_run reports as decision for the same replies. Nothing is estimated: no token evidence is read, no full-distribution host is asked, and no client identity is checked. draws, min_parsed, mode, temperature and seed_base mean what they mean on :class:GuardConfig and are validated the same way, before any request.

Source code in recall_guard/harness/guarded_decision.py
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
def decide_without_estimate(
    prompt: str, definition: DecisionDefinition, *, client: CompletionClient, draws: int = 32, min_parsed: int = 24,
    mode: DrawMode = DrawMode.ENSEMBLE, temperature: float | None = None, seed_base: int | None = None,
) -> UnestimatedDecision:
    """Draw ``prompt`` ``draws`` times and reduce the replies; no calibrator, no recall estimate.

    The requests and the reduction are those of :func:`guarded_run`: each draw
    is one request with the same overrides (``temperature``, and
    ``seed_base + index`` as its seed), never retried; a rejected credential
    or an exhausted budget stops the loop and is raised, any other failure
    counts as a missing reply. The decision is the one :func:`guarded_run`
    reports as ``decision`` for the same replies. Nothing is estimated: no
    token evidence is read, no full-distribution host is asked, and no client
    identity is checked. ``draws``, ``min_parsed``, ``mode``, ``temperature``
    and ``seed_base`` mean what they mean on :class:`GuardConfig` and are
    validated the same way, before any request.
    """
    if not isinstance(prompt, str):
        raise TypeError("prompt must be a string")
    if not isinstance(definition, DecisionDefinition):
        raise TypeError("definition must be a DecisionDefinition")
    mode, temperature = _draw_settings(draws, min_parsed, mode, temperature, seed_base)
    drawn_at = client.config.parameters.get("temperature") if temperature is None else temperature
    drawn_at = float(drawn_at) if _is_real(drawn_at) else None
    seed_of = _seeds(client, seed_base)
    recorded: list[RecordedDraw] = []
    for index in range(draws):
        seed = seed_of(index)
        response, failure = _request(client, prompt, _overrides(temperature, seed_base, seed))
        recorded.append(_record(index, definition, drawn_at, seed, response, failure, None)[0])
    reduced = _reduce(recorded, definition, draws, min_parsed, mode)
    return UnestimatedDecision(
        decision=None if reduced.decision is None else MappingProxyType(reduced.decision),
        reason=reduced.failed_reason,
        n_replies=sum(1 for draw in recorded if not (draw.failure_code or "").startswith(REQUEST_ERROR_PREFIX)),
        n_parsed=len(reduced.parsed),
        distribution=reduced.distribution,
        draws_sha256=reduced.draws_sha256,
    )

decide_from_draws

decide_from_draws(draws, config, identity)

Recompute a guarded decision from recorded draws; no request is issued (Requirement 5.8).

Works for either source and draw mode: the per-draw estimates are on the records and the calibrator's weak flag is on the identity. Raises ValueError when the identity's source or draw count differs from the configuration, when the number of draws differs from config.draws, for a repeated draw_index, or for a parsed vector whose names differ from the definition's components.

Source code in recall_guard/harness/guarded_decision.py
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
def decide_from_draws(draws: Sequence[RecordedDraw], config: GuardConfig, identity: GuardIdentity) -> GuardedDecision:
    """Recompute a guarded decision from recorded draws; no request is issued (Requirement 5.8).

    Works for either source and draw mode: the per-draw estimates are on the
    records and the calibrator's weak flag is on the identity. Raises
    ``ValueError`` when the identity's source or draw count differs from the
    configuration, when the number of draws differs from ``config.draws``, for
    a repeated ``draw_index``, or for a parsed vector whose names differ from
    the definition's components.
    """
    if not isinstance(config, GuardConfig):
        raise TypeError("config must be a GuardConfig")
    if not isinstance(identity, GuardIdentity):
        raise TypeError("identity must be a GuardIdentity")
    if identity.source != config.source:
        raise ValueError(f"identity source {identity.source} differs from the configured source {config.source}")
    if identity.draws != config.draws:
        raise ValueError(f"identity records {identity.draws} draws, the configuration draws={config.draws}")
    reduced = _reduce(draws, config.definition, config.draws, config.min_parsed, config.mode)
    ordered, parsed, names = reduced.ordered, reduced.parsed, reduced.names
    common = {"mode": config.mode, "identity": identity, "draws": ordered, "draws_sha256": reduced.draws_sha256}
    if reduced.decision is None:
        return GuardedDecision(status="failed", decision=None, adjusted=None, p_memorized=None, distribution=None,
                               reason=reduced.failed_reason, category=None, not_assessed=(), **common)
    decision, distribution = reduced.decision, reduced.distribution
    category, not_assessed = reduced.category, reduced.not_assessed
    present = {name: value for name, value in decision.items() if value is not None}

    carried = [draw.estimate for draw in parsed if draw.estimate is not None]
    p_memorized = statistics.fmean(carried) if carried else None
    counts = None
    if carried and len(carried) < len(parsed):
        counts = (f"The estimate uses {len(carried)} of {len(parsed)} parsed draws; "
                  f"the other {len(parsed) - len(carried)} carry no estimate.")
    if p_memorized is None:
        status: GuardStatus = "estimate_unavailable"
        adjusted = dict(decision)
        reason = (f"No parsed draw carries a memorization estimate (estimates on 0 of {len(parsed)} parsed draws), "
                  "so the decision is passed through unadjusted.")
    elif identity.calibrator_is_weak:
        status = "adjustment_skipped_weak_calibrator"
        adjusted = dict(decision)
        reason = ("The calibrator is weak (held-out discrimination below its threshold), so the adjustment was "
                  "skipped and the decision is passed through unadjusted.") + (f" {counts}" if counts else "")
    else:
        status = "ok"
        scaled = adjust(present, p_memorized)
        adjusted = {name: None if decision[name] is None else scaled[name] for name in names}
        reason = counts
    return GuardedDecision(
        status=status, decision=MappingProxyType(decision), adjusted=MappingProxyType(adjusted),
        p_memorized=p_memorized, distribution=distribution, reason=reason, category=category,
        not_assessed=not_assessed, **common,
    )

full_distribution_client

full_distribution_client(profile, *, environment=None)

Build a profile's full-distribution client, resolving full_distribution.endpoint_ref.

The gateway base URL comes from the environment variable that endpoint_ref names when it is set and nonempty, else from the declared loopback endpoint, as :func:~recall_guard.core.profiles.connect resolves a generation endpoint. The bearer stays a reference (credential_ref) that the client reads at request time. No request is sent. A profile without the full-distribution source is refused, naming the sources it offers.

Source code in recall_guard/harness/guarded_decision.py
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def full_distribution_client(
    profile: ProviderProfile | str | Path, *, environment: Mapping[str, str] | None = None
) -> FullDistributionClient:
    """Build a profile's full-distribution client, resolving ``full_distribution.endpoint_ref``.

    The gateway base URL comes from the environment variable that
    ``endpoint_ref`` names when it is set and nonempty, else from the declared
    loopback ``endpoint``, as :func:`~recall_guard.core.profiles.connect`
    resolves a generation endpoint. The bearer stays a reference
    (``credential_ref``) that the client reads at request time. No request is
    sent. A profile without the full-distribution source is refused, naming the
    sources it offers.
    """
    profile = load_profile(profile)
    profile.require_source(FULL_DISTRIBUTION_SOURCE)
    environment = os.environ if environment is None else environment
    if not isinstance(environment, Mapping):
        raise TypeError("environment must be a mapping")
    host = profile.full_distribution
    base_url, name = host.endpoint, None
    if host.endpoint_ref is not None:
        value = environment.get(host.endpoint_ref.removeprefix("env:"))
        if isinstance(value, str) and value.strip():
            base_url, name = value.strip(), host.endpoint_ref.removeprefix("env:")
    try:
        return FullDistributionClient(base_url, model_digest=host.model_digest, credential_ref=host.credential_ref,
                                      environment=environment)
    except ValueError:
        if name is None:
            raise
        # The value is not echoed: an endpoint variable may hold a credential by mistake.
        raise ProfileError(f"{name} must be a credential-free HTTP(S) base URL") from None