OpenIslet

scripts/verify_iip0056_route4_omentum_and_exvivo_rest.py

OpenIslet Wave-6 Round-14 Prospective Candidate W6-C2 (Staged Slot IIP-0047 -> Provisional

script Release v0.8.0 gen-eb955f8266035aba 466 KB · 37 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/verify_iip0056_route4_omentum_and_exvivo_rest.py · SHA-256: 25e12d578ba80b55…

        auc_l95_d: Optional[Decimal] = None
        if auc_l95 is None:
            hold_reasons.append("MISSING_OQ018_FIRST_PHASE_AUC_L95_PCT_CTRL")
        elif not _is_finite_number(auc_l95):
            fail_reasons.append("OQ018_FIRST_PHASE_AUC_L95_LT_85PCT_FAIL")
        else:
            auc_l95_d = _to_exact_decimal(auc_l95)
            if auc_l95_d < Decimal("85"):
                fail_reasons.append("OQ018_FIRST_PHASE_AUC_L95_LT_85PCT_FAIL")

        if auc_pct_d is not None and auc_l95_d is not None and auc_l95_d > auc_pct_d:
            fail_reasons.append("OQ018_FIRST_PHASE_AUC_L95_EXCEEDS_POINT_ESTIMATE_INCONSISTENT")

        if glucagon_pct is None:
            hold_reasons.append("MISSING_OQ018_GLUCAGON_RECOVERY_PCT")
        elif not _is_finite_number(glucagon_pct) or _to_exact_decimal(glucagon_pct) < Decimal("85"):
            fail_reasons.append("OQ018_GLUCAGON_RECOVERY_LT_85PCT_FAIL")

        if necr_cut is None:
            hold_reasons.append("MISSING_H46E03_HYPOXIC_NECROSIS_REDUCTION_PCT")
        elif not _is_finite_number(necr_cut):
            fail_reasons.append("INVALID_H46E03_HYPOXIC_NECROSIS_REDUCTION_PCT")
        else:
            necr_d = _to_exact_decimal(necr_cut)
            if necr_d < ZERO_DEC or necr_d > Decimal("100"):
                fail_reasons.append("INVALID_H46E03_HYPOXIC_NECROSIS_REDUCTION_PCT")
            elif necr_d < Decimal("35"):
                fail_reasons.append("H46E03_HYPOXIC_NECROSIS_REDUCTION_LT_35PCT_FAIL")

        if is_promo:
            rest_ep_type = obs.get("rest_endpoint_type")
            valid_ep_type: Optional[str] = None
            if rest_ep_type is None:
                hold_reasons.append("MISSING_STAGE1_H46E04_REST_ENDPOINT_TYPE")
            elif not _is_literal_nonempty_str(rest_ep_type) or rest_ep_type not in ALLOWED_REST_ENDPOINT_TYPES:
                fail_reasons.append("H46E04_INVALID_REST_ENDPOINT_TYPE")
            else:
                valid_ep_type = rest_ep_type

            rest_col_day = obs.get("rest_collection_day")
            if rest_col_day is None:
                hold_reasons.append("MISSING_STAGE1_H46E04_REST_COLLECTION_DAY")
            elif not _is_finite_number(rest_col_day) or _to_exact_decimal(rest_col_day) <= ZERO_DEC:
                fail_reasons.append("INVALID_H46E04_REST_COLLECTION_DAY")
            elif valid_ep_type == "day7_beta_mass" and _to_exact_decimal(rest_col_day) < Decimal("7"):
                fail_reasons.append("H46E04_COLLECTION_DAY_LT_7_FOR_DAY7_BETA_MASS_FAIL")
            elif valid_ep_type == "day14_stimulated_c_peptide" and _to_exact_decimal(rest_col_day) < Decimal("14"):
                fail_reasons.append("H46E04_COLLECTION_DAY_LT_14_FOR_DAY14_STIMULATED_CPEPTIDE_FAIL")

            ep_rested = obs.get("rest_endpoint_rested_value")
            ep_ctrl = obs.get("rest_endpoint_control_value")
            ep_rested_d: Optional[Decimal] = None
            ep_ctrl_d: Optional[Decimal] = None
            if ep_rested is None:
                hold_reasons.append("MISSING_STAGE1_H46E04_REST_ENDPOINT_RESTED_VALUE")
            elif not _is_finite_number(ep_rested) or _to_exact_decimal(ep_rested) <= ZERO_DEC:
                fail_reasons.append("INVALID_H46E04_REST_ENDPOINT_RESTED_VALUE")
            else:
                ep_rested_d = _to_exact_decimal(ep_rested)
            if ep_ctrl is None:
                hold_reasons.append("MISSING_STAGE1_H46E04_REST_ENDPOINT_CONTROL_VALUE")
            elif not _is_finite_number(ep_ctrl) or _to_exact_decimal(ep_ctrl) <= ZERO_DEC:
                fail_reasons.append("INVALID_H46E04_REST_ENDPOINT_CONTROL_VALUE")
            else:
                ep_ctrl_d = _to_exact_decimal(ep_ctrl)

            # Review #10 / Audit R12-04: Exact Decimal policy check FIRST; also reject float64 display underflow/overflow (e.g. 1e-320 / 1e6)
            if ep_rested_d is not None and ep_ctrl_d is not None:
                if _ratio_lt_dec(ep_rested_d, ep_ctrl_d, Decimal("1.20")):
                    fail_reasons.append("H46E04_DERIVED_ENDPOINT_RATIO_LT_1P20X_FAIL")
                ep_ratio_disp = _dec_div_to_display_float(ep_rested_d, ep_ctrl_d)
                if ep_ratio_disp is not None and math.isfinite(ep_ratio_disp) and ep_ratio_disp > 0.0:
                    derived_rest_endpoint_ratio = ep_ratio_disp
                else:
                    fail_reasons.append("INVALID_H46E04_DERIVED_RATIO_NONFINITE_OR_UNDERFLOW_ZERO")

            d14_fold = obs.get("h46e04_day14_cpeptide_or_mass_fold_ctrl")
            if d14_fold is None:
                hold_reasons.append("MISSING_STAGE1_H46E04_DAY14_EFFICACY_FOLD_CTRL")
            elif not _is_finite_number(d14_fold) or _to_exact_decimal(d14_fold) <= ZERO_DEC:
                fail_reasons.append("INVALID_H46E04_DAY14_FOLD")
            else:
                d14_fold_d = _to_exact_decimal(d14_fold)
                if d14_fold_d < Decimal("1.20"):
                    fail_reasons.append("H46E04_DAY14_EFFICACY_LT_1P20X_DROP_REST_CREDIT")
                if (
                    ep_rested_d is not None
                    and ep_ctrl_d is not None
                    and derived_rest_endpoint_ratio is not None
                    and _dec_rel_diff_exceeds_ratio(d14_fold_d, ep_rested_d, ep_ctrl_d, Decimal("0.01"))
                ):
                    fail_reasons.append("H46E04_CLAIMED_FOLD_CONTRADICTS_DERIVED_MEASURED_RATIO_FAIL")

            zero_delay = obs.get("h46e04_zero_secretory_delay_verified")
            if zero_delay is None:
                hold_reasons.append("MISSING_STAGE1_H46E04_ZERO_SECRETORY_DELAY_BOOL")
            elif not _is_strict_bool(zero_delay):
                fail_reasons.append("INVALID_H46E04_ZERO_SECRETORY_DELAY_BOOL")
            elif not zero_delay:
                fail_reasons.append("H46E04_SECRETORY_DELAY_DETECTED_FAIL")
    else:
        exvivo_agents = obs.get("exvivo_preconditioning_agents")
        if exvivo_agents is None:
            hold_reasons.append("MISSING_EXVIVO_AGENT_MANIFEST")
        elif not isinstance(exvivo_agents, list) or len(exvivo_agents) != 0:
            fail_reasons.append("NONEMPTY_EXVIVO_AGENTS_WHEN_EXVIVO_REST_FALSE")

    return {
        "valid_site": valid_site,
        "valid_scale_mode": valid_scale_mode,
        "envelope_tier": envelope_tier,
        "computed_pitch_um": computed_pitch_um,
        "computed_min_dist_um": computed_min_dist_um,
        "implied_total_loading": implied_total_loading,
        "max_leaf_loading": max_leaf_loading,
        "effective_max_load": effective_max_load,
        "n_leaves_verified": n_leaves_verified,
        "large_animal_pathway": large_animal_pathway,
        "derived_porcine_n": derived_porcine_n,
        "derived_porcine_eligible_visit_n": derived_porcine_eligible_visit_n,
        "derived_porcine_zero_complications": derived_porcine_zero_complications,
        "derived_nhp_n": derived_nhp_n,
        "derived_nhp_eligible_visit_n": derived_nhp_eligible_visit_n,
        "derived_nhp_zero_complications": derived_nhp_zero_complications,
        "derived_nhp_eligible_diabetic_n": derived_nhp_eligible_diabetic_n,
        "derived_nhp_ii": derived_nhp_ii,
        "derived_nhp_cpeptide_extinction_verified_count": derived_nhp_cpeptide_extinction_verified_count,
        "derived_rest_p1_ratio": derived_rest_p1_ratio,
        "derived_rest_p2_ratio": derived_rest_p2_ratio,
        "derived_rest_endpoint_ratio": derived_rest_endpoint_ratio,
    }


def evaluate_gate33_route4_omentum_and_exvivo_rest(
    payload: Dict[str, Any],
    *,
    arm_manifest: Optional[Dict[str, Any]] = None,
    trusted_evidence_store: Optional[Mapping[str, Mapping[str, Any]]] = None,
) -> Dict[str, Any]:
    """
    100% Fail-Closed, Manifest-Linked Gate-35 (provisional IIP-0056 / DEC-137 / GY-034; staged slot IIP-0047, Round-14) Adjudicator.

    Enforces:
      - Cryptographic authentication of caller-supplied arm_manifest (rejecting any mutation).
      - Strict synthetic fixture isolation: ANY SYNTHETIC_FIXTURE record ALWAYS returns
        promotion_authorized=False (decision='SYNTHETIC_SELF_TEST_PASS').
      - Mandatory construct_manifest_sha256 on parent payload & all 4 archived records.
      - Unified v2_round5_unified 14-field upstream & current-assay records in trusted_evidence_store
        with alias-consistency (record_id vs archive_sha256), canonical-body SHA-256 verification,
        collision-free upstream GATE-34 (rejecting live GATE-32 role collision) & current GATE-35
        (rejecting live GATE-33 role collision), prerequisite_archive_sha256s binding inside Gate 34
        (GATE-0V & GATE-5 digests), exact live Blueprint section 7 OQ-012 Gate 5 rules
        (survivor_count_k == 0, clonogenic_fraction_f in (0, 1], spike_in_detection_efficiency_eta in [0.30, 1.0],
        effective_clonogenic_trials_n_eff <= floor(n * f * eta), n_eff >= 299,573,228, and exact 75-digit
        Decimal Clopper-Pearson U95(0, n_eff) <= 1e-8), and rejection of contradictory
        physical_qualification_complete=False / release_authorizing=False / modeled_qualification_only=True flags.
      - Mandatory current_assay_evidence_record (GATE-35) binding & governing ALL current safety,
        physical (including live GY-028 confocal wall clearance >= 7.5 um minimum), per-leaf,
        Stage-1 (DEC-009 0-NHP primate-free primary pathway OR FDA CBER INTERACT/Pre-IND exception NHP cohort
        with decoupled partial-responder paired pre/post-explant C-peptide/LLOQ extinction), and ex-vivo rest
        cutoffs directly from the verified archive.
      - Per-leaf reconciliation BEFORE actual max-leaf steric packing (every leaf + effective_max_load),
        plus scope-bound scale_mode (ANIMAL_PRECLINICAL_SCALE -> STAGE_LIMITED_PRECLINICAL_ONLY with
        promotion_authorized=False; total_implanted_ieq > 100,000 with <2 leaves always fails).
      - End-to-end exact context-independent Decimal comparisons across ALL Gate-35 policy thresholds
        (strict limits, exact-zero limits, inclusive ceilings, lower thresholds, per-leaf & per-subject
        thresholds, exact polynomial steric packing, Gate 5 OQ-012 U95, and Stage-1 chronological bounds;
        ZERO float() conversion before any policy decision; Audit R9-06 / R10-05 / R12-04), with
        zero-division-safe ex-vivo rest ratios and float conversion ONLY for display metadata.
    """
    try:
        return _evaluate_gate33_route4_omentum_and_exvivo_rest_impl(
            payload,
            arm_manifest=arm_manifest,
            trusted_evidence_store=trusted_evidence_store,
        )
    except (DecimalException, OverflowError, ValueError, TypeError) as exc:
        err_code = f"GATE35_NUMERIC_OR_DECIMAL_EVALUATION_ERROR:{type(exc).__name__}"
        return {
            "status": "FAIL",
            "decision": "FAIL_GATE35_ADVERSE_SAFETY_OR_SPEC_VIOLATION",
            "authority_scope": "REJECTED_OR_HELD",
            "promotion_authorized": False,
            "experiment_booking_authorized": False,
            "fail_reasons": [err_code],
            "hold_reasons": [],
            "reasons": [err_code],
        }


def _evaluate_gate33_route4_omentum_and_exvivo_rest_impl(
    payload: Dict[str, Any],
    *,
    arm_manifest: Optional[Dict[str, Any]] = None,
    trusted_evidence_store: Optional[Mapping[str, Mapping[str, Any]]] = None,
) -> Dict[str, Any]:
    """Internal implementation of the fail-closed Gate-35 adjudicator."""
    fail_reasons: List[str] = []
    hold_reasons: List[str] = []

    if not isinstance(payload, dict):
        return {
            "status": "FAIL",
            "decision": "FAIL_GATE35_INVALID_PAYLOAD",
            "promotion_authorized": False,
            "experiment_booking_authorized": False,
            "fail_reasons": ["NON_DICT_PAYLOAD"],
            "hold_reasons": [],
            "reasons": ["NON_DICT_PAYLOAD"],
        }

    manifest, manifest_err = _get_verified_canonical_manifest(arm_manifest)
    if manifest is None or manifest_err is not None:
        err_code = manifest_err or "MUTATED_OR_UNVERIFIED_CALLER_ARM_MANIFEST_REJECTED"
        return {
            "status": "FAIL",
            "decision": "FAIL_GATE35_ADVERSE_SAFETY_OR_SPEC_VIOLATION",
            "promotion_authorized": False,
            "experiment_booking_authorized": False,
            "fail_reasons": [err_code],
            "hold_reasons": [],
            "reasons": [err_code],
        }
    manifest_arms = manifest["arms"]

    # 1. Scope, evidence_tier, lot, bank_id, arm manifest & mandatory parent construct_manifest_sha256 (Review #4)
    scope = payload.get("evaluation_scope")
    if scope is None:
        hold_reasons.append("MISSING_EVALUATION_SCOPE")
        is_promo = True
    elif not _is_literal_nonempty_str(scope) or scope not in ("CLINICAL_PROMOTION", "STAGE0_EXPERIMENT_BOOKING"):
        fail_reasons.append("INVALID_EVALUATION_SCOPE")
        is_promo = True
    else:
        is_promo = (scope == "CLINICAL_PROMOTION")

    evidence_tier = payload.get("evidence_tier")
    valid_evidence_tier: Optional[str] = None
    if evidence_tier is None:
        hold_reasons.append("MISSING_EVIDENCE_TIER")
    elif not _is_literal_nonempty_str(evidence_tier) or evidence_tier not in ALLOWED_EVIDENCE_TIERS:
        fail_reasons.append("INVALID_EVIDENCE_TIER")
    else:
        valid_evidence_tier = evidence_tier

    lot_id = payload.get("lot_id")
    valid_lot_id: Optional[str] = None
    if lot_id is None:
        hold_reasons.append("MISSING_LOT_ID")