Skip to content

recall_guard.harness.intervention_config

recall_guard.harness.intervention_config

Offline validation and call planning for the versioned experiment command.

Items files are objects {schema_version: 1, items: [...]}. The protocol's data_hashes.evaluation hashes their exact UTF-8 file bytes. Other dataset keys need explicit file bindings; original/rewritten_calibration instead bind semantic fitted-scorer fingerprints and are never interpreted as file hashes.

Optional per-cohort historical metadata has period (pre/post), matching_group, matching (source/task/format/selection strings), cutoff (model/date/source_url/ retrieved_at/alias_uncertainty), and outcome_dates keyed by that cohort's item IDs. Outcome dates are never inferred from as_of. A separate source-bearing registry {schema_version: 1, models: {exact_model: {date, source_url, retrieved_at, alias_uncertainty}}} must agree before historical availability is reported. Unknown/ambiguous or absent bases permit general comparisons. These declarations are provenance, not independent evidence of good matching.

InterventionConfig dataclass

Validated offline inputs; no client or resolved credential is retained.

Source code in recall_guard/harness/intervention_config.py
173
174
175
176
177
178
179
@dataclass(frozen=True)
class InterventionConfig:
    """Validated offline inputs; no client or resolved credential is retained."""

    protocol: ExperimentProtocol
    items: tuple[ExperimentItem, ...]
    historical: dict

read_experiment_json

read_experiment_json(path)

Read strict UTF-8 JSON once, retaining the exact bytes for hash checks.

Source code in recall_guard/harness/intervention_config.py
51
52
53
54
def read_experiment_json(path):
    """Read strict UTF-8 JSON once, retaining the exact bytes for hash checks."""
    content = Path(path).read_bytes()
    return json.loads(content.decode("utf-8"), object_pairs_hook=_unique_fields, parse_constant=_invalid_number), content

load_experiment_config

load_experiment_config(
    protocol_path,
    items_path,
    *,
    data_files=None,
    cutoff_registry=None,
)

Validate bytes, schemas, local provider policies and declared comparisons.

Source code in recall_guard/harness/intervention_config.py
182
183
184
185
186
187
188
189
190
191
192
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
221
222
223
224
def load_experiment_config(protocol_path, items_path, *, data_files=None, cutoff_registry=None):
    """Validate bytes, schemas, local provider policies and declared comparisons."""
    raw_protocol, _ = read_experiment_json(protocol_path)
    protocol = ExperimentProtocol.from_dict(raw_protocol)
    raw_items, item_bytes = read_experiment_json(items_path)
    _object(raw_items, {"schema_version", "items"}, "items file")
    if type(raw_items["schema_version"]) is not int or raw_items["schema_version"] != 1:
        raise ValueError("Unsupported items schema_version")
    if not isinstance(raw_items["items"], list) or not raw_items["items"]:
        raise ValueError("items must be a nonempty array")
    items = tuple(ExperimentItem.from_dict(value) for value in raw_items["items"])
    ExperimentCheckpoint(protocol, items)
    if protocol.task_metric != "accuracy":
        raise ValueError("The experiment analyzer currently supports task_metric=accuracy only")
    if protocol.rewrite_method_version != REWRITE_METHOD_VERSION:
        raise ValueError("Unsupported rewrite_method_version")
    protocol.build_ensemble_spec()
    fits = _FIT_KEYS & protocol.data_hashes.keys()
    if fits and fits != _FIT_KEYS:
        raise ValueError("Scored protocol requires both original_calibration and rewritten_calibration fitted scorer fingerprints")
    _nonempty(protocol.audit_selection.get("method"), "audit_selection.method")
    for role in _ROLES:
        model = getattr(protocol, role + "_model")
        try:
            if model.protocol == CompletionProtocol.ANTHROPIC_MESSAGES:
                validate_anthropic_config(model, FeatureChoices(mia_scoring=bool(fits) and role == "target"))
            else:
                validate_features(model, FeatureChoices(mia_scoring=bool(fits) and role == "target"))
        except (ValueError, TypeError) as error:
            raise ValueError(f"{role}: {error}") from None
    bindings = dict(data_files or {})
    if "evaluation" in bindings or _FIT_KEYS & bindings.keys():
        raise ValueError("evaluation is bound to --items; calibration keys bind scorers, not data files")
    expected = set(protocol.data_hashes) - _FIT_KEYS - {"evaluation"}
    if set(bindings) != expected:
        raise ValueError(f"Dataset hash bindings differ: required {sorted(expected)}, supplied {sorted(bindings)}")
    hashes = {"evaluation": hashlib.sha256(item_bytes).hexdigest()}
    hashes.update({name: hashlib.sha256(Path(path).read_bytes()).hexdigest() for name, path in bindings.items()})
    for name, digest in hashes.items():
        if protocol.data_hashes.get(name) != digest:
            raise ValueError(f"Dataset hash mismatch for {name}")
    history = _history(protocol, items, _registry(cutoff_registry))
    return InterventionConfig(protocol, items, history)

