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…

        ],
        "input_payload_sha256": hashlib.sha256(raw_bytes).hexdigest(),
        "input_payload_received_sha256": received_payload_sha256,
        "measurement_validation": measurement_validation,
        "conjugate_posterior_updates_sha256": hashlib.sha256(updates_bytes).hexdigest(),
        "layer2_and_ranker_reconciliation_note_claude_v80_013_017": {
            "status": "TARGET_PRIORS_SEPARATE_FROM_MODEL_REFERENCES_AND_OBSERVATIONS",
            "current_model_references": model_reference_metadata,
            "exact_product_assays": "PREREGISTERED_PENDING",
            "synthetic_calibration_is_empirical": False,
        },
        "conjugate_posterior_updates": updates,
        "optional_pouch_and_36run_screen_updates_v80_070": optional_pouch_and_screen_updates,
        "stage0_decision_tree_evaluation": stage0_eval_report,
    }
    result_report["calibration_state_sha256"] = _calibration_state_sha256(result_report)
    result_report["state_integrity_scope"] = "Checks complete-state consistency and replay history; hashes and PURE_EMPIRICAL labels do not authenticate bench records or donor/clone independence."
    # Strictly verify output has zero NaN/Inf values before returning (AUDIT-REF):
    json.dumps(result_report, allow_nan=False)
    return result_report


def _validate_safe_cli_path(raw_path: str, label: str) -> Path:
    """Validate CLI file path against symlink traversal outside REPO_ROOT or system temp directory (AUDIT-REF)."""
    p = Path(raw_path).expanduser().absolute()
    if p.is_symlink():
        raise ValueError(f"{label} path {p} must not be a symbolic link (AUDIT-REF)")
    macos_system_root_symlinks = {Path("/var"), Path("/tmp"), Path("/etc")}
    for ancestor in p.parents:
        if ancestor in macos_system_root_symlinks:
            continue
        if ancestor.is_symlink():
            raise ValueError(f"{label} ancestor {ancestor} must not be a symbolic link (AUDIT-REF)")
    resolved = p.resolve()
    allowed_roots = (
        REPO_ROOT.resolve(),
        Path(tempfile.gettempdir()).resolve(),
        Path("/tmp").resolve(),
    )
    if not any(resolved == root or root in resolved.parents for root in allowed_roots):
        raise ValueError(f"{label} path {resolved} must reside inside repository or temporary directory (AUDIT-REF)")
    if p.exists():
        info = p.lstat()
        if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
            raise ValueError(f"{label} must be a regular file with one hardlink")
    return resolved


@contextmanager
def _safe_parent_directory(path: Path, *, create: bool = False):
    """Pin every directory component without following attacker-swapped links."""
    resolved = _validate_safe_cli_path(str(path), "JSON path")
    flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0)
    current = os.open("/", flags)
    try:
        for part in resolved.parent.parts[1:]:
            try:
                nxt = os.open(part, flags, dir_fd=current)
            except FileNotFoundError:
                if not create:
                    raise
                try:
                    os.mkdir(part, dir_fd=current)
                except FileExistsError:
                    pass
                nxt = os.open(part, flags, dir_fd=current)
            os.close(current)
            current = nxt
        yield current, resolved.name
    finally:
        os.close(current)


def _regular_single_link_at(parent: int, name: str, *, missing_ok: bool = False) -> None:
    try:
        info = os.stat(name, dir_fd=parent, follow_symlinks=False)
    except FileNotFoundError:
        if missing_ok:
            return
        raise
    if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
        raise ValueError("JSON path must be a regular file with one hardlink")


def _read_safe_json_file(path: Path) -> tuple[Any, bytes]:
    """Open without following a swapped link or blocking on a special file."""
    with _safe_parent_directory(path) as (parent, name):
        flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
        fd = os.open(name, flags, dir_fd=parent)
        try:
            info = os.fstat(fd)
            if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
                raise ValueError("JSON input must be a regular file with one hardlink")
            with os.fdopen(fd, "rb") as stream:
                fd = -1
                raw = stream.read()
            return loads_strict_json(raw.decode("utf-8")), raw
        finally:
            if fd >= 0:
                os.close(fd)


def _existing_json_bytes(path: Path) -> bytes | None:
    _validate_safe_cli_path(str(path), "JSON snapshot")
    try:
        return _read_safe_json_file(path)[1]
    except FileNotFoundError:
        return None


def _atomic_write_bytes(target_path: Path, content: bytes) -> None:
    with _safe_parent_directory(target_path, create=True) as (parent, name):
        _regular_single_link_at(parent, name, missing_ok=True)
        temporary = f".{name}.{uuid.uuid4().hex}.tmp"
        flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)
        fd = os.open(temporary, flags, 0o600, dir_fd=parent)
        try:
            with os.fdopen(fd, "wb") as stream:
                fd = -1
                stream.write(content)
                stream.flush()
                os.fsync(stream.fileno())
            _regular_single_link_at(parent, name, missing_ok=True)
            os.replace(temporary, name, src_dir_fd=parent, dst_dir_fd=parent)
            os.fsync(parent)
        finally:
            if fd >= 0:
                os.close(fd)
            try:
                os.unlink(temporary, dir_fd=parent)
            except FileNotFoundError:
                pass


