OpenIslet

scripts/verify_iip0042_master_multilayer_portfolio_crosswalk.py

IIP-0042 / DEC-121 (CAND-033 / EXP-030): Master Exact 2^20 Multi-Layer Portfolio

script Release v0.8.0 gen-eb955f8266035aba 881 KB · 63 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_iip0042_master_multilayer_portfolio_crosswalk.py · SHA-256: 16964a158458b5cf…

        "independence_evidence_record_id",
        "independent_experimental_unit",
        "predeclared_per_donor_unit_count_n",
        "clustering_controls",
    })

    if not isinstance(donors_raw, list) or len(donors_raw) == 0:
        _escalate("HOLD_INVALID_OR_MISSING_INPUT", "Missing typed tcell_blockade_and_apc_cytotoxicity_donors list (>= 3 distinct donors required)")
    else:
        # Pass 1 (R08 B3 + R10 B1 + R12 0037-B2): Collect ALL raw canonical submitted donor IDs & malformed rows BEFORE
        # deduplication/quarantine filtering, and enforce roster membership & overlap on the COMPLETE raw set!
        donor_id_counts: dict[str, int] = {}
        for d in donors_raw:
            if not isinstance(d, dict):
                malformed_donor_rows_present = True
                continue
            did = d.get("donor_id")
            if type(did) is not str or not did.strip():
                malformed_donor_rows_present = True
                continue
            did_p = did.strip()
            raw_submitted_donor_ids.add(did_p)
            donor_id_counts[did_p] = donor_id_counts.get(did_p, 0) + 1
            if did != did_p or not _SHIELD_STRICT_ID_RE.match(did):
                malformed_donor_rows_present = True

        # Roster-integrity checks run on ALL raw submitted donor IDs BEFORE deduplication (R10 B1!)
        for raw_did_c in sorted(raw_submitted_donor_ids):
            if roster_verified and raw_did_c not in roster_set:
                unrostered_submitted_donors.add(raw_did_c)
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{raw_did_c}]: unrostered ad-hoc donor_id not present in preregistered_donor_family_roster; "
                    f"rejected fail-closed",
                )
            if raw_did_c in valid_excluded_donor_ids or raw_did_c in raw_excluded_donor_ids:
                excluded_overlap_donors.add(raw_did_c)
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{raw_did_c}]: donor appears in BOTH submitted records and excluded_donor_records; rejected fail-closed",
                )
        for raw_ex_did in sorted(raw_excluded_donor_ids):
            if roster_verified and raw_ex_did not in roster_set:
                unrostered_submitted_donors.add(raw_ex_did)

        conflicted_donors = {k for k, cnt in donor_id_counts.items() if cnt > 1}
        for cdid in sorted(conflicted_donors):
            donors_with_invalid_topology.add(cdid)
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"Duplicate/conflicting donor_id in functional cohort: {cdid!r} (count={donor_id_counts[cdid]}); "
                f"all occurrences excluded from biological adjudication and batch-linkage credit",
            )
            invalid_donors_excluded.append(cdid)

        # Pass 1b (R12 0037-B2): Extract EVERY submitted donor's batch/run dependency links into Union-Find
        # topology maps INDEPENDENTLY OF AND BEFORE per-donor outcome/CI/GY-018 validation!
        for d in donors_raw:
            if not isinstance(d, dict):
                continue
            did = d.get("donor_id")
            if type(did) is not str or not did.strip():
                continue
            did_t = did.strip()
            raw_run_t = d.get("assay_run_id")
            if (
                type(raw_run_t) is str
                and raw_run_t
                and raw_run_t == raw_run_t.strip()
                and _SHIELD_STRICT_ID_RE.match(raw_run_t)
            ):
                topology_donor_runs.setdefault(did_t, set()).add(raw_run_t)
            else:
                donors_with_invalid_topology.add(did_t)
                if type(raw_run_t) is str and raw_run_t.strip():
                    topology_donor_runs.setdefault(did_t, set()).add(raw_run_t.strip())
            raw_bids_t = d.get("expression_batch_ids")
            if isinstance(raw_bids_t, list) and len(raw_bids_t) > 0:
                seen_tb: set[str] = set()
                tb_ok = True
                for b_item in raw_bids_t:
                    if type(b_item) is str and b_item.strip():
                        b_norm = b_item.strip()
                        topology_donor_batches.setdefault(did_t, set()).add(b_norm)
                        if b_item != b_norm or b_norm in seen_tb:
                            tb_ok = False
                        seen_tb.add(b_norm)
                    else:
                        tb_ok = False
                if not tb_ok or not seen_tb:
                    donors_with_invalid_topology.add(did_t)
            else:
                donors_with_invalid_topology.add(did_t)

        # Pass 1c (R16 Shared Blocker #1): Reconcile the fixed-horizon predeclared per-donor sample size N
        # commitment across ALL raw submitted rostered donor rows BEFORE the duplicate-donor exclusion gate!
        # Any raw rostered row whose unit counts violate roster_predeclared_n_by_donor[did] (in ANY row order,
        # e.g. [60, 70] or [70, 60] on a conflicted duplicate donor) populates roster_sample_size_plan_mismatched_donors
        # and sets authorization_grade_fwer_bound_valid = False, withholding donor-cohort authorization while
        # preserving zero biological credit for duplicate rows, avoiding false N-mismatches on matching-count
        # duplicates ([60, 60]), and preserving fail-first independent qualified SPR FAIL!
        if roster_verified:
            for idx_n, d_n in enumerate(donors_raw):
                if not isinstance(d_n, dict):
                    continue
                did_raw_n = d_n.get("donor_id")
                if type(did_raw_n) is not str or not did_raw_n.strip():
                    continue
                did_n = did_raw_n.strip()
                if did_n not in roster_predeclared_n_by_donor:
                    continue
                committed_n = roster_predeclared_n_by_donor[did_n]
                has_raw_u_n = "raw_independent_units_n" in d_n and d_n["raw_independent_units_n"] is not None
                has_raw_alias_n = "cytotoxicity_n_raw_units" in d_n and d_n["cytotoxicity_n_raw_units"] is not None
                raw_u_primary_n: int | None = None
                raw_u_alias_n: int | None = None
                if has_raw_u_n:
                    raw_u_primary_n, _ = _shield_check_strict_int(
                        d_n["raw_independent_units_n"], f"donors[{idx_n}].raw_independent_units_n", min_val=1
                    )
                if has_raw_alias_n:
                    raw_u_alias_n, _ = _shield_check_strict_int(
                        d_n["cytotoxicity_n_raw_units"], f"donors[{idx_n}].cytotoxicity_n_raw_units", min_val=1
                    )
                raw_u_ok = (
                    (has_raw_u_n or has_raw_alias_n)
                    and (not has_raw_u_n or raw_u_primary_n == committed_n)
                    and (not has_raw_alias_n or raw_u_alias_n == committed_n)
                )
                n_eff_n, _ = _shield_check_strict_int(
                    d_n.get("apc_cytotoxicity_n_eff"), f"donors[{idx_n}].apc_cytotoxicity_n_eff", min_val=1
                )
                gy_n = d_n.get("gy018_independence_justification")
                pd_n_raw: int | None = None
                if isinstance(gy_n, dict):
                    pd_n_raw, _ = _shield_check_strict_int(
                        gy_n.get("predeclared_per_donor_unit_count_n"),
                        f"donors[{idx_n}].gy018_independence_justification.predeclared_per_donor_unit_count_n",
                        min_val=_SHIELD_MIN_CYTO_N_EFF_PER_DONOR,
                    )
                if not raw_u_ok or n_eff_n != committed_n or pd_n_raw != committed_n:
                    roster_sample_size_plan_mismatched_donors.add(did_n)
                    _escalate(
                        "HOLD_INVALID_OR_MISSING_INPUT",
                        f"donor[{did_n}] (row[{idx_n}]): submitted cytotoxicity sample size "
                        f"(raw_independent_units_n={raw_u_primary_n if has_raw_u_n else raw_u_alias_n}, "
                        f"apc_cytotoxicity_n_eff={n_eff_n}, gy018.predeclared_per_donor_unit_count_n={pd_n_raw}) "
                        f"violates hash-pinned preregistered_donor_family_roster fixed-horizon commitment "
                        f"N={committed_n} (unauthorized post-readout or interim sample-size change invalidates "
                        f"fixed-horizon Bonferroni FWER <= 0.05)",
                    )

        # Pass 2: Validate each non-conflicted donor record (T1D eligibility, assay_run_id, suppression assay acceptance range, GY-018 evidence!)
        for idx, d in enumerate(donors_raw):
            if not isinstance(d, dict):
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"donors[{idx}] must be an object")
                continue
            did = d.get("donor_id")
            if type(did) is not str or not did.strip():
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"donors[{idx}] missing non-empty donor_id")
                continue
            did_c = did.strip()
            seen_donors.add(did_c)
            if did_c in conflicted_donors:
                continue

            donor_valid = True
            if did != did_c or not _SHIELD_STRICT_ID_RE.match(did):
                donor_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donors[{idx}].donor_id={did!r} must be an unpadded canonical ID matching {_SHIELD_STRICT_ID_RE.pattern}",
                )
            if did_c in unrostered_submitted_donors or did_c in excluded_overlap_donors:
                donor_valid = False

            # R08 B5: Mandatory typed T1D donor eligibility verification (excluded from PASS and bio FAIL if invalid!)
            if d.get("t1d_diagnosis_confirmed") is not True:
                donor_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{did_c}]: mandatory t1d_diagnosis_confirmed must be literal boolean True "
                    f"(got {d.get('t1d_diagnosis_confirmed')!r})",
                )
            cohort_raw = d.get("donor_clinical_cohort")
            if type(cohort_raw) is not str or cohort_raw != _SHIELD_REQUIRED_DONOR_CLINICAL_COHORT:
                donor_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{did_c}]: mandatory donor_clinical_cohort must equal "
                    f"{_SHIELD_REQUIRED_DONOR_CLINICAL_COHORT!r} (got {cohort_raw!r})",
                )
            prequal_raw = d.get("t1d_prequalification_ref")
            if type(prequal_raw) is not str or not prequal_raw or prequal_raw != prequal_raw.strip():
                donor_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{did_c}]: mandatory t1d_prequalification_ref must be a non-empty unpadded string "
                    f"(got {prequal_raw!r})",
                )
            if _SHIELD_FORBIDDEN_NON_T1D_DONOR_RE.search(did_c):
                donor_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{did_c}]: contradictory non-T1D donor_id rejected fail-closed regardless of boolean flags",
                )
            if type(prequal_raw) is str and _SHIELD_FORBIDDEN_NON_T1D_DONOR_RE.search(prequal_raw):
                donor_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{did_c}]: contradictory non-T1D t1d_prequalification_ref={prequal_raw!r} rejected fail-closed",
                )

            raw_assay_run = d.get("assay_run_id")
            assay_run_c: str | None = None
            if (
                type(raw_assay_run) is not str
                or not raw_assay_run
                or raw_assay_run != raw_assay_run.strip()
                or not _SHIELD_STRICT_ID_RE.match(raw_assay_run)
            ):
                donor_valid = False
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"donor[{did_c}]: mandatory assay_run_id must be a non-empty unpadded ID matching "
                    f"{_SHIELD_STRICT_ID_RE.pattern} (got {raw_assay_run!r})",
                )
            else:
                assay_run_c = raw_assay_run

            tmp_ref_d: set[str] = set()
            tmp_ck1_d: set[str] = set()
            tmp_ck2_d: set[str] = set()
            b_err = _shield_validate_batch_ids(
                d.get("expression_batch_ids"),
                f"donor[{did_c}]",
                passing_batch_constructs,
                tmp_ref_d,
                require_cocktail_both_leads=True,
                role_comp1_batches=tmp_ck1_d,
                role_comp2_batches=tmp_ck2_d,
            )
            raw_mix_id = d.get("cocktail_mixture_id")
            if b_err is not None:
                donor_valid = False
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", b_err)
            if (
                type(raw_mix_id) is not str
                or not raw_mix_id
                or raw_mix_id != raw_mix_id.strip()