OpenIslet

scripts/ingest_wetlab_results.py

Closed-Loop Wet-Lab Results Ingestor & Bayesian Posterior Updater (`scripts/ingest_wetlab_results.py`, v0.8.0)

script Release v0.8.0 gen-eb955f8266035aba 228 KB · 18 sections

Use this file in any AI chat (paste-only or attachment-capable):

Download as text (.txt) Download section (.txt)

Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/ingest_wetlab_results.py · SHA-256: e050593675170515…

        )
        has_lot_mdm4 = (
            meas_dict.get("obs_1q32_mdm4_single_cell_mosaic_fraction") not in ("UNAVAILABLE", None)
            and float(meas_dict.get("obs_1q32_mdm4_single_cell_mosaic_cells_scored") or 0.0) >= 299.0
        )
        if not (has_mcb_mdm4 or has_lot_mdm4):
            return False
    if "GATE0V_PERSISTENT_VIRAL_POSITIVE" in stop_cats:
        if (
            meas_dict.get("obs_gate0v_day28_persistent_vp1_ie1_positive_cell_pct") != 0.0
            or float(meas_dict.get("obs_gate0v_day28_persistent_vp1_ie1_cells_scored") or 0.0) < 5990.0
        ):
            return False
    if "GATE0S_DUAL_SHEDDING_POSITIVE" in stop_cats:
        if (
            meas_dict.get("obs_gate0s_shedding_ddpcr_events_k") != 0.0
            or float(meas_dict.get("obs_gate0s_shedding_ddpcr_trials_n") or 0.0) < 2995731.0
            or meas_dict.get("obs_gate0s_shedding_viable_events_k") != 0.0
            or float(meas_dict.get("obs_gate0s_shedding_viable_trials_n") or 0.0) < 2995731.0
        ):
            return False
    if "P05_Z70_INTERFACE_H2O2_GT_5UM" in stop_cats:
        z70_m = meas_dict.get("obs_p05_z70_gel_interface_h2o2_max_uM")
        if z70_m in ("UNAVAILABLE", None):
            return False
        _get_stage0_decision_tree_specs()
        t_ppf = getattr(_MEASUREMENT_CONTRACT_MODULE, "student_t_ppf_one_sided_95")
        n_r = meas_dict.get("obs_stage0_independent_lot_replicates_n")
        df_z = max(5.0, float(int(round(float(n_r))) - 1)) if n_r not in ("UNAVAILABLE", None) and float(n_r) >= 6.0 else 5.0
        z70_se_raw = meas_dict.get("obs_p05_z70_gel_interface_h2o2_max_se")
        z70_se = float(z70_se_raw) if z70_se_raw not in ("UNAVAILABLE", None) else 0.10
        if float(z70_m) > 5.0 or (float(z70_m) + float(t_ppf(df_z)) * z70_se) > 5.0:
            return False
    return True


