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…

    "sterility_pass",
    "mycoplasma_negative",
    "analytical_fasl_ug",
    "hepatocyte_72h_caspase37_u95_fold",
    "hepatocyte_72h_alt_ldh_u95_fold",
    "cuff_leachate_assay_passed",
    "construct_layout",
    "construct_thickness_um",
    "cluster_min_diam_um",
    "cluster_d_rms3_um",
    "cluster_d_p95_um",
    "cluster_max_diam_um",
    "staggered_bilayer_plane_offset_um",
    "bilateral_vascular_perfusion_verified",
    "back_to_back_unperfused_stacking",
    "scale_mode",
    "total_implanted_ieq",
    "total_loaded_area_cm2",
    "per_leaf_records",
    "bed_face_bot_po2_mmhg",
    "bed_face_top_po2_mmhg",
    "measured_fibrin_capsule_um",
    "measured_worst_face_o2_mmhg",
    "measured_worst_core_o2_mmhg",
    "measured_lot_ocr_mult",
    "route_specific_clean_t50_min",
    "route_specific_fibrin_t50_min",
    "route_specific_gsis_si",
    "invivo_diazoxide_depot_or_credit_claimed",
    "r3p06_5day_glycemic_clamp_enabled",
    "exvivo_rest_applied",
    "exvivo_preconditioning_agents",
)
CURRENT_ASSAY_STAGE1_OMENTUM_BOUND_FIELDS: Tuple[str, ...] = (
    "porcine_r4o04_zero_bowel_obstruction_torsion_grade3_adhesions",
    "porcine_subjects",
    "porcine_portal_peripheral_insulin_gradient",
    "nhp_r4o05_portal_peripheral_insulin_gradient",
    "nhp_r4o05_post_omentectomy_cpeptide_extinction",
)
CURRENT_ASSAY_STAGE1_COMMON_BOUND_FIELDS: Tuple[str, ...] = (
    "dec009_primate_free_pathway",
    "dec009_fda_cber_nhp_exception_authorized",
    "dec009_pillar1_humanized_mouse_efficacy_pass",
    "dec009_pillar2_chandler_loop_50donor_pass",
    "dec009_pillar1_glp_biodistribution_erasure_pass",
    "dec009_post_explant_cpeptide_extinction_verified",
    "nhp_subjects",
)
CURRENT_ASSAY_EXVIVO_REST_STAGE0_BOUND_FIELDS: Tuple[str, ...] = (
    "exvivo_diazoxide_uM",
    "exvivo_tudca_uM",
    "exvivo_preconditioning_hours",
    "h46e01_fccp_max_reserve_pct_ctrl",
    "washout_cycles_n",
    "lcms_supernatant_diazoxide_uM",
    "lcms_pellet_diazoxide_uM",
    "rest_assay_lot_id",
    "rest_challenge_o2_pct",
    "rest_two_pulse_gsis_verified",
    "rest_pulse1_si_rested",
    "rest_pulse1_si_control",
    "rest_pulse2_si_rested",
    "rest_pulse2_si_control",
    "oq018_post_washout_t50_min",
    "oq018_post_washout_t50_fold_ctrl",
    "oq018_post_washout_gsis_si",
    "oq018_post_washout_first_phase_auc_pct_ctrl",
    "oq018_post_washout_first_phase_auc_l95_pct_ctrl",
    "oq018_post_washout_glucagon_pct_ctrl",
    "h46e03_paired_hypoxic_necrosis_reduction_pct",
)
CURRENT_ASSAY_EXVIVO_REST_STAGE1_BOUND_FIELDS: Tuple[str, ...] = (
    "rest_endpoint_type",
    "rest_collection_day",
    "rest_endpoint_rested_value",
    "rest_endpoint_control_value",
    "h46e04_day14_cpeptide_or_mass_fold_ctrl",
    "h46e04_zero_secretory_delay_verified",
)

_CACHED_CANONICAL_MANIFEST: Optional[Dict[str, Any]] = None


