File size: 11,403 Bytes
fe0ff58 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 | """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),
}
|