def _validate_prior_posterior_report(
    prior_report: Dict[str, Any],
    is_dry_run: bool,
    new_batch_id: str,
    new_batch_payload_sha256: str,
) -> tuple[list[str], list[str], Dict[str, tuple[float, float]]]:
    """
    Strictly validate `prior_posterior_report` schema, epistemic lineage, batch ID history,
    content-hash (`batch_payload_sha256`) history, cryptographic `conjugate_posterior_updates_sha256`,
    and algebraic integrity of all canonical endpoint posteriors before any branch executes
    (closing AUDIT-REF, AUDIT-REF, and AUDIT-REF).
    """
    if not isinstance(prior_report, dict):
        raise ValueError("prior_posterior_report must be a dictionary")
    if (type(prior_report.get("calibration_state_version")) is not int
            or prior_report["calibration_state_version"] != CALIBRATION_STATE_VERSION):
        raise ValueError("Prior report requires calibration_state_version=2; reconstruct legacy empirical history from original ordered observations")
    if prior_report.get("calibration_state_sha256") != _calibration_state_sha256(prior_report):
        raise ValueError("Prior report complete calibration-state digest mismatch")

    for req_key in ("calibration_mode", "ingested_batch_ids", "conjugate_posterior_updates"):
        if req_key not in prior_report:
            raise ValueError(f"prior_posterior_report missing required schema key {req_key!r}")

    prior_mode = prior_report["calibration_mode"]
    if not isinstance(prior_mode, str) or prior_mode not in VALID_CALIBRATION_MODES:
        raise ValueError(f"Invalid prior calibration_mode {prior_mode!r}")

    prior_lineage = prior_report.get("epistemic_lineage_status")
    if ((prior_mode == "EMPIRICAL_WETLAB_INGESTION" and prior_lineage not in SUPPORTED_EMPIRICAL_LINEAGES)
            or (prior_mode != "EMPIRICAL_WETLAB_INGESTION" and prior_lineage != "SYNTHETIC_DRY_RUN_LINEAGE")):
        raise ValueError("Prior calibration mode has inconsistent epistemic lineage")
    if "contains_synthetic_records" in prior_report:
        if type(prior_report["contains_synthetic_records"]) is not bool:
            raise ValueError("prior_posterior_report['contains_synthetic_records'] must be a boolean when provided (WETLAB-01)")
        if (prior_mode == "EMPIRICAL_WETLAB_INGESTION" and prior_report["contains_synthetic_records"] is True) or (
            prior_mode != "EMPIRICAL_WETLAB_INGESTION" and prior_report["contains_synthetic_records"] is False
        ):
            raise ValueError("Prior calibration mode has inconsistent contains_synthetic_records declaration (WETLAB-01)")
        if not is_dry_run and prior_report["contains_synthetic_records"] is not False:
            raise ValueError("Epistemic lineage violation: cannot chain prior report with contains_synthetic_records=True into empirical ingestion (WETLAB-01)")
    if "calibration_lineage_class" in prior_report:
        if not isinstance(prior_report["calibration_lineage_class"], str):
            raise ValueError("prior_posterior_report['calibration_lineage_class'] must be a string when provided (WETLAB-01)")
        if (prior_mode == "EMPIRICAL_WETLAB_INGESTION" and prior_report["calibration_lineage_class"] not in SUPPORTED_EMPIRICAL_LINEAGES) or (
            prior_mode != "EMPIRICAL_WETLAB_INGESTION" and prior_report["calibration_lineage_class"] != "SYNTHETIC_DRY_RUN_LINEAGE"
        ):
            raise ValueError("Prior calibration mode has inconsistent calibration_lineage_class declaration (WETLAB-01)")
    if not is_dry_run and (
        prior_mode != "EMPIRICAL_WETLAB_INGESTION"
        or prior_lineage not in SUPPORTED_EMPIRICAL_LINEAGES
    ):
        raise ValueError(
            f"Epistemic lineage violation: cannot chain prior report with calibration_mode={prior_mode!r}, "
            f"epistemic_lineage_status={prior_lineage!r} into an empirical wet-lab ingestion (AUDIT-REF)."
        )

    raw_batches = prior_report["ingested_batch_ids"]
    if not isinstance(raw_batches, list) or len(raw_batches) == 0:
        raise ValueError("prior_posterior_report['ingested_batch_ids'] must be a non-empty list of batch ID strings")
    norm_batches: list[str] = []
    for b in raw_batches:
        if not isinstance(b, str) or not b.strip() or b != b.strip() or len(b) > 120:
            raise ValueError(f"Invalid batch ID {b!r} in prior_posterior_report['ingested_batch_ids']")
        b_clean = b.strip()
        if not is_dry_run and b_clean.upper().startswith("DRY-RUN"):
            raise ValueError(
                f"Epistemic lineage violation: prior report contains synthetic batch_id {b_clean!r} in empirical mode"
            )
        if b_clean in norm_batches:
            raise ValueError(f"Duplicate batch ID {b_clean!r} inside prior_posterior_report['ingested_batch_ids']")
        norm_batches.append(b_clean)

    parent_digest = prior_report.get("parent_report_sha256")
    if ((len(norm_batches) == 1 and parent_digest is not None)
            or (len(norm_batches) > 1 and (not isinstance(parent_digest, str)
                or re.fullmatch(r"[0-9a-f]{64}", parent_digest) is None))):
        raise ValueError("Prior report parent lineage must be null at genesis and a SHA-256 for sequential batches")

    if new_batch_id in norm_batches:
        raise ValueError(f"Duplicate batch_id {new_batch_id!r} already ingested in prior posterior report!")

    # Validate content-level measurement payload hashes (closing AUDIT-REF):
    raw_prev_hashes = prior_report.get("ingested_batch_payload_sha256s")
    if (not isinstance(raw_prev_hashes, list) or len(raw_prev_hashes) != len(norm_batches)
            or any(not isinstance(h, str) or re.fullmatch(r"[0-9a-f]{64}", h) is None for h in raw_prev_hashes)
            or len(set(raw_prev_hashes)) != len(raw_prev_hashes)):
        raise ValueError("Prior payload digest history must contain one unique lowercase SHA-256 per batch")
    prev_payload_hashes = list(raw_prev_hashes)
    single_prev_hash = prior_report.get("batch_payload_sha256")
    if single_prev_hash != prev_payload_hashes[-1] or prior_report.get("batch_id") != norm_batches[-1]:
        raise ValueError("Latest calibration batch must match the final replay-history entry")

    if new_batch_payload_sha256 in prev_payload_hashes:
        raise ValueError(
            f"Duplicate measurement payload content replay detected: batch_payload_sha256={new_batch_payload_sha256} "
            f"(submitted under batch_id={new_batch_id!r}) matches an already-ingested batch (AUDIT-REF)!"
        )

    raw_updates = prior_report["conjugate_posterior_updates"]
    if not isinstance(raw_updates, dict) or set(raw_updates) != {row[0] for row in ENDPOINT_SPECS}:
        raise ValueError("prior report must contain exactly the canonical core endpoint states")

    # Verify cryptographic digest of conjugate_posterior_updates if present (or require it when exact fields exist; AUDIT-REF):
    expected_updates_sha256 = hashlib.sha256(
        json.dumps(raw_updates, sort_keys=True, allow_nan=False).encode("utf-8")
    ).hexdigest()
    recorded_updates_sha256 = prior_report.get("conjugate_posterior_updates_sha256")
    if recorded_updates_sha256 is None:
        raise ValueError("Prior report missing required conjugate_posterior_updates_sha256")
    if recorded_updates_sha256 is not None:
        if not isinstance(recorded_updates_sha256, str) or recorded_updates_sha256 != expected_updates_sha256:
            raise ValueError(
                f"Prior report integrity violation: conjugate_posterior_updates_sha256={recorded_updates_sha256!r} "
                f"does not match recomputed SHA-256 {expected_updates_sha256!r} (tampered prior_posterior_report rejected; AUDIT-REF)"
            )

    validated_priors: Dict[str, tuple[float, float]] = {}
    for ep_name, _def_m, _def_sd, _mk, _sk, min_valid, max_valid, _unit in ENDPOINT_SPECS:
        if ep_name not in raw_updates:
            raise ValueError(
                f"prior_posterior_report missing required canonical endpoint {ep_name!r} "
                "(silent reset to default prior is prohibited; AUDIT-REF)"
            )
        ep_obj = raw_updates[ep_name]
        if not isinstance(ep_obj, dict):
            raise ValueError(f"Prior endpoint {ep_name!r} must be a dictionary")
        raw_pm = ep_obj.get("posterior_mean_exact", ep_obj.get("posterior_mean"))
        raw_psd = ep_obj.get("posterior_sd_exact", ep_obj.get("posterior_sd"))
        pm = _require_finite_float(raw_pm, f"prior.{ep_name}.posterior_mean")
        psd = _require_finite_float(raw_psd, f"prior.{ep_name}.posterior_sd")
        if psd > 0.0 and (1.0 / psd) ** 2 == 0.0:
            raise ValueError(f"prior.{ep_name}.precision is outside representable numeric range")
        if psd <= MIN_PRIOR_SD_POSITIVITY_FLOOR:
            raise ValueError(
                f"prior.{ep_name}.posterior_sd must be > positivity floor {MIN_PRIOR_SD_POSITIVITY_FLOOR}, got {psd}"
            )
        if pm < min_valid or pm > max_valid:
            raise ValueError(
                f"prior.{ep_name}.posterior_mean={pm} outside valid physical domain [{min_valid}, {max_valid}]"
            )
        _verify_endpoint_algebraic_integrity(ep_name, ep_obj, pm, psd, min_valid=min_valid, max_valid=max_valid)
        validated_priors[ep_name] = (pm, psd)

    raw_ext_updates = prior_report.get("optional_pouch_and_36run_screen_updates_v80_070")
    expected_ext = {row[0] for row in EXTENDED_STAGE0_STAGE1_SPECS}
    if not isinstance(raw_ext_updates, dict) or set(raw_ext_updates) != expected_ext:
        raise ValueError("Prior report must preserve every extended endpoint, including unavailable priors")
    if any(not isinstance(v, dict) for v in raw_ext_updates.values()):
        raise ValueError("Every extended endpoint state must be an object")
    if isinstance(raw_ext_updates, dict):
        for ep_name, _def_m, _def_sd, _mk, _sk, _def_se, min_valid, max_valid, _unit in EXTENDED_STAGE0_STAGE1_SPECS:
            if ep_name in raw_ext_updates and isinstance(raw_ext_updates[ep_name], dict):
                ep_obj = raw_ext_updates[ep_name]
                raw_pm = ep_obj.get("posterior_mean_exact", ep_obj.get("posterior_mean"))
                raw_psd = ep_obj.get("posterior_sd_exact", ep_obj.get("posterior_sd"))
                pm = _require_finite_float(raw_pm, f"prior.{ep_name}.posterior_mean")
                psd = _require_finite_float(raw_psd, f"prior.{ep_name}.posterior_sd")
                if psd > 0.0 and (1.0 / psd) ** 2 == 0.0:
                    raise ValueError(f"prior.{ep_name}.precision is outside representable numeric range")
                if psd <= MIN_PRIOR_SD_POSITIVITY_FLOOR:
                    raise ValueError(f"prior.{ep_name}.posterior_sd must be > {MIN_PRIOR_SD_POSITIVITY_FLOOR}, got {psd}")
                if pm < min_valid or pm > max_valid:
                    raise ValueError(f"prior.{ep_name}.posterior_mean={pm} outside [{min_valid}, {max_valid}]")
                _verify_endpoint_algebraic_integrity(ep_name, ep_obj, pm, psd, min_valid=min_valid, max_valid=max_valid)
                validated_priors[ep_name] = (pm, psd)

    all_updates = [*raw_updates.values(), *raw_ext_updates.values()]
    actual_count = sum(ep["status"] == "UPDATED_FROM_OBSERVED_READOUT" for ep in all_updates)
    if (type(prior_report.get("observed_endpoints_updated_count")) is not int
            or prior_report["observed_endpoints_updated_count"] != actual_count):
        raise ValueError("Prior report observed endpoint count is inconsistent with endpoint state")
    actual_conflict = any(ep["prior_data_conflict_detected"] for ep in all_updates)
    if (type(prior_report.get("any_prior_data_conflict_detected_gt_3sigma")) is not bool
            or prior_report["any_prior_data_conflict_detected_gt_3sigma"] != actual_conflict):
        raise ValueError("Prior report conflict summary is inconsistent with endpoint state")
    latest_measurements = {}
    for specifications, endpoint_states in ((ENDPOINT_SPECS, raw_updates),
                                             (EXTENDED_STAGE0_STAGE1_SPECS, raw_ext_updates)):
        for row in specifications:
            ep_name, default_mean, default_sd, mean_key, se_key = row[:5]
            endpoint = endpoint_states[ep_name]
            if endpoint["status"] == "UPDATED_FROM_OBSERVED_READOUT":
                latest_measurements[mean_key] = endpoint["observed_mean_exact"]
                latest_measurements[se_key] = endpoint["observed_se_exact"]
            else:
                latest_measurements[mean_key] = "UNAVAILABLE"
            initial_precision = (1.0 / default_sd) ** 2
            prior_precision = (1.0 / endpoint["prior_sd_exact"]) ** 2
            # At most one legal independent observation per endpoint per batch;
            # no history can create more precision than n / minimum_SE**2.
            upper_prior_precision = initial_precision + (len(norm_batches) - 1) / MIN_BIOLOGICAL_SE_FLOOR**2
            if (prior_precision < initial_precision * (1.0 - 1e-12)
                    or prior_precision > upper_prior_precision * (1.0 + 1e-12)):
                raise ValueError(f"Prior endpoint {ep_name!r} precision is inconsistent with its batch history")
            # Added sufficient-statistic mass can only be a precision-weighted
            # mean of bounded observations. Zero added precision cannot move
            # the genesis mean. Centering the convex bounds avoids subtracting
            # nearly equal weighted means for genuinely weak observations.
            observation_weight = max(0.0, (prior_precision - initial_precision) / prior_precision)
            lower, upper = row[-3:-1]
            reachable_low = default_mean + observation_weight * (lower - default_mean)
            reachable_high = default_mean + observation_weight * (upper - default_mean)
            # A conservative per-batch floating-point budget for reciprocal,
            # square/root and convex-sum roundoff, scaled in ULPs rather than a
            # fixed physical mean/SD tolerance that could dominate weak data.
            scale = max(abs(lower), abs(upper), abs(default_mean))
            mean_roundoff = 32 * len(norm_batches) * math.ulp(scale)
            if not reachable_low - mean_roundoff <= endpoint["prior_mean_exact"] <= reachable_high + mean_roundoff:
                raise ValueError(f"Prior endpoint {ep_name!r} mean is outside its reachable bounded-observation history")
            if len(norm_batches) == 1 and (
                    not math.isclose(endpoint["prior_mean_exact"], default_mean, rel_tol=1e-12, abs_tol=0.0)
                    or not math.isclose(endpoint["prior_sd_exact"], default_sd, rel_tol=1e-12, abs_tol=0.0)):
                raise ValueError(f"Prior endpoint {ep_name!r} genesis prior differs from the declared initial prior")