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…

            m_plist = meas_probes_rec if meas_probes_rec else [clean_m_rec]
            mol_plist = mol_probes_rec if mol_probes_rec else [clean_mol_rec]
            for _cand_m in m_plist:
                _cand_ext = _extract_stage0_batch_measurements_preserving_explicit_se_iip0026(
                    {**{k: v for k, v in non_obs_raw_m.items() if v is not None}, **_cand_m},
                    wc_helper,
                )
                for _cand_mol in mol_plist:
                    _probe_acc = {**accum, **_cand_ext, **_cand_mol}
                    _probe_ev = wc_helper.evaluate_stage0_product_contract(_probe_acc, root=root)
                    if (
                        _probe_ev.get("overall_status") == "HARD_SAFETY_STOP_REJECTED"
                        and _probe_ev.get("hard_stop_precedence_winner") == "S9_HARD_SAFETY_STOP"
                    ):
                        latched_s9_hard_stop = True
                        latched_switch_decisions = dict(_probe_ev["switch_decisions"])
                    _probe_s11 = _probe_ev.get("s11_evaluation")
                    if isinstance(_probe_s11, dict) and str(_probe_s11.get("status", "")).startswith("FAIL_"):
                        s11_fail_records.append((logical_tk, dict(_probe_s11)))
                    for _pr_code in _probe_ev.get("iip0026_reasons", []):
                        _add_other_fail(str(_pr_code))

        if not rec_has_immutable_conflict:
            combined_m = {**{k: v for k, v in non_obs_raw_m.items() if v is not None}, **clean_m_rec}
            if combined_m:
                accum.update(_extract_stage0_batch_measurements_preserving_explicit_se_iip0026(combined_m, wc_helper))
        if clean_mol_rec:
            accum.update(clean_mol_rec)

        # Accumulate sorted-lot Tier 6B observations across ALL 4 supported containers:
        for src_dict in (rec_san, sc, mol, raw_m_dict):
            if "tier6b_sorted_lot_observations" in src_dict:
                has_any_tier6b_field = True
                t6_in = src_dict["tier6b_sorted_lot_observations"]
                if isinstance(t6_in, (list, tuple)):
                    accum_tier6b_obs.extend(t6_in)
                else:
                    accum_tier6b_obs.append("__EXPLICIT_NULL_OR_MALFORMED_TIER6B_CONTAINER__")
        if has_any_tier6b_field:
            accum["tier6b_sorted_lot_observations"] = list(accum_tier6b_obs)

        # Accumulate valid S11 record onto `accum` when present so single- or multi-record final_eval reflects latest state:
        _rec_s11_dicts = [
            _src_31["iip0031_locus2_record"]
            for _src_31 in (rec_san, sc, mol, raw_m_dict)
            if "iip0031_locus2_record" in _src_31 and isinstance(_src_31["iip0031_locus2_record"], dict)
        ]
        if len(_rec_s11_dicts) == 1:
            accum["iip0031_locus2_record"] = _rec_s11_dicts[0]
        elif len(_rec_s11_dicts) > 1 and any(d != _rec_s11_dicts[0] for d in _rec_s11_dicts[1:]):
            accum["iip0031_locus2_record"] = "CONFLICTING_DUPLICATE_IIP0031_LOCUS2_RECORDS"
        elif any("iip0031_locus2_record" in _src_31 for _src_31 in (rec_san, sc, mol, raw_m_dict)):
            accum["iip0031_locus2_record"] = "__MALFORMED_NON_DICT__"

        rec_29_in = rec_san.get("iip0029_twoclock_record", mol.get("iip0029_twoclock_record"))
        if rec_29_in is not None:
            fp_now = wc_helper._extract_iip0029_source_fingerprint(rec_29_in)
            if locked_iip0029_source_fp is not None and fp_now != locked_iip0029_source_fp:
                _add_other_fail("FAIL_IIP0029_IMMUTABLE_SOURCE_OR_THRESHOLD_REPLACEMENT_DETECTED")
            else:
                locked_iip0029_source_fp = fp_now
            accum["iip0029_twoclock_record"] = rec_29_in
        for clk_k in ("stage7_start_utc", "sort_reaggregation_utc", "assay_harvest_utc", "locked_analysis_plan_id"):
            clk_v = accum.get(clk_k)
            if clk_v is not None:
                if clk_k in locked_iip0029_flat_clocks and locked_iip0029_flat_clocks[clk_k] != clk_v:
                    _add_other_fail("FAIL_IIP0029_IMMUTABLE_SOURCE_OR_THRESHOLD_REPLACEMENT_DETECTED")
                else:
                    locked_iip0029_flat_clocks[clk_k] = clk_v
        if accum.get("terminal_alk5i_tgfb_inhibitor_continued") is True:
            latched_iip0029_alk5i_continued = True
        elif latched_iip0029_alk5i_continued and accum.get("terminal_alk5i_tgfb_inhibitor_continued") is False:
            _add_other_fail("FAIL_IIP0029_IMMUTABLE_SOURCE_OR_THRESHOLD_REPLACEMENT_DETECTED")

        step_eval = wc_helper.evaluate_stage0_product_contract(dict(accum), root=root)
        step_29 = step_eval.get("iip0029_twoclock_maturation_and_repeated_challenge_evaluation")
        if isinstance(step_29, dict):
            if step_29.get("gate0s_escalation_required") is True:
                latched_iip0029_store_gt_138p3 = True
            elif latched_iip0029_store_gt_138p3 and step_29.get("gate0s_escalation_required") is False:
                _add_other_fail("FAIL_IIP0029_IMMUTABLE_SOURCE_OR_THRESHOLD_REPLACEMENT_DETECTED")
        if step_eval.get("overall_status") == "HARD_SAFETY_STOP_REJECTED" and step_eval.get("hard_stop_precedence_winner") == "S9_HARD_SAFETY_STOP":
            latched_s9_hard_stop = True
            latched_switch_decisions = dict(step_eval["switch_decisions"])
        if step_eval.get("tier6b_disposition") == "FAIL_HARD_STOP" or step_eval.get("hard_stop_precedence_winner") == "FAIL_TIER6B_OUTGROWTH_DETECTED":
            latched_tier6b_hard_stop = True
            if isinstance(step_eval.get("tier6b_sorted_lot_evaluation"), dict):
                latched_tier6b_eval = dict(step_eval["tier6b_sorted_lot_evaluation"])
        step_s11 = step_eval.get("s11_evaluation")
        if isinstance(step_s11, dict) and str(step_s11.get("status", "")).startswith("FAIL_"):
            s11_fail_records.append((logical_tk, dict(step_s11)))
        for r in step_eval.get("iip0026_reasons", []):
            _add_other_fail(str(r))

    if latched_s9_rep_conflict:
        accum["_s9_replicate_count_conflict"] = True
    if latched_meas_conflict:
        accum["_stage0_conflicting_measurement"] = True
    final_eval = wc_helper.evaluate_stage0_product_contract(dict(accum), root=root)
    if (
        final_eval.get("overall_status") == "HARD_SAFETY_STOP_REJECTED"
        and final_eval.get("hard_stop_precedence_winner") == "S9_HARD_SAFETY_STOP"
    ):
        latched_s9_hard_stop = True
        if latched_switch_decisions is None:
            latched_switch_decisions = dict(final_eval["switch_decisions"])
    if (
        final_eval.get("tier6b_disposition") == "FAIL_HARD_STOP"
        or final_eval.get("hard_stop_precedence_winner") == "FAIL_TIER6B_OUTGROWTH_DETECTED"
    ):
        latched_tier6b_hard_stop = True
        if latched_tier6b_eval is None and isinstance(final_eval.get("tier6b_sorted_lot_evaluation"), dict):
            latched_tier6b_eval = dict(final_eval["tier6b_sorted_lot_evaluation"])
    final_s11 = final_eval.get("s11_evaluation")
    if isinstance(final_s11, dict) and str(final_s11.get("status", "")).startswith("FAIL_"):
        s11_fail_records.append((((3, 0, ""), 0), dict(final_s11)))

    # Deterministically consolidate all observed S11 failures (earliest chronological instant wins; ties use canonical headline):
    latched_s11_eval: Dict[str, Any] | None = None
    if s11_fail_records:
        min_tk = min(tk for tk, _ in s11_fail_records)
        earliest_evals = [ev for tk, ev in s11_fail_records if tk == min_tk]
        earliest_fails: list[str] = []
        for ev in earliest_evals:
            st = str(ev.get("status", ""))
            if st.startswith("FAIL_") and st not in earliest_fails:
                earliest_fails.append(st)
            for r in ev.get("reasons", []):
                rs = str(r)
                if rs.startswith("FAIL_") and rs not in earliest_fails:
                    earliest_fails.append(rs)
        win_s11 = wc_helper._pick_headline_s11_fail_iip0031(earliest_fails)
        all_s11_fails: list[str] = [win_s11]
        all_s11_holds: list[str] = []
        chosen_base = earliest_evals[0]
        for _, ev in s11_fail_records:
            st = str(ev.get("status", ""))
            if st == win_s11:
                chosen_base = ev
            if st.startswith("FAIL_") and st not in all_s11_fails:
                all_s11_fails.append(st)
            for r in ev.get("reasons", []):
                rs = str(r)
                if rs.startswith("FAIL_"):
                    if rs not in all_s11_fails:
                        all_s11_fails.append(rs)
                elif rs not in all_s11_holds:
                    all_s11_holds.append(rs)
        ordered_s11_fails = [win_s11] + sorted(f for f in all_s11_fails if f != win_s11)
        latched_s11_eval = dict(chosen_base)
        latched_s11_eval["status"] = win_s11
        latched_s11_eval["gate_pass"] = False
        latched_s11_eval["reasons"] = ordered_s11_fails + all_s11_holds

    # SINGLE EXPLICIT GLOBAL PRECEDENCE TABLE: 1. S9 -> 2. Tier 6B -> 3. Rule S11 -> 4. Other FAIL_* -> 5. Malformed HOLD
    if latched_s9_hard_stop:
        final_eval["overall_status"] = "HARD_SAFETY_STOP_REJECTED"
        final_eval["lot_release_readiness_tier"] = "HARD_SAFETY_STOP_REJECTED"
        s9_reasons = ["HARD_SAFETY_STOP_S9"] + [r for r in latched_other_fails if r != "HARD_SAFETY_STOP_S9"]
        final_eval["iip0026_reasons"] = s9_reasons
        final_eval["hard_stop_precedence_winner"] = "S9_HARD_SAFETY_STOP"
        final_eval["execution_supported"] = False
        final_eval["effective_execution_permitted"] = False
        if latched_switch_decisions is not None:
            final_eval["switch_decisions"] = dict(latched_switch_decisions)
    elif latched_tier6b_hard_stop:
        final_eval["overall_status"] = "FAIL_HARD_STOP"
        final_eval["lot_release_readiness_tier"] = "HARD_SAFETY_STOP_REJECTED"
        t6_reasons = ["FAIL_TIER6B_OUTGROWTH_DETECTED"] + [r for r in latched_other_fails if r != "FAIL_TIER6B_OUTGROWTH_DETECTED"]
        final_eval["iip0026_reasons"] = t6_reasons
        final_eval["hard_stop_precedence_winner"] = "FAIL_TIER6B_OUTGROWTH_DETECTED"
        final_eval["execution_supported"] = False
        final_eval["effective_execution_permitted"] = False
    elif latched_s11_eval is not None:
        win_s11 = str(latched_s11_eval["status"])
        merged_s11_reasons: list[str] = [win_s11]
        for r in list(latched_s11_eval.get("reasons", [])) + latched_other_fails + list(final_eval.get("iip0026_reasons", [])):
            rs = str(r)
            if rs not in merged_s11_reasons:
                merged_s11_reasons.append(rs)
        final_eval["overall_status"] = win_s11
        final_eval["lot_release_readiness_tier"] = win_s11
        final_eval["iip0026_reasons"] = merged_s11_reasons
        final_eval["hard_stop_precedence_winner"] = win_s11
        final_eval["execution_supported"] = False
        final_eval["effective_execution_permitted"] = False
    elif latched_other_fails:
        merged_reasons = list(latched_other_fails) + [
            r for r in final_eval["iip0026_reasons"] if r not in latched_other_fails
        ]
        final_eval["iip0026_reasons"] = merged_reasons
        final_eval["overall_status"] = latched_other_fails[0]
        final_eval["lot_release_readiness_tier"] = latched_other_fails[0]
        final_eval["hard_stop_precedence_winner"] = None
        final_eval["execution_supported"] = False
        final_eval["effective_execution_permitted"] = False
    elif malformed_replay:
        reason = "HOLD_MALFORMED_STAGE0_REPLAY_RECORD"
        if reason not in final_eval["iip0026_reasons"]:
            final_eval["iip0026_reasons"] = [*final_eval["iip0026_reasons"], reason]
        if not final_eval["overall_status"].startswith(("HOLD_", "FAIL_")):
            final_eval["overall_status"] = reason
            final_eval["lot_release_readiness_tier"] = reason
        final_eval["execution_supported"] = False
        final_eval["effective_execution_permitted"] = False

    # ALWAYS project latched Tier 6B and Rule S11 diagnostic evaluations even when a higher-precedence hard stop won:
    if latched_tier6b_hard_stop:
        final_eval["tier6b_disposition"] = "FAIL_HARD_STOP"
        final_eval["tier6b_reason"] = "FAIL_TIER6B_OUTGROWTH_DETECTED"
        if latched_tier6b_eval is not None:
            final_eval["tier6b_sorted_lot_evaluation"] = dict(latched_tier6b_eval)
    if latched_s11_eval is not None:
        final_eval["s11_evaluation"] = dict(latched_s11_eval)
        latched_s11_st = str(latched_s11_eval.get("status", "FAIL_S11_LATCHED_FAILURE"))
        if isinstance(final_eval.get("switch_decisions"), dict):
            final_eval["switch_decisions"] = dict(final_eval["switch_decisions"])
            final_eval["switch_decisions"]["S11_Locus2_CIITA_ModeB_Vascular_Complement_and_Efferocytosis_Gate"] = latched_s11_st
            final_eval["switch_decisions"]["JSON_S11_Locus2_CIITA_ModeB_Vascular_Complement_and_Efferocytosis_Gate"] = latched_s11_st
    return final_eval


