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…
'gate_pass': False,
'status': 'HOLD_TIER6B_UNQUALIFIED_FRACTION',
'disposition': 'HOLD_TIER6B_UNQUALIFIED_FRACTION',
'reason_code': reason,
'tier6b_status': 'HOLD_TIER6B_UNQUALIFIED_FRACTION',
'hard_stop': False,
'p_lot_U95': extra.pop('p_lot_U95', None),
'threshold': TIER6B_PER_FRACTION_LOT_CAP_IIP0031,
'd_L_by_fraction': extra.pop('d_L_by_fraction', {}),
'd_L_details': extra.pop('d_L_details', {}),
'detection_floor_cleared': extra.pop('detection_floor_cleared', False),
'deduplicated_sample_ids': extra.pop('deduplicated_sample_ids', []),
**extra,
}
if not isinstance(records, (list, tuple)):
return _hold_unqual('TIER6B_RECORDS_MUST_BE_SEQUENCE')
malformed_seen = False
same_lot_provenance_conflict = False
unlinked_campaign_positive = False
latched_outgrowths: list[dict[str, Any]] = []
unlinked_outgrowths: list[dict[str, Any]] = []
record_conflicts: set[str] = set()
target_recs: list[_Tier6BRawAliquot] = []
ignored_out_of_scope: list[dict[str, Any]] = []
# PASS 1: Scan EVERY entry's outer lot identity + strict integer k_i >= 1 BEFORE parsing ancillary controls.
# Foreign-lot records are excluded BEFORE updating target-lot `malformed_seen` or `record_conflicts` (#23, T5)!
for idx, raw_item in enumerate(records):
observation = _extract_tier6b_outer_and_full_entry_iip0031(raw_item)
if observation is None:
malformed_seen = True
continue
outer_rec, full_rec, primary_id, aliases, positive_count, conflict = observation
is_attr, attr_reason = _is_attributable_to_target_lot_iip0031(
outer_rec,
target_canon_pvid=t_pvid,
target_construct_sha256=t_sha,
target_background_id=t_bg,
target_seedline_id=t_seed,
target_mcb_id=t_mcb,
target_lot_id=t_lot,
target_campaign_id=t_camp,
target_scope_complete=target_scope_complete,
root_path=root_path,
)
if not is_attr:
if positive_count > 0:
unlinked_outgrowths.append({
'index': idx,
'reason': attr_reason,
'lot_id': outer_rec.get('lot_id'),
'campaign_id': outer_rec.get('campaign_id'),
'k': positive_count,
})
if (
outer_rec.get('endpoint_id') == 'lot_tier6b_sorted_prolif_clonogenic_escape'
and outer_rec.get('scope_type', 'LOT_SCOPE') == 'LOT_SCOPE'
and t_lot is not None
and outer_rec.get('lot_id') == t_lot
):
if attr_reason == 'wrong_campaign_id' and positive_count > 0:
unlinked_campaign_positive = True
elif attr_reason in ('wrong_construct_sha256', 'wrong_seed_line_id', 'wrong_mcb_id', 'wrong_background_id', 'invalid_campaign_id'):
same_lot_provenance_conflict = True
elif attr_reason.startswith('wrong_scope_type:') and outer_rec.get('lot_id') == t_lot:
same_lot_provenance_conflict = True
elif outer_rec.get('endpoint_id') != 'lot_tier6b_sorted_prolif_clonogenic_escape' and outer_rec.get('lot_id') in (None, t_lot) and not outer_rec.get('endpoint_id'):
malformed_seen = True
ignored_out_of_scope.append({'index': idx, 'reason': attr_reason, 'endpoint_id': outer_rec.get('endpoint_id')})
continue
if conflict == 'MALFORMED_TIER6B_RECORD_REJECTED':
malformed_seen = True
elif conflict:
record_conflicts.add(conflict)
if positive_count:
latched_outgrowths.append({
'index': idx,
'fraction_id': outer_rec.get('fraction_id'),
'sample_id': outer_rec.get('sample_id'),
'record_id': outer_rec.get('record_id'),
'k': positive_count,
'N': full_rec.get('N'),
'lot_id': outer_rec.get('lot_id'),
'campaign_id': outer_rec.get('campaign_id', t_camp),
})
full_rec.setdefault('sample_n', None)
target_recs.append((full_rec, primary_id, aliases))
if latched_outgrowths:
return {
'gate_pass': False,
'status': 'FAIL_HARD_STOP',
'disposition': 'FAIL_HARD_STOP',
'reason_code': 'FAIL_TIER6B_OUTGROWTH_DETECTED',
'tier6b_status': 'FAIL_TIER6B_OUTGROWTH_DETECTED',
'hard_stop': True,
'latched_outgrowth_events': latched_outgrowths,
'unlinked_or_foreign_outgrowth_events': unlinked_outgrowths,
'malformed_records_observed': malformed_seen,
'p_lot_U95': None,
'threshold': TIER6B_PER_FRACTION_LOT_CAP_IIP0031,
'd_L_by_fraction': {},
'd_L_details': {},
'detection_floor_cleared': False,
'deduplicated_sample_ids': [],
}
# PASS 2: Strict provenance, completeness, per-observation calibration/CFU/mass-balance, and exact zero-outgrowth math:
if t_l2_sha_mismatch:
return _hold_unqual('OUTER_CONSTRUCT_SHA256_MISMATCH_WITH_LOCUS2_BINDING', unlinked_or_foreign_outgrowth_events=unlinked_outgrowths)
if not target_scope_complete:
return _hold_unqual('MISSING_OR_INVALID_OUTER_TARGET_IMMUTABLE_PROVENANCE_SCOPE', unlinked_or_foreign_outgrowth_events=unlinked_outgrowths)
if unlinked_campaign_positive:
return _hold_unqual('UNLINKED_CAMPAIGN_TIER6B_POSITIVE_EVENT', unlinked_or_foreign_outgrowth_events=unlinked_outgrowths)
if malformed_seen:
return _hold_unqual('MALFORMED_TIER6B_RECORD_REJECTED', unlinked_or_foreign_outgrowth_events=unlinked_outgrowths)
if record_conflicts:
return _hold_unqual(min(record_conflicts), unlinked_or_foreign_outgrowth_events=unlinked_outgrowths)
if same_lot_provenance_conflict:
return _hold_unqual('INCONSISTENT_PROVENANCE_ACROSS_SAME_LOT_TIER6B_RECORDS', unlinked_or_foreign_outgrowth_events=unlinked_outgrowths)
if not target_recs:
return _hold_unqual('MISSING_SORTED_LOT_TIER6B_EVIDENCE', ignored_out_of_scope=ignored_out_of_scope, unlinked_or_foreign_outgrowth_events=unlinked_outgrowths)
# Examine every lot declaration, including duplicate aliquots, before deduplication (including lot-consistent timepoint/assay_version/unit, T11):
lot_fields = {
'presort_total_input_cells': 'INCONSISTENT_PRESORT_TOTAL_INPUT_CELLS_ACROSS_RECORDS',
'presort_reconciled_loss_cells': 'INCONSISTENT_PRESORT_RECONCILED_LOSS_CELLS_ACROSS_RECORDS',
'unreconciled_loss_fraction': 'INCONSISTENT_UNRECONCILED_LOSS_FRACTION_ACROSS_RECORDS',
'declared_fraction_roster': 'INCONSISTENT_FRACTION_ROSTER_ACROSS_RECORDS',
'timepoint': 'INCONSISTENT_TIER6B_TIMEPOINT_ACROSS_LOT_RECORDS',
'assay_version': 'INCONSISTENT_TIER6B_ASSAY_VERSION_ACROSS_LOT_RECORDS',
'unit': 'INCONSISTENT_TIER6B_UNIT_ACROSS_LOT_RECORDS',
}
try:
lot_conflicts = [
reason for key, reason in lot_fields.items()
if len({_tier6b_signature(rec.get(key)) for rec, _, _ in target_recs}) > 1
]
except (TypeError, ValueError, OverflowError, RecursionError):
return _hold_unqual('MALFORMED_TIER6B_RECORD_REJECTED')
distinct_records, deduplicated_sample_ids, duplicate_error = _tier6b_distinct_aliquots(target_recs)
if duplicate_error:
return _hold_unqual(duplicate_error)
# Validate per-row metadata BEFORE lot-level consistency checks so invalid stage/assay/unit labels surface their specific reason:
lot_roster: list[str] | None = None
lot_risk_unit: str | None = None
lot_bg_seen: str | None = t_bg
lot_presort_total_cells: int | None = None
lot_reconciled_loss_cells: int | None = None
seen_untr_sid_to_frac: dict[str, str] = {}
seen_cal_batch_to_frac: dict[str, str] = {}
seen_cal_specimen_to_frac: dict[str, str] = {}
all_treated_sample_ids: set[str] = set()
all_untreated_sample_ids: set[str] = set()
all_calibrant_specimen_ids: set[str] = set()
agg_by_frac: dict[str, dict[str, Any]] = {}
_allowed_untr_keys = frozenset({
'untreated_sample_id', 'untreated_cfu_colonies_k', 'untreated_plated_cells_n',
'treated', 'ap1903_treated', 'is_untreated', 'control_role',
*_TIER6B_SAMPLE_ALIASES, *_TIER6B_RECORD_ID_ALIASES,
})
_allowed_cal_dict_keys = frozenset({
'r_k', 'r_n', 'cal_batch_id', 'calibrant_role', 'treated', 'ap1903_treated',
*_TIER6B_SAMPLE_ALIASES, *_TIER6B_RECORD_ID_ALIASES,
})
for rec, aliquot_tokens in distinct_records:
if t_camp is not None and rec.get('campaign_id') != t_camp:
return _hold_unqual('INCONSISTENT_RECORD_CAMPAIGN_WITH_TARGET_LOT')
if rec.get('scope_type') != 'LOT_SCOPE':
return _hold_unqual('MISSING_OR_INVALID_TIER6B_LOT_SCOPE')
if rec.get('kind') != 'EXACT_INTEGER_COUNT':
return _hold_unqual('NON_COUNT_OR_METADATA_TIER6B_SUBSTITUTE_REJECTED')
tp_val = rec.get('timepoint')
if not isinstance(tp_val, str) or not tp_val.strip() or tp_val != tp_val.strip() or tp_val not in TIER6B_ALLOWED_TIMEPOINTS_IIP0031:
return _hold_unqual('INVALID_OR_WRONG_STAGE_TIER6B_TIMEPOINT')
for _stage_k in ('differentiation_stage', 'stage', 'cell_stage', 'developmental_stage'):
if _stage_k in rec and rec[_stage_k] is not None:
_sv = rec[_stage_k]
if not isinstance(_sv, str) or not _sv.strip() or _sv != _sv.strip() or _sv not in TIER6B_ALLOWED_STAGE_LABELS_IIP0031:
return _hold_unqual('INVALID_OR_WRONG_STAGE_TIER6B_TIMEPOINT')
if 'assembly_state' in rec and rec['assembly_state'] is not None and rec['assembly_state'] != 'PRE_ASSEMBLY':
return _hold_unqual('INVALID_OR_WRONG_STAGE_TIER6B_TIMEPOINT')
if 'pre_assembly' in rec and rec['pre_assembly'] is not None and rec['pre_assembly'] is not True:
return _hold_unqual('INVALID_OR_WRONG_STAGE_TIER6B_TIMEPOINT')
av_val = rec.get('assay_version')
if not isinstance(av_val, str) or not av_val.strip() or av_val != av_val.strip() or av_val not in TIER6B_ALLOWED_ASSAY_VERSIONS_IIP0031:
return _hold_unqual('UNVALIDATED_TIER6B_ASSAY_VERSION')
unit_val = rec.get('unit')
if not isinstance(unit_val, str) or not unit_val.strip() or unit_val != unit_val.strip() or unit_val not in TIER6B_ALLOWED_UNITS_IIP0031:
return _hold_unqual('INCOMPATIBLE_TIER6B_MEASUREMENT_UNIT')
if rec.get('sample_n') is not None:
return _hold_unqual('INVALID_TIER6B_SAMPLE_N_FOR_EXACT_COUNT')
for req_id_k in ('product_variant_id', 'construct_sha256', 'donor_seedline_id', 'mcb_id', 'lot_id', 'sample_id', 'fraction_id'):
v_id = rec.get(req_id_k)
if not isinstance(v_id, str) or not v_id.strip() or v_id != v_id.strip():
return _hold_unqual(f'MISSING_OR_INVALID_PROVENANCE_FIELD:{req_id_k}')
rec_pvid_c, _ = _canonicalize_product_id_iip0031(rec['product_variant_id'], root_path)
if (
rec_pvid_c != t_pvid
or rec['construct_sha256'] != t_sha
or rec['donor_seedline_id'] != t_seed
or rec['mcb_id'] != t_mcb
or rec['lot_id'] != t_lot
):
return _hold_unqual('INCONSISTENT_RECORD_PROVENANCE_WITH_TARGET_LOT')
r_bg_val = rec.get('background_id')
if t_bg is not None and r_bg_val != t_bg:
return _hold_unqual('MISSING_OR_MISMATCHED_BACKGROUND_ID')
if r_bg_val is not None:
if not isinstance(r_bg_val, str) or not r_bg_val.strip() or r_bg_val != r_bg_val.strip():
return _hold_unqual('INVALID_BACKGROUND_ID')
if lot_bg_seen is None:
lot_bg_seen = r_bg_val
elif lot_bg_seen != r_bg_val:
return _hold_unqual('INCONSISTENT_BACKGROUND_ID_ACROSS_FRACTIONS')
# Strictly prohibit calculation-only supplied d_L, single-fraction bypass, and caller weight overrides/unverified bounds:
if rec.get('calculation_only_supplied_d_L') not in (None, False) or 'supplied_d_i_L' in rec:
return _hold_unqual('CALCULATION_ONLY_SUPPLIED_D_L_PROHIBITED_ON_LIVE_PATHS')
if rec.get('single_fraction_unsorted_lot') not in (None, False):
return _hold_unqual('SINGLE_FRACTION_UNSORTED_BYPASS_PROHIBITED_IN_SORTED_LOT_TIER6B')
for _forb_wk in ('w_i_lo', 'w_i_hi', 'w_i_upper', 'weight_override', 'w_override'):
if _forb_wk in rec and rec[_forb_wk] is not None:
return _hold_unqual('CALLER_WEIGHT_OVERRIDE_OR_UNVERIFIED_BOUNDS_PROHIBITED')
# Validate per-row `w_i` type and bounds BEFORE aggregation so lexical row order never masks Boolean/invalid `w_i` (#25):
if 'w_i' in rec:
w_row_raw = rec.get('w_i')
if not _is_strict_finite_number_iip0024(w_row_raw):
return _hold_unqual(f'INVALID_OR_MISSING_FRACTION_WEIGHT:{rec["fraction_id"]}')
if not (0.0 < float(w_row_raw) <= 1.0):
return _hold_unqual(f'OUT_OF_RANGE_FRACTION_WEIGHT:{rec["fraction_id"]}')
k_raw = rec.get('k')
n_raw = rec.get('N')
if type(k_raw) is not int or type(n_raw) is not int:
return _hold_unqual('NON_INTEGER_OR_BOOLEAN_TIER6B_COUNT_OR_DENOMINATOR')
if n_raw < 1 or k_raw != 0 or k_raw > n_raw:
return _hold_unqual('INVALID_TIER6B_DENOMINATOR_OR_COUNT_BOUNDS')
if rec.get('clustered_sampling') is True or (
rec.get('clustered_sampling') is not None and type(rec.get('clustered_sampling')) is not bool
):
return _hold_unqual('UNSUPPORTED_CLUSTERED_SAMPLING_REJECTED')