def _get_verified_canonical_manifest(arm_manifest: Optional[Dict[str, Any]] = None) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
    """Return authenticated canonical manifest; REJECT any mutated caller-supplied manifest dict."""
    global _CACHED_CANONICAL_MANIFEST
    if arm_manifest is not None:
        if not isinstance(arm_manifest, dict):
            return None, "MUTATED_OR_UNVERIFIED_CALLER_ARM_MANIFEST_REJECTED"
        try:
            caller_sha = _canonical_json_sha256(arm_manifest)
        except (TypeError, ValueError, OverflowError, DecimalException):
            return None, "MUTATED_OR_UNVERIFIED_CALLER_ARM_MANIFEST_REJECTED"
        if caller_sha != EXPECTED_CANONICAL_MANIFEST_CANONICAL_JSON_SHA256:
            return None, "MUTATED_OR_UNVERIFIED_CALLER_ARM_MANIFEST_REJECTED"
        return arm_manifest, None
    if _CACHED_CANONICAL_MANIFEST is None:
        loaded = load_and_verify_canonical_contracts()
        _CACHED_CANONICAL_MANIFEST = loaded["manifest"]
    return _CACHED_CANONICAL_MANIFEST, None


def _is_fasl_or_cd95_token(token: str) -> bool:
    low = token.lower()
    return ("fasl" in low) or ("cd95" in low) or ("apo010" in low) or ("fas_l" in low) or ("fas-l" in low)


def _fixture_construct_manifest_sha256(arm_key: str, product_id: str) -> str:
    """Deterministic non-zero 64-hex lot construct FASTA digest, strictly distinct from arm manifest digest."""
    return sha256_bytes(f"OPENISLET_WAVE6_R5_FIXTURE_CONSTRUCT_FASTA:{arm_key}:{product_id}".encode("utf-8"))


def seal_upstream_evidence_record(record_body: Dict[str, Any]) -> Dict[str, Any]:
    """Compute canonical archive_sha256 over all fields except archive_sha256 (for trusted store fixtures)."""
    body_no_sha = {k: v for k, v in record_body.items() if k != "archive_sha256"}
    return {**body_no_sha, "archive_sha256": _canonical_json_sha256(body_no_sha)}


def _check_no_contradictory_authority_flags(
    rec: Mapping[str, Any],
    prefix: str,
    fail_reasons: List[str],
) -> None:
    """Reject contradictory physical/release/modeled authority flags on any upstream or current record (Audit R4-01)."""
    if "physical_qualification_complete" in rec:
        pqc = rec["physical_qualification_complete"]
        if not _is_strict_bool(pqc) or pqc is False:
            fail_reasons.append(f"{prefix}_PHYSICAL_QUALIFICATION_INCOMPLETE_REJECTED")
    if "release_authorizing" in rec:
        ra = rec["release_authorizing"]
        if not _is_strict_bool(ra) or ra is False:
            fail_reasons.append(f"{prefix}_RELEASE_AUTHORIZING_FALSE_REJECTED")
    if "modeled_qualification_only" in rec:
        mqo = rec["modeled_qualification_only"]
        if not _is_strict_bool(mqo) or mqo is True:
            fail_reasons.append(f"{prefix}_MODELED_QUALIFICATION_ONLY_REJECTED")
    if "qualification_scope" in rec:
        qs = rec["qualification_scope"]
        if not _is_literal_nonempty_str(qs):
            fail_reasons.append(f"{prefix}_MODELED_OR_PENDING_QUALIFICATION_SCOPE_REJECTED")
        else:
            qlow = qs.lower()
            if any(tok in qlow for tok in ("modeled", "pending", "bank_only", "synthetic")):
                fail_reasons.append(f"{prefix}_MODELED_OR_PENDING_QUALIFICATION_SCOPE_REJECTED")