experiment_plan

experiment_plan(config, *, prior_run=None)

Return a credential-free offline plan of physical request attempts.

Nominal counts assume accepted rewrites and first-attempt successes. Retry upper bounds are subordinate to the shared remaining cap. A safe resume probes all roles again and schedules only pending whole arms.

Source code in recall_guard/harness/intervention_config.py
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
def experiment_plan(config, *, prior_run=None):
    """Return a credential-free offline plan of physical request attempts.

    Nominal counts assume accepted rewrites and first-attempt successes. Retry
    upper bounds are subordinate to the shared remaining cap. A safe resume
    probes all roles again and schedules only pending whole arms.
    """
    protocol, items = config.protocol, config.items
    used, pending = 0, {(item.item_id, arm) for item in items for arm in ("original", "rewritten")}
    stopped = False
    if prior_run is not None:
        resume = prior_run.checkpoint.validate_restart(protocol, items)
        used = resume.prior_used_requests
        pending -= {(arm.item_id, arm.arm.value) for arm in prior_run.arms}
        stopped = bool(prior_run.stop_reason) or prior_run.checkpoint.status == "completed"
    nominal = {role: 0 if stopped else 1 for role in _ROLES}
    if not stopped:
        nominal["target"] += len(pending) * protocol.draws
        rewritten = sum(arm == "rewritten" for _, arm in pending)
        nominal["rewriter"] += rewritten
        nominal["verifier"] += rewritten
    upper = {role: count * (1 + getattr(protocol, role + "_model").max_retries) for role, count in nominal.items()}
    roles = {}
    for role in _ROLES:
        model = getattr(protocol, role + "_model")
        features = FeatureChoices(ensemble_draws=protocol.draws, rewriting=True,
                                  mia_scoring=bool(_FIT_KEYS & protocol.data_hashes.keys())) if role == "target" else FeatureChoices()
        declared = model.inspect(features)
        roles[role] = {"config": model.to_dict(), "selected_features": asdict(features),
                       "declared_capabilities": {name: evidence.to_dict() for name, evidence in declared.capabilities.items()},
                       "actual_capabilities": {name: {"status": "unverified", "observed": False,
                                                      "source": "No actual probe in this offline plan"}
                                               for name in declared.capabilities}}
    fits = sorted(_FIT_KEYS & protocol.data_hashes.keys())
    plan = {"protocol_id": protocol.protocol_id, "conditions": list(CONDITION_ORDER), "single_draw_index": 0,
            "draws_per_arm": protocol.draws, "rewrite_scope": protocol.rewrite_scope,
            "shared_target_settings": True, "roles": roles, "ready_for_batch": False,
            "calibration": {"required_fingerprints": {key: protocol.data_hashes[key] for key in fits},
                            "available": False, "reason": "CLI has no fitted scorers; use the Python ExperimentRunner API"
                            if fits else "MIA/MCS not selected; raw confidence is a separate optional response field"},
            "audit_selection": protocol.to_dict()["audit_selection"], "task_metric": protocol.task_metric,
            "utility_tolerance": protocol.utility_tolerance, "data_hashes": dict(protocol.data_hashes),
            "historical": config.historical,
            "physical_calls": {"nominal_by_role": nominal, "nominal_total": sum(nominal.values()),
                               "retry_upper_bound_by_role": upper, "retry_upper_bound_total": sum(upper.values()),
                               "hard_request_cap": protocol.request_budget, "prior_used": used,
                               "hard_remaining_cap": protocol.request_budget - used,
                               "nominal_fits_remaining_cap": sum(nominal.values()) <= protocol.request_budget - used,
                               "basis": "Fresh execution has one probe per role; resume intentionally re-probes. "
                               "Fidelity rejection, failures and hard cap can reduce verification/target calls. "
                               "Single conditions reuse ensemble draw 0; n is not total request cost."}}
    check_execution_metadata(plan)
    return plan