OpenIslet

scripts/verify_wave7_cellgemma_2p24_rebase.py

Wave-7 CellGemma-Islet (IIP-0062 to IIP-0065 / GATE-40 to GATE-43) Pure-CPU

script Release v0.8.0 gen-eb955f8266035aba 1.37 MB · 90 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_wave7_cellgemma_2p24_rebase.py · SHA-256: 5f31a6369f25031d…

#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""
Wave-7 CellGemma-Islet (IIP-0062 to IIP-0065 / GATE-40 to GATE-43) Pure-CPU
Rebase Verifier, Exact 2^24 Portfolio Crosswalk & Executable Stage-0 Gate Suite.

(Note: IIP-0059 / DEC-140 / GATE-38 [Issue #59], IIP-0060 / DEC-141 / GATE-39 [Issue #60], and IIP-0061 / DEC-142 [Issue #61, Layer-1 normative prose sync] occupy #59-#61 and GATE-38..GATE-39; Wave-7 occupies IIP-0062..IIP-0065 / DEC-143..DEC-146 / GATE-40..GATE-43.)

Rebases the frozen CellGemma-Islet v0.9.0 provenance package
(`cellgemma_islet_v0_1_receipt.json`, `portable_payload_sha256:
ba72c6eb81f29be7ab1f0b2ef17ca6397eb342f1a2788913475919f48f89e2ab`) onto the
landed Wave-6 (`IIP-0055`..`IIP-0058`) 6-arm `2^24` portfolio engine
(`wave6_master_contract.json`, `71.7864%` modular / `70.5959%` locked /
`74.9586%` ceiling) with:
  - Canonical Wave-6 `v0.9.0` product & native safety-switch binding
    (`wave6_canonical_arm_manifest.json`: `ISLET1_DESIGN_B_V090`,
    `ISLET1_DESIGN_Y_V3`, `ISLET1_DESIGN_X_V090`, `ISLET1_DESIGN_D1B_LEAN_K2`,
    `ISLET1_ARM_Z_ENSC_V090`), strictly prohibiting transfer of legacy `v0.8.0`
    passes onto Wave-6 `v0.9.0` arms and enforcing active gate product/route scope.
  - Zero double-counting via proportional remaining-failure-headroom compression
    on Wave-6's `c4_univ = 0.950` (`scale = 0.625`) and `c3_base = 0.942`
    (`scale = 0.773333`, lifted central `0.948573`), keeping `Route 4` naked
    omental fold-back untouched (`c4_r4 = 0.870`) in primary scope.
  - Strict physical AND numerical Design-A drug-free firewall:
    * All Design-A aliases (`A`, `DESIGN_A`, `ISLET1_A4_ARM1B`,
      `ISLET1_DESIGN_A_V080_REF`, `ISLET1_DESIGN_A_V090_TBP_CANDIDATE`) hard-blocked
      on both `target_arm` and `product_id`.
    * `INC_A_DRUGFREE` cell class restricts Design A exclusively to uncoated
      `R1` whenever `R2` is drug-coated (`p_design_a_only_with_coated_route == 0.0`).
    * Design-A 4 marginals `(0.88, 0.78, 0.57, 0.69)`, standalone (`26.9961%`),
      and `(A, D)` H2 4-cell joint verified invariant to `<= 1e-12`.
  - Exact `192`-state (`24 Wave-6 states x 8 Wave-7 (A, B, C) states`) state-by-state
    pre-wet-lab scenario average plus Foundry-conditional sensitivities.
  - Hardened fail-closed Stage-0 gate adjudicators (`GATE-40`..`GATE-43`) with
    structured scope-bound same-lot evidence receipts, strict schema unknown-key
    rejection, bench-only vs exact-product phase separation, manifest-derived
    construct density applicability, explicit `release_authorizing = False`,
    and 280 deterministic regression tests (zero `assert` statements; 100%
    fail-closed under `python3 -W error -O -B`).

Usage:
  PYTHONDONTWRITEBYTECODE=1 python3 -W error -O -B verify_wave7_cellgemma_2p24_rebase.py --generate
  PYTHONDONTWRITEBYTECODE=1 python3 -W error -O -B verify_wave7_cellgemma_2p24_rebase.py --check
"""

from __future__ import annotations

import argparse
import hashlib
import json
import math
from pathlib import Path
from typing import Any, Callable, FrozenSet, Mapping, Optional, Sequence

EXPECTED_CELLGEMMA_PAYLOAD_SHA256 = "ba72c6eb81f29be7ab1f0b2ef17ca6397eb342f1a2788913475919f48f89e2ab"
EXPECTED_CELLGEMMA_FILE_SHA256 = "33e6f8a8ee7a0d0a51c3bcd1718a6d0f2364f94d55d585eafc39214136273cb8"
EXPECTED_WAVE6_CONTRACT_SHA256 = "53f90447f1f32213adff883f26d30aa1268f4848e6d3d1d946c03d9c7c8a8b42"

PINNED_WAVE6_EXACT = {
    "L0_core_3arm_modular": 54.116275172928866,
    "L0_core_3arm_locked": 50.778198035232116,
    "L1_shipped_5arm_modular": 61.592086541953336,
    "L1_shipped_5arm_locked": 60.64389039505886,
    "Wave5_L3B_modular": 66.57313735189612,
    "Wave5_L3B_locked": 66.00787450699171,
    "Wave6_5Arm_Central_modular": 70.1592137514282,
    "Wave6_5Arm_Central_locked": 68.461471997588,
    "Wave6_6Arm_Central_modular": 71.78644962735174,
    "Wave6_6Arm_Central_locked": 70.59588306296519,
    "Wave6_6Arm_Central_ceiling": 74.95863978207102,
}

# Canonical Wave-6 v0.9.0 arm registry (matching data/protocols/wave6_canonical_arm_manifest.json)
DESIGN_A_ALIASES: FrozenSet[str] = frozenset({
    "A", "DESIGN_A", "ISLET1_A4_ARM1B", "ISLET1_DESIGN_A_V080_REF", "ISLET1_DESIGN_A_V090_TBP_CANDIDATE",
})

ACTIVE_COATING_PRODUCT_ROUTES: FrozenSet[tuple[str, str]] = frozenset({
    ("ISLET1_DESIGN_Y_V3", "R3P"),
    ("ISLET1_DESIGN_B_V090", "R2"),
})

CANONICAL_WAVE6_PRODUCTS: Mapping[str, Mapping[str, Any]] = {
    "ISLET1_DESIGN_A_V080_REF": {
        "arm": "A", "version": "v0.8.0_ref", "required_switch": "AAVS1::iCasp9",
        "home_route": "R1", "allowed_routes": frozenset({"R1", "R2"}), "drug_coating_allowed": False,
        "hla_e_engineered": True, "cd47_engineered": True, "autologous_self_hla": False,
        "foundry_v2_biologics_eligible": False, "execution_supported_in_registry": False,
    },
    "ISLET1_DESIGN_B_V090": {
        "arm": "B", "version": "v0.9.0", "required_switch": "TBP::iCasp9",
        "home_route": "R2", "allowed_routes": frozenset({"R1", "R2"}), "drug_coating_allowed": True,
        "hla_e_engineered": False, "cd47_engineered": True, "autologous_self_hla": False,
        "foundry_v2_biologics_eligible": True, "execution_supported_in_registry": False,
    },
    "ISLET1_DESIGN_X_V090": {
        "arm": "X", "version": "v0.9.0", "required_switch": "TBP::iCasp9",
        "home_route": "R1", "allowed_routes": frozenset({"R1", "R2"}), "drug_coating_allowed": True,
        "hla_e_engineered": False, "cd47_engineered": True, "autologous_self_hla": False,
        "foundry_v2_biologics_eligible": True, "requires_gate31_same_lot": True,
        "execution_supported_in_registry": False,
    },
    "ISLET1_DESIGN_Y_V3": {
        "arm": "Y", "version": "v0.9.0", "required_switch": "DUAL_TBP_ICASP9_PLUS_CDK1_HSVTK",
        "home_route": "R3P", "allowed_routes": frozenset({"R3P", "R4"}), "drug_coating_allowed": True,
        "hla_e_engineered": True, "cd47_engineered": True, "autologous_self_hla": False,
        "foundry_v2_biologics_eligible": True, "execution_supported_in_registry": False,
    },
    "ISLET1_DESIGN_D1B_LEAN_K2": {
        "arm": "D", "version": "v0.9.0", "required_switch": "ACTB::iCasp8",
        "home_route": "R4", "allowed_routes": frozenset({"R3P", "R4"}), "drug_coating_allowed": True,
        "hla_e_engineered": False, "cd47_engineered": False, "autologous_self_hla": True,
        "foundry_v2_biologics_eligible": True, "execution_supported_in_registry": False,
    },
    "ISLET1_ARM_Z_ENSC_V090": {
        "arm": "Z", "version": "v0.9.0", "required_switch": "DUAL_TBP_ICASP9_PLUS_CDK1_HSVTK",
        "home_route": "R4", "allowed_routes": frozenset({"R3P", "R4"}), "drug_coating_allowed": True,
        "hla_e_engineered": True, "cd47_engineered": True, "autologous_self_hla": False,
        "foundry_v2_biologics_eligible": True, "execution_supported_in_registry": False,
    },
}

LEGACY_V080_PRODUCTS: Mapping[str, Mapping[str, Any]] = {
    "ISLET1_A4_ARM1B": {"arm": "A", "required_switch": "AAVS1::iCasp9", "execution_supported_in_registry": True},
    "ISLET1_A4_X_MOL_RNLS_WT": {"arm": "X", "required_switch": "AAVS1::iCasp9", "execution_supported_in_registry": True},
    "ISLET1_B2_5LOCUS_BASE": {"arm": "B", "required_switch": "AAVS1::iCasp9", "execution_supported_in_registry": False},
    "ISLET1_B2_5LOCUS_TYK2_PE": {"arm": "B", "required_switch": "AAVS1::iCasp9", "execution_supported_in_registry": False},
    "ISLET1_Y_FULLSTACK_V2_B2M_11TU": {"arm": "Y", "required_switch": "B2M_ICASP9_PLUS_GATE33_HTMPK", "execution_supported_in_registry": False},
    "ISLET1_D1_AUTO_V2_L1A_CIITA_CD64T_IL1RN": {"arm": "D", "required_switch": "AAVS1_ICASP9_PLUS_GATE33_HTMPK_PLUS_D1_08", "execution_supported_in_registry": False},
}

SCALE_C4_UNIV = (1.0 - 0.950) / (1.0 - 0.920)  # 0.625
SCALE_C3_BASE = (1.0 - 0.942) / (1.0 - 0.925)  # 0.7733333333333333


def require(cond: bool, msg: str) -> None:
    if not cond:
        raise RuntimeError(f"FAIL-CLOSED WAVE-7 ERROR: {msg}")


def is_strict_bool(v: Any) -> bool:
    return isinstance(v, bool)


def is_strict_int(v: Any) -> bool:
    return isinstance(v, int) and not isinstance(v, bool)


def is_finite_num(v: Any) -> bool:
    if isinstance(v, bool) or v is None:
        return False
    if isinstance(v, Decimal):
        return v.is_finite()
    return isinstance(v, (int, float)) and math.isfinite(float(v))


def is_nonempty_str(v: Any) -> bool:
    return isinstance(v, str) and bool(v.strip())


def is_sha256_hex(v: Any) -> bool:
    return isinstance(v, str) and len(v) == 64 and all(ch in "0123456789abcdef" for ch in v.lower())


def sha256_bytes(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def _canonical_json_default(obj: Any) -> Any:
    if isinstance(obj, Decimal):
        require(obj.is_finite(), f"Non-finite Decimal in canonical JSON: {obj!r}")
        return format(obj.normalize(), "f")
    raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")


def canonical_json_bytes(obj: Any) -> bytes:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=_canonical_json_default).encode("utf-8")


def check_all_finite(obj: Any, path: str = "root") -> None:
    if isinstance(obj, float):
        require(math.isfinite(obj), f"Non-finite float at {path}: {obj!r}")
    elif isinstance(obj, Decimal):
        require(obj.is_finite(), f"Non-finite Decimal at {path}: {obj!r}")
    elif isinstance(obj, dict):
        for k, v in obj.items():
            check_all_finite(v, f"{path}.{k}")
    elif isinstance(obj, list):
        for idx, v in enumerate(obj):
            check_all_finite(v, f"{path}[{idx}]")


def load_strict_json(raw_text: str, label: str = "json", *, parse_float_as_decimal: bool = False) -> Any:
    def _no_dup(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
        out: dict[str, Any] = {}
        for k, v in pairs:
            if k in out:
                raise RuntimeError(f"Duplicate JSON key in {label}: {k!r}")
            out[k] = v
        return out

    def _no_const(tok: str) -> Any:
        raise RuntimeError(f"Non-finite JSON constant in {label}: {tok!r}")

    kwargs: dict[str, Any] = {"object_pairs_hook": _no_dup, "parse_constant": _no_const}
    if parse_float_as_decimal:
        kwargs["parse_float"] = Decimal
    obj = json.loads(raw_text, **kwargs)
    check_all_finite(obj, label)
    return obj


def load_exact_receipt_json(raw_text: str, label: str = "receipt") -> Any:
    """Decode receipt JSON preserving exact finite decimal tokens as Decimal (zero binary-float rounding)."""
    return load_strict_json(raw_text, label=label, parse_float_as_decimal=True)


def subadditive_overlap(base: float, delta_a: float, delta_b: float, omega: float) -> float:
    for nm, val in (("base", base), ("delta_a", delta_a), ("delta_b", delta_b), ("omega", omega)):
        require(is_finite_num(val), f"Non-finite overlap input {nm}={val!r}")
    require(0.0 <= base < 1.0, f"Invalid base={base}")
    require(delta_a >= 0.0 and delta_b >= 0.0, f"Negative deltas: {delta_a}, {delta_b}")
    require(base + delta_a < 1.0 and base + delta_b < 1.0, f"Envelope breach: {base}, {delta_a}, {delta_b}")
    require(0.0 <= omega <= 1.0, f"Invalid omega={omega}")
    hi, lo = max(delta_a, delta_b), min(delta_a, delta_b)
    if lo == 0.0:
        return base + hi
    rem_frac = max(0.0, 1.0 - hi / (1.0 - base))
    val = base + hi + (1.0 - omega) * lo * rem_frac
    require(base <= val < 1.0, f"Out-of-envelope combined value={val}")
    return val


# ---------------------------------------------------------------------------
# Pure-Stdlib Exact 2^20 / 2^24 Probability & LP Primitives
# ---------------------------------------------------------------------------

def biv_bern(p1: float, p2: float, phi: float) -> dict[tuple[int, int], float]:
    require(-1e-12 <= p1 <= 1.0 + 1e-12 and -1e-12 <= p2 <= 1.0 + 1e-12, f"biv_bern domain: {p1}, {p2}")
    require(0.0 <= phi <= 1.0, f"biv_bern phi={phi}")
    p1 = min(1.0, max(0.0, p1))
    p2 = min(1.0, max(0.0, p2))
    p11 = (1.0 - phi) * (p1 * p2) + phi * min(p1, p2)
    return {
        (0, 0): max(0.0, 1.0 - p1 - p2 + p11),
        (1, 0): max(0.0, p1 - p11),
        (0, 1): max(0.0, p2 - p11),
        (1, 1): max(0.0, p11),
    }