"""Flat submission contracts, failure reason enums, and report builders.""" from __future__ import annotations import math from typing import Any from core.ztp_client import is_valid_sha384_hex FAILURE_REASONS = ( "none", "physics_violation", "seal_invalid", "budget_exhausted", "schema_error", "harness_error", ) MAX_SUBMISSION_TOP_KEYS = 6 def is_finite_number(val: Any) -> bool: """True iff `val` is a finite int/float (excluding bool).""" if isinstance(val, bool) or not isinstance(val, (int, float)): return False return math.isfinite(float(val)) def extract_seal_tokens(raw_seals: Any) -> tuple[bool, list[str], str | None]: """Parse `submission['seals']` accepting either a list[str] or dict[str, str]. Returns `(container_valid, ordered_unique_tokens, schema_error_or_None)`. Individual token format/provenance checks happen downstream so malformed hex strings classify cleanly as `seal_invalid`, not `schema_error`. """ if isinstance(raw_seals, list): if not raw_seals: return False, [], "Field 'seals' must be a non-empty list or object of 96-hex SHA-384 hashes." tokens: list[str] = [] for idx, item in enumerate(raw_seals): if not isinstance(item, str): return False, [], f"Field 'seals[{idx}]' must be a SHA-384 hex string, got {type(item).__name__}." tok = item.strip().lower() if tok not in tokens: tokens.append(tok) return True, tokens, None if isinstance(raw_seals, dict): if not raw_seals: return False, [], "Field 'seals' object must contain at least one 96-hex SHA-384 hash." tokens = [] for key, item in raw_seals.items(): if not isinstance(item, str): return False, [], f"Field 'seals[{key!r}]' must be a SHA-384 hex string, got {type(item).__name__}." tok = item.strip().lower() if tok not in tokens: tokens.append(tok) return True, tokens, None return False, [], "Field 'seals' must be a list of SHA-384 hex strings or a label->hash object." def validate_syn_submission( sub: Any, task_id: str, required_design_vars: tuple[str, ...] | list[str], ) -> tuple[bool, list[str], list[str]]: """Validate flat <=6-key SYN submission contract (`task_id`, `design_variables`, `seals`). Returns `(schema_ok, errors, parsed_seal_tokens)`. """ if not isinstance(sub, dict): return False, ["Submission root must be a JSON object."], [] if len(sub) > MAX_SUBMISSION_TOP_KEYS: return ( False, [f"Submission has {len(sub)} top-level keys; maximum allowed is {MAX_SUBMISSION_TOP_KEYS}."], [], ) errors: list[str] = [] if sub.get("task_id") != task_id: errors.append(f"Expected task_id={task_id!r}, got {sub.get('task_id')!r}.") dv = sub.get("design_variables") if not isinstance(dv, dict): errors.append("Field 'design_variables' must be a JSON object of numeric parameters.") else: for k in required_design_vars: if k not in dv: errors.append(f"Missing required design variable 'design_variables.{k}'.") elif not is_finite_number(dv[k]): errors.append(f"Design variable 'design_variables.{k}' must be a finite number, got {dv[k]!r}.") ok_seals, seal_tokens, seal_err = extract_seal_tokens(sub.get("seals")) if not ok_seals and seal_err: errors.append(seal_err) return len(errors) == 0, errors, seal_tokens def validate_clc_submission( sub: Any, task_id: str, ) -> tuple[bool, list[str], list[str]]: """Validate flat <=6-key CLC submission (`task_id`, `steps` and/or `seals`).""" if not isinstance(sub, dict): return False, ["Submission root must be a JSON object."], [] if len(sub) > MAX_SUBMISSION_TOP_KEYS: return ( False, [f"Submission has {len(sub)} top-level keys; maximum allowed is {MAX_SUBMISSION_TOP_KEYS}."], [], ) errors: list[str] = [] if sub.get("task_id") != task_id: errors.append(f"Expected task_id={task_id!r}, got {sub.get('task_id')!r}.") seal_tokens: list[str] = [] has_seals = "seals" in sub and sub["seals"] is not None if has_seals: ok_seals, s_toks, seal_err = extract_seal_tokens(sub["seals"]) if not ok_seals and seal_err: errors.append(seal_err) else: seal_tokens.extend(s_toks) steps = sub.get("steps") if steps is not None: if not isinstance(steps, list) or not steps: errors.append("Field 'steps' (when provided) must be a non-empty list.") else: for idx, st in enumerate(steps): if not isinstance(st, dict): errors.append(f"steps[{idx}] must be a JSON object.") continue for sk in ("seal", "chain_seal", "run_seal", "receipt_sha384"): v = st.get(sk) if isinstance(v, str) and v.strip(): tok = v.strip().lower() if tok not in seal_tokens: seal_tokens.append(tok) if not has_seals and not seal_tokens: errors.append("Must provide 'seals' (list or dict of SHA-384 seals) or sealed 'steps'.") return len(errors) == 0, errors, seal_tokens def validate_vnv_submission( sub: Any, task_id: str, required_design_vars: tuple[str, ...] | list[str], required_certified_bounds: tuple[str, ...] | list[str], ) -> tuple[bool, list[str], list[str]]: """Validate flat <=6-key VNV submission (`task_id`, `design_variables`, `certified_bounds`, `seals`).""" if not isinstance(sub, dict): return False, ["Submission root must be a JSON object."], [] if len(sub) > MAX_SUBMISSION_TOP_KEYS: return ( False, [f"Submission has {len(sub)} top-level keys; maximum allowed is {MAX_SUBMISSION_TOP_KEYS}."], [], ) errors: list[str] = [] if sub.get("task_id") != task_id: errors.append(f"Expected task_id={task_id!r}, got {sub.get('task_id')!r}.") dv = sub.get("design_variables") if not isinstance(dv, dict): errors.append("Field 'design_variables' must be a JSON object of numeric parameters.") else: for k in required_design_vars: if k not in dv: errors.append(f"Missing required design variable 'design_variables.{k}'.") elif not is_finite_number(dv[k]): errors.append(f"Design variable 'design_variables.{k}' must be a finite number, got {dv[k]!r}.") cb = sub.get("certified_bounds") if not isinstance(cb, dict): errors.append("Field 'certified_bounds' must be a JSON object of conservative V&V limits.") else: for k in required_certified_bounds: if k not in cb: errors.append(f"Missing required bound 'certified_bounds.{k}'.") elif not is_finite_number(cb[k]): errors.append(f"Certified bound 'certified_bounds.{k}' must be a finite number, got {cb[k]!r}.") ok_seals, seal_tokens, seal_err = extract_seal_tokens(sub.get("seals")) if not ok_seals and seal_err: errors.append(seal_err) return len(errors) == 0, errors, seal_tokens def validate_flt_submission( sub: Any, task_id: str, required_fault_keys: tuple[str, ...] | list[str], required_remediation_vars: tuple[str, ...] | list[str], ) -> tuple[bool, list[str], list[str]]: """Validate flat <=6-key FLT submission (`task_id`, `trusted_packet_ids`, `fault_diagnosis`, `remediation_variables`, `seals`).""" if not isinstance(sub, dict): return False, ["Submission root must be a JSON object."], [] if len(sub) > MAX_SUBMISSION_TOP_KEYS: return ( False, [f"Submission has {len(sub)} top-level keys; maximum allowed is {MAX_SUBMISSION_TOP_KEYS}."], [], ) errors: list[str] = [] if sub.get("task_id") != task_id: errors.append(f"Expected task_id={task_id!r}, got {sub.get('task_id')!r}.") tp = sub.get("trusted_packet_ids") if not isinstance(tp, list) or not tp or not all(isinstance(x, str) and x.strip() for x in tp): errors.append("Field 'trusted_packet_ids' must be a non-empty list of packet ID strings.") fd = sub.get("fault_diagnosis") if not isinstance(fd, dict): errors.append("Field 'fault_diagnosis' must be a JSON object of identified plant fault scalars.") else: for k in required_fault_keys: if k not in fd: errors.append(f"Missing required fault scalar 'fault_diagnosis.{k}'.") elif not is_finite_number(fd[k]): errors.append(f"Fault scalar 'fault_diagnosis.{k}' must be a finite number, got {fd[k]!r}.") rv = sub.get("remediation_variables") if not isinstance(rv, dict): errors.append("Field 'remediation_variables' must be a JSON object of numeric remediation setpoints.") else: for k in required_remediation_vars: if k not in rv: errors.append(f"Missing required remediation setpoint 'remediation_variables.{k}'.") elif not is_finite_number(rv[k]): errors.append(f"Remediation variable 'remediation_variables.{k}' must be a finite number, got {rv[k]!r}.") ok_seals, seal_tokens, seal_err = extract_seal_tokens(sub.get("seals")) if not ok_seals and seal_err: errors.append(seal_err) return len(errors) == 0, errors, seal_tokens def all_tokens_well_formed_hex(tokens: list[str]) -> tuple[bool, str | None]: """Return `(True, None)` if all tokens are 96 lowercase hex chars, else `(False, bad_token)`.""" for tok in tokens: if not is_valid_sha384_hex(tok): return False, tok return True, None def make_grade_report( *, task_id: str, binary_reward: int, shaped_score: float, seals_verified: bool, failure_reason: str, autopsy: str, stage_breakdown: dict[str, Any], ledger_audit: dict[str, Any] | None, verification_ms: float, ) -> dict[str, Any]: """Build canonical grader report JSON with invariant enforcement.""" if failure_reason not in FAILURE_REASONS: raise ValueError(f"Invalid failure_reason {failure_reason!r}") reward = 1 if int(binary_reward) == 1 else 0 clamped = round(max(0.0, min(1.0, float(shaped_score))), 6) if reward == 1: assert seals_verified is True, "Passed evaluation requires seals_verified=True" assert failure_reason == "none", "Passed evaluation requires failure_reason='none'" clamped = 1.0 else: assert failure_reason != "none", "Failed evaluation requires explicit non-'none' failure_reason" return { "task_id": task_id, "binary_reward": reward, "passed": reward == 1, "shaped_score": clamped, "seals_verified": bool(seals_verified), "failure_reason": failure_reason, "autopsy": autopsy, "stage_breakdown": stage_breakdown, "ledger_audit": ledger_audit, "verification_ms": round(float(verification_ms), 2), }