OpenIslet

scripts/verify_iip0057_foundry_v2_shield_invvax_insl82i_cuffv2.py

W6-C3 (Provisional Next-Free IIP-0057 / DEC-138 / GATE-36 / GY-035; staging slot iip0057,

script Release v0.8.0 gen-eb955f8266035aba 412 KB · 32 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_iip0057_foundry_v2_shield_invvax_insl82i_cuffv2.py · SHA-256: 1c63dcf649c42be4…

        fail_reasons.append(f"{tag}_CROSS_LOT_MISMATCH:{parsed['lot_id']}!={parent_id['lot_id']}")
        integrity_ok = False
    if parent_id["bank_id"] is not None and "bank_id" in parsed and parsed["bank_id"] != parent_id["bank_id"]:
        fail_reasons.append(f"{tag}_CROSS_BANK_MISMATCH:{parsed['bank_id']}!={parent_id['bank_id']}")
        integrity_ok = False
    if parent_id["bank_origin"] is not None and "bank_origin" in parsed and parsed["bank_origin"] != parent_id["bank_origin"]:
        fail_reasons.append(f"{tag}_PARENT_BANK_ORIGIN_MISMATCH:{parsed['bank_origin']}!={parent_id['bank_origin']}")
        integrity_ok = False

    if _check_authority_tuple_coherence(
        parsed,
        tag=tag,
        allowed_auth_decisions=allowed_auth_decisions,
        fail_reasons=fail_reasons,
        allow_partial_hold_decisions=allow_partial_hold_decisions,
    ):
        integrity_ok = False

    return (parsed if all_present else None), (integrity_ok and all_present)


def _lookup_and_verify_store_record(
    trusted_evidence_store: Any,
    *,
    field_name: str,
    rec_raw: dict[str, Any],
    parsed: dict[str, Any],
    expected_gate_source: str,
    allowed_auth_decisions: frozenset[str],
    allow_partial_hold_decisions: frozenset[str] = frozenset(),
) -> tuple[str | None, list[str], bool, list[str]]:
    """Resolve record by record_id and/or archive_sha256 in trusted_evidence_store with alias-consistency & full-body SHA-256 verification (Review #5 / Audit R4-01 / Audit R10-03 / Round-14 live GATE-32).

    Returns (status, all_errs, store_integrity_ok, integrity_errs).
    `store_integrity_ok` is True iff the stored archive entry resolves cleanly without index alias conflict,
    corrupt non-dict payload, body/digest mismatch, field mismatch, or contradictory producer flags.
    """
    if not isinstance(trusted_evidence_store, dict):
        return "HOLD_UNRESOLVED", [f"UNRESOLVED_IN_TRUSTED_EVIDENCE_STORE:{field_name}"], False, []

    rid = parsed["record_id"]
    asha = parsed["archive_sha256"]
    has_rid = rid in trusted_evidence_store
    has_sha = asha in trusted_evidence_store
    if not has_rid and not has_sha:
        return "HOLD_UNRESOLVED", [f"UNRESOLVED_IN_TRUSTED_EVIDENCE_STORE:{field_name}"], False, []

    integrity_errs: list[str] = []
    release_errs: list[str] = []
    if has_rid and has_sha:
        stored_by_id = trusted_evidence_store[rid]
        stored_by_sha = trusted_evidence_store[asha]
        if not isinstance(stored_by_id, dict) or not isinstance(stored_by_sha, dict):
            corrupt_errs = [
                f"CONFLICTING_TRUSTED_STORE_INDEX_ALIASES:{field_name}",
                f"TRUSTED_EVIDENCE_STORE_ENTRY_NOT_DICT:{field_name}",
            ]
            return "FAIL_CORRUPT", corrupt_errs, False, corrupt_errs
        check_strictly_finite(stored_by_id, f"store[{field_name}:rid]")
        check_strictly_finite(stored_by_sha, f"store[{field_name}:sha]")
        j_id = json.dumps(stored_by_id, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False)
        j_sha = json.dumps(stored_by_sha, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False)
        if stored_by_id != stored_by_sha or j_id != j_sha:
            alias_errs = [f"CONFLICTING_TRUSTED_STORE_INDEX_ALIASES:{field_name}"]
            return "FAIL_MISMATCH", alias_errs, False, alias_errs
        stored = stored_by_id
    else:
        stored = trusted_evidence_store[rid] if has_rid else trusted_evidence_store[asha]

    if not isinstance(stored, dict):
        nd_errs = [f"TRUSTED_EVIDENCE_STORE_ENTRY_NOT_DICT:{field_name}"]
        return "FAIL_CORRUPT", nd_errs, False, nd_errs
    check_strictly_finite(stored, f"store[{field_name}]")

    stored_sha = stored.get("archive_sha256")
    if not _is_valid_nonzero_sha256(stored_sha):
        integrity_errs.append(f"TRUSTED_EVIDENCE_STORE_INVALID_ARCHIVE_SHA256:{field_name}")
    else:
        recomp_stored = compute_canonical_record_sha256(stored)
        if recomp_stored != stored_sha:
            integrity_errs.append(f"TRUSTED_EVIDENCE_STORE_BODY_DIGEST_MISMATCH:{field_name}")
        if recomp_stored != asha:
            integrity_errs.append(f"TRUSTED_EVIDENCE_STORE_ARCHIVE_SHA256_MISMATCH:{field_name}")

    for fld in UPSTREAM_EVIDENCE_REQUIRED_FIELDS:
        sval = stored.get(fld)
        pval = parsed[fld]
        if type(sval) is not type(pval) or sval != pval:
            integrity_errs.append(f"TRUSTED_EVIDENCE_STORE_MISMATCH:{field_name}.{fld}")

    stored_canon = json.dumps(stored, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False)
    rec_canon = json.dumps(rec_raw, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False)
    if stored_canon != rec_canon:
        integrity_errs.append(f"TRUSTED_EVIDENCE_STORE_FULL_BODY_MISMATCH:{field_name}")

    _check_contradictory_producer_flags(
        stored,
        tag=f"TRUSTED_EVIDENCE_STORE_{field_name.upper()}",
        field_name=f"store[{field_name}]",
        evidence_tier=stored.get("evidence_tier") if isinstance(stored.get("evidence_tier"), str) else None,
        fail_reasons=integrity_errs,
    )

    if stored.get("evidence_tier") != "AUTHENTICATED_ARCHIVED_WETLAB":
        integrity_errs.append(f"TRUSTED_EVIDENCE_STORE_TIER_NOT_AUTHENTICATED_WETLAB:{field_name}")
    if stored.get("gate_source") != expected_gate_source:
        if (
            field_name == "upstream_lot_evidence_record"
            and stored.get("gate_source") == CANONICAL_LIVE_GATE32_DEBRIS_RECALL_SOURCE
        ):
            integrity_errs.append(f"TRUSTED_EVIDENCE_STORE_LIVE_GATE32_ROLE_COLLISION_REJECTED:{field_name}")
        integrity_errs.append(f"TRUSTED_EVIDENCE_STORE_GATE_SOURCE_MISMATCH:{field_name}")
    if stored.get("canonical_arm_manifest_sha256") != EXPECTED_ARM_MANIFEST_SHA256:
        integrity_errs.append(f"TRUSTED_EVIDENCE_STORE_ARM_MANIFEST_MISMATCH:{field_name}")
    if "archived_payload_bytes_sha256" in stored and stored["archived_payload_bytes_sha256"] != asha:
        integrity_errs.append(f"TRUSTED_EVIDENCE_STORE_PAYLOAD_DIGEST_MISMATCH:{field_name}")

    is_stored_partial_hold = (
        stored.get("decision") in allow_partial_hold_decisions
        and stored.get("authority_scope") == "REJECTED_OR_HELD"
        and stored.get("bank_qualified") is False
        and stored.get("promotion_authorized") is False
    )
    if not is_stored_partial_hold:
        if stored.get("decision") not in allowed_auth_decisions:
            release_errs.append(f"TRUSTED_EVIDENCE_STORE_DECISION_NOT_AUTHORIZED:{field_name}")
        if stored.get("authority_scope") != "CLINICAL_LOT_RELEASE":
            release_errs.append(f"TRUSTED_EVIDENCE_STORE_AUTHORITY_SCOPE_NOT_CLINICAL_LOT_RELEASE:{field_name}")
        if stored.get("bank_qualified") is not True:
            release_errs.append(f"TRUSTED_EVIDENCE_STORE_BANK_NOT_QUALIFIED:{field_name}")
        if stored.get("promotion_authorized") is not True:
            release_errs.append(f"TRUSTED_EVIDENCE_STORE_PROMOTION_NOT_AUTHORIZED:{field_name}")

    all_errs = integrity_errs + release_errs
    store_integrity_ok = len(integrity_errs) == 0
    if all_errs:
        return "FAIL_MISMATCH", all_errs, store_integrity_ok, integrity_errs
    if is_stored_partial_hold:
        return "HOLD_PARTIAL_COVERAGE", [], True, []
    return None, [], True, []


def _evaluate_live_gate32_debris_recall_fields(
    g32_raw: dict[str, Any],
    *,
    parsed_g32: dict[str, Any] | None,
    fail_reasons: list[str],
    missing_fields: list[str],
    hold_reasons: list[str],
) -> None:
    """Enforce live GATE-32 (DEC-130 / GY-010) whole-islet-debris recall thresholds directly on the archived record."""
    pfx = "live_gate32_debris_recall_record."
    rec_tier = parsed_g32.get("evidence_tier") if parsed_g32 is not None else None
    rec_dec = parsed_g32.get("decision") if parsed_g32 is not None else None

    if "debris_recall_verdict" not in g32_raw or g32_raw["debris_recall_verdict"] is None:
        missing_fields.append(f"{pfx}debris_recall_verdict")
        verdict_val: str | None = None
    else:
        verdict_val = _require_nonempty_str(g32_raw["debris_recall_verdict"], f"{pfx}debris_recall_verdict")

    is_coherent_partial_hold = False
    if verdict_val is not None:
        if rec_tier == "AUTHENTICATED_ARCHIVED_WETLAB":
            if rec_dec in ALLOWED_LIVE_GATE32_DEBRIS_PARTIAL_HOLD_DECISIONS:
                if verdict_val != rec_dec:
                    fail_reasons.append(f"LIVE_GATE32_VERDICT_DECISION_MISMATCH:{verdict_val}!={rec_dec}")
                elif (
                    parsed_g32 is not None
                    and parsed_g32.get("authority_scope") == "REJECTED_OR_HELD"
                    and parsed_g32.get("bank_qualified") is False
                    and parsed_g32.get("promotion_authorized") is False
                ):
                    is_coherent_partial_hold = True
                    hold_reasons.append("HOLD_LIVE_GATE32_PARTIAL_EPITOPE_COVERAGE_GRADED_CAP")
            elif verdict_val in ALLOWED_LIVE_GATE32_DEBRIS_PARTIAL_HOLD_DECISIONS:
                if rec_dec in ALLOWED_LIVE_GATE32_DEBRIS_FULL_CREDIT_DECISIONS:
                    fail_reasons.append(f"LIVE_GATE32_VERDICT_DECISION_MISMATCH:{verdict_val}!={rec_dec}")
                else:
                    hold_reasons.append("HOLD_LIVE_GATE32_PARTIAL_EPITOPE_COVERAGE_GRADED_CAP")
            elif verdict_val != "PASS_DEBRIS_RECALL_FULL_CREDIT":
                fail_reasons.append(f"LIVE_GATE32_DEBRIS_RECALL_VERDICT_FAIL:{verdict_val}")
        else:
            if verdict_val in ALLOWED_LIVE_GATE32_DEBRIS_PARTIAL_HOLD_DECISIONS:
                is_coherent_partial_hold = True
                hold_reasons.append("HOLD_LIVE_GATE32_PARTIAL_EPITOPE_COVERAGE_GRADED_CAP")
            elif verdict_val != "PASS_DEBRIS_RECALL_FULL_CREDIT":
                fail_reasons.append(f"LIVE_GATE32_DEBRIS_RECALL_VERDICT_FAIL:{verdict_val}")

    if "debris_recall_l95_suppressed_frac" not in g32_raw or g32_raw["debris_recall_l95_suppressed_frac"] is None:
        missing_fields.append(f"{pfx}debris_recall_l95_suppressed_frac")
        l95_val: float | None = None
    else:
        l95_val = _require_bounded_float(
            g32_raw["debris_recall_l95_suppressed_frac"], f"{pfx}debris_recall_l95_suppressed_frac", lo=0.0, hi=1.0
        )
    if l95_val is not None and l95_val < LIVE_GATE32_MIN_L95_SUPPRESSED_FRAC:
        if is_coherent_partial_hold:
            hold_reasons.append(f"HOLD_LIVE_GATE32_DEBRIS_RECALL_L95_BELOW_0P70:{l95_val!r}")
        else:
            fail_reasons.append(f"LIVE_GATE32_DEBRIS_RECALL_L95_BELOW_0P70_FAIL:{l95_val!r}")

    if "residual_class2_recall_u95_frac" not in g32_raw or g32_raw["residual_class2_recall_u95_frac"] is None:
        missing_fields.append(f"{pfx}residual_class2_recall_u95_frac")
        res_val: float | None = None
    else:
        res_val = _require_bounded_float(
            g32_raw["residual_class2_recall_u95_frac"], f"{pfx}residual_class2_recall_u95_frac", lo=0.0, hi=1.0
        )
    if res_val is not None and res_val > LIVE_GATE32_MAX_RESIDUAL_CLASS2_U95_FRAC:
        if is_coherent_partial_hold:
            hold_reasons.append(f"HOLD_LIVE_GATE32_RESIDUAL_CLASS2_RECALL_U95_GT_0P30:{res_val!r}")
        else:
            fail_reasons.append(f"LIVE_GATE32_RESIDUAL_CLASS2_RECALL_U95_GT_0P30_FAIL:{res_val!r}")

    if "unrelated_recall_preserved" not in g32_raw or g32_raw["unrelated_recall_preserved"] is None:
        missing_fields.append(f"{pfx}unrelated_recall_preserved")
        unrel_val: bool | None = None
    else:
        unrel_val = _require_exact_bool(g32_raw["unrelated_recall_preserved"], f"{pfx}unrelated_recall_preserved")
    if unrel_val is False:
        fail_reasons.append("LIVE_GATE32_UNRELATED_RECALL_NOT_PRESERVED_FAIL")


def _verify_upstream_evidence_and_finalize(
    obs: dict[str, Any],
    expected_module_gate_source: str,
    module_binding_checker: Callable[[dict[str, Any], list[str], list[str], list[str]], None] | None,
    arm_entry: dict[str, Any] | None,
    trusted_evidence_store: dict[str, dict[str, Any]] | None,
    fail_reasons: list[str],
    missing_fields: list[str],
    hold_reasons: list[str],
    extra_out: dict[str, Any] | None = None,
    *,
    verified_manifest: dict[str, Any] | None = None,
    extra_builder: Callable[[dict[str, Any]], dict[str, Any]] | None = None,
    require_live_gate32_debris_recall: bool = False,
) -> dict[str, Any]:
    """Enforce v2_round5_unified evidence schema across parent, W6-C1 GATE-34 upstream, independent GATE-36-<MODULE> current-assay, & (for SHIELD) mandatory live GATE-32 whole-islet-debris recall records with unconditional store authentication before statistics emission (Audit R10-03 / Round-14 Review)."""
    parent_id, parent_env_ok = _parse_parent_identity_and_tier(obs, arm_entry, fail_reasons, missing_fields)

    allowed_cur_decisions = frozenset({
        "PASS",
        f"PASS_{expected_module_gate_source.replace('-', '_')}",
        f"PASS_{expected_module_gate_source.replace('-', '')}",
    })

    up_raw = obs.get("upstream_lot_evidence_record") if "upstream_lot_evidence_record" in obs else None
    cur_raw = obs.get("current_assay_evidence_record") if "current_assay_evidence_record" in obs else None