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…
for key, val in pairs:
if key in obj:
raise StrictJSONDecodeError(
f"Duplicate JSON object key rejected: {key!r}",
reason_code="DUPLICATE_JSON_KEY",
)
if preserve_boundary_decimals and key in _EXACT_DECIMAL_PRESERVED_JSON_KEYS:
obj[key] = val
else:
obj[key] = _coerce_non_dict_decimals_to_float(val)
return obj
return _hook
_strict_json_object_pairs_hook = _make_strict_json_object_pairs_hook(True)
def _strict_json_reject_constant(token: str) -> Any:
raise StrictJSONDecodeError(
f"Non-standard JSON constant rejected: {token!r}",
reason_code="NON_STANDARD_JSON_CONSTANT",
)
def _strict_json_parse_finite_float(token: str) -> Decimal:
"""
R12-B2 Exact-Decimal JSON float token parser:
- Parses every JSON float token via exact `Decimal(token)` inside an isolated untrapped context.
- Rejects NaN, Infinity, or magnitude > 1e300 (`NON_FINITE_JSON_FLOAT`).
- Rejects nonzero IEEE-754 float64 underflow (e.g. `-1e-400`, `1e-400`, `-1e-325` where
`dec_val != 0` yet `float(token) == 0.0`) with `NONZERO_FLOAT_UNDERFLOW_REJECTED`.
- Returns exact `Decimal` so adjudication-boundary keys preserve full precision and sign
(including `-0.0` and `1.00000000000000001`).
"""
with localcontext(
Context(
prec=120,
rounding=ROUND_HALF_EVEN,
Emax=decimal.MAX_EMAX,
Emin=decimal.MIN_EMIN,
capitals=1,
clamp=0,
flags=[],
traps=[],
)
):
try:
dec_val = Decimal(token)
except (decimal.InvalidOperation, ValueError) as exc:
raise StrictJSONDecodeError(
f"Unrepresentable JSON float rejected: {token!r}",
reason_code="NON_FINITE_JSON_FLOAT",
) from exc
if not dec_val.is_finite() or dec_val.copy_abs() > Decimal("1e300"):
raise StrictJSONDecodeError(
f"Non-finite or overflowing JSON float rejected: {token!r}",
reason_code="NON_FINITE_JSON_FLOAT",
)
try:
fval = float(token)
except (OverflowError, ValueError) as exc:
raise StrictJSONDecodeError(
f"Unrepresentable JSON float rejected: {token!r}",
reason_code="NON_FINITE_JSON_FLOAT",
) from exc
if not math.isfinite(fval) or abs(fval) > 1e300:
raise StrictJSONDecodeError(
f"Non-finite or overflowing JSON float rejected: {token!r}",
reason_code="NON_FINITE_JSON_FLOAT",
)
if dec_val != Decimal(0) and fval == 0.0:
raise StrictJSONDecodeError(
f"Nonzero JSON float underflowing float64 to zero rejected: {token!r}",
reason_code="NONZERO_FLOAT_UNDERFLOW_REJECTED",
)
return dec_val
def _make_bounded_int_parser(max_int_abs: int | None):
def _parse_bounded_int(token: str) -> int:
try:
val = int(token)
except ValueError as exc:
raise StrictJSONDecodeError(
f"Out-of-range JSON integer literal rejected (length={len(token)})",
reason_code="OUT_OF_RANGE_JSON_INTEGER",
) from exc
if token.startswith("-") and val == 0:
raise StrictJSONDecodeError(
f"Signed negative-zero JSON integer literal rejected: {token!r}",
reason_code="INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE",
)
if max_int_abs is not None and abs(val) > max_int_abs:
raise StrictJSONDecodeError(
f"Out-of-float64-range JSON integer rejected (digits={len(token.lstrip('+-'))})",
reason_code="OUT_OF_RANGE_JSON_INTEGER",
)
return val
return _parse_bounded_int
def _is_negative_zero(val: Any) -> bool:
"""Return True strictly when `val` is a signed negative zero (`-0.0`, `Decimal('-0.0')`, `'-0.0'`)."""
if isinstance(val, bool) or val is None:
return False
if isinstance(val, Decimal):
with localcontext(
Context(prec=120, rounding=ROUND_HALF_EVEN, Emax=decimal.MAX_EMAX, Emin=decimal.MIN_EMIN, traps=[])
):
return bool(val.is_finite() and val == Decimal(0) and val.is_signed())
if isinstance(val, float):
return bool(math.isfinite(val) and val == 0.0 and math.copysign(1.0, val) < 0.0)
if isinstance(val, str):
s = val.strip()
if not s:
return False
with localcontext(
Context(prec=120, rounding=ROUND_HALF_EVEN, Emax=decimal.MAX_EMAX, Emin=decimal.MIN_EMIN, traps=[])
):
try:
d = Decimal(s)
except (decimal.InvalidOperation, ValueError):
return False
return bool(d.is_finite() and d == Decimal(0) and d.is_signed())
return False
def _safe_finite_float(val: Any, name: str) -> float:
"""Safely convert non-bool int/float/Decimal to finite IEEE-754 float64, rejecting NaN/Inf,
magnitude > 1e300, OverflowError, and nonzero float64 underflow."""
if isinstance(val, bool) or not isinstance(val, (int, float, Decimal)):
raise ValueError(f"Non-finite or non-numeric {name}={val!r}")
if isinstance(val, Decimal):
with localcontext(
Context(prec=120, rounding=ROUND_HALF_EVEN, Emax=decimal.MAX_EMAX, Emin=decimal.MIN_EMIN, traps=[])
):
if not val.is_finite() or val.copy_abs() > Decimal("1e300"):
raise ValueError(f"Non-finite or overflowing {name}={val!r}")
try:
fval = float(val)
except (OverflowError, TypeError, ValueError) as exc:
raise ValueError(f"Out-of-float64-range or invalid {name}") from exc
if not math.isfinite(fval) or abs(fval) > 1e300:
raise ValueError(f"Non-finite or overflowing {name}={val!r}")
if val != Decimal(0) and fval == 0.0:
raise ValueError(f"NONZERO_FLOAT_UNDERFLOW_REJECTED:{name}={val!r}")
return fval
try:
fval = float(val)
except (OverflowError, TypeError, ValueError) as exc:
raise ValueError(f"Out-of-float64-range or invalid {name}") from exc
if not math.isfinite(fval) or abs(fval) > 1e300:
raise ValueError(f"Non-finite {name}={val!r}")
return fval
def _parse_nw08_boundary_scalar(
val: Any,
name: str,
*,
non_negative: bool = True,
strictly_positive: bool = False,
) -> Tuple[float, Decimal]:
"""
R12-B2 Strictly validate an NW-08 numeric boundary parameter (`int`, `float`, or exact `Decimal`):
- Rejects bool, str, None, NaN, Infinity, magnitude > 1e300, and nonzero float64 underflow.
- When `non_negative=True` or `strictly_positive=True`, explicitly rejects signed negative zero
(`-0.0`, `Decimal('-0.0')`) and negative values BEFORE float64 conversion with
`INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE`.
- Returns `(float64_val, exact_decimal_val)` preserving exact precision and sign.
"""
if (non_negative or strictly_positive) and _is_negative_zero(val):
raise ValueError(f"INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE:{name}={val!r}")
if isinstance(val, bool) or not isinstance(val, (int, float, Decimal)):
raise ValueError(f"Non-finite or non-numeric {name}={val!r}")
with localcontext(
Context(prec=120, rounding=ROUND_HALF_EVEN, Emax=decimal.MAX_EMAX, Emin=decimal.MIN_EMIN, traps=[])
):
if isinstance(val, Decimal):
if not val.is_finite() or val.copy_abs() > Decimal("1e300"):
raise ValueError(f"Non-finite or overflowing {name}={val!r}")
dec_val = val
try:
fval = float(val)
except (OverflowError, TypeError, ValueError) as exc:
raise ValueError(f"Out-of-float64-range or invalid {name}") from exc
if not math.isfinite(fval) or abs(fval) > 1e300:
raise ValueError(f"Non-finite or overflowing {name}={val!r}")
if dec_val != Decimal(0) and fval == 0.0:
raise ValueError(f"NONZERO_FLOAT_UNDERFLOW_REJECTED:{name}={val!r}")
elif isinstance(val, int):
if abs(val) > MAX_STRICT_JSON_INT_ABS:
raise ValueError(f"Out-of-float64-range {name}")
dec_val = Decimal(val)
try:
fval = float(val)
except (OverflowError, TypeError, ValueError) as exc:
raise ValueError(f"Out-of-float64-range or invalid {name}") from exc
if not math.isfinite(fval):
raise ValueError(f"Non-finite {name}")
else:
if not math.isfinite(val) or abs(val) > 1e300:
raise ValueError(f"Non-finite or overflowing {name}={val!r}")
fval = val
dec_val = Decimal(str(val))
if (non_negative or strictly_positive) and _is_negative_zero(val):
raise ValueError(f"INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE:{name}={val!r}")
if strictly_positive and dec_val <= Decimal(0):
raise ValueError(f"INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE:{name} must be > 0; got {val!r}")
if non_negative and dec_val < Decimal(0):
raise ValueError(f"INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE:{name} must be >= 0; got {val!r}")
return fval, dec_val
def _parse_strict_utc_timestamp(val: Any) -> datetime | None:
"""Parse strict RFC-3339/ISO-8601 UTC timestamp (`YYYY-MM-DDTHH:MM:SS[.ffffff](Z|+00:00)`)."""
if not isinstance(val, str) or val != val.strip():
return None
if not _UTC_ISO8601_RE.fullmatch(val):
return None
try:
iso_norm = val[:-1] + "+00:00" if val.endswith("Z") else val
dt = datetime.fromisoformat(iso_norm)
except ValueError:
return None
if dt.tzinfo is None or dt.utcoffset() != timezone.utc.utcoffset(dt):
return None
return dt.astimezone(timezone.utc)
def strict_json_loads(
raw_text: str,
*,
max_int_abs: int | None = None,
max_depth: int = MAX_JSON_NESTING_DEPTH,
preserve_boundary_decimals: bool = True,
) -> Any:
"""
R09-B1 + R10-B2 + R11-B4 + R12-B2 Single canonical strict RFC-8259 JSON decoder enforced across ALL IIP-0043 intake boundaries:
- Enforces bounded JSON nesting depth (`max_depth = MAX_JSON_NESTING_DEPTH = 64`) via a
purely iterative O(n) pre-scanner AND maps any parser `RecursionError` to
`StrictJSONDecodeError(reason_code="JSON_DEPTH_OR_RECURSION_LIMIT_EXCEEDED")`.
- Rejects duplicate object keys at ANY nesting depth (including unicode-escaped duplicates)
via `object_pairs_hook`, raising `StrictJSONDecodeError(reason_code="DUPLICATE_JSON_KEY")`.
- Rejects non-standard `NaN`, `Infinity`, and `-Infinity` constants via `parse_constant`,
raising `StrictJSONDecodeError(reason_code="NON_STANDARD_JSON_CONSTANT")`.
- Parses every JSON float via exact `Decimal(token)`, rejecting NaN/Inf/magnitude > 1e300
(`NON_FINITE_JSON_FLOAT`) AND rejecting nonzero float64 underflow (e.g. `-1e-400`, `1e-400`)
with `StrictJSONDecodeError(reason_code="NONZERO_FLOAT_UNDERFLOW_REJECTED")`.
- When `preserve_boundary_decimals=True` (default for all operator adjudication intake),