OpenIslet

scripts/ingest_wetlab_results.py

Closed-Loop Wet-Lab Results Ingestor & Bayesian Posterior Updater (`scripts/ingest_wetlab_results.py`, v0.8.0)

script Release v0.8.0 gen-eb955f8266035aba 228 KB · 18 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/ingest_wetlab_results.py · SHA-256: e050593675170515…

                            try:
                                os.unlink(name, dir_fd=parent)
                            except FileNotFoundError:
                                pass
                            os.fsync(parent)
                    else:
                        _atomic_write_bytes(target, old)
                except BaseException as failure:
                    rollback_errors.append(str(failure))
            if rollback_errors:
                raise RuntimeError("Calibration publication failed and rollback requires manual recovery: "
                                   + "; ".join(rollback_errors)) from original
            raise


def _load_contract_helper_iip0026(root: Path | str | None = None) -> Any:
    global _MEASUREMENT_CONTRACT_MODULE
    if root is not None:
        root_p = Path(root)
        if root_p.resolve() != REPO_ROOT.resolve():
            spec = importlib.util.spec_from_file_location("openislet_measurement_contract_custom", root_p / "scripts/wetlab_contract.py")
            helper = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(helper)
            return helper
    if _MEASUREMENT_CONTRACT_MODULE is None:
        spec = importlib.util.spec_from_file_location("openislet_measurement_contract", REPO_ROOT / "scripts/wetlab_contract.py")
        helper = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(helper)
        _MEASUREMENT_CONTRACT_MODULE = helper
    return _MEASUREMENT_CONTRACT_MODULE


def _nonfinite_stage0_measurement_keys(measurements: dict) -> set:
    """Include integers and floats that cannot be represented finitely by the measurement normalizer."""
    out = set()
    for key, value in measurements.items():
        if type(value) in (int, float):
            try:
                if not (-sys.float_info.max <= value <= sys.float_info.max):
                    out.add(key)
            except (OverflowError, TypeError):
                out.add(key)
    return out


def _conflicting_stage0_batch_scope(record: dict, contract: Any, root_path: Path) -> bool:
    """A structured scope must agree with provenance aliases on the envelope."""
    scope_obj = record.get("scope")
    scope_dict = scope_obj if isinstance(scope_obj, dict) else {}
    for names in (("product_variant_id",), ("lot_id", "current_lot_id"), ("campaign_id", "assay_campaign_id")):
        values = [container[key] for container in (record, scope_dict)
                  for key in names if key in container]
        if len(values) < 2 or all(value == values[0] for value in values):
            continue
        if names == ("product_variant_id",) and all(isinstance(value, str) for value in values):
            canonical = {contract._canonicalize_product_id_iip0031(value, root_path)[0] or value for value in values}
            if len(canonical) == 1:
                continue
        return True
    return False


def _sanitize_stage0_envelope_iip0031(doc: Dict[str, Any]) -> Tuple[Dict[str, Any], List[str], bool]:
    """
    Isolate malformed envelope container blocks and non-finite/oversized scalar entries without
    suppressing independently attributable safety stops (S9, Tier 6B, Rule S11).
    """
    bad_struct_names = [
        name
        for name in ("scope", "measurements", "iip0026_molecular_observations")
        if name in doc and not isinstance(doc[name], dict)
    ]
    top_nf = _nonfinite_stage0_measurement_keys(doc)
    had_nonfinite = bool(top_nf)
    sanitized: Dict[str, Any] = {
        k: v
        for k, v in doc.items()
        if k not in bad_struct_names and k not in top_nf
    }
    for ctr_name in ("scope", "measurements", "iip0026_molecular_observations"):
        if ctr_name in sanitized and isinstance(sanitized[ctr_name], dict):
            ctr_nf = _nonfinite_stage0_measurement_keys(sanitized[ctr_name])
            if ctr_nf:
                had_nonfinite = True
                sanitized[ctr_name] = {k: v for k, v in sanitized[ctr_name].items() if k not in ctr_nf}
            else:
                sanitized[ctr_name] = dict(sanitized[ctr_name])
    scope_d = sanitized.get("scope") if isinstance(sanitized.get("scope"), dict) else {}
    mol_d = sanitized.get("iip0026_molecular_observations") if isinstance(sanitized.get("iip0026_molecular_observations"), dict) else {}
    if (
        scope_d.get("sample_id") is not None
        and sanitized.get("sample_id") is not None
        and scope_d.get("sample_id") != sanitized.get("sample_id")
        and scope_d.get("sample_unit_id") is None
        and sanitized.get("sample_unit_id") is None
    ):
        sanitized["sample_unit_id"] = scope_d["sample_id"]
    if (
        scope_d.get("sample_unit_id") is not None
        and sanitized.get("sample_unit_id") is not None
        and scope_d.get("sample_unit_id") != sanitized.get("sample_unit_id")
        and scope_d.get("sample_id") is None
        and sanitized.get("sample_id") is None
    ):
        sanitized["sample_id"] = scope_d["sample_unit_id"]
    if (
        "iip0029_twoclock_record" not in sanitized
        and "iip0029_twoclock_record" in mol_d
        and mol_d["iip0029_twoclock_record"] is not None
    ):
        sanitized["iip0029_twoclock_record"] = mol_d["iip0029_twoclock_record"]
    return sanitized, bad_struct_names, had_nonfinite