def _atomic_write_json(target_path: Path, data: Dict[str, Any]) -> None:
    _atomic_write_bytes(target_path, (json.dumps(data, indent=2, allow_nan=False) + "\n").encode("utf-8"))


@contextmanager
def _calibration_output_lock(path: Path):
    # Keep the small lock inode: unlinking it after unlocking permits two later
    # writers to lock different inodes for the same output. Dry-run/no-write
    # execution never enters this context and never creates it.
    lock_path = path.with_name(f".{path.name}.lock")
    with _safe_parent_directory(lock_path, create=True) as (parent, name):
        flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
        fd = os.open(name, flags, 0o600, dir_fd=parent)
        try:
            info = os.fstat(fd)
            if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
                raise ValueError("Calibration lock must be a regular file with one hardlink")
            try:
                fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
            except BlockingIOError as exc:
                raise ValueError("Another calibration writer holds this output lock") from exc

            def verify_ownership():
                # An operator/revoker can unlink or replace a flock inode. The
                # old descriptor remains locked but no longer excludes writers
                # opening the replacement pathname.
                try:
                    with _safe_parent_directory(lock_path) as (current_parent, current_name):
                        named = os.stat(current_name, dir_fd=current_parent, follow_symlinks=False)
                    held = os.fstat(fd)
                except (OSError, ValueError) as exc:
                    raise ValueError("Calibration writer lock ownership was revoked") from exc
                if (not stat.S_ISREG(named.st_mode) or named.st_nlink != 1 or held.st_nlink != 1
                        or (named.st_dev, named.st_ino) != (held.st_dev, held.st_ino)):
                    raise ValueError("Calibration writer lock ownership was revoked")

            verify_ownership()
            yield verify_ownership
            verify_ownership()
        finally:
            os.close(fd)


def _publish_calibration_report(
    output_path: Path, report: Dict[str, Any], expected_snapshots: Dict[Path, bytes | None],
    *, force_overwrite_empirical: bool = False,
) -> None:
    """Reject stale writers, protect empirical lineage, and roll back alias failures.

    Each rename is atomic; the canonical/legacy pair is rollback protected under
    one writer lock. This is not a multi-file transaction for uncooperative readers.
    """
    output_path = _validate_safe_cli_path(str(output_path), "output")
    canonical_path, alias_path = DEFAULT_OUT.resolve(), LEGACY_ALIAS_PATH.resolve()
    def portable_identity(path: Path) -> Path:
        # Same NFC/casefold contract as study_artifact_exports._portable_path_key;
        # it also protects reserved targets before either file exists.
        return Path(unicodedata.normalize("NFC", str(path)).casefold())
    def same_destination(left: Path, right: Path) -> bool:
        if portable_identity(left) == portable_identity(right):
            return True
        try:
            return left.samefile(right)
        except FileNotFoundError:
            return False
    if same_destination(canonical_path, alias_path):
        raise ValueError("Canonical calibration and legacy alias require distinct portable identities")
    if same_destination(output_path, alias_path):
        raise ValueError("The legacy alias cannot be an independent output; publish through the canonical calibration path")
    if same_destination(output_path, canonical_path) and output_path != canonical_path:
        raise ValueError("Use the canonical calibration path spelling so every writer shares its publication lock")
    targets = [output_path]
    if output_path == canonical_path:
        targets.append(_validate_safe_cli_path(str(LEGACY_ALIAS_PATH), "legacy alias"))
    if set(expected_snapshots) != set(targets):
        raise ValueError("Output publication requires an entry snapshot for every target")
    published_bytes = (json.dumps(report, indent=2, allow_nan=False) + "\n").encode("utf-8")
    with _calibration_output_lock(output_path) as verify_ownership:
        for target in targets:
            current = _existing_json_bytes(target)
            if current != expected_snapshots[target]:
                raise ValueError("Calibration output changed since this update began; reload the latest posterior")
            if current is None:
                continue
            existing = loads_strict_json(current.decode("utf-8"))
            if isinstance(existing, dict) and existing.get("calibration_mode") == "EMPIRICAL_WETLAB_INGESTION":
                if report["calibration_mode"] != "EMPIRICAL_WETLAB_INGESTION":
                    if not force_overwrite_empirical:
                        raise ValueError("Refusing to overwrite empirical calibration with a synthetic dry-run")
                elif report.get("parent_report_sha256") != hashlib.sha256(
                        json.dumps(existing, sort_keys=True, allow_nan=False).encode("utf-8")).hexdigest():
                    raise ValueError("Empirical overwrite must extend the currently published posterior")
        published: list[Path] = []
        try:
            for target in targets:
                verify_ownership()
                if _existing_json_bytes(target) != expected_snapshots[target]:
                    raise ValueError("Calibration output changed during publication; preserving intervening bytes")
                # Track attempts before writing: rename may have succeeded even
                # when a subsequent directory fsync raises an exception.
                published.append(target)
                _atomic_write_json(target, report)
                verify_ownership()
        except BaseException as original:
            rollback_errors = []
            for target in reversed(published):
                try:
                    verify_ownership()
                    old = expected_snapshots[target]
                    current = _existing_json_bytes(target)
                    if current == old:
                        continue  # The attempted write failed before replacement.
                    if current != published_bytes:
                        raise ValueError(f"Preserving intervening calibration bytes at {target}")
                    if old is None:
                        with _safe_parent_directory(target) as (parent, name):