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…
('background_id',),
('donor_seedline_id', 'seed_line_id'),
('mcb_id',),
('lot_id', 'current_lot_id'),
('campaign_id', 'assay_campaign_id'),
('scope_type',),
)
for grp in _prov_equiv_groups:
o_vals = [outer[k] for k in grp if k in outer and outer[k] is not None]
c_vals = [controls[k] for k in grp if k in controls and controls[k] is not None]
if o_vals and c_vals and any(cv != o_vals[0] for cv in c_vals):
nested_prov_conflict = True
conflict = 'CONFLICTING_OUTER_AND_NESTED_PROVENANCE'
elif not o_vals and c_vals:
if len(set(repr(cv) for cv in c_vals)) > 1:
nested_prov_conflict = True
conflict = 'CONFLICTING_OUTER_AND_NESTED_PROVENANCE'
else:
outer[grp[0]] = c_vals[0]
for id_k in _TIER6B_SAMPLE_ALIASES + _TIER6B_RECORD_ID_ALIASES:
if id_k in outer and id_k in controls and outer[id_k] != controls[id_k]:
conflict = f'CONFLICTING_OUTER_AND_NESTED_IDENTITY:{id_k}'
fields: dict[str, Any] = {}
aliases: list[Any] = []
outer_positive = 0
controls_positive = 0
for src_idx, source in enumerate((outer, controls)):
for raw_key, value in source.items():
if raw_key in _TIER6B_SAMPLE_ALIASES:
if value is not None:
aliases.append(value)
continue
key = _TIER6B_FIELD_ALIASES.get(raw_key, raw_key)
if key == 'k' and type(value) is int and value > 0:
if src_idx == 0:
outer_positive = max(outer_positive, value)
else:
controls_positive = max(controls_positive, value)
value = _tier6b_field_value(key, value)
if key in fields:
try:
if _tier6b_signature(fields[key]) != _tier6b_signature(value):
if conflict is None:
conflict = 'CONFLICTING_TIER6B_OBSERVATION_FIELDS'
except (TypeError, ValueError, OverflowError, RecursionError):
conflict = 'MALFORMED_TIER6B_RECORD_REJECTED'
else:
fields[key] = value
# Never let a nested positive with conflicting/foreign nested provenance inherit an outer zero's target lot (#6):
positive_count = outer_positive if nested_prov_conflict else max(outer_positive, controls_positive)
# Background / fraction / record_id carried inside controls for typed atoms use the same binding:
for key in ('fraction_id', 'record_id', 'background_id'):
if key not in outer and key in fields:
outer[key] = fields[key]
primary_id = next((source[key] for source in (outer, controls)
for key in ('sample_id', 'sample_unit_id') if source.get(key) is not None), None)
outer['sample_id'] = primary_id
return outer, fields, primary_id, aliases, positive_count, conflict
def _tier6b_distinct_aliquots(
records: list[_Tier6BRawAliquot],
) -> tuple[list[tuple[_Tier6BFields, list[str]]], list[str], str | None]:
"""Check the complete payload of every member of each transitive physical-identity group."""
parents: dict[str, str] = {}
def representative(token: str) -> str:
parents.setdefault(token, token)
while token != parents[token]:
parents[token] = parents[parents[token]]
token = parents[token]
return token
for fields, primary_id, aliases in records:
if not isinstance(primary_id, str) or not primary_id or primary_id.strip() != primary_id:
return [], [], 'MISSING_OR_INVALID_PROVENANCE_FIELD:sample_id'
for token in aliases:
if not isinstance(token, str) or not token or token.strip() != token:
return [], [], 'INVALID_SAMPLE_OR_SOURCE_SAMPLE_ID'
left, right = representative(primary_id), representative(token)
parents[max(left, right)] = min(left, right)
by_sample = {}
by_record_id: dict[tuple[str, str], tuple[str, str]] = {}
duplicate_ids = set()
try:
for fields, primary_id, aliases in records:
canonical_id = representative(primary_id)
rec_id_vals: list[tuple[str, str]] = []
for rk_alias in _TIER6B_RECORD_ID_ALIASES:
if rk_alias in fields and fields[rk_alias] is not None:
rv = fields[rk_alias]
if not isinstance(rv, str) or not rv.strip() or rv != rv.strip():
return [], [], f'INVALID_TIER6B_RECORD_ID:{rk_alias}'
rec_id_vals.append((rk_alias, rv))
elif rk_alias in fields and fields[rk_alias] is None:
return [], [], f'INVALID_TIER6B_RECORD_ID:{rk_alias}'
if len({rv for _, rv in rec_id_vals}) > 1:
return [], [], 'CONFLICTING_TIER6B_RECORD_ID_ALIASES'
signature = _tier6b_signature({k: v for k, v in fields.items() if k not in _TIER6B_RECORD_ID_ALIASES})
for rk_alias, rv in rec_id_vals:
for ns_key in (('any_record_id', rv), (rk_alias, rv)):
if ns_key in by_record_id:
prev_canon_sid, prev_rec_sig = by_record_id[ns_key]
if canonical_id != prev_canon_sid or signature != prev_rec_sig:
return [], [], f'CONFLICTING_OR_RELABELED_DUPLICATE_RECORD_ID:{rv}'
else:
by_record_id[ns_key] = (canonical_id, signature)
if canonical_id in by_sample:
previous, previous_signature, component_aliases = by_sample[canonical_id]
if fields.get('fraction_id') != previous.get('fraction_id'):
return [], [], f'DUPLICATE_SAMPLE_ID_ACROSS_FRACTIONS:{canonical_id}'
if signature != previous_signature:
return [], [], f'CONFLICTING_REPLAYED_SAMPLE_ID:{canonical_id}'
component_aliases.update(aliases)
duplicate_ids.add(canonical_id)
else:
by_sample[canonical_id] = (fields, signature, set(aliases))
except (TypeError, ValueError, OverflowError, RecursionError):
return [], [], 'MALFORMED_TIER6B_RECORD_REJECTED'
distinct = [
(dict(fields, sample_id=sid), sorted(aliases))
for sid, (fields, _, aliases) in sorted(by_sample.items())
]
return distinct, sorted(duplicate_ids), None
def _is_valid_sha256_hex_iip0031(val: Any) -> bool:
return isinstance(val, str) and len(val) == 64 and all(c in '0123456789abcdef' for c in val)
def _is_attributable_to_target_lot_iip0031(
rec: dict[str, Any],
*,
target_canon_pvid: str | None,
target_construct_sha256: str | None,
target_background_id: str | None,
target_seedline_id: str | None,
target_mcb_id: str | None,
target_lot_id: str | None,
target_campaign_id: str | None,
target_scope_complete: bool,
root_path: Path,
) -> tuple[bool, str]:
if rec.get('endpoint_id') != 'lot_tier6b_sorted_prolif_clonogenic_escape':
return False, 'non_sorted_lot_tier6b_endpoint'
st = rec.get('scope_type', 'LOT_SCOPE')
if st != 'LOT_SCOPE':
return False, f'wrong_scope_type:{st}'
if not target_scope_complete:
return False, 'incomplete_or_invalid_target_scope'
r_pvid_raw = rec.get('product_variant_id')
if r_pvid_raw is None:
return False, 'missing_product_variant_id'
r_pvid, r_pdef = _canonicalize_product_id_iip0031(r_pvid_raw, root_path)
if r_pdef is None or r_pvid != target_canon_pvid:
return False, 'product_variant_mismatch'
r_lot = rec.get('lot_id', rec.get('current_lot_id'))
if not isinstance(r_lot, str) or not r_lot.strip() or r_lot != r_lot.strip():
return False, 'missing_lot_id'
if r_lot != target_lot_id:
return False, 'wrong_lot_id'
r_sha = rec.get('construct_sha256')
if not _is_valid_sha256_hex_iip0031(r_sha) or r_sha != target_construct_sha256:
return False, 'wrong_construct_sha256'
r_seed = rec.get('donor_seedline_id', rec.get('seed_line_id'))
if not isinstance(r_seed, str) or not r_seed.strip() or r_seed != r_seed.strip() or r_seed != target_seedline_id:
return False, 'wrong_seed_line_id'
r_mcb = rec.get('mcb_id')
if not isinstance(r_mcb, str) or not r_mcb.strip() or r_mcb != r_mcb.strip() or r_mcb != target_mcb_id:
return False, 'wrong_mcb_id'
r_bg = rec.get('background_id')
if r_bg is not None:
if not isinstance(r_bg, str) or not r_bg.strip() or r_bg != r_bg.strip():
return False, 'wrong_background_id'
if target_background_id is not None and r_bg != target_background_id:
return False, 'wrong_background_id'
if 'campaign_id' in rec or 'assay_campaign_id' in rec:
r_camp = rec.get('campaign_id', rec.get('assay_campaign_id'))
if r_camp is not None:
if not isinstance(r_camp, str) or not r_camp.strip() or r_camp != r_camp.strip():
return False, 'invalid_campaign_id'
if target_campaign_id is not None and r_camp != target_campaign_id:
return False, 'wrong_campaign_id'
else:
return False, 'invalid_campaign_id'
return True, 'matched'
def evaluate_tier6b_per_fraction_thinning_iip0031(
records: Any,
*,
target_scope: dict[str, Any],
root: Path | str | None = None,
) -> dict[str, Any]:
"""
Auditable GY-018-compliant pre-assembly Stage-7 CD31-/CD144- sorted-lot Tier 6B
per-fraction binomial-thinning evaluator (IIP-0031; DEC-110).
"""
root_path = Path(root) if root is not None else Path(__file__).resolve().parents[1]
target_scope_malformed = not isinstance(target_scope, dict)
if target_scope_malformed:
target_scope = {}
t_pvid, t_pdef = _canonicalize_product_id_iip0031(target_scope.get('product_variant_id'), root_path)
t_sha_raw = target_scope.get('construct_sha256')
t_sha = t_sha_raw if _is_valid_sha256_hex_iip0031(t_sha_raw) else None
t_bg_raw = target_scope.get('background_id')
if (not isinstance(t_bg_raw, str) or not t_bg_raw.strip()) and isinstance(t_pdef, dict):
l2b = t_pdef.get('staged_locus2_modeb_donor_binding')
if isinstance(l2b, dict) and isinstance(l2b.get('background_id'), str):
t_bg_raw = l2b['background_id']
t_bg = t_bg_raw if isinstance(t_bg_raw, str) and t_bg_raw.strip() and t_bg_raw == t_bg_raw.strip() else None
t_seed_raw = target_scope.get('donor_seedline_id', target_scope.get('seed_line_id'))
t_seed = t_seed_raw if isinstance(t_seed_raw, str) and t_seed_raw.strip() and t_seed_raw == t_seed_raw.strip() else None
t_mcb_raw = target_scope.get('mcb_id')
t_mcb = t_mcb_raw if isinstance(t_mcb_raw, str) and t_mcb_raw.strip() and t_mcb_raw == t_mcb_raw.strip() else None
t_lot_raw = target_scope.get('lot_id', target_scope.get('current_lot_id'))
t_lot = t_lot_raw if isinstance(t_lot_raw, str) and t_lot_raw.strip() and t_lot_raw == t_lot_raw.strip() else None
t_camp_raw = target_scope.get('campaign_id', target_scope.get('assay_campaign_id'))
t_camp_invalid = (
('campaign_id' in target_scope or 'assay_campaign_id' in target_scope)
and t_camp_raw is not None
and (not isinstance(t_camp_raw, str) or not t_camp_raw.strip() or t_camp_raw != t_camp_raw.strip())
)
t_camp = t_camp_raw if isinstance(t_camp_raw, str) and t_camp_raw.strip() and t_camp_raw == t_camp_raw.strip() else None
t_l2_sha_mismatch = False
if isinstance(t_pdef, dict) and isinstance(t_pdef.get('staged_locus2_modeb_donor_binding'), dict):
exp_l2_sha = t_pdef['staged_locus2_modeb_donor_binding'].get('locus2_donor_sha256')
if isinstance(exp_l2_sha, str) and t_sha != exp_l2_sha:
t_l2_sha_mismatch = True
target_scope_complete = bool(
not target_scope_malformed
and not t_camp_invalid
and not t_l2_sha_mismatch
and t_pvid is not None
and t_pdef is not None
and t_sha is not None
and t_seed is not None
and t_mcb is not None
and t_lot is not None
)
def _hold_unqual(reason: str, **extra: Any) -> dict[str, Any]:
return {