def _is_hard_stop_result_iip0031(res: Dict[str, Any]) -> bool:
    """Return True iff `res` carries an independently attributable S9, Tier 6B, or Rule S11 hard stop."""
    winner = res.get("hard_stop_precedence_winner")
    return bool(
        winner in ("S9_HARD_SAFETY_STOP", "FAIL_TIER6B_OUTGROWTH_DETECTED")
        or (isinstance(winner, str) and winner.startswith("FAIL_S11_"))
    )


def _hard_stop_rank_iip0031(res: Dict[str, Any]) -> int:
    """Global hard-stop precedence rank: 0 = S9, 1 = Tier 6B, 2 = Rule S11, 3 = none."""
    winner = res.get("hard_stop_precedence_winner")
    if winner == "S9_HARD_SAFETY_STOP":
        return 0
    if winner == "FAIL_TIER6B_OUTGROWTH_DETECTED":
        return 1
    if isinstance(winner, str) and winner.startswith("FAIL_S11_"):
        return 2
    return 3


def _parse_replay_timestamp_iip0031(ts_raw: Any) -> Tuple[int, int, str]:
    """Parse ISO-8601 UTC timestamps into an exact integer microsecond epoch key for chronological sorting."""
    if isinstance(ts_raw, str):
        ts_clean = ts_raw.strip()
        if ts_clean:
            try:
                norm = ts_clean[:-1] + "+00:00" if ts_clean.endswith(("Z", "z")) else ts_clean
                dt = datetime.fromisoformat(norm)
                if dt.tzinfo is None:
                    dt = dt.replace(tzinfo=timezone.utc)
                delta = dt.astimezone(timezone.utc) - datetime(1970, 1, 1, tzinfo=timezone.utc)
                epoch_us = (delta.days * 86400 + delta.seconds) * 1_000_000 + delta.microseconds
                return (0, epoch_us, "")
            except ValueError:
                return (1, 0, ts_clean)
    return (2, 0, "")


def _extract_stage0_batch_measurements_preserving_explicit_se_iip0026(
    raw_meas: Dict[str, Any],
    wc_helper: Any,
) -> Dict[str, Any]:
    """Extract canonical measurements via `_extract_canonical_measurements` without fabricating explicit SE provenance, overflowing on huge ints, or erasing strict int types (IIP-0026; DEC-105)."""
    bad_nf = _nonfinite_stage0_measurement_keys(raw_meas)
    finite_raw = {k: v for k, v in raw_meas.items() if k not in bad_nf} if bad_nf else raw_meas
    extracted = _extract_canonical_measurements(finite_raw)
    strict_int_keys = getattr(wc_helper, "STAGE0_STRICT_INTEGER_COUNT_AND_DENOMINATOR_KEYS", frozenset())
    out: Dict[str, Any] = {}
    for k, v in extracted.items():
        if v == "UNAVAILABLE":
            continue
        if k.endswith("_se") and k not in finite_raw:
            continue
        if k in strict_int_keys and k in finite_raw:
            orig = finite_raw[k]
            if type(orig) is bool:
                out[k] = orig
            elif type(orig) is int:
                out[k] = orig
            else:
                out[k] = v
        else:
            out[k] = v
    # Preserve any invalid/boolean finite measurement attempts so downstream guardrail evaluation fails closed identically to direct calls:
    for k, orig in finite_raw.items():
        if k not in out and orig is not None:
            out[k] = orig
    return out


