OpenIslet

scripts/wetlab_contract.py

One measurement contract for Python ingestion and generated MCP metadata.

script Release v0.8.0 gen-eb955f8266035aba 913 KB · 68 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/wetlab_contract.py · SHA-256: 6bb3955530f8f05d…

                                        latched_s11_all_fail_reasons.append(str(_rf31))
                                if latched_s11_fail_eval is None or (
                                    b_idx == latched_s11_fail_b_idx
                                    and _pick_headline_s11_fail_iip0031([str(res_31['status']), str(latched_s11_fail_eval['status'])]) == str(res_31['status'])
                                ):
                                    latched_s11_fail_eval = dict(res_31)
                                    latched_s11_fail_b_idx = b_idx
                            s11_panel_eval_collected = res_31
                        atom_status = 'PASS' if res_31.get('gate_pass') is True else st_31
                elif atom.endpoint_id == 'stage0_twoclock_repeated_challenge_panel':
                    if atom.scope_type != 'LOT_SCOPE':
                        atom_status = 'HOLD_IIP0029_PANEL_REQUIRES_LOT_SCOPE'
                    else:
                        rec_29 = dict(p_dict) if isinstance(p_dict, dict) else {}
                        rec_29.setdefault(
                            'lot_scope_key',
                            {
                                'product_variant_id': atom.scope_key.product_variant_id,
                                'construct_sha256': atom.scope_key.construct_sha256,
                                'donor_seedline_id': atom.scope_key.donor_seedline_id,
                                'mcb_id': atom.scope_key.mcb_id,
                                'lot_id': atom.scope_key.lot_id,
                            },
                        )
                        res_29 = evaluate_stage0_twoclock_and_repeated_challenge_iip_0029(rec_29, root=root_path)
                        fp_29 = _extract_iip0029_source_fingerprint(rec_29)
                        if sk_tup == lot_k_c.as_tuple():
                            if iip0029_lot_source_fingerprint is not None and fp_29 != iip0029_lot_source_fingerprint:
                                atom_status = 'FAIL_HARD_STOP'
                                structural_holds.append('FAIL_IIP0029_IMMUTABLE_SOURCE_OR_THRESHOLD_REPLACEMENT_DETECTED')
                            else:
                                iip0029_lot_source_fingerprint = fp_29
                                if res_29.get('gate0s_escalation_required') is True:
                                    elevated_store_gate0s_escalated_on_lot = True
                                if res_29.get('subgate_pass') is True:
                                    atom_status = 'PASS'
                                elif res_29.get('gate0s_escalation_required') is True and res_29.get('all_non_store_ceiling_checks_passed') is True:
                                    atom_status = 'PASS_PENDING_GATE0S_ESCALATION'
                                else:
                                    atom_status = str(res_29.get('status', 'HOLD_IIP0029_SUBGATE_FAILED'))
                        else:
                            atom_status = 'PASS' if res_29.get('subgate_pass') is True else str(res_29.get('status', 'HOLD_IIP0029_SUBGATE_FAILED'))
                else:
                    atom_status = 'HOLD_UNKNOWN_STRUCTURED_PANEL'

            latch_key = (atom.endpoint_id, sk_tup)
            _campaign_linked_for_latch = (
                atom.scope_type == 'MCB_SCOPE'
                or atom.campaign_id == target_campaign_id
            )
            if atom_status == 'FAIL_HARD_STOP':
                if _campaign_linked_for_latch:
                    latched_adverse[latch_key] = {'stop_idx': b_idx, 'repeats': {}}
                elif sk_tup in target_scope_tuples:
                    structural_holds.append(f'HOLD_UNLINKED_CAMPAIGN_ADVERSE_OBSERVATION:{atom.endpoint_id}:{atom.campaign_id}')
            elif (
                latch_key in latched_adverse
                and atom_status == 'PASS'
                and b_idx > latched_adverse[latch_key]['stop_idx']
                and batch.get('reset_prior_safety_stop_after_investigation') is not True
            ):
                raw_bid = batch.get('batch_id')
                if (
                    dict(atom.controls).get('washout_and_retest_verified') is True
                    and atom.campaign_id == target_campaign_id
                    and isinstance(raw_bid, str)
                    and raw_bid.strip()
                    and raw_bid == raw_bid.strip()
                ):
                    latched_adverse[latch_key]['repeats'][raw_bid] = atom.sample_unit_id

            if atom.scope_type == 'MCB_SCOPE':
                if sk_tup == mcb_k_c.as_tuple():
                    mcb_store[atom.endpoint_id] = atom
                    atom_status_by_store_key[('MCB_SCOPE', atom.endpoint_id)] = atom_status
            elif atom.scope_type == 'LOT_SCOPE':
                if sk_tup == lot_k_c.as_tuple():
                    if atom.campaign_id != target_campaign_id:
                        structural_holds.append(f'HOLD_UNLINKED_CAMPAIGN:{atom.endpoint_id}')
                    else:
                        lot_store[atom.endpoint_id] = atom
                        atom_status_by_store_key[('LOT_SCOPE', atom.endpoint_id)] = atom_status
                elif sk_tup[:4] == mcb_k_c.as_tuple():
                    invalidated_stale_keys.add(atom.endpoint_id)
            elif atom.scope_type == 'ASSEMBLED_DEVICE_LOT_SCOPE':
                same_or_sister = (
                    dev_k_c is not None
                    and early_device_or_route_hold is None
                    and sk_tup[:5] == lot_k_c.as_tuple()
                    and atom.scope_key.physical_route_id == dev_k_c.physical_route_id
                    and (
                        atom.scope_key.device_assembly_id == dev_k_c.device_assembly_id
                        or atom.scope_key.device_assembly_id in authorized_sister_assembly_ids
                    )
                )
                if same_or_sister:
                    if atom.scope_key.device_assembly_id != dev_k_c.device_assembly_id and atom.endpoint_id not in sister_terminal_ids:
                        structural_holds.append(f'HOLD_SISTER_UNIT_NON_TERMINAL_TRANSFER_FORBIDDEN:{atom.endpoint_id}')
                    elif atom.campaign_id != target_campaign_id:
                        structural_holds.append(f'HOLD_UNLINKED_CAMPAIGN:{atom.endpoint_id}')
                    else:
                        dev_store[atom.endpoint_id] = atom
                        atom_status_by_store_key[('ASSEMBLED_DEVICE_LOT_SCOPE', atom.endpoint_id)] = atom_status
                elif sk_tup[:4] == mcb_k_c.as_tuple():
                    invalidated_stale_keys.add(atom.endpoint_id)

        if batch.get('reset_prior_safety_stop_after_investigation') is True:
            req_eid = batch.get('reset_prior_safety_stop_target_category')
            rep_ids = batch.get('reset_prior_safety_stop_repeat_batch_ids')
            qp_id = batch.get('reset_prior_safety_stop_independent_qp_approver_id')
            sub_id = batch.get('submitter_id')
            r_code = batch.get('reset_prior_safety_stop_reason_code')
            cur_bid = batch.get('batch_id')
            if 'reset_prior_safety_stop_target_scope_tuple' in batch and batch['reset_prior_safety_stop_target_scope_tuple'] is not None:
                req_scope = batch['reset_prior_safety_stop_target_scope_tuple']
                if isinstance(req_scope, (list, tuple)) and all(isinstance(x, str) and x.strip() and x == x.strip() for x in req_scope):
                    allowed_scopes_for_reset = {tuple(req_scope)}
                else:
                    allowed_scopes_for_reset = set()
            else:
                allowed_scopes_for_reset = target_scope_tuples
            if (
                isinstance(req_eid, str)
                and req_eid.strip()
                and req_eid == req_eid.strip()
                and isinstance(qp_id, str)
                and qp_id.strip()
                and qp_id == qp_id.strip()
                and isinstance(sub_id, str)
                and sub_id.strip()
                and sub_id == sub_id.strip()
                and qp_id != sub_id
                and isinstance(r_code, str)
                and r_code in ALLOWED_STICKY_S9_RESET_REASON_CODES
                and isinstance(rep_ids, list)
                and all(isinstance(x, str) and x.strip() and x == x.strip() for x in rep_ids)
                and len(set(rep_ids)) >= 2
                and (not isinstance(cur_bid, str) or cur_bid not in rep_ids)
                and bool(allowed_scopes_for_reset)
            ):
                for lk_cand in list(latched_adverse.keys()):
                    if lk_cand[0] == req_eid and lk_cand[1] in allowed_scopes_for_reset and lk_cand[1] in target_scope_tuples:
                        reps_map = latched_adverse[lk_cand]['repeats']
                        if set(rep_ids).issubset(set(reps_map.keys())) and len({reps_map[r] for r in rep_ids if str(reps_map[r]).strip()}) >= 2:
                            retained_reset_audit_log.append({
                                'cleared_endpoint_id': req_eid,
                                'scope_tuple': list(lk_cand[1]),
                                'qp_approver_id': qp_id,
                                'submitter_id': sub_id,
                                'repeat_batch_ids': list(rep_ids),
                                'reason_code': r_code,
                            })
                            del latched_adverse[lk_cand]

    tier6b_eval = evaluate_tier6b_per_fraction_thinning_iip0031(
        tier6b_atoms_collected,
        target_scope={**target_provenance, 'product_variant_id': pvid_canon, 'campaign_id': target_campaign_id},
        root=root_path,
    )
    if latched_s11_fail_eval is not None:
        s11_eval = dict(latched_s11_fail_eval)
        merged_s11_reasons = list(latched_s11_all_fail_reasons) + [
            r for r in s11_eval.get('reasons', []) if r not in latched_s11_all_fail_reasons
        ]
        s11_eval['reasons'] = merged_s11_reasons
    elif s11_panel_eval_collected is not None:
        s11_eval = s11_panel_eval_collected
    else:
        s11_eval = evaluate_locus2_ciita_modeb_challenger_v3_gate(
            {
                'product_variant_id': pvid_canon,
                'construct_sha256': mcb_k_c.construct_sha256,
                'donor_seedline_id': lot_k_c.donor_seedline_id,
                'mcb_id': lot_k_c.mcb_id,
                'lot_id': lot_k_c.lot_id,
                **({'background_id': target_provenance['background_id']} if 'background_id' in target_provenance else {}),
                **({'l2_v3_donor_id': target_provenance['l2_v3_donor_id']} if 'l2_v3_donor_id' in target_provenance else {}),
                **({'donor_id': target_provenance['donor_id']} if 'donor_id' in target_provenance else {}),
            },
            root=root_path,
            product_def=pdef,
            _trusted_p_mod=p_mod,
        )
    _t6b_meta = {
        'tier6b_sorted_lot_evaluation': tier6b_eval,
        'tier6b_disposition': tier6b_eval['disposition'],
        'tier6b_reason': tier6b_eval['reason_code'],
        's11_evaluation': s11_eval,
        's9_point_estimate_fallback_se_policy': 'SCALE_AWARE_DEFAULT_SE_IMPUTED_ON_SCALAR_OMISSION_TYPED_ATOM_REQUIRES_MEASURED_SE',
        's9_se_imputed_endpoints': [],
    }

    holds: list[str] = list(structural_holds)
    if early_device_or_route_hold is not None:
        holds.append(f'{early_device_or_route_hold[0]}:{early_device_or_route_hold[1]}')
    if elevated_store_gate0s_escalated_on_lot:
        _g0s_req_ids = (
            'gate0s_ap1903_1h_insulin_burst_iu',
            'gate0s_ap1903_24h_insulin_dump_fraction',
            'obs_explant_en_bloc_recovery_fraction',
        )
        _g0s_all_ok = all(
            (eid in dev_store) and (atom_status_by_store_key.get(('ASSEMBLED_DEVICE_LOT_SCOPE', eid)) == 'PASS')
            for eid in _g0s_req_ids
        )
        if _g0s_all_ok:
            if atom_status_by_store_key.get(('LOT_SCOPE', 'stage0_twoclock_repeated_challenge_panel')) == 'PASS_PENDING_GATE0S_ESCALATION':
                atom_status_by_store_key[('LOT_SCOPE', 'stage0_twoclock_repeated_challenge_panel')] = 'PASS'
        else:
            holds.append('HOLD_STORED_INSULIN_EXCEEDS_138P3_IU_REQUIRES_FULL_LINKED_GATE0S_LEDGER_REVIEW')
    for (_sc_t, _eid_t), _st_t in sorted(atom_status_by_store_key.items()):
        if _st_t == 'PASS_PENDING_GATE0S_ESCALATION':
            if 'HOLD_STORED_INSULIN_EXCEEDS_138P3_IU_REQUIRES_FULL_LINKED_GATE0S_LEDGER_REVIEW' not in holds:
                holds.append('HOLD_STORED_INSULIN_EXCEEDS_138P3_IU_REQUIRES_FULL_LINKED_GATE0S_LEDGER_REVIEW')
        elif _eid_t == 'stage0_locus2_modeb_v3_panel' and _st_t.startswith(('HOLD_S11_', 'FAIL_S11_')):
            continue
        elif _st_t not in ('PASS', 'FAIL_HARD_STOP'):
            holds.append(f'{_st_t}:{_eid_t}')

    # PRECEDENCE 1: Independent S9 Hard Safety Stop ALWAYS keeps first precedence:
    active_target_latches = [eid for (eid, skt) in latched_adverse if skt in target_scope_tuples]
    if active_target_latches:
        return {
            'readiness_tier': 'HARD_SAFETY_STOP_REJECTED',
            'overall_status': 'HARD_SAFETY_STOP_REJECTED',
            'hard_stop_precedence_winner': 'S9_HARD_SAFETY_STOP',
            'execution_supported': False,
            'holds': [f'latched_adverse:{e}' for e in sorted(active_target_latches)] + holds,
            'invalidated_stale_keys': sorted(invalidated_stale_keys),
            'retained_reset_audit_log': retained_reset_audit_log,
            **_t6b_meta,
        }

    # PRECEDENCE 2: Attributable sorted-lot Tier 6B integer k_i >= 1 latches FAIL_HARD_STOP BEFORE
    # calibration holds, malformed records, completeness holds, or non-executable research holds:
    if tier6b_eval.get('hard_stop') is True:
        return {
            'readiness_tier': 'HARD_SAFETY_STOP_REJECTED',
            'overall_status': 'FAIL_HARD_STOP',
            'hard_stop_precedence_winner': 'FAIL_TIER6B_OUTGROWTH_DETECTED',
            'execution_supported': False,
            'holds': ['FAIL_TIER6B_OUTGROWTH_DETECTED'] + holds,
            'invalidated_stale_keys': sorted(invalidated_stale_keys),
            'retained_reset_audit_log': retained_reset_audit_log,
            **_t6b_meta,
        }

    # PRECEDENCE 3: Rule S11 hard architectural/safety stops evaluate BEFORE non-executable research holds:
    if str(s11_eval.get('status', '')).startswith('FAIL_'):
        return {