def replay_stage0_chronological_batches(
    records: list[Dict[str, Any]],
    *,
    root: Path | str | None = None,
) -> Dict[str, Any]:
    """
    Path 4 Chronological Multi-Record Stage-0 Replay Evaluator (IIP-0026; DEC-105; hardened IIP-0031; DEC-110).
    Enforces:
      - Exact UTC instant chronological sorting by `(parsed_utc_timestamp, seq_index)` with deterministic tie handling.
      - Per-scope `(product_variant_id, lot_id, campaign_id)` and conditioning-arm partitioning so mixed-envelope
        rejections (`FAIL_CROSS_LOT_OR_CAMPAIGN_REPLAY_MIXING`, `FAIL_CROSS_CONDITIONING_ARM_REPLAY_MIXING`)
        never suppress independently attributable S9, Tier 6B, or Rule S11 hard stops.
      - Monotonic adverse-event latching (`S9` -> `Tier 6B` -> `Rule S11` -> other `FAIL_*`) surviving
        subsequent malformed records, incomplete-scope peers, and later clean zero repeats.
      - Exact branch (`switch_decisions`) and lot parity with Direct evaluation, Atomic Ledger, and Serialized JSON Ingestion.
    """
    wc_helper = _load_contract_helper_iip0026(root)
    if not records:
        return wc_helper.evaluate_stage0_product_contract({}, root=root)
    root_path = Path(root) if root is not None else REPO_ROOT

    def _replay_sort_key(indexed_r: tuple[int, Any]) -> tuple[int, Tuple[int, int, str], int, int]:
        idx, r = indexed_r
        if isinstance(r, dict):
            raw_seq = r.get("seq_index", idx)
            seq_i = raw_seq if (type(raw_seq) is int) else idx
            return (0, _parse_replay_timestamp_iip0031(r.get("utc_timestamp")), seq_i, idx)
        return (1, (3, 0, ""), idx, idx)