def ingest_stage0_research_or_wetlab_batch(
    raw_json_or_dict: str | Dict[str, Any],
    *,
    root: Path | str | None = None,
) -> Dict[str, Any]:
    """
    Path 2 Stage-0 Research & Wet-Lab Batch Ingestion Evaluator (IIP-0026; DEC-105; hardened IIP-0031).
    Parses a serialized JSON document or dictionary strictly via `loads_strict_json` (rejecting
    unreadable JSON, duplicate keys, and non-finite JSON tokens), then routes through the shared
    registry-bound `evaluate_stage0_product_contract` validator so Direct, Dict Ingestion, Wire
    Ingestion, and Chronological Replay share identical provenance, alias, BAF, S9, Tier 6B, and
    Rule S11 semantics. When an unambiguously decoded JSON object contains a malformed auxiliary
    envelope field or out-of-range integer alongside an independently attributable hard safety stop,
    the hard safety stop is preserved with explicit malformed-envelope diagnostics; otherwise the
    strict schema `ValueError` is raised.
    """
    doc = loads_strict_json(raw_json_or_dict) if isinstance(raw_json_or_dict, str) else raw_json_or_dict
    if not isinstance(doc, dict):
        raise ValueError("Stage-0 ingest batch document must decode to a JSON object (IIP-0026; DEC-105)")
    wc_helper = _load_contract_helper_iip0026(root)
    root_path = Path(root) if root is not None else REPO_ROOT
    if _conflicting_stage0_batch_scope(doc, wc_helper, root_path):
        raise ValueError("Conflicting Stage-0 batch scope")

    sanitized_doc, bad_struct_names, had_nonfinite = _sanitize_stage0_envelope_iip0031(doc)
    out = wc_helper.evaluate_stage0_product_contract(sanitized_doc, root=root)
    if bad_struct_names or had_nonfinite:
        if _is_hard_stop_result_iip0031(out):
            reasons = list(out.get("iip0026_reasons", []))
            if bad_struct_names and "HOLD_MALFORMED_STAGE0_ENVELOPE_FIELD" not in reasons:
                reasons.append("HOLD_MALFORMED_STAGE0_ENVELOPE_FIELD")
            if had_nonfinite and "HOLD_NONFINITE_STAGE0_MEASUREMENT" not in reasons:
                reasons.append("HOLD_NONFINITE_STAGE0_MEASUREMENT")
            out["iip0026_reasons"] = reasons
            return out
        if bad_struct_names:
            raise ValueError(f"Stage-0 batch field {bad_struct_names[0]!r} must be an object")
        raise ValueError("Stage-0 measurements must be finite and representable")
    return out


def _replay_single_scope_iip0031(
    scope_key: Tuple[str, str, str],
    scoped_items: List[Tuple[Tuple[Any, ...], Dict[str, Any], bool]],
    *,
    has_external_malformed: bool,
    root: Path | str | None,
    root_path: Path,
    wc_helper: Any,
) -> Dict[str, Any]:
    """Chronologically replay all records attributed to a single immutable `(product_variant_id, lot_id, campaign_id)` partition."""
    s_pid, s_lot, s_camp = scope_key
    allowed_mol = set(getattr(wc_helper, "IIP0026_ALLOWED_MOLECULAR_OBS_KEYS")) | set(
        getattr(wc_helper, "_ALL_S11_RECOGNIZED_EVIDENCE_KEYS", ())
    )
    forbidden_ovr = getattr(wc_helper, "IIP0026_FORBIDDEN_CALLER_OVERRIDE_KEYS")
    bool_flags = set(getattr(wc_helper, "STAGE0_DECISION_TREE_BOOLEAN_KEYS", ()))
    all_s9_rep_keys = frozenset(k for ks in wc_helper.S9_REPLICATE_KEYS.values() for k in ks)
    all_alias_keys = frozenset(
        k
        for sh, ob, _ in getattr(wc_helper, "_IIP0026_DESIGNB_TYK2_ALIAS_PAIRS", ())
        for k in (sh, ob)
    ) | frozenset({
        "post_edit_per_locus_segmented_baf",
        "per_locus_segmented_baf",