scripts/wetlab_contract.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/wetlab_contract.py · SHA-256: 6bb3955530f8f05d…
def _valid_construct_sha256_iip0029(val: Any) -> bool:
if not isinstance(val, str) or not _HEX64_RE_IIP0029.fullmatch(val):
return False
return val != ('0' * 64)
def _parse_utc_iso_iip0029(val: Any) -> datetime | None:
s = _strict_unpadded_str_iip0029(val, 16)
if s is None:
return None
try:
iso = s[:-1] + '+00:00' if s.endswith('Z') else s
dt = datetime.fromisoformat(iso)
except ValueError:
return None
if dt.tzinfo is None:
return None
return dt.astimezone(timezone.utc)
def _coerce_lot_scope_key_iip0029(raw: Any) -> LotScopeKey | None:
if isinstance(raw, LotScopeKey):
return raw
if isinstance(raw, (dict, MappingProxyType)):
req = ('product_variant_id', 'construct_sha256', 'donor_seedline_id', 'mcb_id', 'lot_id')
if set(raw.keys()) != set(req):
return None
try:
return LotScopeKey(
raw['product_variant_id'],
raw['construct_sha256'],
raw['donor_seedline_id'],
raw['mcb_id'],
raw['lot_id'],
)
except (TypeError, ValueError):
return None
return None
def _one_sided_t_bounds_iip0029(
vals: list[float],
t_crit: float,
*,
extra_within_var: float = 0.0,
) -> tuple[float, float, float]:
n = len(vals)
if n < 2:
return (vals[0] if vals else float('nan'), float('-inf'), float('inf'))
mu = sum(vals) / float(n)
s2 = sum((x - mu) ** 2 for x in vals) / float(n - 1)
if s2 <= 0.0:
# Degenerate zero-between-lot-variance arrays cannot pass uncertainty gates:
return mu, float('-inf'), float('inf')
se = math.sqrt(max(0.0, s2 / float(n) + max(0.0, float(extra_within_var))))
return mu, mu - t_crit * se, mu + t_crit * se
def _extract_iip0029_source_fingerprint(record: Any) -> tuple[Any, ...]:
if not isinstance(record, (dict, MappingProxyType)):
return ()
sk = _coerce_lot_scope_key_iip0029(record.get('lot_scope_key'))
csha = sk.construct_sha256 if sk is not None else None
lids = tuple(record.get('confirmation_lot_ids') or ()) if isinstance(record.get('confirmation_lot_ids'), (list, tuple)) else ()
lot_obs = record.get('lot_observations') or ()
tids: list[str] = []
if isinstance(lot_obs, (list, tuple)):
for it in lot_obs:
if isinstance(it, (dict, MappingProxyType)):
tids.append(str(it.get('trace_id', '')))
if 'matched_100mmhg_trace_id' in it:
tids.append(str(it.get('matched_100mmhg_trace_id', '')))
return (
csha,
record.get('stage7_start_utc'),
record.get('sort_reaggregation_utc'),
record.get('assay_harvest_utc'),
record.get('locked_analysis_plan_id'),
lids,
tuple(tids),
)
def evaluate_stage0_twoclock_and_repeated_challenge_iip_0029(
record: dict[str, Any] | MappingProxyType,
*,
root: Path | str | None = None,
) -> dict[str, Any]:
"""
Fail-closed Stage-0 two-clock & repeated-challenge empirical qualification subgate (IIP-0029; DEC-108).
NEVER grants standalone clinical release authority (`release_authority` remains strictly
'DELEGATED_TO_LIVE_ATOMIC_STAGE0_LEDGER', preserving registry `execution_supported` holds on
ISLET1_B2_5LOCUS_BASE and ISLET1_Z_X_MOL_140UM_ZERO_CAO2).
Enforces:
1. Unit-bound absolute increment floors (Z1, Z2) PLUS contemporaneous same-assay primary adult
human islet second-pulse floor (L95_t(RefAdult_Z2) >= z_min and L95_t(Z2 - 0.50 * RefAdult_Z2) >= 0)
both inside and outside Rule S8, plus immutable within-recipe Rule S8 Fieller (theta_0 = 0.85)
with exact Bonferroni across K windows or disjoint pilot with locked_analysis_plan_id.
2. Preserved canonical Readout 2 (SI_1 >= 3.0, Peak1/Basal1 >= 4.5 <= 8.0 min, t50 <= 3.0 min)
and full Gate 0M (t90 <= 3.0 min, t50_b < t90_b, Basal1/Peak1 <= 0.15 explicitly separated from
nominal Readout 2 4.5x with window definitions, glucagon >= 2.0x, threshold >= 4.5 mM,
UCN3 >= 0.70, counterregulation >= 0.80).
3. Non-overridable escalation to full scope-matched Gate 0S atomic-ledger review whenever
U95_t(stored_insulin_iu) > 138.3 IU OR max_lot > 138.3 IU.
4. Locked UTC timestamps for dual clocks (phenotype failure remains S8 hold trigger; clocks classify
extended exposure), independent differentiation_block_id coverage at BOTH 40 mmHg AND 100 mmHg,
per-trace tracer alignment (tau_chamber_b <= 0.50 min AND U95_t <= 0.50 min) & censored short
low-interval handling, common-denominator sorting+reaggregation recovery, registered-mixture +
measured (beta, alpha, delta) DEC-084 linkage, pre-iEC LC-MS/MS washout + vascular function
verification, mature-insulin-specific inventory assay, and explicit exploratory labeling of
Keymeulen proinsulin:C-peptide <= 0.10.
"""
C = STAGE0_IIP0029_CONSTANTS
def _hold(status: str, **extra: Any) -> dict[str, Any]:
out: dict[str, Any] = {
'subgate_pass': False,
'release_authority': 'DELEGATED_TO_LIVE_ATOMIC_STAGE0_LEDGER',
'gate0s_escalation_required': False,
'all_non_store_ceiling_checks_passed': False,
'status': status,
}
out.update(extra)
return out
if not isinstance(record, (dict, MappingProxyType)):
return _hold('HOLD_INVALID_RECORD_TYPE')
# Reject any caller attempt to override registry execution_supported, release authority, or Gate 0S ceiling:
if any(k in record for k in _FORBIDDEN_IIP0029_OVERRIDE_KEYS):
return _hold('HOLD_FORBIDDEN_CALLER_RELEASE_OR_EXECUTION_OVERRIDE')
root_path = Path(root) if root is not None else Path(__file__).resolve().parents[1]
p_mod = _load_product_contract_module(root_path)
prod_doc = p_mod.load_product_contracts(root_path)
product_registry = {str(p['product_variant_id']): p for p in prod_doc['products']}
# 1. Registry-bound LotScopeKey & strict 64-hex non-zero construct_sha256:
scope_key = _coerce_lot_scope_key_iip0029(record.get('lot_scope_key'))
if scope_key is None:
return _hold('HOLD_MISSING_OR_INVALID_IIP0024_LOT_SCOPE_KEY')
pvid = _strict_unpadded_str_iip0029(scope_key.product_variant_id, 4)
if pvid is None or pvid not in product_registry:
return _hold('HOLD_UNREGISTERED_OR_UNSUPPORTED_PRODUCT_VARIANT_ID')
reg_entry = product_registry[pvid]
registry_exec_supported = bool(reg_entry.get('execution_supported', False))
if not _valid_construct_sha256_iip0029(scope_key.construct_sha256):
return _hold('HOLD_INVALID_OR_ZERO_CONSTRUCT_SHA256')
if (
_strict_unpadded_str_iip0029(scope_key.donor_seedline_id, 2) is None
or _strict_unpadded_str_iip0029(scope_key.mcb_id, 2) is None
or _strict_unpadded_str_iip0029(scope_key.lot_id, 2) is None
):
return _hold('HOLD_INVALID_SCOPE_PROVENANCE_IDENTIFIERS')
# 2. Registered mixture + measured (beta, alpha, delta) composition linkage to DEC-084 (Sol BOX2 Fix #4):
reg_mix_id = _strict_unpadded_str_iip0029(record.get('registered_mixture_id'), 4)
if reg_mix_id is None or reg_mix_id not in C['REGISTERED_MIXTURES']:
return _hold('HOLD_MISSING_OR_UNREGISTERED_MIXTURE_ID')
mix_spec = C['REGISTERED_MIXTURES'][reg_mix_id]
beta_frac = _strict_finite_float_iip0029(record.get('beta_cell_fraction'))
alpha_frac = _strict_finite_float_iip0029(record.get('alpha_cell_fraction'))
delta_frac = _strict_finite_float_iip0029(record.get('delta_cell_fraction'))
imp_ieq = _strict_finite_float_iip0029(record.get('implanted_total_ieq'))
if (
beta_frac is None
or alpha_frac is None
or delta_frac is None
or imp_ieq is None
or imp_ieq <= 0.0
or not (0.0 < beta_frac <= 1.0)
or not (0.0 <= alpha_frac <= 1.0)
or not (0.0 <= delta_frac <= 1.0)
):
return _hold('HOLD_MISSING_OR_INVALID_MEASURED_COMPOSITION_OR_IEQ')
comp_sum = beta_frac + alpha_frac + delta_frac
if not (0.95 <= comp_sum <= 1.0 + 1e-6):
return _hold('HOLD_INVALID_MEASURED_ENDOCRINE_COMPOSITION_SUM')
comp_within_registered_band = (
abs(beta_frac - float(mix_spec['beta'])) <= 0.05 + 1e-9
and abs(alpha_frac - float(mix_spec['alpha'])) <= 0.05 + 1e-9
and abs(delta_frac - float(mix_spec['delta'])) <= 0.03 + 1e-9
)
if mix_spec['is_reference']:
alpha_delta_ratio = alpha_frac / max(1e-9, delta_frac)
if not comp_within_registered_band or not (2.0 <= alpha_delta_ratio <= 4.5):
return _hold(
'HOLD_MEASURED_COMPOSITION_DRIFT_FROM_REGISTERED_MIXTURE_REQUIRES_DEC084_QUALIFICATION',
measured_composition={'beta': beta_frac, 'alpha': alpha_frac, 'delta': delta_frac},
)
elif not comp_within_registered_band:
return _hold(
'HOLD_MEASURED_COMPOSITION_OUTSIDE_REGISTERED_DEC084_TOLERANCE',
measured_composition={'beta': beta_frac, 'alpha': alpha_frac, 'delta': delta_frac},
)
is_dec084_non_ref_mixture = not bool(mix_spec['is_reference'])
n_lots = _strict_pos_int_iip0029(record.get('n_independent_lots'))
min_n_req = int(C['MIN_DEC084_MIXTURE_LOTS_N'] if is_dec084_non_ref_mixture else C['MIN_INDEPENDENT_LOTS_N'])
if n_lots is None or n_lots < min_n_req:
return _hold(
'HOLD_DEC084_MIXTURE_REQUIRES_N_GE_8_CONFIRMATION_BLOCKS'
if is_dec084_non_ref_mixture
else 'HOLD_INSUFFICIENT_INDEPENDENT_LOTS_REQUIRES_N_GE_6'
)
if is_dec084_non_ref_mixture:
dec084_obs = record.get('dec084_mixture_observations')
if isinstance(dec084_obs, (dict, MappingProxyType)):
dec084_res = evaluate_dec084_measured_potency_mixture_gate_iip_0028(dict(dec084_obs))
if dec084_res.get('gate_pass') is not True:
return _hold(
'HOLD_DEC084_REQUIRES_LINKED_MATCHED_AGE_MIXTURE_GATE',
dec084_gate_status=dec084_res.get('status'),
)
elif record.get('dec084_matched_age_mixture_gate_passed') is not True:
return _hold('HOLD_DEC084_REQUIRES_LINKED_MATCHED_AGE_MIXTURE_GATE')
lot_ids_raw = record.get('confirmation_lot_ids')
if not isinstance(lot_ids_raw, (list, tuple)) or len(lot_ids_raw) != n_lots:
return _hold('HOLD_DUPLICATE_OR_INVALID_CONFIRMATION_LOT_IDS')
if any(_strict_unpadded_str_iip0029(x, 2) is None for x in lot_ids_raw):
return _hold('HOLD_DUPLICATE_OR_INVALID_CONFIRMATION_LOT_IDS')
lot_ids = [str(x) for x in lot_ids_raw]
if len(set(lot_ids)) != n_lots:
return _hold('HOLD_DUPLICATE_OR_INVALID_CONFIRMATION_LOT_IDS')
# 3. Locked analysis plan, explicit K, pilot disjointness, and exact Bonferroni multiplicity:
locked_plan_id = _strict_unpadded_str_iip0029(record.get('locked_analysis_plan_id'), 4)
if locked_plan_id is None:
return _hold('HOLD_MISSING_LOCKED_ANALYSIS_PLAN_ID')
if 'candidate_windows_evaluated_k' not in record:
return _hold('HOLD_MISSING_EXPLICIT_CANDIDATE_WINDOWS_K')
k_cand = _strict_pos_int_iip0029(record.get('candidate_windows_evaluated_k'))
if k_cand is None or k_cand > 5:
return _hold('HOLD_INVALID_CANDIDATE_WINDOW_COUNT')
win_design = record.get('window_selection_design')
pilot_block_ids_set: set[str] = set()
if win_design == 'SINGLE_PRESPECIFIED_PRIMARY':
if k_cand != 1:
return _hold('HOLD_WINNERS_CURSE_UNADJUSTED_MULTIWINDOW_OR_LOT_OVERLAP')
t_crit = student_t_ppf(0.95, float(n_lots - 1))
elif win_design == 'PILOT_SCREEN_THEN_DISJOINT_CONFIRMATION':
pilot_raw = record.get('pilot_selection_lot_ids')
pilot_blk_raw = record.get('pilot_differentiation_block_ids')
if (
not isinstance(pilot_raw, (list, tuple))