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…

    _excluded_merge_d = _all_s9_rep_d | _all_alias_d | frozenset({
        'scope', 'measurements', 'iip0026_molecular_observations',
        'tier6b_sorted_lot_observations', 'iip0031_locus2_record', 'iip0029_twoclock_record',
        '_s9_replicate_count_conflict', '_stage0_conflicting_measurement',
    })
    _d_s9_resolved, _d_s9_conflicts, _d_s9_any_conflict = _resolve_s9_replicate_counts_detailed_iip0031(
        _direct_containers,
        flag_explicit_none=True,
    )
    _clean_aliases_d, _alias_cands_d, _clean_baf_d, _baf_cands_d, _alias_or_baf_conflict_d = _reconcile_iip0026_aliases_and_baf_iip0031(
        _direct_containers
    )
    _direct_clean_obs, _direct_probes, _direct_meas_conflict = _merge_stage0_container_fields_iip0031(
        _direct_containers,
        excluded_keys=_excluded_merge_d,
        key_predicate=lambda k: k.startswith('obs_') or k in IIP0026_ALLOWED_MOLECULAR_OBS_KEYS or k in _ALL_S11_RECOGNIZED_EVIDENCE_KEYS or k in STAGE0_DECISION_TREE_BOOLEAN_KEYS,
    )
    canonical_payload: dict[str, Any] = {
        k: v for _src_c in (_nested_scope_d, payload) for k, v in _src_c.items() if isinstance(k, str)
    }
    canonical_payload['product_variant_id'] = pid
    for _ck_rm in list(canonical_payload.keys()):
        if (
            _ck_rm not in _excluded_merge_d
            and (_ck_rm.startswith('obs_') or _ck_rm in IIP0026_ALLOWED_MOLECULAR_OBS_KEYS or _ck_rm in _ALL_S11_RECOGNIZED_EVIDENCE_KEYS or _ck_rm in STAGE0_DECISION_TREE_BOOLEAN_KEYS)
        ):
            canonical_payload.pop(_ck_rm, None)
        elif _ck_rm in _all_alias_d or _ck_rm in _all_s9_rep_d:
            canonical_payload.pop(_ck_rm, None)
    canonical_payload.update(_direct_clean_obs)
    canonical_payload.update(_clean_aliases_d)
    if _clean_baf_d is not None:
        canonical_payload['post_edit_per_locus_segmented_baf'] = dict(_clean_baf_d)
    for _grp_d, _gkeys_d in S9_REPLICATE_KEYS.items():
        if _d_s9_resolved.get(_grp_d) is not None:
            canonical_payload[_gkeys_d[0]] = _d_s9_resolved[_grp_d]
    if _d_s9_any_conflict:
        canonical_payload['_s9_replicate_count_conflict'] = True

    safe_s0_obs = _build_safe_stage0_tree_obs_iip0026(canonical_payload, root_path=root_path)
    tree_eval, _tree_alias_conflict = _eval_stage0_tree_preserving_s9_iip0031(safe_s0_obs, root_path=root_path)
    if not tree_eval['safety_kill_s9_triggered'] and _direct_probes:
        for _p_cand in _direct_probes:
            _p_full = {**canonical_payload, **_p_cand}
            _p_safe = _build_safe_stage0_tree_obs_iip0026(_p_full, root_path=root_path)
            _p_tree, _p_ac = _eval_stage0_tree_preserving_s9_iip0031(_p_safe, root_path=root_path)
            if _p_ac:
                _tree_alias_conflict = True
            if _p_tree['safety_kill_s9_triggered']:
                tree_eval = _p_tree
                break
    switch_decisions = dict(tree_eval['switch_decisions'])

    _l2_bind_cur = pdef_cur.get('staged_locus2_modeb_donor_binding') if isinstance(pdef_cur, dict) else None
    _target_scope_6b = {
        'product_variant_id': pid,
        'construct_sha256': canonical_payload.get('construct_sha256'),
        'background_id': canonical_payload.get('background_id') or (_l2_bind_cur.get('background_id') if isinstance(_l2_bind_cur, dict) else None),
        'donor_seedline_id': canonical_payload.get('donor_seedline_id', canonical_payload.get('seed_line_id')),
        'mcb_id': canonical_payload.get('mcb_id'),
        'lot_id': canonical_payload.get('lot_id', canonical_payload.get('current_lot_id')),
        'campaign_id': canonical_payload.get('campaign_id', canonical_payload.get('assay_campaign_id')),
    }
    _direct_t6b_merged: list[Any] = []
    _direct_t6b_present = False
    for _d_src in (payload, _nested_scope_d, _nested_mol_d, _nested_meas_d):
        if 'tier6b_sorted_lot_observations' in _d_src:
            _direct_t6b_present = True
            _dv = _d_src['tier6b_sorted_lot_observations']
            if isinstance(_dv, (list, tuple)):
                _direct_t6b_merged.extend(_dv)
            else:
                _direct_t6b_merged.append('__EXPLICIT_NULL_OR_MALFORMED_TIER6B_CONTAINER__')
    tier6b_eval = evaluate_tier6b_per_fraction_thinning_iip0031(
        _direct_t6b_merged if _direct_t6b_present else [],
        target_scope=_target_scope_6b,
        root=root_path,
    )
    s11_eval = _evaluate_all_s11_containers_iip0031(
        canonical_payload,
        (payload, _nested_scope_d, _nested_mol_d, _nested_meas_d),
        root_path=root_path,
        product_def=pdef_cur,
    )
    switch_decisions[RULE_S11_GATE_ID_IIP0031] = str(s11_eval['status'])
    switch_decisions[f'JSON_{RULE_S11_GATE_ID_IIP0031}'] = str(s11_eval['status'])
    _t6b_common = {
        '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': tree_eval.get(
            's9_point_estimate_fallback_se_policy',
            'SCALE_AWARE_DEFAULT_SE_IMPUTED_ON_SCALAR_OMISSION_TYPED_ATOM_REQUIRES_MEASURED_SE',
        ),
        's9_se_imputed_endpoints': list(tree_eval.get('s9_se_imputed_endpoints', [])),
    }

    _caller_override_rejected = any(
        isinstance(k, str) and (
            (k in IIP0026_FORBIDDEN_CALLER_OVERRIDE_KEYS)
            or k.endswith('_lifecycle_state')
            or k.endswith('_execution_supported')
        )
        for _ovr_ctr in (payload, _nested_scope_d, _nested_mol_d)
        for k in _ovr_ctr
    )

    # PRECEDENCE 1: Independent S9 Hard Safety Stop ALWAYS keeps first precedence:
    if tree_eval['safety_kill_s9_triggered']:
        _s9_reasons = ['HARD_SAFETY_STOP_S9']
        if _caller_override_rejected:
            _s9_reasons.append('FAIL_CALLER_LIFECYCLE_OR_EXECUTION_OVERRIDE_REJECTED')
        if _direct_scope_conflict:
            _s9_reasons.append('FAIL_CROSS_LOT_OR_CAMPAIGN_REPLAY_MIXING')
        return {
            'overall_status': 'HARD_SAFETY_STOP_REJECTED',
            'lot_release_readiness_tier': 'HARD_SAFETY_STOP_REJECTED',
            'iip0026_reasons': _s9_reasons,
            'hard_stop_precedence_winner': 'S9_HARD_SAFETY_STOP',
            'lifecycle_state': lifecycle_state,
            'execution_supported': False,
            'effective_execution_permitted': False,
            'switch_decisions': switch_decisions,
            **_t6b_common,
        }

    # PRECEDENCE 2: Attributable sorted-lot Tier 6B integer k_i >= 1 latches FAIL_HARD_STOP BEFORE
    # calibration holds, completeness holds, malformed records, caller overrides, or non-executable holds:
    if tier6b_eval.get('hard_stop') is True:
        _t6_reasons = ['FAIL_TIER6B_OUTGROWTH_DETECTED']
        if _caller_override_rejected:
            _t6_reasons.append('FAIL_CALLER_LIFECYCLE_OR_EXECUTION_OVERRIDE_REJECTED')
        if _direct_scope_conflict:
            _t6_reasons.append('FAIL_CROSS_LOT_OR_CAMPAIGN_REPLAY_MIXING')
        return {
            'overall_status': 'FAIL_HARD_STOP',
            'lot_release_readiness_tier': 'HARD_SAFETY_STOP_REJECTED',
            'iip0026_reasons': _t6_reasons,
            'hard_stop_precedence_winner': 'FAIL_TIER6B_OUTGROWTH_DETECTED',
            'lifecycle_state': lifecycle_state,
            'execution_supported': False,
            'effective_execution_permitted': False,
            'switch_decisions': switch_decisions,
            **_t6b_common,
        }

    if _direct_scope_conflict:
        return {
            'overall_status': 'FAIL_CROSS_LOT_OR_CAMPAIGN_REPLAY_MIXING',
            'lot_release_readiness_tier': 'FAIL_CROSS_LOT_OR_CAMPAIGN_REPLAY_MIXING',
            'iip0026_reasons': ['FAIL_CROSS_LOT_OR_CAMPAIGN_REPLAY_MIXING'],
            'hard_stop_precedence_winner': None,
            'lifecycle_state': lifecycle_state,
            'execution_supported': False,
            'effective_execution_permitted': False,
            'switch_decisions': switch_decisions,
            **_t6b_common,
        }

    lot_id = canonical_payload.get('lot_id', canonical_payload.get('current_lot_id'))
    campaign_id = canonical_payload.get('campaign_id', canonical_payload.get('assay_campaign_id'))
    _missing_lot_or_campaign = bool(
        not isinstance(lot_id, str)
        or not lot_id.strip()
        or not isinstance(campaign_id, str)
        or not campaign_id.strip()
    )

    # PRECEDENCE 3: Rule S11 hard architectural/safety stops evaluate BEFORE caller overrides, missing-obs, or research holds:
    if not _missing_lot_or_campaign and str(s11_eval.get('status', '')).startswith('FAIL_'):
        _s11_fail = str(s11_eval['status'])
        _s11_reasons_out = list(s11_eval.get('reasons', [_s11_fail]))
        if _caller_override_rejected and 'FAIL_CALLER_LIFECYCLE_OR_EXECUTION_OVERRIDE_REJECTED' not in _s11_reasons_out:
            _s11_reasons_out.append('FAIL_CALLER_LIFECYCLE_OR_EXECUTION_OVERRIDE_REJECTED')
        if (
            payload.get('_stage0_conflicting_measurement') is True
            or _direct_meas_conflict
            or _alias_or_baf_conflict_d
            or _tree_alias_conflict
        ) and 'HOLD_CONFLICTING_STAGE0_MEASUREMENT' not in _s11_reasons_out:
            _s11_reasons_out.append('HOLD_CONFLICTING_STAGE0_MEASUREMENT')
        return {
            'overall_status': _s11_fail,
            'lot_release_readiness_tier': _s11_fail,
            'iip0026_reasons': _s11_reasons_out,
            'hard_stop_precedence_winner': _s11_fail,
            'lifecycle_state': lifecycle_state,
            'execution_supported': False,
            'effective_execution_permitted': False,
            'switch_decisions': switch_decisions,
            **_t6b_common,
        }

    # Reject any caller attempt to supply or override lifecycle_state or execution_supported:
    if _caller_override_rejected:
        return {
            'overall_status': 'FAIL_CALLER_LIFECYCLE_OR_EXECUTION_OVERRIDE_REJECTED',
            'lot_release_readiness_tier': 'FAIL_CALLER_LIFECYCLE_OR_EXECUTION_OVERRIDE_REJECTED',
            'iip0026_reasons': ['FAIL_CALLER_LIFECYCLE_OR_EXECUTION_OVERRIDE_REJECTED'],
            'hard_stop_precedence_winner': None,
            'lifecycle_state': lifecycle_state,
            'execution_supported': False,
            'effective_execution_permitted': False,
            'switch_decisions': switch_decisions,
            **_t6b_common,
        }

    if _missing_lot_or_campaign:
        return {
            'overall_status': 'HOLD_MISSING_LOT_OR_CAMPAIGN_SCOPE',
            'lot_release_readiness_tier': 'HOLD_MISSING_LOT_OR_CAMPAIGN_SCOPE',
            'iip0026_reasons': ['HOLD_MISSING_LOT_OR_CAMPAIGN_SCOPE'],
            'hard_stop_precedence_winner': None,
            'lifecycle_state': lifecycle_state,
            'execution_supported': False,
            'effective_execution_permitted': False,
            'switch_decisions': switch_decisions,
            **_t6b_common,
        }

    if reg['bound_c1_c5_pair_sha256'] is not None:
        supplied_sha = canonical_payload.get('bound_c1_c5_pair_sha256')
        if supplied_sha != reg['bound_c1_c5_pair_sha256']:
            reason_sha = (
                'HOLD_MISSING_BOUND_C1_C5_DONOR_PAIR_DIGEST'
                if supplied_sha is None
                else 'FAIL_DONOR_REGISTRY_DIGEST_MISMATCH'
            )
            return {
                'overall_status': reason_sha,
                'lot_release_readiness_tier': reason_sha,
                'iip0026_reasons': [reason_sha],
                'hard_stop_precedence_winner': None,
                'lifecycle_state': lifecycle_state,
                'execution_supported': False,
                'effective_execution_permitted': False,
                'switch_decisions': switch_decisions,
                **_t6b_common,
            }

    # Evaluate candidate Design-B / TYK2 / BAF adverse failures across all containers BEFORE returning
    # conflict holds so a contradictory 0-alias can NEVER suppress an attributable positive failure (#13, #15):
    _cand_iip0026_fails = _evaluate_iip0026_candidate_fails_iip0031(
        reg,
        _direct_containers,
        _alias_cands_d,
        _baf_cands_d,
    )