# SPDX-License-Identifier: MIT """Build a non-submitted OpenLab validation draft from a LakeIce clean-room seal. The adapter is intentionally offline and fail-closed. It checks the exact published task file, the report seal and the three local artifact hashes before writing a draft. Its output is structural review material only; it does not submit files or establish identity, independence, validation or discovery. """ from __future__ import annotations import argparse from datetime import datetime, timezone from hashlib import sha256 import json import os from pathlib import Path import re import sys DRAFT_SCHEMA = "openlab-independent-validation-draft-v2" DRAFT_STATUS = "offline_draft_not_submitted_or_validated" CATALOG_SHA256 = "d063dd33d84f436033e6dfa9a2d152efff0dd0f2a25e39f69ee801d0ada0d6df" VALIDATION_CONTRACT_SHA256 = "5334ebf3965dbf4563d5c862dad7533147c8537361191eb7df636378efedbc71" TASK_SLUG = "lakeice-model-onefit" TASK_SHA256 = "149e7e4b190a62966be869851f150c43efc006546c1969d2fa4937804615c88f" TASK_SPEC_SLUG = "lakeice-cleanroom-fold0-seed0-three-arm-check" TASK_FILE_SHA256 = "75cf12ea44c0f8ec94b880967e6300167b424c8f7666fd8b59456f36d2a19c5c" ALLOWED_SCOPE = "bounded_offline_research" REPORT_SCHEMA = "kiwerb-lakeice-cleanroom-onefit-report-v1" SEAL_SCHEMA = "kiwerb-lakeice-cleanroom-seal-v1" DECLARATIONS_SCHEMA = "kiwerb-lakeice-cleanroom-validation-bridge-declarations-v1" MAX_ARTIFACT_BYTES = 2 * 1024 * 1024 * 1024 SHA256_RE = re.compile(r"^[0-9a-f]{64}$") CREDENTIAL_RE = re.compile( r"(?:sk-[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9]{20,}|" r"AIza[A-Za-z0-9_-]{20,}|olr?_[A-Za-z0-9_-]{32,})" ) ROLES = ("independent_source_code", "run_log", "row_level_predictions") REPORT_FIELDS = { "schema", "task_slug", "authored_at_utc", "contributor_role", "prior_kiwerb_code_or_result_exposure", "collaboration_and_method_influence", "conflicts_of_interest", "source_hash_verification", "original_csv_precision_check", "fold_partition_and_group_integrity", "arm_selection_and_exposure_checks", "environment", "method_deviations", "one_fit_results", "interpretation_and_uncertainty", "full_25_pair_comparison_complete", "independent_scientific_validation_claimed", "scientific_discovery_claimed", "artifacts", } REPORT_TEXT_FIELDS = ( "contributor_role", "prior_kiwerb_code_or_result_exposure", "collaboration_and_method_influence", "conflicts_of_interest", "source_hash_verification", "original_csv_precision_check", "fold_partition_and_group_integrity", "arm_selection_and_exposure_checks", "method_deviations", "interpretation_and_uncertainty", ) DECLARATION_FIELDS = { "schema_version", "independence_statement", "independent_of_kiwerb_result", "unpublished_kiwerb_answer_used", "optional_pseudonym", } def _json_bytes(value: object, *, sort_keys: bool = False, newline: bool = False) -> bytes: text = json.dumps(value, ensure_ascii=False, sort_keys=sort_keys, separators=(",", ":")) return (text + ("\n" if newline else "")).encode("utf-8") def _read_regular(path: Path, label: str, limit: int | None = None) -> bytes: if path.is_symlink() or not path.is_file(): raise ValueError(f"{label} must be a regular non-symlink file") if limit is not None and path.stat().st_size > limit: raise ValueError(f"{label} exceeds {limit} bytes") return path.read_bytes() def _load_json(raw: bytes, label: str) -> object: def reject_nonfinite(value: str) -> None: raise ValueError(f"{label} contains non-finite number {value}") try: return json.loads(raw.decode("utf-8"), parse_constant=reject_nonfinite) except (UnicodeError, json.JSONDecodeError) as exc: raise ValueError(f"{label} must be UTF-8 JSON") from exc def _exact_object(value: object, fields: set[str], label: str) -> dict: if not isinstance(value, dict) or set(value) != fields: raise ValueError(f"{label} fields do not match the required exact set") return value def _clean_text(value: object, label: str, minimum: int = 1, maximum: int = 4000) -> str: if not isinstance(value, str): raise ValueError(f"{label} must be text") value = value.strip() if not minimum <= len(value) <= maximum: raise ValueError(f"{label} must contain {minimum} to {maximum} nonblank characters") upper = value.upper() if "[FILL" in upper or "[EDIT" in upper or "PLACEHOLDER" in upper: raise ValueError(f"{label} still contains a placeholder") if CREDENTIAL_RE.search(value): raise ValueError(f"{label} contains credential-like text") return value def _validate_task(raw: bytes) -> None: if sha256(raw).hexdigest() != TASK_FILE_SHA256: raise ValueError("task.json SHA-256 drift") task = _load_json(raw, "task.json") if not isinstance(task, dict) or task.get("slug") != TASK_SPEC_SLUG: raise ValueError("task.json identity drift") def _validate_report(report: object) -> dict: report = _exact_object(report, REPORT_FIELDS, "clean-room report") if report["schema"] != REPORT_SCHEMA or report["task_slug"] != TASK_SPEC_SLUG: raise ValueError("clean-room report identity drift") for field in REPORT_TEXT_FIELDS: report[field] = _clean_text(report[field], field) for field in ( "full_25_pair_comparison_complete", "independent_scientific_validation_claimed", "scientific_discovery_claimed", ): if report[field] is not False: raise ValueError(f"clean-room one-fit report requires {field}=false") environment = _exact_object( report["environment"], {"python", "numpy", "scikit_learn", "cpu_threads"}, "environment" ) for field in environment: environment[field] = _clean_text(environment[field], f"environment.{field}", 1, 300) results = _exact_object(report["one_fit_results"], {"official", "purged", "control"}, "one_fit_results") if any(value is None for value in results.values()): raise ValueError("one_fit_results values cannot be null") authored = _clean_text(report["authored_at_utc"], "authored_at_utc", 20, 40) try: parsed = datetime.fromisoformat(authored.replace("Z", "+00:00")) except ValueError as exc: raise ValueError("authored_at_utc must be an ISO-8601 timestamp") from exc if parsed.tzinfo is None or parsed.utcoffset() != timezone.utc.utcoffset(parsed): raise ValueError("authored_at_utc must use UTC") if parsed > datetime.now(timezone.utc): raise ValueError("authored_at_utc cannot be in the future") artifacts = report["artifacts"] if not isinstance(artifacts, list) or len(artifacts) != len(ROLES): raise ValueError("clean-room report must declare the exact three artifacts") by_role: dict[str, str] = {} for item in artifacts: item = _exact_object(item, {"role", "sha256"}, "artifact declaration") role, digest = item["role"], item["sha256"] if role not in ROLES or role in by_role or not isinstance(digest, str) or not SHA256_RE.fullmatch(digest): raise ValueError("artifact declarations require unique known roles and lowercase SHA-256 values") by_role[role] = digest if set(by_role) != set(ROLES) or len(set(by_role.values())) != len(ROLES): raise ValueError("artifact declarations require three distinct hashes") report["authored_at_utc"] = authored return report def _validate_seal(raw: bytes) -> tuple[dict, str]: sealed = _exact_object(_load_json(raw, "sealed report"), {"schema", "report_sha256", "report"}, "sealed report") if (sealed["schema"] != SEAL_SCHEMA or not isinstance(sealed["report_sha256"], str) or not SHA256_RE.fullmatch(sealed["report_sha256"])): raise ValueError("sealed report identity drift") actual = sha256(_json_bytes(sealed["report"], sort_keys=True, newline=True)).hexdigest() if sealed["report_sha256"] != actual: raise ValueError("sealed report hash mismatch") report = _validate_report(sealed["report"]) return report, sha256(raw).hexdigest() def _validate_declarations(raw: bytes) -> dict: value = _exact_object(_load_json(raw, "declarations"), DECLARATION_FIELDS, "declarations") if value["schema_version"] != DECLARATIONS_SCHEMA: raise ValueError("declarations schema drift") if value["independent_of_kiwerb_result"] is not True or value["unpublished_kiwerb_answer_used"] is not False: raise ValueError("result-blind declarations are not eligible for this bridge") value["independence_statement"] = _clean_text( value["independence_statement"], "independence_statement", 10, 4000 ) pseudonym = value["optional_pseudonym"] if pseudonym is not None: value["optional_pseudonym"] = _clean_text(pseudonym, "optional_pseudonym", 1, 120) return value def _parse_artifacts(values: list[str]) -> dict[str, Path]: supplied: dict[str, Path] = {} identities: set[str] = set() for value in values: if "=" not in value: raise ValueError("artifact must use ROLE=PATH") role, raw_path = value.split("=", 1) if role not in ROLES or role in supplied: raise ValueError("unknown or duplicate artifact role") path = Path(raw_path) if path.is_symlink() or not path.is_file(): raise ValueError("artifact must be a regular non-symlink file") identity = os.path.normcase(str(path.resolve())) if identity in identities: raise ValueError("one file cannot satisfy multiple artifact roles") identities.add(identity) supplied[role] = path if set(supplied) != set(ROLES): raise ValueError("all three artifact roles are required") return supplied def _artifact_hash(path: Path) -> str: digest = sha256() total = 0 with path.open("rb") as stream: for block in iter(lambda: stream.read(1024 * 1024), b""): total += len(block) if total > MAX_ARTIFACT_BYTES: raise ValueError(f"artifact exceeds {MAX_ARTIFACT_BYTES} bytes") digest.update(block) return digest.hexdigest() def _bounded(label: str, *parts: str) -> str: value = "\n".join(part.strip() for part in parts if part.strip()) return _clean_text(value, label, 10, 4000) def convert(sealed_path: Path, declarations_path: Path, task_path: Path, artifact_values: list[str]) -> dict: task_raw = _read_regular(task_path, "task.json", 256 * 1024) _validate_task(task_raw) sealed_raw = _read_regular(sealed_path, "sealed report", 2 * 1024 * 1024) report, sealed_file_sha256 = _validate_seal(sealed_raw) declarations = _validate_declarations(_read_regular(declarations_path, "declarations", 64 * 1024)) supplied = _parse_artifacts(artifact_values) expected = {item["role"]: item["sha256"] for item in report["artifacts"]} actual = {role: _artifact_hash(supplied[role]) for role in ROLES} for role in ROLES: if actual[role] != expected[role]: raise ValueError(f"artifact hash mismatch for {role}") artifact_sha256s = [sealed_file_sha256, TASK_FILE_SHA256, *(actual[role] for role in ROLES)] if len(set(artifact_sha256s)) != len(artifact_sha256s): raise ValueError("draft artifact hashes must remain distinct") authored = datetime.fromisoformat(report["authored_at_utc"].replace("Z", "+00:00")) body = { "schema_version": DRAFT_SCHEMA, "status": DRAFT_STATUS, "catalog_sha256": CATALOG_SHA256, "validation_contract_sha256": VALIDATION_CONTRACT_SHA256, "selected_task_slug": TASK_SLUG, "selected_task_sha256": TASK_SHA256, "allowed_scope": ALLOWED_SCOPE, "verifier_role": _clean_text(report["contributor_role"], "verifier_role", 10, 4000), "independence_statement": declarations["independence_statement"], "independent_of_kiwerb_result": True, "unpublished_kiwerb_answer_used": False, "prior_access_or_collaboration": _bounded( "prior_access_or_collaboration", f"Prior KIWERB code or result exposure: {report['prior_kiwerb_code_or_result_exposure']}", f"Collaboration and method influence: {report['collaboration_and_method_influence']}", ), "source_access_observed": _bounded( "source_access_observed", f"Source hash verification: {report['source_hash_verification']}", f"Original CSV precision check: {report['original_csv_precision_check']}", ), "method": _bounded( "method", "Environment: " + json.dumps(report["environment"], ensure_ascii=False, sort_keys=True, separators=(",", ":")), f"Method deviations: {report['method_deviations']}", ), "observations": _bounded( "observations", f"Fold partition and group integrity: {report['fold_partition_and_group_integrity']}", f"Arm selection and exposure checks: {report['arm_selection_and_exposure_checks']}", ), "result": _bounded( "result", "Participant-authored one-fit results: " + json.dumps(report["one_fit_results"], ensure_ascii=False, sort_keys=True, separators=(",", ":")), ), "uncertainty_and_limits": _bounded( "uncertainty_and_limits", f"Interpretation and uncertainty: {report['interpretation_and_uncertainty']}", "Full 25-pair comparison complete: false. This bridge does not verify identity, independence, scientific accuracy, validation or discovery.", ), "conflicts_of_interest": _clean_text(report["conflicts_of_interest"], "conflicts_of_interest", 10, 4000), "artifact_sha256s": artifact_sha256s, "observation_date": authored.date().isoformat(), "optional_pseudonym": declarations["optional_pseudonym"], "dataset_accessed": True, "submission_enabled": False, "independent_validation_claimed": False, "discovery_claimed": False, } return {**body, "draft_sha256": sha256(_json_bytes(body)).hexdigest()} def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--sealed-report", required=True, type=Path) parser.add_argument("--declarations", required=True, type=Path) parser.add_argument("--task", required=True, type=Path) parser.add_argument("--artifact", action="append", required=True, help="ROLE=PATH; provide each exact role once") parser.add_argument("--out", required=True, type=Path) args = parser.parse_args() try: draft = convert(args.sealed_report, args.declarations, args.task, args.artifact) with args.out.open("x", encoding="utf-8") as stream: json.dump(draft, stream, ensure_ascii=False, indent=2) stream.write("\n") except (OSError, ValueError, KeyError, TypeError, json.JSONDecodeError) as exc: print(f"error: {exc}", file=sys.stderr) raise SystemExit(2) print( f"Offline validation draft written to {args.out}; no submission, acceptance, " "identity verification, scientific validation, contact or discovery claim was created." ) if __name__ == "__main__": main()