def _resolve_store_entry_with_alias_consistency(
    *,
    rec: Mapping[str, Any],
    record_id: str,
    rec_archive_sha: str,
    prefix: str,
    trusted_evidence_store: Mapping[str, Mapping[str, Any]],
    fail_reasons: List[str],
) -> Optional[Dict[str, Any]]:
    """Resolve record from trusted_evidence_store enforcing alias consistency (Review #5) & full-body SHA-256."""
    has_id = isinstance(record_id, str) and record_id in trusted_evidence_store
    has_sha = isinstance(rec_archive_sha, str) and rec_archive_sha in trusted_evidence_store
    if not has_id and not has_sha:
        fail_reasons.append(f"{prefix}_RECORD_NOT_FOUND_IN_TRUSTED_STORE")
        return None

    stored_by_id = trusted_evidence_store[record_id] if has_id else None
    stored_by_sha = trusted_evidence_store[rec_archive_sha] if has_sha else None

    if has_id and has_sha:
        if not isinstance(stored_by_id, Mapping) or not isinstance(stored_by_sha, Mapping):
            fail_reasons.append(f"{prefix}_CONFLICTING_STORE_INDEX_ALIASES")
            return None
        try:
            canon_by_id = canonical_json_dumps(dict(stored_by_id))
            canon_by_sha = canonical_json_dumps(dict(stored_by_sha))
        except (TypeError, ValueError, OverflowError, DecimalException):
            fail_reasons.append(f"{prefix}_CONFLICTING_STORE_INDEX_ALIASES")
            return None
        if canon_by_id != canon_by_sha:
            fail_reasons.append(f"{prefix}_CONFLICTING_STORE_INDEX_ALIASES")
            return None

    stored = stored_by_id if has_id else stored_by_sha
    if not isinstance(stored, Mapping):
        fail_reasons.append(f"{prefix}_TRUSTED_STORE_ENTRY_MALFORMED")
        return None

    stored_dict = dict(stored)
    stored_sha = stored_dict.get("archive_sha256")
    if not _is_non_all_zero_sha256_hex(stored_sha) or stored_sha != rec_archive_sha:
        fail_reasons.append(f"{prefix}_TRUSTED_ARCHIVE_DIGEST_MISMATCH")
        return stored_dict

    try:
        recomputed_stored_sha = _canonical_json_sha256({k: v for k, v in stored_dict.items() if k != "archive_sha256"})
    except (TypeError, ValueError, OverflowError, DecimalException):
        fail_reasons.append(f"{prefix}_TRUSTED_STORE_UNSERIALIZABLE")
        return stored_dict
    if recomputed_stored_sha != stored_sha:
        fail_reasons.append(f"{prefix}_TRUSTED_ARCHIVE_BODY_TAMPERED")
        return stored_dict

    try:
        recomputed_rec_sha = _canonical_json_sha256({k: v for k, v in rec.items() if k != "archive_sha256"})
        stored_canon = canonical_json_dumps(stored_dict)
        rec_canon = canonical_json_dumps(dict(rec))
    except (TypeError, ValueError, OverflowError, DecimalException):
        fail_reasons.append(f"{prefix}_SUBMITTED_BODY_UNSERIALIZABLE")
        return stored_dict

    if recomputed_rec_sha != rec_archive_sha:
        fail_reasons.append(f"{prefix}_SUBMITTED_BODY_DIGEST_MISMATCH")
    if stored_canon != rec_canon:
        fail_reasons.append(f"{prefix}_TRUSTED_STORE_FULL_BODY_MISMATCH")

    return stored_dict


def _check_retrieval_residual_reconciliation(
    *,
    prefix: str,
    retrieval_mass_pct: Any,
    total_implanted_cells: Any,
    residual_viable_cells_measured: Any,
    residual_sampling_fraction: Any,
    require_ge_99p9: bool,
    fail_reasons: List[str],
) -> bool:
    """Validate retrieval mass %, residual viable cells, >=1% sampling denominator & reconciliation in exact Decimal (Audit F5 / R4-04 / R12-04)."""
    ok = True
    any_missing = False
    r_pct_d: Optional[Decimal] = None
    n_imp_d: Optional[Decimal] = None
    n_res_d: Optional[Decimal] = None
    f_samp_d: Optional[Decimal] = None

    if retrieval_mass_pct is None:
        any_missing = True
    elif not _is_finite_number(retrieval_mass_pct):
        fail_reasons.append(f"INVALID_{prefix}_RETRIEVAL_MASS_PCT")
        ok = False
    else:
        r_pct_d = _to_exact_decimal(retrieval_mass_pct)
        if r_pct_d < ZERO_DEC or r_pct_d > Decimal("100"):
            fail_reasons.append(f"INVALID_{prefix}_RETRIEVAL_MASS_PCT")
            ok = False
        elif require_ge_99p9 and r_pct_d < Decimal("99.9"):
            fail_reasons.append(f"{prefix}_ENBLOC_MASS_RETRIEVAL_LT_99P9PCT_FAIL")
            ok = False

    if total_implanted_cells is None:
        any_missing = True