scripts/verify_iip0043_wholegraft_gate0v_and_calibration.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0043_wholegraft_gate0v_and_calibration.py · SHA-256: 20706180ed1ed6a2…
Resolve a prior qualification record AND its archived payload STRICTLY from an
independently controlled external store path (embedded-dict registry JSON file or
file-backed directory store), distinguishing absent vs non-object/unreadable/ambiguous archives.
Enforces `strict_json_load_file` (rejecting duplicate object keys and NaN/Infinity constants)
across registry, record, and archived payload files. NEVER reads caller-supplied inline lot payloads!
"""
if store_path is None:
return None, None, ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE_NOT_PROVIDED"], None, "store_not_provided"
if not isinstance(store_path, (Path, str)):
return None, None, ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE_INVALID_PATH_TYPE"], None, "invalid_store_path"
sp = Path(store_path)
if not sp.exists():
return None, None, ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE_PATH_MISSING"], str(sp.name), "store_missing"
if not _is_valid_sha256_hex(expected_sha256):
return None, None, ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE_INVALID_REF_SHA256"], str(sp.name), "invalid_ref_sha256"
try:
if sp.is_file():
doc = strict_json_load_file(sp, max_int_abs=MAX_STRICT_JSON_INT_ABS)
if not isinstance(doc, dict):
return None, None, ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE_MALFORMED_REGISTRY"], str(sp.name), "malformed_registry"
bucket = doc.get(category)
rec: Dict[str, Any] | None = None
if isinstance(bucket, dict):
cand = bucket.get(expected_sha256)
if isinstance(cand, dict):
rec = cand
elif isinstance(bucket, list):
for item in bucket:
if isinstance(item, dict) and item.get("sha256") == expected_sha256:
rec = item
break
if rec is None:
return None, None, ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE_RECORD_NOT_FOUND"], str(sp.name), "record_not_found"
raw_arch_map = doc.get("archived_payloads")
p_key = rec.get("bank_payload_sha256") or rec.get("process_qual_payload_sha256")
archived: Dict[str, Any] | None = None
if raw_arch_map is None:
arch_status = "absent"
elif not isinstance(raw_arch_map, dict):
arch_status = f"invalid_container_non_object:{type(raw_arch_map).__name__}"
elif not (isinstance(p_key, str) and _is_valid_sha256_hex(p_key)):
arch_status = "missing_or_invalid_payload_key"
elif p_key not in raw_arch_map:
arch_status = "absent"
else:
raw_arch = raw_arch_map[p_key]
if raw_arch is None:
arch_status = "absent_null"
elif isinstance(raw_arch, dict):
archived = raw_arch
arch_status = "present_object"
else:
arch_status = f"non_object:{type(raw_arch).__name__}"
return rec, archived, [], f"registry_file:{sp.name}", arch_status
if sp.is_dir():
rec = None
archived = None
for cand_path in (sp / category / f"{expected_sha256}.json", sp / f"{expected_sha256}.json"):
if cand_path.is_file():
loaded = strict_json_load_file(cand_path, max_int_abs=MAX_STRICT_JSON_INT_ABS)
if isinstance(loaded, dict):
rec = loaded
break
if rec is None and (sp / "registry.json").is_file():
return _lookup_in_trusted_qualification_store_with_archive_status(
sp / "registry.json", category=category, expected_sha256=expected_sha256
)
if rec is None:
return None, None, ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE_RECORD_NOT_FOUND"], str(sp.name), "record_not_found"
p_key = rec.get("bank_payload_sha256") or rec.get("process_qual_payload_sha256")
arch_dir = sp / "archived_payloads"
if not (isinstance(p_key, str) and _is_valid_sha256_hex(p_key)):
arch_status = "missing_or_invalid_payload_key"
elif arch_dir.exists() and not arch_dir.is_dir():
arch_status = "invalid_container_non_directory"
else:
arch_file = arch_dir / f"{p_key}.json"
if not arch_file.is_file():
arch_status = "absent"
else:
try:
loaded_arch = strict_json_load_file(arch_file, max_int_abs=MAX_STRICT_JSON_INT_ABS)
except StrictJSONDecodeError as exc:
arch_status = f"ambiguous_or_noncanonical_json:{exc.reason_code.lower()}"
except RecursionError:
arch_status = "ambiguous_or_noncanonical_json:json_depth_or_recursion_limit_exceeded"
except (OSError, UnicodeDecodeError, json.JSONDecodeError, TypeError, ValueError, OverflowError):
arch_status = "unreadable_or_malformed_json"
else:
if loaded_arch is None:
arch_status = "absent_null"
elif isinstance(loaded_arch, dict):
archived = loaded_arch
arch_status = "present_object"
else:
arch_status = f"non_object:{type(loaded_arch).__name__}"
return rec, archived, [], f"store_dir:{sp.name}", arch_status
except StrictJSONDecodeError as exc:
return (
None,
None,
[
"HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE",
"HOLD_INVALID_INPUT_JSON",
f"HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE_AMBIGUOUS_OR_NONCANONICAL_JSON:{exc.reason_code}",
],
str(sp.name),
f"ambiguous_or_noncanonical_json:{exc.reason_code.lower()}",
)
except RecursionError:
return (
None,
None,
[
"HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE",
"HOLD_INVALID_INPUT_JSON",
"HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE_AMBIGUOUS_OR_NONCANONICAL_JSON:JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED",
],
str(sp.name),
"ambiguous_or_noncanonical_json:json_depth_or_recursion_limit_exceeded",
)
except (OSError, UnicodeDecodeError, json.JSONDecodeError, TypeError, ValueError, OverflowError):
return None, None, ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE_UNREADABLE"], str(sp.name), "store_unreadable"
return None, None, ["HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE", "HOLD_UNVERIFIED_EXTERNAL_APPROVAL_STORE_UNSUPPORTED_PATH"], str(sp.name), "unsupported_store_path"
def _lookup_in_trusted_qualification_store(
store_path: Path | str | None,
*,
category: str,
expected_sha256: Any,
) -> Tuple[Dict[str, Any] | None, Dict[str, Any] | None, List[str], str | None]:
"""
Backward-compatible 4-tuple wrapper around `_lookup_in_trusted_qualification_store_with_archive_status`.
"""
rec, archived, lookup_errs, store_src, _arch_status = _lookup_in_trusted_qualification_store_with_archive_status(
store_path,
category=category,
expected_sha256=expected_sha256,
)
return rec, archived, lookup_errs, store_src
def validate_canonical_composite_envelope(
composite_doc: Any,
*,
openislet_root: Path | None = None,
expected_tier: str | None = None,
expected_lot_id: Any = None,
expected_mcb_id: Any = None,
expected_product_variant_id: Any = None,
) -> Dict[str, Any]:
"""
R08-B1 Shared Canonical Composite Envelope Validator executed identically at BOTH:
1. Direct composite submission (`evaluate_gate0v_composite_release.evaluate_composite_clinical_release`), AND
2. Archived composite bank verification (`resolve_and_verify_trusted_bank_qualification`).
Enforces:
- Canonical top-level `product_variant_id` (mandatory clean non-empty string; alias-only
`product_variant` is ALWAYS rejected with `HOLD_COMPOSITE_MISSING_TOP_PRODUCT_VARIANT_ID`),
reconciled with optional `product_variant` alias and nested legacy/Gate-0V `product_variant_id`s.
- Reconciled `lot_id` (plus top-level/nested lot aliases) and `mcb_id` across top-level,
`legacy_stage0_observations`, and `gate0v_wholegraft_payload`.
- Verified top-level canonical `payload_sha256`.
- Exhaustive reconciliation of EVERY supplied tier field independently (ZERO `or`
short-circuiting!): top-level `qualification_tier`, top-level `operational_tier`, nested
`gate0v_wholegraft_payload.qualification_tier` and `.operational_tier`, and any tier field
supplied on `legacy_stage0_observations` MUST ALL match the active/expected tier, else
`HOLD_COMPOSITE_OPERATIONAL_TIER_MISMATCH`.
- Top-level `antiviral_genotype_stratum` (when present) reconciled against nested Gate-0V.
- Canonical product-family-to-tier allowlist enforcement.
"""
holds: List[str] = []
def _add_hold(tok: str) -> None:
if tok not in holds:
holds.append(tok)
if not isinstance(composite_doc, dict):
return {
"valid": False,
"holds": ["HOLD_COMPOSITE_PAYLOAD_NOT_DICT"],
"top_lot": None,
"top_mcb": None,
"top_pvid_raw": None,
"top_sha": None,
"computed_comp_sha": None,
"canonical_product_def": None,
"canonical_pvid": None,
"legacy_obs": None,
"gate0v_obs": None,
"leg_pvid_canon": None,
"g0v_pvid_canon": None,
"qual_tier": None,
"tier_allowed_for_product": False,
"planned_nw08_route_id": None,
"planned_nw08_route_errors": [],
"planned_nw08_measurement_evidence_sha256": None,
"planned_nw08_measurement_not_before_utc": None,
"require_trusted_nw08_ocr_record": False,
}
top_lot = composite_doc.get("lot_id")
top_mcb = composite_doc.get("mcb_id")
top_pvid_raw = composite_doc.get("product_variant_id")
top_pv_legacy = composite_doc.get("product_variant")
top_sha = composite_doc.get("payload_sha256")
computed_comp_sha = _safe_canonical_lot_sha256(composite_doc)
if computed_comp_sha is None:
_add_hold("HOLD_COMPOSITE_NONCANONICAL_OR_NONFINITE_PAYLOAD")
if not _is_clean_nonempty_str(top_lot):
_add_hold("HOLD_COMPOSITE_MISSING_TOP_LOT_ID")
else:
for ak in ("current_lot_id", "batch_id"):
if ak in composite_doc and composite_doc.get(ak) is not None and composite_doc.get(ak) != top_lot:
_add_hold("HOLD_COMPOSITE_TOP_LOT_ALIAS_MISMATCH")
if expected_lot_id is not None and top_lot != expected_lot_id:
_add_hold("HOLD_COMPOSITE_TOP_LOT_ID_MISMATCH")
if not _is_clean_nonempty_str(top_mcb):
_add_hold("HOLD_COMPOSITE_MISSING_TOP_MCB_ID")
elif expected_mcb_id is not None and top_mcb != expected_mcb_id:
_add_hold("HOLD_COMPOSITE_TOP_MCB_ID_MISMATCH")
canonical_product_def: Dict[str, Any] | None = None
canonical_pvid: str | None = None
if not _is_clean_nonempty_str(top_pvid_raw):
_add_hold("HOLD_COMPOSITE_MISSING_TOP_PRODUCT_VARIANT_ID")
else:
canonical_product_def = resolve_canonical_product_variant(top_pvid_raw, openislet_root=openislet_root)
if canonical_product_def is None:
_add_hold("HOLD_COMPOSITE_UNREGISTERED_PRODUCT_VARIANT_ID")
else:
canonical_pvid = canonical_product_def["product_variant_id"]
if expected_product_variant_id is not None and canonical_pvid != expected_product_variant_id:
_add_hold("HOLD_COMPOSITE_TOP_PRODUCT_VARIANT_ID_MISMATCH")
if top_pv_legacy is not None:
pv_leg_res = resolve_canonical_product_variant(top_pv_legacy, openislet_root=openislet_root)
if pv_leg_res is None:
_add_hold("HOLD_COMPOSITE_UNREGISTERED_TOP_PRODUCT_VARIANT_ALIAS")
else:
if canonical_pvid is not None and pv_leg_res["product_variant_id"] != canonical_pvid:
_add_hold("HOLD_COMPOSITE_TOP_PRODUCT_VARIANT_ALIAS_MISMATCH")