Spaces:
Running
Running
chore(sync): mirror backend .py + Dockerfile to Space (hf-sync-backend)
Browse filesAutomated backend sync from szl-holdings/a11oy main via hf-sync-backend.
Updated (differed from the Space): Dockerfile, a11oy_frontier_page.py, serve.py, szl_agentic_loop.py, szl_frontier_manifest.py, szl_gpu_quant.py, szl_involution_probe.py, szl_runtime_contracts.py
Deleted (gone from the repo + Dockerfile COPY set): (none)
Keeps the Space-built backend (serve.py + the Dockerfile-COPY'd .py
modules) identical to GitHub main so the Space never rebuilds from a
stale backend, new endpoints don't 404 there, and orphaned modules
removed from the repo don't linger in the Space tree.
- Dockerfile +5 -0
- a11oy_frontier_page.py +16 -6
- serve.py +34 -3
- szl_agentic_loop.py +187 -22
- szl_frontier_manifest.py +314 -60
- szl_gpu_quant.py +453 -110
- szl_involution_probe.py +383 -0
- szl_runtime_contracts.py +421 -0
Dockerfile
CHANGED
|
@@ -145,6 +145,11 @@ COPY szl_waqay_security_loop.py ./
|
|
| 145 |
# reviewed source contracts.
|
| 146 |
COPY szl_claim_rupture_gate.py ./
|
| 147 |
COPY schemas/evidenceos/ ./schemas/evidenceos/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
# Quantum Utility Gate wave 16: pure-stdlib proposal analysis only. No provider
|
| 149 |
# SDK, QPU call, credential path, external effector, or finance-engine coupling.
|
| 150 |
COPY szl_quantum_utility.py ./
|
|
|
|
| 145 |
# reviewed source contracts.
|
| 146 |
COPY szl_claim_rupture_gate.py ./
|
| 147 |
COPY schemas/evidenceos/ ./schemas/evidenceos/
|
| 148 |
+
# Wave 38 evidence surfaces: involution probe + runtime contracts + committed quant
|
| 149 |
+
# benchmark receipt (read-only, validated+signature-checked at serve time).
|
| 150 |
+
COPY szl_involution_probe.py ./
|
| 151 |
+
COPY szl_runtime_contracts.py ./
|
| 152 |
+
COPY benchmarks/quant_live/receipts/latest.json ./benchmarks/quant_live/receipts/latest.json
|
| 153 |
# Quantum Utility Gate wave 16: pure-stdlib proposal analysis only. No provider
|
| 154 |
# SDK, QPU call, credential path, external effector, or finance-engine coupling.
|
| 155 |
COPY szl_quantum_utility.py ./
|
a11oy_frontier_page.py
CHANGED
|
@@ -20,7 +20,8 @@ The whole stack on one surface:
|
|
| 20 |
- the multi-node sovereign GPU fabric (REAL reachability probe),
|
| 21 |
- the MODELED orbital tier (links out to the /orbital page),
|
| 22 |
- governance / restraint (codified doctrine + signed DSSE receipts),
|
| 23 |
-
- the
|
|
|
|
| 24 |
|
| 25 |
HONESTY (doctrine v11, non-negotiable):
|
| 26 |
* A persistent honest banner is pinned to the top of every viewport and a
|
|
@@ -687,7 +688,7 @@ function tileCard(t) {{
|
|
| 687 |
else if (label === 'SAMPLE')
|
| 688 |
banner = `<div class="tile-banner sample">SAMPLE — illustrative value, never billable or live.</div>`;
|
| 689 |
else if (label === 'UNAVAILABLE')
|
| 690 |
-
banner = `<div class="tile-banner unavailable">UNAVAILABLE —
|
| 691 |
return `<div class="card" style="--edge:${{edge}}">
|
| 692 |
<div class="cat">${{esc(t.category || '')}}</div>
|
| 693 |
<h3><span>${{esc(t.name || '')}}</span><span class="badge ${{c}}">${{esc(label)}}</span></h3>
|
|
@@ -792,6 +793,11 @@ document.getElementById('brain-query-form').addEventListener('submit', async eve
|
|
| 792 |
const tiles = m.capabilities || [];
|
| 793 |
const s = m.summary || {{}};
|
| 794 |
const lc = s.label_counts || {{}};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 795 |
|
| 796 |
// roll-up chips (honest counts straight from the manifest)
|
| 797 |
document.getElementById('rollup').innerHTML = [
|
|
@@ -799,18 +805,22 @@ document.getElementById('brain-query-form').addEventListener('submit', async eve
|
|
| 799 |
`<span class="chip">MEASURED <b>${{esc(lc.MEASURED || 0)}}</b></span>`,
|
| 800 |
`<span class="chip">MODELED <b>${{esc(lc.MODELED || 0)}}</b></span>`,
|
| 801 |
`<span class="chip">ROADMAP <b>${{esc(lc.ROADMAP || 0)}}</b></span>`,
|
| 802 |
-
`<span class="chip">
|
|
|
|
| 803 |
(s.degraded_tiles && s.degraded_tiles.length)
|
| 804 |
? `<span class="chip">degraded: <b>${{esc(s.degraded_tiles.join(', '))}}</b></span>` : '',
|
|
|
|
|
|
|
| 805 |
].join('');
|
| 806 |
|
| 807 |
document.getElementById('grid').innerHTML = tiles.map(tileCard).join('');
|
| 808 |
drawConstellation(tiles);
|
| 809 |
|
| 810 |
const el = document.getElementById('status');
|
| 811 |
-
el.textContent = '
|
| 812 |
-
' · ' + esc(s.tiles ?? tiles.length) + ' tiles ·
|
| 813 |
-
esc(
|
|
|
|
| 814 |
document.getElementById('subline').innerHTML =
|
| 815 |
'Every capability we run, on one screen — composed live by <code>/frontier/manifest</code>. ' +
|
| 816 |
'Each tile shows its <b>honest label</b> and a <b>link to the proof</b>. No label is upgraded.';
|
|
|
|
| 20 |
- the multi-node sovereign GPU fabric (REAL reachability probe),
|
| 21 |
- the MODELED orbital tier (links out to the /orbital page),
|
| 22 |
- governance / restraint (codified doctrine + signed DSSE receipts),
|
| 23 |
+
- the composite inference-provenance capability (UNAVAILABLE until a real write
|
| 24 |
+
has minted an independently visible artifact).
|
| 25 |
|
| 26 |
HONESTY (doctrine v11, non-negotiable):
|
| 27 |
* A persistent honest banner is pinned to the top of every viewport and a
|
|
|
|
| 688 |
else if (label === 'SAMPLE')
|
| 689 |
banner = `<div class="tile-banner sample">SAMPLE — illustrative value, never billable or live.</div>`;
|
| 690 |
else if (label === 'UNAVAILABLE')
|
| 691 |
+
banner = `<div class="tile-banner unavailable">UNAVAILABLE — source, dependency, or required artifact is not operationally evidenced.</div>`;
|
| 692 |
return `<div class="card" style="--edge:${{edge}}">
|
| 693 |
<div class="cat">${{esc(t.category || '')}}</div>
|
| 694 |
<h3><span>${{esc(t.name || '')}}</span><span class="badge ${{c}}">${{esc(label)}}</span></h3>
|
|
|
|
| 793 |
const tiles = m.capabilities || [];
|
| 794 |
const s = m.summary || {{}};
|
| 795 |
const lc = s.label_counts || {{}};
|
| 796 |
+
const source = s.source_reachability || {{state:'UNKNOWN'}};
|
| 797 |
+
const readiness = s.operational_readiness || {{state:'UNKNOWN', ready:false, blocked_tiles:[]}};
|
| 798 |
+
const blockedNames = Array.isArray(readiness.blocked_tiles)
|
| 799 |
+
? readiness.blocked_tiles.map(row => row && row.name ? row.name : row).filter(Boolean)
|
| 800 |
+
: [];
|
| 801 |
|
| 802 |
// roll-up chips (honest counts straight from the manifest)
|
| 803 |
document.getElementById('rollup').innerHTML = [
|
|
|
|
| 805 |
`<span class="chip">MEASURED <b>${{esc(lc.MEASURED || 0)}}</b></span>`,
|
| 806 |
`<span class="chip">MODELED <b>${{esc(lc.MODELED || 0)}}</b></span>`,
|
| 807 |
`<span class="chip">ROADMAP <b>${{esc(lc.ROADMAP || 0)}}</b></span>`,
|
| 808 |
+
`<span class="chip">source reachability <b>${{esc(source.state || 'UNKNOWN')}}</b></span>`,
|
| 809 |
+
`<span class="chip">operational readiness <b>${{esc(readiness.state || 'UNKNOWN')}}</b></span>`,
|
| 810 |
(s.degraded_tiles && s.degraded_tiles.length)
|
| 811 |
? `<span class="chip">degraded: <b>${{esc(s.degraded_tiles.join(', '))}}</b></span>` : '',
|
| 812 |
+
blockedNames.length
|
| 813 |
+
? `<span class="chip">not ready: <b>${{esc(blockedNames.join(', '))}}</b></span>` : '',
|
| 814 |
].join('');
|
| 815 |
|
| 816 |
document.getElementById('grid').innerHTML = tiles.map(tileCard).join('');
|
| 817 |
drawConstellation(tiles);
|
| 818 |
|
| 819 |
const el = document.getElementById('status');
|
| 820 |
+
el.textContent = 'manifest reachable · composed from ' + esc(MANIFEST_EP) +
|
| 821 |
+
' · ' + esc(s.tiles ?? tiles.length) + ' tiles · source=' +
|
| 822 |
+
esc(source.state || 'UNKNOWN') + ' · operational=' +
|
| 823 |
+
esc(readiness.state || 'UNKNOWN');
|
| 824 |
document.getElementById('subline').innerHTML =
|
| 825 |
'Every capability we run, on one screen — composed live by <code>/frontier/manifest</code>. ' +
|
| 826 |
'Each tile shows its <b>honest label</b> and a <b>link to the proof</b>. No label is upgraded.';
|
serve.py
CHANGED
|
@@ -77,8 +77,13 @@ def gov_envelope(payload=None, status="REAL", citations=None, reason=None, **ext
|
|
| 77 |
return out
|
| 78 |
# === END GOVERNED ENVELOPE ===
|
| 79 |
|
| 80 |
-
# RESET:
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
ASSETS_DIR = STATIC_DIR / "assets"
|
| 83 |
INDEX_HTML = STATIC_DIR / "index.html"
|
| 84 |
A11OY_BACKEND_PORT = 8081
|
|
@@ -2012,6 +2017,18 @@ try:
|
|
| 2012 |
except Exception as _szl_gq_e: # pragma: no cover
|
| 2013 |
print(f"[a11oy] GPU-Quant engine NOT registered: {_szl_gq_e!r}", file=__import__("sys").stderr)
|
| 2014 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2015 |
# ── Agentic PINN + Physical-Bounds Certifier MESH (pinn-bounds) — closes the audited
|
| 2016 |
# gap where the PINN / FE-NO Physics-ML verticals lived ONLY in `platform` and were
|
| 2017 |
# NOT in a11oy's governed /api/a11oy/v1/<name> route table. Adds /api/a11oy/v1/pinn/*:
|
|
@@ -3447,6 +3464,18 @@ except Exception as _vsp_e:
|
|
| 3447 |
print(f"[a11oy] vsp-otel VSP skipped: {_vsp_e!r}", file=_vsp_sys.stderr)
|
| 3448 |
# --- end vsp-otel VSP ---
|
| 3449 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3450 |
|
| 3451 |
# ── Live 3D Wires (PURIQ / Doctrine v12) — ADDITIVE, re-pinned FIRST ─────────
|
| 3452 |
# Registered immediately after the app is constructed so FastAPI's ordered route
|
|
@@ -3654,7 +3683,9 @@ except Exception as _sec_hdr_e: # pragma: no cover
|
|
| 3654 |
# ===========================================================================
|
| 3655 |
from fastapi.responses import RedirectResponse as _PTG_Redirect
|
| 3656 |
|
| 3657 |
-
|
|
|
|
|
|
|
| 3658 |
|
| 3659 |
def _ptg_serve(filename: str):
|
| 3660 |
async def _h() -> Response:
|
|
|
|
| 77 |
return out
|
| 78 |
# === END GOVERNED ENVELOPE ===
|
| 79 |
|
| 80 |
+
# RESET: the image serves the SPA from /app/static after Docker copies
|
| 81 |
+
# console/ there. Local verification must resolve the same source tree rather
|
| 82 |
+
# than trying to return a container-only path (which turns an otherwise honest
|
| 83 |
+
# 404 or history fallback into a 500).
|
| 84 |
+
_IMAGE_STATIC_DIR = Path("/app/static")
|
| 85 |
+
_LOCAL_STATIC_DIR = Path(__file__).resolve().parent / "console"
|
| 86 |
+
STATIC_DIR = _IMAGE_STATIC_DIR if (_IMAGE_STATIC_DIR / "index.html").is_file() else _LOCAL_STATIC_DIR
|
| 87 |
ASSETS_DIR = STATIC_DIR / "assets"
|
| 88 |
INDEX_HTML = STATIC_DIR / "index.html"
|
| 89 |
A11OY_BACKEND_PORT = 8081
|
|
|
|
| 2017 |
except Exception as _szl_gq_e: # pragma: no cover
|
| 2018 |
print(f"[a11oy] GPU-Quant engine NOT registered: {_szl_gq_e!r}", file=__import__("sys").stderr)
|
| 2019 |
|
| 2020 |
+
# -- EvidenceOS involution probe: bounded clean-room boundary/bulk decomposition.
|
| 2021 |
+
# The endpoint requires a caller-declared finite involution, performs no writes or
|
| 2022 |
+
# effectors, and returns a content digest plus explicit PROVEN/MODELED/REPORTED scope.
|
| 2023 |
+
try:
|
| 2024 |
+
import szl_involution_probe as _szl_involution_probe
|
| 2025 |
+
_szl_involution_probe.register(app, ns="a11oy")
|
| 2026 |
+
print("[a11oy] EvidenceOS involution probe registered: /api/a11oy/v1/evidenceos/involution/*",
|
| 2027 |
+
file=__import__("sys").stderr)
|
| 2028 |
+
except Exception as _szl_involution_e: # pragma: no cover
|
| 2029 |
+
print(f"[a11oy] EvidenceOS involution probe NOT registered: {_szl_involution_e!r}",
|
| 2030 |
+
file=__import__("sys").stderr)
|
| 2031 |
+
|
| 2032 |
# ── Agentic PINN + Physical-Bounds Certifier MESH (pinn-bounds) — closes the audited
|
| 2033 |
# gap where the PINN / FE-NO Physics-ML verticals lived ONLY in `platform` and were
|
| 2034 |
# NOT in a11oy's governed /api/a11oy/v1/<name> route table. Adds /api/a11oy/v1/pinn/*:
|
|
|
|
| 3464 |
print(f"[a11oy] vsp-otel VSP skipped: {_vsp_e!r}", file=_vsp_sys.stderr)
|
| 3465 |
# --- end vsp-otel VSP ---
|
| 3466 |
|
| 3467 |
+
# -- Runtime contracts: process liveness, fail-closed readiness, build identity,
|
| 3468 |
+
# explicit OTEL exporter/collector evidence, and soft-404 protection for unknown
|
| 3469 |
+
# file-like discovery paths. Read-only GETs; no receipt minting or external calls.
|
| 3470 |
+
try:
|
| 3471 |
+
import szl_runtime_contracts as _szl_runtime_contracts
|
| 3472 |
+
_runtime_contracts_status = _szl_runtime_contracts.register(app, ns="a11oy")
|
| 3473 |
+
print(f"[a11oy] Runtime contracts registered: {_runtime_contracts_status}",
|
| 3474 |
+
file=__import__("sys").stderr)
|
| 3475 |
+
except Exception as _runtime_contracts_e: # pragma: no cover
|
| 3476 |
+
print(f"[a11oy] Runtime contracts NOT registered: {_runtime_contracts_e!r}",
|
| 3477 |
+
file=__import__("sys").stderr)
|
| 3478 |
+
|
| 3479 |
|
| 3480 |
# ── Live 3D Wires (PURIQ / Doctrine v12) — ADDITIVE, re-pinned FIRST ─────────
|
| 3481 |
# Registered immediately after the app is constructed so FastAPI's ordered route
|
|
|
|
| 3683 |
# ===========================================================================
|
| 3684 |
from fastapi.responses import RedirectResponse as _PTG_Redirect
|
| 3685 |
|
| 3686 |
+
_PTG_IMAGE_WEB = Path("/app/web")
|
| 3687 |
+
_PTG_LOCAL_WEB = Path(__file__).resolve().parent / "web"
|
| 3688 |
+
_PTG_WEB = _PTG_IMAGE_WEB if _PTG_IMAGE_WEB.is_dir() else _PTG_LOCAL_WEB
|
| 3689 |
|
| 3690 |
def _ptg_serve(filename: str):
|
| 3691 |
async def _h() -> Response:
|
szl_agentic_loop.py
CHANGED
|
@@ -10,9 +10,11 @@
|
|
| 10 |
# chained, signed receipt.
|
| 11 |
#
|
| 12 |
# WHAT IT EXPOSES (all registered BEFORE the SPA catch-all via routes.insert(0)):
|
| 13 |
-
# GET /mcp/ — MCP discovery
|
| 14 |
# POST /mcp/ — MCP JSON-RPC (initialize, tools/list, tools/call)
|
| 15 |
# GET /api/<ns>/v1/agent/tools — plain tool catalog (mirror of MCP tools/list)
|
|
|
|
|
|
|
| 16 |
# POST /api/<ns>/v1/agent/run — the GOVERNED AGENT RUN (the whole loop)
|
| 17 |
# POST /api/<ns>/v1/agent/verify-chain— re-verify a run's chained receipt
|
| 18 |
# GET /ask-and-act — the consumer/investor UI (one button)
|
|
@@ -36,10 +38,17 @@ from __future__ import annotations
|
|
| 36 |
import hashlib
|
| 37 |
import json
|
| 38 |
import math
|
|
|
|
| 39 |
import time
|
| 40 |
import uuid
|
| 41 |
from datetime import datetime, timezone
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
# ----------------------------------------------------------------------------
|
| 44 |
# FORMULA WIRING (ADDITIVE 2026-06-06): the ~80 kernel-verified theorems wired
|
| 45 |
# to REAL work. szl_formula_wiring exposes deterministic mechanisms that COMPUTE
|
|
@@ -747,9 +756,14 @@ def register(app, ns: str, sign_fn, verify_fn=None, pub_pem_fn=None,
|
|
| 747 |
from starlette.responses import JSONResponse, HTMLResponse
|
| 748 |
from starlette.requests import Request
|
| 749 |
|
| 750 |
-
#
|
| 751 |
_RUN_CHAIN = [] # list of {run_id, final_hash, prev_run_hash}
|
| 752 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 753 |
def _do_run(query: str, action: str, severity: str, confidence: float,
|
| 754 |
reversible: bool, untrusted_input: str = "", approval_grant=None,
|
| 755 |
precondition_hash=None):
|
|
@@ -823,7 +837,7 @@ def register(app, ns: str, sign_fn, verify_fn=None, pub_pem_fn=None,
|
|
| 823 |
"quarantined": True,
|
| 824 |
"feeds_decision": False})
|
| 825 |
|
| 826 |
-
# ---- HOP 3: MCP tool-call (policy_check tool, via the
|
| 827 |
with tr.span("tool_call", "mcp") as sp:
|
| 828 |
tool_name = "policy_check"
|
| 829 |
tool_input = {"action": action, "severity": severity,
|
|
@@ -1023,6 +1037,7 @@ def register(app, ns: str, sign_fn, verify_fn=None, pub_pem_fn=None,
|
|
| 1023 |
sealed = _chain_receipt("emit", {"decision": decision,
|
| 1024 |
"emitted": effect["emitted"],
|
| 1025 |
"signed": bool(envelope.get("signed"))})
|
|
|
|
| 1026 |
|
| 1027 |
# ---- OPERATOR + GRAPH + UNIFYING FORMULA WIRING (real, executed on the
|
| 1028 |
# ---- SEALED chain) — these mechanisms run on the actual receipts below.
|
|
@@ -1088,11 +1103,12 @@ def register(app, ns: str, sign_fn, verify_fn=None, pub_pem_fn=None,
|
|
| 1088 |
"decision": decision}
|
| 1089 |
_RUN_CHAIN.append(run_record)
|
| 1090 |
|
| 1091 |
-
|
| 1092 |
"run_id": tr.trace_id,
|
| 1093 |
"decision": decision,
|
| 1094 |
"emitted": effect["emitted"],
|
| 1095 |
-
"summary": _plain_summary(decision, action, effect, reasons, trust, trust_pass
|
|
|
|
| 1096 |
"retrieved": chunks,
|
| 1097 |
"untrusted": {"present": bool(untrusted_input),
|
| 1098 |
"excerpt": (untrusted_input or "")[:240],
|
|
@@ -1118,25 +1134,34 @@ def register(app, ns: str, sign_fn, verify_fn=None, pub_pem_fn=None,
|
|
| 1118 |
"signed_receipt": envelope,
|
| 1119 |
"chain_final_hash": prev_hash,
|
| 1120 |
"chain_depth": len(chain),
|
| 1121 |
-
"signer": signer_label,
|
|
|
|
|
|
|
| 1122 |
"verify_hint": ("Re-verify with POST /api/%s/v1/agent/verify-chain "
|
| 1123 |
-
"(send the whole run object back).
|
| 1124 |
-
"
|
| 1125 |
"doctrine": "v11",
|
| 1126 |
"honesty": ("Trust score is advisory (Conjecture 1). RAG retrieves over the "
|
| 1127 |
-
"in-image governance corpus.
|
|
|
|
| 1128 |
}
|
| 1129 |
-
|
| 1130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1131 |
if decision == "ALLOW":
|
| 1132 |
return ("Allowed. After retrieving the relevant guidance, calling the policy "
|
| 1133 |
"tool, passing the safety gate and the advisory trust check (score "
|
| 1134 |
-
"%.2f), the action \"%s\" was %s.
|
| 1135 |
-
% (trust, action, effect["effect"]))
|
| 1136 |
why = "; ".join(reasons) if reasons else ("advisory trust score %.2f below the floor" % trust)
|
| 1137 |
return ("Blocked. The safety/trust gate denied \"%s\" because: %s. No action was "
|
| 1138 |
-
"taken
|
| 1139 |
-
% (action, why))
|
| 1140 |
|
| 1141 |
def _verify_chain(run: dict):
|
| 1142 |
"""Re-verify a run object: (1) chain integrity (each prev_hash links and each
|
|
@@ -1188,6 +1213,122 @@ def register(app, ns: str, sign_fn, verify_fn=None, pub_pem_fn=None,
|
|
| 1188 |
"Flip any byte in any receipt body and chain_intact becomes false."),
|
| 1189 |
}
|
| 1190 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1191 |
# ------------------------------------------------------------------ #
|
| 1192 |
# OUROBOROS CLOSED LOOP (ADDITIVE 2026-07-03, default-OFF, honest).
|
| 1193 |
# Wraps the single governed pass `_do_run` into a BOUNDED, WITNESSED,
|
|
@@ -1398,7 +1539,7 @@ def register(app, ns: str, sign_fn, verify_fn=None, pub_pem_fn=None,
|
|
| 1398 |
except Exception: # pragma: no cover - SGH must never take the cycle down
|
| 1399 |
return core
|
| 1400 |
|
| 1401 |
-
# ---- MCP JSON-RPC handler (
|
| 1402 |
async def _mcp_post(request: Request):
|
| 1403 |
try:
|
| 1404 |
body = await request.json()
|
|
@@ -1496,18 +1637,21 @@ def register(app, ns: str, sign_fn, verify_fn=None, pub_pem_fn=None,
|
|
| 1496 |
return {"_error": True, "detail": "unknown tool: %s" % name}
|
| 1497 |
|
| 1498 |
async def _mcp_get(request: Request):
|
| 1499 |
-
#
|
|
|
|
| 1500 |
return JSONResponse({
|
| 1501 |
"name": "szl-%s-mcp" % ns,
|
| 1502 |
-
"title": "SZL %s —
|
| 1503 |
"protocol": "Model Context Protocol (JSON-RPC over Streamable HTTP)",
|
| 1504 |
"protocolVersion": "2024-11-05",
|
| 1505 |
"transport": {"post": "/mcp/ (JSON-RPC: initialize, tools/list, tools/call)"},
|
| 1506 |
"tools": _tool_catalog(ns),
|
| 1507 |
"tool_count": len(_tool_catalog(ns)),
|
| 1508 |
-
"
|
| 1509 |
-
"
|
| 1510 |
-
|
|
|
|
|
|
|
| 1511 |
"doctrine": "v11",
|
| 1512 |
})
|
| 1513 |
|
|
@@ -1529,7 +1673,17 @@ def register(app, ns: str, sign_fn, verify_fn=None, pub_pem_fn=None,
|
|
| 1529 |
|
| 1530 |
async def _agent_tools(request: Request):
|
| 1531 |
return JSONResponse({"tools": _tool_catalog(ns), "count": len(_tool_catalog(ns)),
|
| 1532 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1533 |
|
| 1534 |
async def _agent_governance_standards(request: Request):
|
| 1535 |
return JSONResponse(governance_standards_note())
|
|
@@ -1595,6 +1749,10 @@ def register(app, ns: str, sign_fn, verify_fn=None, pub_pem_fn=None,
|
|
| 1595 |
Route("/mcp", _mcp_any, methods=["GET", "POST"], name="%s_mcp_noslash" % ns),
|
| 1596 |
Route("/api/%s/v1/agent/run" % ns, _agent_run, methods=["POST"], name="%s_agent_run" % ns),
|
| 1597 |
Route("/api/%s/v1/agent/tools" % ns, _agent_tools, methods=["GET"], name="%s_agent_tools" % ns),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1598 |
Route("/api/%s/v1/agent/governance-standards" % ns, _agent_governance_standards,
|
| 1599 |
methods=["GET"], name="%s_agent_gov_standards" % ns),
|
| 1600 |
Route("/api/%s/v1/agent/verify-chain" % ns, _agent_verify, methods=["POST"], name="%s_agent_verify" % ns),
|
|
@@ -1602,6 +1760,13 @@ def register(app, ns: str, sign_fn, verify_fn=None, pub_pem_fn=None,
|
|
| 1602 |
Route("/ask-and-act", _ask_and_act_ui, methods=["GET"], name="%s_ask_and_act" % ns),
|
| 1603 |
Route("/governed-run", _ask_and_act_ui, methods=["GET"], name="%s_governed_run" % ns),
|
| 1604 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1605 |
# insert at position 0 so they win over the SPA catch-all (the known gotcha).
|
| 1606 |
for r in reversed(routes):
|
| 1607 |
app.router.routes.insert(0, r)
|
|
|
|
| 10 |
# chained, signed receipt.
|
| 11 |
#
|
| 12 |
# WHAT IT EXPOSES (all registered BEFORE the SPA catch-all via routes.insert(0)):
|
| 13 |
+
# GET /mcp/ — MCP runtime discovery (declaration only)
|
| 14 |
# POST /mcp/ — MCP JSON-RPC (initialize, tools/list, tools/call)
|
| 15 |
# GET /api/<ns>/v1/agent/tools — plain tool catalog (mirror of MCP tools/list)
|
| 16 |
+
# GET /api/<ns>/v1/agent/evidence — observed, read-only receipt evidence
|
| 17 |
+
# GET /api/<ns>/v1/agent/invocations — bounded, ephemeral receipt summaries
|
| 18 |
# POST /api/<ns>/v1/agent/run — the GOVERNED AGENT RUN (the whole loop)
|
| 19 |
# POST /api/<ns>/v1/agent/verify-chain— re-verify a run's chained receipt
|
| 20 |
# GET /ask-and-act — the consumer/investor UI (one button)
|
|
|
|
| 38 |
import hashlib
|
| 39 |
import json
|
| 40 |
import math
|
| 41 |
+
import threading
|
| 42 |
import time
|
| 43 |
import uuid
|
| 44 |
from datetime import datetime, timezone
|
| 45 |
|
| 46 |
+
|
| 47 |
+
# The Hatun read surface exposes only a bounded, in-process summary of receipts
|
| 48 |
+
# that this module actually observed creating. It is deliberately ephemeral: a
|
| 49 |
+
# restart clears the feed, and no GET handler signs or appends anything.
|
| 50 |
+
_HATUN_FEED_LIMIT = 32
|
| 51 |
+
|
| 52 |
# ----------------------------------------------------------------------------
|
| 53 |
# FORMULA WIRING (ADDITIVE 2026-06-06): the ~80 kernel-verified theorems wired
|
| 54 |
# to REAL work. szl_formula_wiring exposes deterministic mechanisms that COMPUTE
|
|
|
|
| 756 |
from starlette.responses import JSONResponse, HTMLResponse
|
| 757 |
from starlette.requests import Request
|
| 758 |
|
| 759 |
+
# In-memory chain of full runs (each run is itself a chained sub-ledger).
|
| 760 |
_RUN_CHAIN = [] # list of {run_id, final_hash, prev_run_hash}
|
| 761 |
|
| 762 |
+
# Bounded read model derived only from receipts created by _do_run. This is
|
| 763 |
+
# not a durable ledger and it is never populated by a GET request.
|
| 764 |
+
_HATUN_EVIDENCE = []
|
| 765 |
+
_HATUN_EVIDENCE_LOCK = threading.Lock()
|
| 766 |
+
|
| 767 |
def _do_run(query: str, action: str, severity: str, confidence: float,
|
| 768 |
reversible: bool, untrusted_input: str = "", approval_grant=None,
|
| 769 |
precondition_hash=None):
|
|
|
|
| 837 |
"quarantined": True,
|
| 838 |
"feeds_decision": False})
|
| 839 |
|
| 840 |
+
# ---- HOP 3: MCP tool-call (policy_check tool, via the registered MCP) ----
|
| 841 |
with tr.span("tool_call", "mcp") as sp:
|
| 842 |
tool_name = "policy_check"
|
| 843 |
tool_input = {"action": action, "severity": severity,
|
|
|
|
| 1037 |
sealed = _chain_receipt("emit", {"decision": decision,
|
| 1038 |
"emitted": effect["emitted"],
|
| 1039 |
"signed": bool(envelope.get("signed"))})
|
| 1040 |
+
receipt_has_signature = bool(envelope.get("signed") and envelope.get("signatures"))
|
| 1041 |
|
| 1042 |
# ---- OPERATOR + GRAPH + UNIFYING FORMULA WIRING (real, executed on the
|
| 1043 |
# ---- SEALED chain) — these mechanisms run on the actual receipts below.
|
|
|
|
| 1103 |
"decision": decision}
|
| 1104 |
_RUN_CHAIN.append(run_record)
|
| 1105 |
|
| 1106 |
+
result = {
|
| 1107 |
"run_id": tr.trace_id,
|
| 1108 |
"decision": decision,
|
| 1109 |
"emitted": effect["emitted"],
|
| 1110 |
+
"summary": _plain_summary(decision, action, effect, reasons, trust, trust_pass,
|
| 1111 |
+
receipt_has_signature),
|
| 1112 |
"retrieved": chunks,
|
| 1113 |
"untrusted": {"present": bool(untrusted_input),
|
| 1114 |
"excerpt": (untrusted_input or "")[:240],
|
|
|
|
| 1134 |
"signed_receipt": envelope,
|
| 1135 |
"chain_final_hash": prev_hash,
|
| 1136 |
"chain_depth": len(chain),
|
| 1137 |
+
"signer": signer_label if receipt_has_signature else None,
|
| 1138 |
+
"signer_claim_status": ("SIGNATURE_PRESENT_UNVERIFIED"
|
| 1139 |
+
if receipt_has_signature else "UNAVAILABLE"),
|
| 1140 |
"verify_hint": ("Re-verify with POST /api/%s/v1/agent/verify-chain "
|
| 1141 |
+
"(send the whole run object back). A signature is not called "
|
| 1142 |
+
"valid until that verifier succeeds." % ns),
|
| 1143 |
"doctrine": "v11",
|
| 1144 |
"honesty": ("Trust score is advisory (Conjecture 1). RAG retrieves over the "
|
| 1145 |
+
"in-image governance corpus. Receipt signature state is %s."
|
| 1146 |
+
% ("PRESENT_UNVERIFIED" if receipt_has_signature else "UNAVAILABLE")),
|
| 1147 |
}
|
| 1148 |
+
_remember_hatun_receipt(result, decision_payload, tool_name)
|
| 1149 |
+
return result
|
| 1150 |
+
|
| 1151 |
+
def _plain_summary(decision, action, effect, reasons, trust, trust_pass,
|
| 1152 |
+
receipt_has_signature):
|
| 1153 |
+
receipt_note = ("A receipt envelope with signature bytes was produced; verification "
|
| 1154 |
+
"is a separate check." if receipt_has_signature else
|
| 1155 |
+
"The receipt is UNSIGNED because no signature evidence was available.")
|
| 1156 |
if decision == "ALLOW":
|
| 1157 |
return ("Allowed. After retrieving the relevant guidance, calling the policy "
|
| 1158 |
"tool, passing the safety gate and the advisory trust check (score "
|
| 1159 |
+
"%.2f), the action \"%s\" was %s. %s"
|
| 1160 |
+
% (trust, action, effect["effect"], receipt_note))
|
| 1161 |
why = "; ".join(reasons) if reasons else ("advisory trust score %.2f below the floor" % trust)
|
| 1162 |
return ("Blocked. The safety/trust gate denied \"%s\" because: %s. No action was "
|
| 1163 |
+
"taken. %s This is the gate working."
|
| 1164 |
+
% (action, why, receipt_note))
|
| 1165 |
|
| 1166 |
def _verify_chain(run: dict):
|
| 1167 |
"""Re-verify a run object: (1) chain integrity (each prev_hash links and each
|
|
|
|
| 1213 |
"Flip any byte in any receipt body and chain_intact becomes false."),
|
| 1214 |
}
|
| 1215 |
|
| 1216 |
+
def _signature_evidence_status(run: dict, verification: dict) -> str:
|
| 1217 |
+
"""Classify only evidence present on an observed receipt.
|
| 1218 |
+
|
| 1219 |
+
A self-reported ``signed`` flag is not enough to call a signature
|
| 1220 |
+
verified. Verification requires the host-provided verifier to have run
|
| 1221 |
+
and returned a positive result.
|
| 1222 |
+
"""
|
| 1223 |
+
envelope = run.get("signed_receipt") or {}
|
| 1224 |
+
has_signature = bool(envelope.get("signed") and envelope.get("signatures"))
|
| 1225 |
+
if (verify_fn is not None and has_signature
|
| 1226 |
+
and verification.get("signature_valid") is True):
|
| 1227 |
+
return "VERIFIED"
|
| 1228 |
+
if verify_fn is not None and has_signature:
|
| 1229 |
+
return "INVALID"
|
| 1230 |
+
if has_signature:
|
| 1231 |
+
return "PRESENT_UNVERIFIED"
|
| 1232 |
+
return "UNAVAILABLE"
|
| 1233 |
+
|
| 1234 |
+
def _remember_hatun_receipt(run: dict, decision_payload: dict, tool_name: str) -> None:
|
| 1235 |
+
"""Append a bounded, redacted summary of an actual governed-run receipt."""
|
| 1236 |
+
verification = _verify_chain(run)
|
| 1237 |
+
signature_status = _signature_evidence_status(run, verification)
|
| 1238 |
+
if run.get("decision") == "DENY":
|
| 1239 |
+
outcome = "DENY"
|
| 1240 |
+
elif run.get("emitted"):
|
| 1241 |
+
outcome = "ALLOW_EMITTED"
|
| 1242 |
+
else:
|
| 1243 |
+
outcome = "ALLOW_HELD"
|
| 1244 |
+
entry = {
|
| 1245 |
+
"namespace": ns,
|
| 1246 |
+
"ts": decision_payload.get("issued_at"),
|
| 1247 |
+
"run_id": run.get("run_id"),
|
| 1248 |
+
"source": "governed_agent_run_receipt",
|
| 1249 |
+
"tool": tool_name,
|
| 1250 |
+
"outcome": outcome,
|
| 1251 |
+
"receipt_hash": run.get("chain_final_hash"),
|
| 1252 |
+
"chain_depth": run.get("chain_depth"),
|
| 1253 |
+
"chain_status": ("OBSERVED_INTACT"
|
| 1254 |
+
if verification.get("chain_intact") is True
|
| 1255 |
+
else "OBSERVED_BROKEN"),
|
| 1256 |
+
"signature_status": signature_status,
|
| 1257 |
+
"signer": signer_label if signature_status == "VERIFIED" else None,
|
| 1258 |
+
"maturity": "OBSERVED",
|
| 1259 |
+
}
|
| 1260 |
+
with _HATUN_EVIDENCE_LOCK:
|
| 1261 |
+
_HATUN_EVIDENCE.append(entry)
|
| 1262 |
+
overflow = len(_HATUN_EVIDENCE) - _HATUN_FEED_LIMIT
|
| 1263 |
+
if overflow > 0:
|
| 1264 |
+
del _HATUN_EVIDENCE[:overflow]
|
| 1265 |
+
|
| 1266 |
+
def _hatun_invocation_contract() -> dict:
|
| 1267 |
+
with _HATUN_EVIDENCE_LOCK:
|
| 1268 |
+
items = [dict(item) for item in reversed(_HATUN_EVIDENCE)]
|
| 1269 |
+
return {
|
| 1270 |
+
"schema": "szl.hatun.invocation-feed.v1",
|
| 1271 |
+
"namespace": ns,
|
| 1272 |
+
"status": "OBSERVED" if items else "UNKNOWN",
|
| 1273 |
+
"read_only": True,
|
| 1274 |
+
"get_mints_receipt": False,
|
| 1275 |
+
"ephemeral": True,
|
| 1276 |
+
"limit": _HATUN_FEED_LIMIT,
|
| 1277 |
+
"count": len(items),
|
| 1278 |
+
"source": "bounded in-process summaries of actual governed agent-run receipts",
|
| 1279 |
+
"items": items,
|
| 1280 |
+
}
|
| 1281 |
+
|
| 1282 |
+
def _hatun_evidence_contract() -> dict:
|
| 1283 |
+
feed = _hatun_invocation_contract()
|
| 1284 |
+
items = feed["items"]
|
| 1285 |
+
latest = items[0] if items else None
|
| 1286 |
+
verified = next((item for item in items
|
| 1287 |
+
if item.get("signature_status") == "VERIFIED"), None)
|
| 1288 |
+
if verified:
|
| 1289 |
+
signer = {"status": "OBSERVED_VERIFIED", "label": verified.get("signer")}
|
| 1290 |
+
elif any(item.get("signature_status") in ("PRESENT_UNVERIFIED", "INVALID")
|
| 1291 |
+
for item in items):
|
| 1292 |
+
signer = {"status": "UNVERIFIED", "label": None}
|
| 1293 |
+
elif items:
|
| 1294 |
+
signer = {"status": "UNAVAILABLE", "label": None}
|
| 1295 |
+
else:
|
| 1296 |
+
signer = {"status": "UNKNOWN", "label": None}
|
| 1297 |
+
|
| 1298 |
+
return {
|
| 1299 |
+
"schema": "szl.hatun.evidence.v1",
|
| 1300 |
+
"namespace": ns,
|
| 1301 |
+
"read_only": True,
|
| 1302 |
+
"get_mints_receipt": False,
|
| 1303 |
+
"runtime": {
|
| 1304 |
+
"status": "AVAILABLE",
|
| 1305 |
+
"mcp_endpoint": "/mcp/",
|
| 1306 |
+
"protocol_version": "2024-11-05",
|
| 1307 |
+
},
|
| 1308 |
+
"tool_catalog": {
|
| 1309 |
+
"status": "RUNTIME_DECLARED",
|
| 1310 |
+
"count": len(_tool_catalog(ns)),
|
| 1311 |
+
"evidence_boundary": "declaration and route presence; not execution proof",
|
| 1312 |
+
},
|
| 1313 |
+
"signer": signer,
|
| 1314 |
+
"receipt_chain": {
|
| 1315 |
+
"status": latest.get("chain_status") if latest else "UNKNOWN",
|
| 1316 |
+
"observed_receipts": len(items),
|
| 1317 |
+
"latest_receipt_hash": latest.get("receipt_hash") if latest else None,
|
| 1318 |
+
"latest_chain_depth": latest.get("chain_depth") if latest else None,
|
| 1319 |
+
},
|
| 1320 |
+
"invocations": {
|
| 1321 |
+
"status": feed["status"],
|
| 1322 |
+
"count": feed["count"],
|
| 1323 |
+
"ephemeral": True,
|
| 1324 |
+
"endpoint": "/api/hatun/invocations" if ns == "a11oy"
|
| 1325 |
+
else "/api/%s/v1/agent/invocations" % ns,
|
| 1326 |
+
},
|
| 1327 |
+
"honesty": ("No receipt or signer claim is promoted by this GET. UNKNOWN and "
|
| 1328 |
+
"UNAVAILABLE remain visible until an observed governed run supplies "
|
| 1329 |
+
"the corresponding evidence."),
|
| 1330 |
+
}
|
| 1331 |
+
|
| 1332 |
# ------------------------------------------------------------------ #
|
| 1333 |
# OUROBOROS CLOSED LOOP (ADDITIVE 2026-07-03, default-OFF, honest).
|
| 1334 |
# Wraps the single governed pass `_do_run` into a BOUNDED, WITNESSED,
|
|
|
|
| 1539 |
except Exception: # pragma: no cover - SGH must never take the cycle down
|
| 1540 |
return core
|
| 1541 |
|
| 1542 |
+
# ---- MCP JSON-RPC handler (runtime-declared MCP surface) ----
|
| 1543 |
async def _mcp_post(request: Request):
|
| 1544 |
try:
|
| 1545 |
body = await request.json()
|
|
|
|
| 1637 |
return {"_error": True, "detail": "unknown tool: %s" % name}
|
| 1638 |
|
| 1639 |
async def _mcp_get(request: Request):
|
| 1640 |
+
# The response proves this route was reachable for this request. Its tool
|
| 1641 |
+
# list remains a runtime declaration, not proof of tool execution.
|
| 1642 |
return JSONResponse({
|
| 1643 |
"name": "szl-%s-mcp" % ns,
|
| 1644 |
+
"title": "SZL %s — governed MCP runtime" % ns,
|
| 1645 |
"protocol": "Model Context Protocol (JSON-RPC over Streamable HTTP)",
|
| 1646 |
"protocolVersion": "2024-11-05",
|
| 1647 |
"transport": {"post": "/mcp/ (JSON-RPC: initialize, tools/list, tools/call)"},
|
| 1648 |
"tools": _tool_catalog(ns),
|
| 1649 |
"tool_count": len(_tool_catalog(ns)),
|
| 1650 |
+
"runtime_status": "AVAILABLE",
|
| 1651 |
+
"catalog_evidence": "RUNTIME_DECLARED",
|
| 1652 |
+
"execution_evidence": "/api/%s/v1/agent/evidence" % ns,
|
| 1653 |
+
"note": ("This GET confirms route reachability and returns the catalog declared "
|
| 1654 |
+
"by this runtime. It does not prove a tool ran or a receipt was signed."),
|
| 1655 |
"doctrine": "v11",
|
| 1656 |
})
|
| 1657 |
|
|
|
|
| 1673 |
|
| 1674 |
async def _agent_tools(request: Request):
|
| 1675 |
return JSONResponse({"tools": _tool_catalog(ns), "count": len(_tool_catalog(ns)),
|
| 1676 |
+
"mcp_endpoint": "/mcp/",
|
| 1677 |
+
"catalog_evidence": "RUNTIME_DECLARED",
|
| 1678 |
+
"doctrine": "v11"})
|
| 1679 |
+
|
| 1680 |
+
async def _agent_evidence(request: Request):
|
| 1681 |
+
return JSONResponse(_hatun_evidence_contract(),
|
| 1682 |
+
headers={"Cache-Control": "no-store"})
|
| 1683 |
+
|
| 1684 |
+
async def _agent_invocations(request: Request):
|
| 1685 |
+
return JSONResponse(_hatun_invocation_contract(),
|
| 1686 |
+
headers={"Cache-Control": "no-store"})
|
| 1687 |
|
| 1688 |
async def _agent_governance_standards(request: Request):
|
| 1689 |
return JSONResponse(governance_standards_note())
|
|
|
|
| 1749 |
Route("/mcp", _mcp_any, methods=["GET", "POST"], name="%s_mcp_noslash" % ns),
|
| 1750 |
Route("/api/%s/v1/agent/run" % ns, _agent_run, methods=["POST"], name="%s_agent_run" % ns),
|
| 1751 |
Route("/api/%s/v1/agent/tools" % ns, _agent_tools, methods=["GET"], name="%s_agent_tools" % ns),
|
| 1752 |
+
Route("/api/%s/v1/agent/evidence" % ns, _agent_evidence,
|
| 1753 |
+
methods=["GET"], name="%s_agent_evidence" % ns),
|
| 1754 |
+
Route("/api/%s/v1/agent/invocations" % ns, _agent_invocations,
|
| 1755 |
+
methods=["GET"], name="%s_agent_invocations" % ns),
|
| 1756 |
Route("/api/%s/v1/agent/governance-standards" % ns, _agent_governance_standards,
|
| 1757 |
methods=["GET"], name="%s_agent_gov_standards" % ns),
|
| 1758 |
Route("/api/%s/v1/agent/verify-chain" % ns, _agent_verify, methods=["POST"], name="%s_agent_verify" % ns),
|
|
|
|
| 1760 |
Route("/ask-and-act", _ask_and_act_ui, methods=["GET"], name="%s_ask_and_act" % ns),
|
| 1761 |
Route("/governed-run", _ask_and_act_ui, methods=["GET"], name="%s_governed_run" % ns),
|
| 1762 |
]
|
| 1763 |
+
if ns == "a11oy":
|
| 1764 |
+
routes.extend([
|
| 1765 |
+
Route("/api/hatun/evidence", _agent_evidence, methods=["GET"],
|
| 1766 |
+
name="hatun_evidence"),
|
| 1767 |
+
Route("/api/hatun/invocations", _agent_invocations, methods=["GET"],
|
| 1768 |
+
name="hatun_invocations"),
|
| 1769 |
+
])
|
| 1770 |
# insert at position 0 so they win over the SPA catch-all (the known gotcha).
|
| 1771 |
for r in reversed(routes):
|
| 1772 |
app.router.routes.insert(0, r)
|
szl_frontier_manifest.py
CHANGED
|
@@ -10,7 +10,7 @@ capability as a labeled tile. The manifest is REAL data pulled IN-PROCESS from t
|
|
| 10 |
already-wired surfaces — it never fabricates a status, joule, receipt, or label:
|
| 11 |
|
| 12 |
* energy operator — szl_energy_operator.handle_status() (MEASURED joules/jobs)
|
| 13 |
-
* energy ledger — szl_energy_ledger.handle_ledger() (
|
| 14 |
* energy provenance— szl_energy_provenance summary (tamper-evident chain)
|
| 15 |
* UDS bundle sig — szl_uds_fleet narrative (cosign+Rekor pattern) (label honest)
|
| 16 |
* orbital tier — szl_orbital_topology / _projection (MODELED roadmap)
|
|
@@ -34,12 +34,12 @@ DOCTRINE v11 (this surface is a roll-up — be ruthless about honesty):
|
|
| 34 |
- If a sub-source raises or is down, its tile says so honestly
|
| 35 |
(label "UNAVAILABLE", ok:false, the error) — we degrade the tile, never the truth,
|
| 36 |
and the manifest as a whole still returns 200 with the surviving tiles.
|
| 37 |
-
- The
|
| 38 |
-
|
| 39 |
-
|
| 40 |
|
| 41 |
-
The composition is the whole point: SZL already holds the parts (
|
| 42 |
-
receipts MEASURED, signed UDS bundle MEASURED, governance doctrine MEASURED, MODELED
|
| 43 |
orbital roadmap). This manifest shows them as one frontier surface, honestly labeled.
|
| 44 |
"""
|
| 45 |
from __future__ import annotations
|
|
@@ -57,7 +57,7 @@ UNAVAILABLE = "UNAVAILABLE"
|
|
| 57 |
_API = "/api/a11oy/v1"
|
| 58 |
|
| 59 |
# UNIVERSAL Khipu verifier (judge-facing audit layer, szl_khipu_verify). A reader
|
| 60 |
-
# pastes ANY receipt digest from ANY organ and gets
|
| 61 |
# PASS|FAIL|NOT_FOUND (SHA3-256 seal recompute + prev-link re-walk to genesis).
|
| 62 |
# This is the REAL endpoint each verifiable tile's `verify` field points to. Only
|
| 63 |
# tiles whose receipts genuinely live in a shared szl_khipu organ DAG (immune,
|
|
@@ -105,6 +105,115 @@ def _unavailable_tile(name: str, category: str, provenance: dict, err: str) -> d
|
|
| 105 |
error=err)
|
| 106 |
|
| 107 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
# ---------------------------------------------------------------------------
|
| 109 |
# Per-capability tile builders. Each pulls IN-PROCESS from the live surface.
|
| 110 |
# ---------------------------------------------------------------------------
|
|
@@ -134,6 +243,11 @@ def _tile_energy_operator() -> dict:
|
|
| 134 |
joules_measured_total=measured_total,
|
| 135 |
measured_jobs=measured_jobs,
|
| 136 |
jobs_done=st.get("jobs_done"),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
)
|
| 138 |
|
| 139 |
|
|
@@ -151,14 +265,16 @@ def _tile_energy_ledger() -> dict:
|
|
| 151 |
if isinstance(head, dict):
|
| 152 |
head_digest = head.get("entry_digest") or head.get("digest") \
|
| 153 |
or (head.get("receipt") or {}).get("payload_digest")
|
| 154 |
-
status = (f"OK ({chain_len}
|
| 155 |
if chain_len else "IDLE (chain empty — no jobs minted yet)")
|
| 156 |
return _tile(
|
| 157 |
-
"
|
| 158 |
provenance={
|
| 159 |
"endpoint": f"{_API}/energy/ledger",
|
| 160 |
-
"kind": "
|
|
|
|
| 161 |
"chain_head_digest": head_digest,
|
|
|
|
| 162 |
"single_receipt": f"{_API}/energy/receipt/{{idempotency_key}}",
|
| 163 |
# The energy ledger is its OWN hash-chained JouleCharge chain (not a shared
|
| 164 |
# szl_khipu organ DAG), so its honest verify surface is the ledger endpoint
|
|
@@ -172,6 +288,17 @@ def _tile_energy_ledger() -> dict:
|
|
| 172 |
persistence_label=persistence.get("label"),
|
| 173 |
survives_redeploy=survives,
|
| 174 |
persistence_note=persistence.get("note"),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
)
|
| 176 |
|
| 177 |
|
|
@@ -179,7 +306,8 @@ def _tile_energy_provenance() -> dict:
|
|
| 179 |
import szl_energy_provenance as ep
|
| 180 |
summ = ep._CHAIN.summary()
|
| 181 |
length = summ.get("length", 0)
|
| 182 |
-
|
|
|
|
| 183 |
else "EMPTY (no receipts this process)")
|
| 184 |
return _tile(
|
| 185 |
"Energy provenance chain", "provenance", status=status, label=MEASURED,
|
|
@@ -188,12 +316,24 @@ def _tile_energy_provenance() -> dict:
|
|
| 188 |
"kind": "tamper-evident hash-linked + Bekenstein-gated chain",
|
| 189 |
"head_hash": summ.get("head_hash"),
|
| 190 |
"link_rule": summ.get("link_rule"),
|
|
|
|
| 191 |
# Its OWN Bekenstein-gated chain (not a shared szl_khipu organ) -> honest
|
| 192 |
# verify surface is its own endpoint, re-walked. Not pointed at /khipu/verify.
|
| 193 |
"verify": f"{_API}/energy/provenance",
|
| 194 |
},
|
| 195 |
length=length,
|
| 196 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
)
|
| 198 |
|
| 199 |
|
|
@@ -219,6 +359,11 @@ def _tile_uds_bundle() -> dict:
|
|
| 219 |
"sbom": "CycloneDX / SPDX in-toto attestation",
|
| 220 |
"backing_module": backing,
|
| 221 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
)
|
| 223 |
|
| 224 |
|
|
@@ -243,6 +388,11 @@ def _tile_orbital() -> dict:
|
|
| 243 |
# reachable_nodes is REAL-PROBE-ONLY and MUST be 0 — no orbital hardware to probe.
|
| 244 |
reachable_nodes=reachable,
|
| 245 |
note="every orbital node is modeled:true / reachable:false; a MODELED orbital joule is NEVER MEASURED",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
)
|
| 247 |
|
| 248 |
|
|
@@ -271,6 +421,11 @@ def _tile_compute_fabric() -> dict:
|
|
| 271 |
# reachable / gpu_reachable are REAL-PROBE-ONLY facts.
|
| 272 |
nodes_reachable=reachable_n,
|
| 273 |
gpu_reachable=gpu_reachable,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 274 |
)
|
| 275 |
|
| 276 |
|
|
@@ -281,35 +436,50 @@ def _tile_governance() -> dict:
|
|
| 281 |
import szl_restraint as rs
|
| 282 |
info = rs.info()
|
| 283 |
doctrine = info.get("doctrine", {}) or {}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 284 |
return _tile(
|
| 285 |
-
"Governance / restraint", "governance", status=
|
| 286 |
label=MEASURED,
|
| 287 |
provenance={
|
| 288 |
"endpoint": f"{_API}/restraint/info",
|
| 289 |
-
"kind": "codified restraint
|
|
|
|
| 290 |
"doctrine_version": doctrine.get("version"),
|
| 291 |
"kernel_commit": doctrine.get("kernel_commit"),
|
| 292 |
},
|
| 293 |
-
|
|
|
|
|
|
|
|
|
|
| 294 |
runtime_cdn=doctrine.get("runtime_cdn"),
|
| 295 |
lambda_=doctrine.get("lambda"),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
)
|
| 297 |
|
| 298 |
|
| 299 |
def _concept_tile_inference_provenance() -> dict:
|
| 300 |
"""#1 frontier play — composite inference-provenance receipt (the inference-side C2PA).
|
| 301 |
|
| 302 |
-
|
| 303 |
-
NEVER mints a receipt. The capstone surface szl_provenance_receipt composes ONE
|
| 304 |
-
Khipu envelope binding
|
| 305 |
PAC-Bayes bound + MEASURED/MODELED/SAMPLE energy label + governed model identity + Lean
|
| 306 |
-
backing)
|
| 307 |
-
|
|
|
|
| 308 |
chain head (depth + most-recent composite digest, if any) and re-verify chain
|
| 309 |
integrity, so the tile honestly DESCRIBES the capability and points to where the real
|
| 310 |
artifacts live (/provenance/receipt + the energy ledger) without growing the chain.
|
| 311 |
Honesty held: a GET does not fabricate or mint a composite; if no composite exists yet
|
| 312 |
-
the tile
|
| 313 |
import szl_khipu
|
| 314 |
import szl_provenance_receipt as pr
|
| 315 |
|
|
@@ -320,30 +490,61 @@ def _concept_tile_inference_provenance() -> dict:
|
|
| 320 |
head = dag.head()
|
| 321 |
# Most-recent composite digest already on the chain (a READ, never a mint).
|
| 322 |
last_composite = None
|
|
|
|
| 323 |
for r in reversed(dag.tail(depth or 1)):
|
| 324 |
if r.get("action") == "provenance.composite":
|
| 325 |
last_composite = r.get("digest")
|
|
|
|
| 326 |
break
|
| 327 |
|
| 328 |
minted = last_composite is not None
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 333 |
label = MEASURED
|
| 334 |
-
note = ("inference-side
|
| 335 |
-
"
|
|
|
|
| 336 |
"MEASURED/MODELED/SAMPLE energy label, the governed model identity, and the "
|
| 337 |
-
"exact Lean backing. Each part KEEPS its own label; no label is upgraded
|
| 338 |
-
"
|
| 339 |
"NOT mint a receipt per page view. POST the endpoint to mint one for a real "
|
| 340 |
"action, then GET it back by digest.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 341 |
else:
|
| 342 |
-
status = ("
|
| 343 |
-
"
|
| 344 |
-
label =
|
| 345 |
-
note = ("inference-side C2PA capability is
|
| 346 |
-
"
|
|
|
|
| 347 |
"/provenance/receipt (immune verdict + PAC-Bayes bound + energy label + "
|
| 348 |
"governed model identity + Lean backing) — never fabricated, never minted by "
|
| 349 |
"loading this manifest.")
|
|
@@ -352,10 +553,9 @@ def _concept_tile_inference_provenance() -> dict:
|
|
| 352 |
"Composite inference-provenance receipt", "frontier-concept",
|
| 353 |
status=status, label=label,
|
| 354 |
provenance={
|
| 355 |
-
"kind": "composite composed in-process
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
"chain head and NEVER mints a receipt per page view",
|
| 359 |
"endpoint": f"{_API}/provenance/receipt",
|
| 360 |
# Composite receipts live in the shared szl_khipu `provenance` organ, so a
|
| 361 |
# judge can re-verify a composite digest TWO honest ways: the composite
|
|
@@ -368,16 +568,36 @@ def _concept_tile_inference_provenance() -> dict:
|
|
| 368 |
"latest_composite_digest": last_composite,
|
| 369 |
"chain_head": head,
|
| 370 |
"chain_verified": chain.get("ok"),
|
|
|
|
|
|
|
|
|
|
| 371 |
"composes_measured": f"{_API}/immune/verdict (REAL fail-closed gate) + the "
|
| 372 |
"MEASURED energy joule-truth path",
|
| 373 |
-
"
|
|
|
|
| 374 |
},
|
| 375 |
# READ facts straight off the chain — this tile mints nothing on a GET.
|
| 376 |
on_artifact_minted=minted,
|
| 377 |
composite_digest=last_composite,
|
| 378 |
chain_ok=chain.get("ok"),
|
| 379 |
chain_length=depth,
|
|
|
|
|
|
|
| 380 |
note=note,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 381 |
)
|
| 382 |
|
| 383 |
|
|
@@ -386,7 +606,7 @@ def _concept_tile_inference_provenance() -> dict:
|
|
| 386 |
_TILE_SPECS: list[tuple[Callable[[], dict], str, str, dict]] = [
|
| 387 |
(_tile_energy_operator, "Energy operator", "energy",
|
| 388 |
{"endpoint": f"{_API}/energy/operator/status"}),
|
| 389 |
-
(_tile_energy_ledger, "
|
| 390 |
{"endpoint": f"{_API}/energy/ledger"}),
|
| 391 |
(_tile_energy_provenance, "Energy provenance chain", "provenance",
|
| 392 |
{"endpoint": f"{_API}/energy/provenance"}),
|
|
@@ -430,7 +650,8 @@ def _build_manifest() -> dict:
|
|
| 430 |
tiles.append(tile if tile is not None
|
| 431 |
else _unavailable_tile(name, category, prov, err or "unknown error"))
|
| 432 |
|
| 433 |
-
#
|
|
|
|
| 434 |
concept, c_err = _safe(_concept_tile_inference_provenance)
|
| 435 |
if concept is None: # pragma: no cover — the concept tile is pure data
|
| 436 |
concept = _unavailable_tile("Composite inference-provenance receipt",
|
|
@@ -441,47 +662,79 @@ def _build_manifest() -> dict:
|
|
| 441 |
for t in tiles:
|
| 442 |
label_counts[t["label"]] = label_counts.get(t["label"], 0) + 1
|
| 443 |
degraded = [t["name"] for t in tiles if not t.get("ok", True)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 444 |
|
| 445 |
return {
|
| 446 |
"ok": True,
|
| 447 |
"endpoint": "frontier/manifest",
|
| 448 |
"service": "a11oy.frontier.manifest",
|
| 449 |
"what": ("one honest roll-up of the SZL governed-provenance ecosystem — every "
|
| 450 |
-
"capability as a tile with its
|
| 451 |
"a provenance pointer. Composed live, in-process, from the wired surfaces."),
|
| 452 |
"doctrine": (
|
| 453 |
"v11: REAL composed data only. No label is upgraded (orbital stays MODELED, "
|
| 454 |
"ROADMAP stays ROADMAP). reachable/running/survives_redeploy are REAL-PROBE-ONLY "
|
| 455 |
"and read straight from the live surfaces. A down sub-source yields an honest "
|
| 456 |
-
"UNAVAILABLE tile, never a fabricated OK. The
|
| 457 |
-
"
|
| 458 |
"Λ = Conjecture 1."
|
| 459 |
),
|
| 460 |
"universal_verifier": {
|
| 461 |
-
"what": "judge-facing
|
| 462 |
"szl_khipu organ (immune, materials, kverify, provenance, sda, "
|
| 463 |
-
"nemo_agents) and get
|
| 464 |
"verify_post": _KHIPU_VERIFY,
|
| 465 |
"verify_link": _KHIPU_VERIFY_PATH,
|
| 466 |
"organs": _KHIPU_ORGANS,
|
| 467 |
-
"method": "SHA3-256 seal recompute
|
| 468 |
-
"
|
| 469 |
-
"
|
| 470 |
-
"signature_status": "DSSE_PLACEHOLDER
|
| 471 |
-
|
|
|
|
|
|
|
|
|
|
| 472 |
},
|
| 473 |
"labels_legend": {
|
| 474 |
-
"MEASURED": "real measured/shipped capability (e.g.
|
|
|
|
| 475 |
"MODELED": "design artifact derived from a real measurement (e.g. orbital joules from ground coeff)",
|
| 476 |
"ROADMAP": "named forward work; no fabricated artifact",
|
| 477 |
"SAMPLE": "illustrative sample value, never billable/live",
|
| 478 |
-
"UNAVAILABLE": "
|
| 479 |
},
|
| 480 |
"summary": {
|
| 481 |
"tiles": len(tiles),
|
| 482 |
"label_counts": label_counts,
|
| 483 |
"degraded_tiles": degraded,
|
| 484 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 485 |
},
|
| 486 |
"capabilities": tiles,
|
| 487 |
"timestamp_utc": _now_iso(),
|
|
@@ -574,7 +827,7 @@ if __name__ == "__main__":
|
|
| 574 |
|
| 575 |
# 4) the #1 frontier composite tile READS the provenance chain; it NEVER mints a
|
| 576 |
# receipt on a manifest GET. A fresh process has an empty provenance chain, so the
|
| 577 |
-
# tile is honestly
|
| 578 |
import szl_khipu as _kh
|
| 579 |
import szl_provenance_receipt as _pr
|
| 580 |
_prov = _kh.get_dag(_pr._KHIPU_ORGAN, ns="a11oy")
|
|
@@ -584,10 +837,11 @@ if __name__ == "__main__":
|
|
| 584 |
assert _after == _before, (
|
| 585 |
f"manifest GET must NOT mint a provenance receipt (chain grew {_before}->{_after})")
|
| 586 |
concept = next(t for t in tiles if t["category"] == "frontier-concept")
|
| 587 |
-
assert concept["label"] in (
|
| 588 |
-
# On a fresh process (empty chain) the tile is honestly
|
| 589 |
if _before == 0:
|
| 590 |
-
assert concept["label"] ==
|
|
|
|
| 591 |
assert concept.get("on_artifact_minted") is False, "no composite minted by a GET"
|
| 592 |
assert concept.get("composite_digest") is None, "no digest fabricated on a GET"
|
| 593 |
assert concept["provenance"].get("chain_verified") is True, "provenance chain must verify"
|
|
@@ -596,6 +850,8 @@ if __name__ == "__main__":
|
|
| 596 |
|
| 597 |
# 5) labels legend + summary present; degraded tiles (if any) reported honestly
|
| 598 |
assert "labels_legend" in m and "summary" in m
|
|
|
|
|
|
|
| 599 |
print(f"[5] summary: {_json.dumps(m['summary'])}")
|
| 600 |
|
| 601 |
print("\n--- tiles (name / label / status) ---")
|
|
@@ -603,5 +859,3 @@ if __name__ == "__main__":
|
|
| 603 |
print(f" - {t['name']:38s} {t['label']:11s} {t['status']}")
|
| 604 |
print("\nok:true checks:5")
|
| 605 |
_sys.exit(0)
|
| 606 |
-
|
| 607 |
-
|
|
|
|
| 10 |
already-wired surfaces — it never fabricates a status, joule, receipt, or label:
|
| 11 |
|
| 12 |
* energy operator — szl_energy_operator.handle_status() (MEASURED joules/jobs)
|
| 13 |
+
* energy ledger — szl_energy_ledger.handle_ledger() (tamper-evident chain)
|
| 14 |
* energy provenance— szl_energy_provenance summary (tamper-evident chain)
|
| 15 |
* UDS bundle sig — szl_uds_fleet narrative (cosign+Rekor pattern) (label honest)
|
| 16 |
* orbital tier — szl_orbital_topology / _projection (MODELED roadmap)
|
|
|
|
| 34 |
- If a sub-source raises or is down, its tile says so honestly
|
| 35 |
(label "UNAVAILABLE", ok:false, the error) — we degrade the tile, never the truth,
|
| 36 |
and the manifest as a whole still returns 200 with the surviving tiles.
|
| 37 |
+
- The composite inference-provenance capability is UNAVAILABLE until a real governed
|
| 38 |
+
action has minted an artifact. A read never creates one and an unminted capability is
|
| 39 |
+
never presented as operational merely because its source module is reachable.
|
| 40 |
|
| 41 |
+
The composition is the whole point: SZL already holds the parts (tamper-evident
|
| 42 |
+
energy receipts MEASURED, signed UDS bundle MEASURED, governance doctrine MEASURED, MODELED
|
| 43 |
orbital roadmap). This manifest shows them as one frontier surface, honestly labeled.
|
| 44 |
"""
|
| 45 |
from __future__ import annotations
|
|
|
|
| 57 |
_API = "/api/a11oy/v1"
|
| 58 |
|
| 59 |
# UNIVERSAL Khipu verifier (judge-facing audit layer, szl_khipu_verify). A reader
|
| 60 |
+
# pastes ANY receipt digest from ANY organ and gets a COMPUTED integrity
|
| 61 |
# PASS|FAIL|NOT_FOUND (SHA3-256 seal recompute + prev-link re-walk to genesis).
|
| 62 |
# This is the REAL endpoint each verifiable tile's `verify` field points to. Only
|
| 63 |
# tiles whose receipts genuinely live in a shared szl_khipu organ DAG (immune,
|
|
|
|
| 105 |
error=err)
|
| 106 |
|
| 107 |
|
| 108 |
+
def _tile_operational_readiness(tile: dict) -> tuple[bool, list[str]]:
|
| 109 |
+
"""Derive runtime readiness from tile evidence without upgrading its label.
|
| 110 |
+
|
| 111 |
+
A source can answer while its operator is stopped, its chain is empty, its
|
| 112 |
+
hardware is unreachable, or its required artifact has not been minted.
|
| 113 |
+
Reachability is therefore reported separately from operational readiness.
|
| 114 |
+
"""
|
| 115 |
+
reasons: list[str] = []
|
| 116 |
+
label = str(tile.get("label") or UNAVAILABLE).upper()
|
| 117 |
+
status = str(tile.get("status") or "").upper()
|
| 118 |
+
evidence = tile.get("operational_evidence")
|
| 119 |
+
|
| 120 |
+
# Absence of a negative is not positive evidence. Every ready tile must name
|
| 121 |
+
# its exact bounded predicate and report that predicate satisfied.
|
| 122 |
+
if not isinstance(evidence, dict):
|
| 123 |
+
reasons.append("explicit_operational_evidence_missing")
|
| 124 |
+
else:
|
| 125 |
+
predicate = evidence.get("predicate")
|
| 126 |
+
if not isinstance(predicate, str) or not predicate.strip():
|
| 127 |
+
reasons.append("explicit_operational_predicate_missing")
|
| 128 |
+
if evidence.get("satisfied") is not True:
|
| 129 |
+
evidence_reasons = evidence.get("reasons")
|
| 130 |
+
if isinstance(evidence_reasons, list) and evidence_reasons:
|
| 131 |
+
reasons.extend(str(reason) for reason in evidence_reasons)
|
| 132 |
+
else:
|
| 133 |
+
reasons.append("explicit_operational_evidence_not_satisfied")
|
| 134 |
+
|
| 135 |
+
if not tile.get("ok", True):
|
| 136 |
+
reasons.append("source_unavailable")
|
| 137 |
+
if label in {UNAVAILABLE, MODELED, ROADMAP, SAMPLE}:
|
| 138 |
+
reasons.append(f"label_{label.lower()}_is_not_operational_evidence")
|
| 139 |
+
if any(token in status for token in ("UNAVAILABLE", "IDLE", "EMPTY", "STOPPED")):
|
| 140 |
+
reasons.append("status_not_running")
|
| 141 |
+
if tile.get("running") is False:
|
| 142 |
+
reasons.append("operator_stopped")
|
| 143 |
+
if tile.get("on_artifact_minted") is False:
|
| 144 |
+
reasons.append("artifact_not_minted")
|
| 145 |
+
if tile.get("on_orbit_hardware") is False:
|
| 146 |
+
reasons.append("hardware_not_present")
|
| 147 |
+
if "nodes_reachable" in tile and int(tile.get("nodes_reachable") or 0) < 1:
|
| 148 |
+
reasons.append("no_nodes_reachable")
|
| 149 |
+
if "reachable_nodes" in tile and int(tile.get("reachable_nodes") or 0) < 1:
|
| 150 |
+
reasons.append("no_nodes_reachable")
|
| 151 |
+
if "chain_length" in tile and int(tile.get("chain_length") or 0) < 1:
|
| 152 |
+
reasons.append("no_chain_entries")
|
| 153 |
+
if "length" in tile and int(tile.get("length") or 0) < 1:
|
| 154 |
+
reasons.append("no_chain_entries")
|
| 155 |
+
if "links_intact" in tile and tile.get("links_intact") is not True:
|
| 156 |
+
reasons.append("chain_links_not_verified")
|
| 157 |
+
if "chain_ok" in tile and tile.get("chain_ok") is not True:
|
| 158 |
+
reasons.append("chain_not_verified")
|
| 159 |
+
if "survives_redeploy" in tile and tile.get("survives_redeploy") is not True:
|
| 160 |
+
reasons.append("persistence_not_verified")
|
| 161 |
+
if tile.get("signature_required") is True and tile.get("signature_verified") is not True:
|
| 162 |
+
reasons.append("cryptographic_signature_not_verified")
|
| 163 |
+
|
| 164 |
+
unique_reasons = list(dict.fromkeys(reasons))
|
| 165 |
+
return not unique_reasons, unique_reasons
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _runtime_signature_readiness(info: dict) -> tuple[bool, list[str], dict]:
|
| 169 |
+
"""Require an observed runtime signer and a cryptographically verified receipt.
|
| 170 |
+
|
| 171 |
+
Static policy metadata such as ``signed_receipts=true`` describes an intended
|
| 172 |
+
contract. It is neither signer health nor proof that a signature was produced
|
| 173 |
+
and verified, so it cannot make the governance tile operational.
|
| 174 |
+
"""
|
| 175 |
+
signer = info.get("signer_health") if isinstance(info.get("signer_health"), dict) else {}
|
| 176 |
+
verification = (info.get("receipt_verification")
|
| 177 |
+
if isinstance(info.get("receipt_verification"), dict) else {})
|
| 178 |
+
method = str(verification.get("method") or "").strip()
|
| 179 |
+
method_upper = method.upper()
|
| 180 |
+
signature_count = verification.get("signature_count")
|
| 181 |
+
try:
|
| 182 |
+
signature_count = int(signature_count)
|
| 183 |
+
except (TypeError, ValueError):
|
| 184 |
+
signature_count = 0
|
| 185 |
+
|
| 186 |
+
reasons = []
|
| 187 |
+
if signer.get("observed_this_process") is not True:
|
| 188 |
+
reasons.append("signer_health_not_observed")
|
| 189 |
+
if signer.get("ready") is not True:
|
| 190 |
+
reasons.append("signer_not_ready")
|
| 191 |
+
if verification.get("observed_this_process") is not True:
|
| 192 |
+
reasons.append("receipt_verification_not_observed")
|
| 193 |
+
if verification.get("cryptographically_verified") is not True:
|
| 194 |
+
reasons.append("cryptographic_signature_not_verified")
|
| 195 |
+
if signature_count < 1:
|
| 196 |
+
reasons.append("verified_signature_missing")
|
| 197 |
+
if not method or "PLACEHOLDER" in method_upper or method_upper in {"HASH", "HASH_CHAIN"}:
|
| 198 |
+
reasons.append("cryptographic_verification_method_missing")
|
| 199 |
+
|
| 200 |
+
evidence = {
|
| 201 |
+
"signer_observed_this_process": signer.get("observed_this_process") is True,
|
| 202 |
+
"signer_ready": signer.get("ready") is True,
|
| 203 |
+
"signer_identity": signer.get("identity"),
|
| 204 |
+
"receipt_verification_observed_this_process": (
|
| 205 |
+
verification.get("observed_this_process") is True
|
| 206 |
+
),
|
| 207 |
+
"cryptographically_verified": (
|
| 208 |
+
verification.get("cryptographically_verified") is True
|
| 209 |
+
),
|
| 210 |
+
"signature_count": signature_count,
|
| 211 |
+
"verification_method": method or None,
|
| 212 |
+
}
|
| 213 |
+
unique_reasons = list(dict.fromkeys(reasons))
|
| 214 |
+
return not unique_reasons, unique_reasons, evidence
|
| 215 |
+
|
| 216 |
+
|
| 217 |
# ---------------------------------------------------------------------------
|
| 218 |
# Per-capability tile builders. Each pulls IN-PROCESS from the live surface.
|
| 219 |
# ---------------------------------------------------------------------------
|
|
|
|
| 243 |
joules_measured_total=measured_total,
|
| 244 |
measured_jobs=measured_jobs,
|
| 245 |
jobs_done=st.get("jobs_done"),
|
| 246 |
+
operational_evidence={
|
| 247 |
+
"predicate": "energy operator reports running=true",
|
| 248 |
+
"satisfied": running,
|
| 249 |
+
"reasons": [] if running else ["operator_stopped"],
|
| 250 |
+
},
|
| 251 |
)
|
| 252 |
|
| 253 |
|
|
|
|
| 265 |
if isinstance(head, dict):
|
| 266 |
head_digest = head.get("entry_digest") or head.get("digest") \
|
| 267 |
or (head.get("receipt") or {}).get("payload_digest")
|
| 268 |
+
status = (f"OK ({chain_len} integrity-only receipts, links_intact={links_intact})"
|
| 269 |
if chain_len else "IDLE (chain empty — no jobs minted yet)")
|
| 270 |
return _tile(
|
| 271 |
+
"Tamper-evident energy ledger", "energy", status=status, label=MEASURED,
|
| 272 |
provenance={
|
| 273 |
"endpoint": f"{_API}/energy/ledger",
|
| 274 |
+
"kind": ("tamper-evident integrity-only JouleCharge hash chain; "
|
| 275 |
+
"no cryptographic signature is verified by this surface"),
|
| 276 |
"chain_head_digest": head_digest,
|
| 277 |
+
"signature_status": "NOT_VERIFIED_INTEGRITY_ONLY",
|
| 278 |
"single_receipt": f"{_API}/energy/receipt/{{idempotency_key}}",
|
| 279 |
# The energy ledger is its OWN hash-chained JouleCharge chain (not a shared
|
| 280 |
# szl_khipu organ DAG), so its honest verify surface is the ledger endpoint
|
|
|
|
| 288 |
persistence_label=persistence.get("label"),
|
| 289 |
survives_redeploy=survives,
|
| 290 |
persistence_note=persistence.get("note"),
|
| 291 |
+
operational_evidence={
|
| 292 |
+
"predicate": "non-empty ledger + intact links + verified redeploy persistence",
|
| 293 |
+
"satisfied": bool(chain_len and links_intact is True and survives),
|
| 294 |
+
"reasons": [
|
| 295 |
+
reason for failed, reason in (
|
| 296 |
+
(not chain_len, "no_chain_entries"),
|
| 297 |
+
(links_intact is not True, "chain_links_not_verified"),
|
| 298 |
+
(not survives, "persistence_not_verified"),
|
| 299 |
+
) if failed
|
| 300 |
+
],
|
| 301 |
+
},
|
| 302 |
)
|
| 303 |
|
| 304 |
|
|
|
|
| 306 |
import szl_energy_provenance as ep
|
| 307 |
summ = ep._CHAIN.summary()
|
| 308 |
length = summ.get("length", 0)
|
| 309 |
+
verify = summ.get("verify", {}) or {}
|
| 310 |
+
status = (f"INTEGRITY-VERIFIED ({length} tamper-evident receipts)" if length
|
| 311 |
else "EMPTY (no receipts this process)")
|
| 312 |
return _tile(
|
| 313 |
"Energy provenance chain", "provenance", status=status, label=MEASURED,
|
|
|
|
| 316 |
"kind": "tamper-evident hash-linked + Bekenstein-gated chain",
|
| 317 |
"head_hash": summ.get("head_hash"),
|
| 318 |
"link_rule": summ.get("link_rule"),
|
| 319 |
+
"signature_status": "NOT_VERIFIED_INTEGRITY_ONLY",
|
| 320 |
# Its OWN Bekenstein-gated chain (not a shared szl_khipu organ) -> honest
|
| 321 |
# verify surface is its own endpoint, re-walked. Not pointed at /khipu/verify.
|
| 322 |
"verify": f"{_API}/energy/provenance",
|
| 323 |
},
|
| 324 |
length=length,
|
| 325 |
+
integrity_chain_status=summ.get("status"),
|
| 326 |
+
verification_scope="content and hash-link integrity only; authorship not verified",
|
| 327 |
+
operational_evidence={
|
| 328 |
+
"predicate": "non-empty provenance chain + computed chain verification",
|
| 329 |
+
"satisfied": bool(length and verify.get("ok") is True),
|
| 330 |
+
"reasons": [
|
| 331 |
+
reason for failed, reason in (
|
| 332 |
+
(not length, "no_chain_entries"),
|
| 333 |
+
(verify.get("ok") is not True, "chain_not_verified"),
|
| 334 |
+
) if failed
|
| 335 |
+
],
|
| 336 |
+
},
|
| 337 |
)
|
| 338 |
|
| 339 |
|
|
|
|
| 359 |
"sbom": "CycloneDX / SPDX in-toto attestation",
|
| 360 |
"backing_module": backing,
|
| 361 |
},
|
| 362 |
+
operational_evidence={
|
| 363 |
+
"predicate": "a concrete UDS attestation is independently verified at runtime",
|
| 364 |
+
"satisfied": False,
|
| 365 |
+
"reasons": ["runtime_attestation_receipt_not_observed"],
|
| 366 |
+
},
|
| 367 |
)
|
| 368 |
|
| 369 |
|
|
|
|
| 388 |
# reachable_nodes is REAL-PROBE-ONLY and MUST be 0 — no orbital hardware to probe.
|
| 389 |
reachable_nodes=reachable,
|
| 390 |
note="every orbital node is modeled:true / reachable:false; a MODELED orbital joule is NEVER MEASURED",
|
| 391 |
+
operational_evidence={
|
| 392 |
+
"predicate": "at least one on-orbit hardware node is positively reachable",
|
| 393 |
+
"satisfied": False,
|
| 394 |
+
"reasons": ["hardware_not_present"],
|
| 395 |
+
},
|
| 396 |
)
|
| 397 |
|
| 398 |
|
|
|
|
| 421 |
# reachable / gpu_reachable are REAL-PROBE-ONLY facts.
|
| 422 |
nodes_reachable=reachable_n,
|
| 423 |
gpu_reachable=gpu_reachable,
|
| 424 |
+
operational_evidence={
|
| 425 |
+
"predicate": "at least one sovereign GPU node passes the live reachability probe",
|
| 426 |
+
"satisfied": gpu_reachable > 0,
|
| 427 |
+
"reasons": [] if gpu_reachable > 0 else ["no_sovereign_gpu_reachable"],
|
| 428 |
+
},
|
| 429 |
)
|
| 430 |
|
| 431 |
|
|
|
|
| 436 |
import szl_restraint as rs
|
| 437 |
info = rs.info()
|
| 438 |
doctrine = info.get("doctrine", {}) or {}
|
| 439 |
+
crypto_ready, crypto_reasons, crypto_evidence = _runtime_signature_readiness(info)
|
| 440 |
+
status = ("OK (runtime signer healthy; receipt signature cryptographically verified)"
|
| 441 |
+
if crypto_ready else
|
| 442 |
+
"DEGRADED (doctrine loaded; runtime signer/receipt verification not observed)")
|
| 443 |
return _tile(
|
| 444 |
+
"Governance / restraint", "governance", status=status,
|
| 445 |
label=MEASURED,
|
| 446 |
provenance={
|
| 447 |
"endpoint": f"{_API}/restraint/info",
|
| 448 |
+
"kind": ("codified restraint policy metadata; operational status additionally "
|
| 449 |
+
"requires observed signer health and cryptographic receipt verification"),
|
| 450 |
"doctrine_version": doctrine.get("version"),
|
| 451 |
"kernel_commit": doctrine.get("kernel_commit"),
|
| 452 |
},
|
| 453 |
+
signed_receipts_declared=doctrine.get("signed_receipts"),
|
| 454 |
+
signer_health=crypto_evidence,
|
| 455 |
+
signature_required=True,
|
| 456 |
+
signature_verified=crypto_ready,
|
| 457 |
runtime_cdn=doctrine.get("runtime_cdn"),
|
| 458 |
lambda_=doctrine.get("lambda"),
|
| 459 |
+
operational_evidence={
|
| 460 |
+
"predicate": ("runtime signer health observed + at least one receipt signature "
|
| 461 |
+
"cryptographically verified this process"),
|
| 462 |
+
"satisfied": crypto_ready,
|
| 463 |
+
"reasons": crypto_reasons,
|
| 464 |
+
},
|
| 465 |
)
|
| 466 |
|
| 467 |
|
| 468 |
def _concept_tile_inference_provenance() -> dict:
|
| 469 |
"""#1 frontier play — composite inference-provenance receipt (the inference-side C2PA).
|
| 470 |
|
| 471 |
+
Capability surfaced by READING the shared provenance Khipu chain — this tile
|
| 472 |
+
NEVER mints a receipt. The capstone surface szl_provenance_receipt composes ONE
|
| 473 |
+
tamper-evident Khipu envelope binding fields for a single governed action (immune verdict +
|
| 474 |
PAC-Bayes bound + MEASURED/MODELED/SAMPLE energy label + governed model identity + Lean
|
| 475 |
+
backing). It becomes signed evidence only when a cryptographic DSSE signature is observed
|
| 476 |
+
and verified. A real governed action POSTs /provenance/receipt; loading this page never
|
| 477 |
+
creates evidence. Here we READ the
|
| 478 |
chain head (depth + most-recent composite digest, if any) and re-verify chain
|
| 479 |
integrity, so the tile honestly DESCRIBES the capability and points to where the real
|
| 480 |
artifacts live (/provenance/receipt + the energy ledger) without growing the chain.
|
| 481 |
Honesty held: a GET does not fabricate or mint a composite; if no composite exists yet
|
| 482 |
+
the tile is UNAVAILABLE, awaiting a real governed write."""
|
| 483 |
import szl_khipu
|
| 484 |
import szl_provenance_receipt as pr
|
| 485 |
|
|
|
|
| 490 |
head = dag.head()
|
| 491 |
# Most-recent composite digest already on the chain (a READ, never a mint).
|
| 492 |
last_composite = None
|
| 493 |
+
last_composite_receipt = None
|
| 494 |
for r in reversed(dag.tail(depth or 1)):
|
| 495 |
if r.get("action") == "provenance.composite":
|
| 496 |
last_composite = r.get("digest")
|
| 497 |
+
last_composite_receipt = r
|
| 498 |
break
|
| 499 |
|
| 500 |
minted = last_composite is not None
|
| 501 |
+
signature = ((last_composite_receipt or {}).get("signature")
|
| 502 |
+
if last_composite_receipt else None)
|
| 503 |
+
verification = ((last_composite_receipt or {}).get("cryptographic_verification")
|
| 504 |
+
if isinstance((last_composite_receipt or {}).get(
|
| 505 |
+
"cryptographic_verification"), dict) else {})
|
| 506 |
+
verification_method = str(verification.get("method") or "").strip()
|
| 507 |
+
try:
|
| 508 |
+
verified_signature_count = int(verification.get("signature_count") or 0)
|
| 509 |
+
except (TypeError, ValueError):
|
| 510 |
+
verified_signature_count = 0
|
| 511 |
+
signature_verified = bool(
|
| 512 |
+
minted
|
| 513 |
+
and verification.get("observed_this_process") is True
|
| 514 |
+
and verification.get("verified") is True
|
| 515 |
+
and verified_signature_count > 0
|
| 516 |
+
and verification_method
|
| 517 |
+
and "PLACEHOLDER" not in verification_method.upper()
|
| 518 |
+
and signature not in (None, "", "DSSE_PLACEHOLDER")
|
| 519 |
+
)
|
| 520 |
+
if minted and signature_verified:
|
| 521 |
+
status = (f"LIVE ({depth} receipts on the provenance chain; latest composite has an "
|
| 522 |
+
"observed, cryptographically verified signature and binds immune verdict + "
|
| 523 |
+
"PAC-Bayes bound + energy label + governed model identity + Lean backing).")
|
| 524 |
label = MEASURED
|
| 525 |
+
note = ("inference-side composite, LIVE: the latest Khipu envelope has an observed, "
|
| 526 |
+
"cryptographically verified signature and composes the REAL immune verdict, "
|
| 527 |
+
"the PAC-Bayes bound (ROADMAP Lean), the "
|
| 528 |
"MEASURED/MODELED/SAMPLE energy label, the governed model identity, and the "
|
| 529 |
+
"exact Lean backing. Each part KEEPS its own label; no label is upgraded. "
|
| 530 |
+
"This tile READS the chain — it does "
|
| 531 |
"NOT mint a receipt per page view. POST the endpoint to mint one for a real "
|
| 532 |
"action, then GET it back by digest.")
|
| 533 |
+
elif minted:
|
| 534 |
+
status = (f"INTEGRITY-ONLY ({depth} hash-chained receipts; latest composite exists, "
|
| 535 |
+
"but no cryptographically verified DSSE signature was observed)")
|
| 536 |
+
label = UNAVAILABLE
|
| 537 |
+
note = ("the composite is content-addressed and its Khipu prev-links re-walk, but "
|
| 538 |
+
"DSSE_PLACEHOLDER is not a signature and proves no authorship. The signed "
|
| 539 |
+
"composite capability remains operationally blocked until real DSSE evidence "
|
| 540 |
+
"is verified this process.")
|
| 541 |
else:
|
| 542 |
+
status = ("UNAVAILABLE (capability wired, but no composite receipt has been observed "
|
| 543 |
+
"in this process; only a real governed POST can mint one)")
|
| 544 |
+
label = UNAVAILABLE
|
| 545 |
+
note = ("inference-side C2PA capability is reachable but not operationally evidenced: "
|
| 546 |
+
"no composite has been minted in "
|
| 547 |
+
"this process yet. A composite is created ONLY on a real POST to "
|
| 548 |
"/provenance/receipt (immune verdict + PAC-Bayes bound + energy label + "
|
| 549 |
"governed model identity + Lean backing) — never fabricated, never minted by "
|
| 550 |
"loading this manifest.")
|
|
|
|
| 553 |
"Composite inference-provenance receipt", "frontier-concept",
|
| 554 |
status=status, label=label,
|
| 555 |
provenance={
|
| 556 |
+
"kind": ("composite composed in-process and recorded in a tamper-evident Khipu "
|
| 557 |
+
"hash chain; DSSE_PLACEHOLDER is integrity-only metadata, not a "
|
| 558 |
+
"cryptographic signature; this manifest READS and never mints"),
|
|
|
|
| 559 |
"endpoint": f"{_API}/provenance/receipt",
|
| 560 |
# Composite receipts live in the shared szl_khipu `provenance` organ, so a
|
| 561 |
# judge can re-verify a composite digest TWO honest ways: the composite
|
|
|
|
| 568 |
"latest_composite_digest": last_composite,
|
| 569 |
"chain_head": head,
|
| 570 |
"chain_verified": chain.get("ok"),
|
| 571 |
+
"signature_status": ("CRYPTOGRAPHICALLY_VERIFIED" if signature_verified else
|
| 572 |
+
"NOT_VERIFIED_INTEGRITY_ONLY"),
|
| 573 |
+
"signature_verification_method": verification_method or None,
|
| 574 |
"composes_measured": f"{_API}/immune/verdict (REAL fail-closed gate) + the "
|
| 575 |
"MEASURED energy joule-truth path",
|
| 576 |
+
"open_dependencies": f"{_API}/materials/certify (PAC-Bayes/Lean evidence must "
|
| 577 |
+
"retain the status reported by that dependency)",
|
| 578 |
},
|
| 579 |
# READ facts straight off the chain — this tile mints nothing on a GET.
|
| 580 |
on_artifact_minted=minted,
|
| 581 |
composite_digest=last_composite,
|
| 582 |
chain_ok=chain.get("ok"),
|
| 583 |
chain_length=depth,
|
| 584 |
+
signature_required=True,
|
| 585 |
+
signature_verified=signature_verified,
|
| 586 |
note=note,
|
| 587 |
+
operational_evidence={
|
| 588 |
+
"predicate": ("a composite exists, its Khipu integrity chain verifies, and its "
|
| 589 |
+
"DSSE signature is cryptographically verified this process"),
|
| 590 |
+
"satisfied": bool(minted and depth > 0 and chain.get("ok") is True
|
| 591 |
+
and signature_verified),
|
| 592 |
+
"reasons": [
|
| 593 |
+
reason for failed, reason in (
|
| 594 |
+
(not minted, "artifact_not_minted"),
|
| 595 |
+
(depth < 1, "no_chain_entries"),
|
| 596 |
+
(chain.get("ok") is not True, "chain_not_verified"),
|
| 597 |
+
(not signature_verified, "cryptographic_signature_not_verified"),
|
| 598 |
+
) if failed
|
| 599 |
+
],
|
| 600 |
+
},
|
| 601 |
)
|
| 602 |
|
| 603 |
|
|
|
|
| 606 |
_TILE_SPECS: list[tuple[Callable[[], dict], str, str, dict]] = [
|
| 607 |
(_tile_energy_operator, "Energy operator", "energy",
|
| 608 |
{"endpoint": f"{_API}/energy/operator/status"}),
|
| 609 |
+
(_tile_energy_ledger, "Tamper-evident energy ledger", "energy",
|
| 610 |
{"endpoint": f"{_API}/energy/ledger"}),
|
| 611 |
(_tile_energy_provenance, "Energy provenance chain", "provenance",
|
| 612 |
{"endpoint": f"{_API}/energy/provenance"}),
|
|
|
|
| 650 |
tiles.append(tile if tile is not None
|
| 651 |
else _unavailable_tile(name, category, prov, err or "unknown error"))
|
| 652 |
|
| 653 |
+
# Composite capability — always present, but UNAVAILABLE until a real write has
|
| 654 |
+
# minted an artifact. A manifest read never creates operational evidence.
|
| 655 |
concept, c_err = _safe(_concept_tile_inference_provenance)
|
| 656 |
if concept is None: # pragma: no cover — the concept tile is pure data
|
| 657 |
concept = _unavailable_tile("Composite inference-provenance receipt",
|
|
|
|
| 662 |
for t in tiles:
|
| 663 |
label_counts[t["label"]] = label_counts.get(t["label"], 0) + 1
|
| 664 |
degraded = [t["name"] for t in tiles if not t.get("ok", True)]
|
| 665 |
+
reachable = [t["name"] for t in tiles if t.get("ok", True)]
|
| 666 |
+
readiness_rows = []
|
| 667 |
+
for tile in tiles:
|
| 668 |
+
ready, reasons = _tile_operational_readiness(tile)
|
| 669 |
+
readiness_rows.append({"name": tile["name"], "ready": ready, "reasons": reasons})
|
| 670 |
+
blocked = [row for row in readiness_rows if not row["ready"]]
|
| 671 |
+
all_sources_reachable = len(degraded) == 0
|
| 672 |
+
operationally_ready = not blocked and bool(tiles)
|
| 673 |
|
| 674 |
return {
|
| 675 |
"ok": True,
|
| 676 |
"endpoint": "frontier/manifest",
|
| 677 |
"service": "a11oy.frontier.manifest",
|
| 678 |
"what": ("one honest roll-up of the SZL governed-provenance ecosystem — every "
|
| 679 |
+
"capability as a tile with its own honesty label and "
|
| 680 |
"a provenance pointer. Composed live, in-process, from the wired surfaces."),
|
| 681 |
"doctrine": (
|
| 682 |
"v11: REAL composed data only. No label is upgraded (orbital stays MODELED, "
|
| 683 |
"ROADMAP stays ROADMAP). reachable/running/survives_redeploy are REAL-PROBE-ONLY "
|
| 684 |
"and read straight from the live surfaces. A down sub-source yields an honest "
|
| 685 |
+
"UNAVAILABLE tile, never a fabricated OK. The composite receipt remains "
|
| 686 |
+
"UNAVAILABLE until a real governed write has minted an artifact. "
|
| 687 |
"Λ = Conjecture 1."
|
| 688 |
),
|
| 689 |
"universal_verifier": {
|
| 690 |
+
"what": "judge-facing integrity layer: paste ANY receipt digest from ANY shared "
|
| 691 |
"szl_khipu organ (immune, materials, kverify, provenance, sda, "
|
| 692 |
+
"nemo_agents) and get a COMPUTED hash-chain PASS|FAIL|NOT_FOUND",
|
| 693 |
"verify_post": _KHIPU_VERIFY,
|
| 694 |
"verify_link": _KHIPU_VERIFY_PATH,
|
| 695 |
"organs": _KHIPU_ORGANS,
|
| 696 |
+
"method": "integrity-only SHA3-256 seal recompute + prev-link re-walk to genesis; "
|
| 697 |
+
"digest_matches + chain_to_genesis_verified are COMPUTED, never "
|
| 698 |
+
"asserted; this does not verify authorship",
|
| 699 |
+
"signature_status": ("NOT_VERIFIED_INTEGRITY_ONLY; DSSE_PLACEHOLDER is not a "
|
| 700 |
+
"cryptographic signature"),
|
| 701 |
+
"khipu_kind": ("tamper-evident integrity chain only; authorship remains blocked "
|
| 702 |
+
"until a real DSSE signature is verified; BFT/consensus is "
|
| 703 |
+
"Conjecture 2"),
|
| 704 |
},
|
| 705 |
"labels_legend": {
|
| 706 |
+
"MEASURED": ("real measured/shipped capability (e.g. tamper-evident joule "
|
| 707 |
+
"receipts, REAL probes); MEASURED never implies signed"),
|
| 708 |
"MODELED": "design artifact derived from a real measurement (e.g. orbital joules from ground coeff)",
|
| 709 |
"ROADMAP": "named forward work; no fabricated artifact",
|
| 710 |
"SAMPLE": "illustrative sample value, never billable/live",
|
| 711 |
+
"UNAVAILABLE": "source, dependency, or required artifact unavailable right now",
|
| 712 |
},
|
| 713 |
"summary": {
|
| 714 |
"tiles": len(tiles),
|
| 715 |
"label_counts": label_counts,
|
| 716 |
"degraded_tiles": degraded,
|
| 717 |
+
"source_reachability": {
|
| 718 |
+
"state": "REACHABLE" if all_sources_reachable else "DEGRADED",
|
| 719 |
+
"all_sources_reachable": all_sources_reachable,
|
| 720 |
+
"reachable_tiles": reachable,
|
| 721 |
+
"unavailable_tiles": degraded,
|
| 722 |
+
},
|
| 723 |
+
"operational_readiness": {
|
| 724 |
+
"state": "READY" if operationally_ready else "NOT_READY",
|
| 725 |
+
"ready": operationally_ready,
|
| 726 |
+
"ready_tiles": [row["name"] for row in readiness_rows if row["ready"]],
|
| 727 |
+
"blocked_tiles": blocked,
|
| 728 |
+
},
|
| 729 |
+
# Deprecated for old clients. This value is intentionally stricter than source
|
| 730 |
+
# reachability and cannot be true while a required tile is stopped, unminted,
|
| 731 |
+
# modeled, sampled, or unavailable.
|
| 732 |
+
"all_sources_live": operationally_ready,
|
| 733 |
+
"all_sources_live_compatibility": {
|
| 734 |
+
"deprecated": True,
|
| 735 |
+
"meaning": "legacy alias for operational_readiness.ready; not source reachability",
|
| 736 |
+
"value": operationally_ready,
|
| 737 |
+
},
|
| 738 |
},
|
| 739 |
"capabilities": tiles,
|
| 740 |
"timestamp_utc": _now_iso(),
|
|
|
|
| 827 |
|
| 828 |
# 4) the #1 frontier composite tile READS the provenance chain; it NEVER mints a
|
| 829 |
# receipt on a manifest GET. A fresh process has an empty provenance chain, so the
|
| 830 |
+
# tile is honestly UNAVAILABLE / no-artifact; building the manifest must not grow it.
|
| 831 |
import szl_khipu as _kh
|
| 832 |
import szl_provenance_receipt as _pr
|
| 833 |
_prov = _kh.get_dag(_pr._KHIPU_ORGAN, ns="a11oy")
|
|
|
|
| 837 |
assert _after == _before, (
|
| 838 |
f"manifest GET must NOT mint a provenance receipt (chain grew {_before}->{_after})")
|
| 839 |
concept = next(t for t in tiles if t["category"] == "frontier-concept")
|
| 840 |
+
assert concept["label"] in (UNAVAILABLE, MEASURED), concept["label"]
|
| 841 |
+
# On a fresh process (empty chain) the tile is honestly UNAVAILABLE with no artifact.
|
| 842 |
if _before == 0:
|
| 843 |
+
assert concept["label"] == UNAVAILABLE, \
|
| 844 |
+
"empty chain -> honest UNAVAILABLE, no fabricated artifact"
|
| 845 |
assert concept.get("on_artifact_minted") is False, "no composite minted by a GET"
|
| 846 |
assert concept.get("composite_digest") is None, "no digest fabricated on a GET"
|
| 847 |
assert concept["provenance"].get("chain_verified") is True, "provenance chain must verify"
|
|
|
|
| 850 |
|
| 851 |
# 5) labels legend + summary present; degraded tiles (if any) reported honestly
|
| 852 |
assert "labels_legend" in m and "summary" in m
|
| 853 |
+
assert "source_reachability" in m["summary"]
|
| 854 |
+
assert "operational_readiness" in m["summary"]
|
| 855 |
print(f"[5] summary: {_json.dumps(m['summary'])}")
|
| 856 |
|
| 857 |
print("\n--- tiles (name / label / status) ---")
|
|
|
|
| 859 |
print(f" - {t['name']:38s} {t['label']:11s} {t['status']}")
|
| 860 |
print("\nok:true checks:5")
|
| 861 |
_sys.exit(0)
|
|
|
|
|
|
szl_gpu_quant.py
CHANGED
|
@@ -30,10 +30,10 @@ HONESTY SPINE (doctrine v11 — the non-negotiable part of this build):
|
|
| 30 |
(cuML LedoitWolf + cuPy eigh + giotto-tda / Ripser++) is labeled ROADMAP. GPU
|
| 31 |
reachability and dependency imports are readiness only; MEASURED requires a distinct
|
| 32 |
accelerated path plus device/kernel/timing execution evidence.
|
| 33 |
-
* Every receipt is
|
| 34 |
-
is present in the runtime;
|
| 35 |
-
|
| 36 |
-
|
| 37 |
* No fabricated metric. No live-trading claim. No backtest claim. cuML speedups are
|
| 38 |
cited to NVIDIA/STAC docs, never asserted as SZL-measured.
|
| 39 |
|
|
@@ -41,34 +41,29 @@ Routes (NEW; never collide):
|
|
| 41 |
GET /api/{ns}/v1/quant/pca — Layer 1 PCA-Risk (LW + MP) on a SAMPLE universe
|
| 42 |
GET /api/{ns}/v1/quant/tda — Layer 2 TDA fracture score f_t, z_t, Betti β0/β1
|
| 43 |
GET /api/{ns}/v1/quant/kelly — Layer 3 HJB-Kelly weights w* with σ²_eff
|
| 44 |
-
GET /api/{ns}/v1/quant/pipeline — full 3-layer pass + ONE
|
| 45 |
GET /api/{ns}/v1/quant/tiers — 2-GPU serve tier panel (TP=2 / role-split / NIM cloud)
|
| 46 |
-
GET /api/{ns}/v1/quant/verify-claims —
|
| 47 |
GET /quant — unified mobile-first "Quant Engine" tab (0 CDN)
|
| 48 |
|
| 49 |
Pure stdlib. Defensive: a compute failure NEVER raises out of a handler.
|
| 50 |
"""
|
| 51 |
from __future__ import annotations
|
| 52 |
|
|
|
|
| 53 |
import hashlib as _hashlib
|
| 54 |
-
import html as _html_lib
|
| 55 |
import json as _json
|
| 56 |
import math as _math
|
| 57 |
import os as _os
|
|
|
|
| 58 |
import random as _random
|
| 59 |
import time as _time
|
| 60 |
from datetime import datetime, timezone
|
| 61 |
|
| 62 |
-
from szl_quant_claims import resolved_claims as _resolved_quant_claims
|
| 63 |
-
|
| 64 |
-
try:
|
| 65 |
-
import szl_formula_registry as _formula_registry
|
| 66 |
-
except Exception: # pragma: no cover - missing registry stays explicit
|
| 67 |
-
_formula_registry = None
|
| 68 |
-
|
| 69 |
# --- signed receipts: the SINGLE source of truth (never fabricate a signature) ----
|
| 70 |
try:
|
| 71 |
from szl_dsse import sign_payload as _sign_payload # REAL ECDSA when key present
|
|
|
|
| 72 |
_SIGN_AVAILABLE = True
|
| 73 |
except Exception: # pragma: no cover — defensive; honest unsigned fallback below
|
| 74 |
_SIGN_AVAILABLE = False
|
|
@@ -87,6 +82,9 @@ except Exception: # pragma: no cover — defensive; honest unsigned fallback be
|
|
| 87 |
"no signature fabricated."),
|
| 88 |
}
|
| 89 |
|
|
|
|
|
|
|
|
|
|
| 90 |
_QUANT_PAYLOAD_TYPE = "application/vnd.szl.quant.receipt+json"
|
| 91 |
|
| 92 |
# --- optional acceleration probes (honest GPU-path labels) ------------------------
|
|
@@ -166,38 +164,12 @@ def _compute_backend() -> dict:
|
|
| 166 |
}
|
| 167 |
|
| 168 |
|
| 169 |
-
def _formula_doctrine() -> dict:
|
| 170 |
-
"""Read the quant page's doctrine from the verified formula registry."""
|
| 171 |
-
if _formula_registry is None:
|
| 172 |
-
return {
|
| 173 |
-
"locked_proven": [], "locked_count": 0, "corpus": "UNAVAILABLE",
|
| 174 |
-
"kernel_commit": "UNAVAILABLE", "registry_digest": None,
|
| 175 |
-
"registry_signature": "UNAVAILABLE", "registry_status": "UNAVAILABLE",
|
| 176 |
-
}
|
| 177 |
-
try:
|
| 178 |
-
document = _formula_registry.load_registry(verify=True)
|
| 179 |
-
payload = document["payload"]
|
| 180 |
-
return {
|
| 181 |
-
"locked_proven": list(_formula_registry.LOCKED_PROVEN_IDS),
|
| 182 |
-
"locked_count": _formula_registry.LOCKED_PROVEN_COUNT,
|
| 183 |
-
"corpus": "registry-crosswalk (non-exhaustive)",
|
| 184 |
-
"kernel_commit": payload["locked_kernel_commit_prefix"],
|
| 185 |
-
"registry_digest": document["registry_digest"]["value"],
|
| 186 |
-
"registry_signature": document["signature"]["status"],
|
| 187 |
-
"registry_status": "VERIFIED",
|
| 188 |
-
}
|
| 189 |
-
except Exception as exc: # fail closed; never fall back to stale doctrine
|
| 190 |
-
return {
|
| 191 |
-
"locked_proven": [], "locked_count": 0, "corpus": "UNAVAILABLE",
|
| 192 |
-
"kernel_commit": "UNAVAILABLE", "registry_digest": None,
|
| 193 |
-
"registry_signature": "UNAVAILABLE",
|
| 194 |
-
"registry_status": "UNAVAILABLE: " + type(exc).__name__,
|
| 195 |
-
}
|
| 196 |
-
|
| 197 |
-
|
| 198 |
DOCTRINE = {
|
| 199 |
"version": "v11",
|
| 200 |
-
|
|
|
|
|
|
|
|
|
|
| 201 |
"lambda": "Conjecture 1 (advisory floor; uniqueness machine-checked FALSE unconditionally; NOT a theorem)",
|
| 202 |
"slsa": "L1 honest / L2 attested (.att emitted, not independently verified) / L3 roadmap",
|
| 203 |
}
|
|
@@ -698,10 +670,10 @@ def layer3_hjb_kelly(l1=None, l2=None, gamma=0.5, kappa=1.0, stress=False):
|
|
| 698 |
|
| 699 |
|
| 700 |
# =====================================================================================
|
| 701 |
-
# FULL PIPELINE -> ONE
|
| 702 |
# =====================================================================================
|
| 703 |
def run_pipeline(stress=False, gamma=0.5, kappa=1.0) -> dict:
|
| 704 |
-
"""Full 3-layer pass
|
| 705 |
returns = _sample_returns(stress=stress)
|
| 706 |
l1 = layer1_pca_risk(returns=returns, stress=stress)
|
| 707 |
l2 = layer2_tda_fracture(returns=returns, stress=stress)
|
|
@@ -847,37 +819,403 @@ def tiers_panel() -> dict:
|
|
| 847 |
|
| 848 |
|
| 849 |
# =====================================================================================
|
| 850 |
-
# VERIFY-THE-CLAIMS panel:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 851 |
# =====================================================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 852 |
def verify_claims_panel() -> dict:
|
| 853 |
-
"""
|
| 854 |
|
| 855 |
-
|
| 856 |
-
|
| 857 |
"""
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
|
| 861 |
-
"
|
| 862 |
-
|
| 863 |
-
|
| 864 |
-
|
| 865 |
-
|
| 866 |
-
|
| 867 |
-
|
| 868 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 869 |
return {
|
| 870 |
"service": "verify-the-claims",
|
| 871 |
"doctrine": DOCTRINE["version"],
|
| 872 |
-
"
|
| 873 |
-
|
| 874 |
-
"
|
| 875 |
-
|
|
|
|
| 876 |
"rows": rows,
|
| 877 |
-
"
|
| 878 |
-
|
| 879 |
-
"
|
| 880 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 881 |
"citations": [CITATIONS["rapids_cuml"], CITATIONS["ripserpp"]],
|
| 882 |
"computed_at": _now_iso(),
|
| 883 |
}
|
|
@@ -918,10 +1256,23 @@ def _html(pipe: dict, tiers: dict, verify: dict) -> str:
|
|
| 918 |
+ row("de-risk ratio", fmt(l3["derisk_ratio_vs_uninflated"]))
|
| 919 |
+ row("γ, κ", "%s, %s <small>(uncalibrated)</small>" % (l3["gamma"], l3["kappa"])))
|
| 920 |
dsse = pipe["signed_receipt"]["dsse"]
|
| 921 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 922 |
rc_body = (row("data source", "SAMPLE_SYNTHETIC")
|
| 923 |
+ row("pipeline", "<code>szl-gpu-quant-v0.1</code>")
|
| 924 |
-
+ row("
|
| 925 |
+ row("PAE sha256", "<code>%s…</code>" % str(dsse.get("_pae_sha256", ""))[:16])
|
| 926 |
+ row("label", "<small>%s</small>" % SAMPLE_LABEL))
|
| 927 |
|
|
@@ -937,39 +1288,29 @@ def _html(pipe: dict, tiers: dict, verify: dict) -> str:
|
|
| 937 |
+ gpus)
|
| 938 |
tier_cards += card(t["tier"], t["label"], body, t.get("fits", ""))
|
| 939 |
|
| 940 |
-
def esc(value):
|
| 941 |
-
return _html_lib.escape(str(value), quote=True)
|
| 942 |
-
|
| 943 |
-
def measured_text(value):
|
| 944 |
-
if value is None:
|
| 945 |
-
return "—"
|
| 946 |
-
return "%s %s (%s)" % (value["value"], value["unit"], value["estimator"])
|
| 947 |
-
|
| 948 |
vrows = ""
|
| 949 |
for r in verify["rows"]:
|
| 950 |
-
|
| 951 |
-
|
| 952 |
-
|
| 953 |
-
|
| 954 |
-
|
| 955 |
-
|
| 956 |
-
|
| 957 |
-
|
| 958 |
-
|
| 959 |
-
|
| 960 |
-
|
| 961 |
-
|
| 962 |
-
|
| 963 |
-
|
| 964 |
-
|
| 965 |
|
| 966 |
cards = "".join([
|
| 967 |
card("Layer 1 · PCA Risk (LW + MP)", l1["label"].split(" | ")[0].replace("_SIGNAL", ""), l1_body, l1["honest_note"]),
|
| 968 |
card("Layer 2 · TDA Fracture (β0/β1)", "SAMPLE", l2_body, l2["honest_note"]),
|
| 969 |
card("Layer 3 · HJB-Kelly Sizing", "MODELED", l3_body, l3["honest_note"]),
|
| 970 |
-
card(
|
| 971 |
-
("DSSE envelope over the canonical receipt — REAL ECDSA when the cosign key is in the "
|
| 972 |
-
"runtime, else an explicit UNSIGNED honesty marker (never a fabricated signature).")),
|
| 973 |
])
|
| 974 |
|
| 975 |
return """<!doctype html>
|
|
@@ -1005,18 +1346,18 @@ def _html(pipe: dict, tiers: dict, verify: dict) -> str:
|
|
| 1005 |
<header>
|
| 1006 |
<h1>Sovereign Quant Engine</h1>
|
| 1007 |
<p class="summary">__SUMMARY__</p>
|
| 1008 |
-
<p class="sub">Three orthogonal risk signals per bar — PCA-Risk · TDA-Fracture · HJB-Kelly —
|
| 1009 |
<p class="state">backend=__BACKEND__ · gpu_reachable=__REACH__ · scenario=__SCEN__</p>
|
| 1010 |
</header>
|
| 1011 |
-
<h2>3-Layer Pipeline (
|
| 1012 |
<section class="grid">__CARDS__</section>
|
| 1013 |
<h2>2-GPU Sovereign Serve · Throttle Both</h2>
|
| 1014 |
<section class="grid">__TIERS__</section>
|
| 1015 |
-
<h2>Verify the Claims —
|
| 1016 |
-
<section>__VERIFY__<p class="note">__VNOTE__</p></section>
|
| 1017 |
<footer>
|
| 1018 |
-
<p class="lock">Doctrine __DV__ LOCKED · locked-proven=__LC__ {__LP__} · __CORPUS__ @ __KC__ ·
|
| 1019 |
-
<p>SAMPLE = honest synthetic fixture (not live) · MODELED = labeled model output (uncalibrated) · ROADMAP = wiring ready, not measured yet (never faked).
|
| 1020 |
</footer>
|
| 1021 |
<script src="/static/shared/szl_label_engine.js"></script>
|
| 1022 |
<script>
|
|
@@ -1029,7 +1370,8 @@ def _html(pipe: dict, tiers: dict, verify: dict) -> str:
|
|
| 1029 |
title: (label === "SAMPLE") ? "Honest synthetic fixture — not a live feed, no backtest." :
|
| 1030 |
(label === "MODELED") ? "Labeled model output — uncalibrated, not measured." :
|
| 1031 |
(label === "LIVE") ? "Real backend wired and live." :
|
| 1032 |
-
"
|
|
|
|
| 1033 |
}
|
| 1034 |
return '<span>' + label + '</span>';
|
| 1035 |
}
|
|
@@ -1039,21 +1381,21 @@ def _html(pipe: dict, tiers: dict, verify: dict) -> str:
|
|
| 1039 |
})();
|
| 1040 |
</script>
|
| 1041 |
</body></html>""" \
|
| 1042 |
-
.replace("__SUMMARY__", "
|
| 1043 |
.replace("__BACKEND__", str(backend["backend"])) \
|
| 1044 |
.replace("__REACH__", str(backend["gpu_reachable"])) \
|
| 1045 |
.replace("__SCEN__", str(pipe["scenario"])) \
|
|
|
|
| 1046 |
.replace("__CARDS__", cards) \
|
| 1047 |
.replace("__TIERS__", tier_cards) \
|
| 1048 |
.replace("__VERIFY__", verify_tbl) \
|
|
|
|
| 1049 |
.replace("__VNOTE__", verify["honesty"]) \
|
| 1050 |
.replace("__DV__", d["version"]) \
|
| 1051 |
.replace("__LC__", str(d["locked_count"])) \
|
| 1052 |
.replace("__LP__", ", ".join(d["locked_proven"])) \
|
| 1053 |
.replace("__CORPUS__", d["corpus"]) \
|
| 1054 |
.replace("__KC__", d["kernel_commit"]) \
|
| 1055 |
-
.replace("__RD__", str(d.get("registry_digest") or "UNAVAILABLE")) \
|
| 1056 |
-
.replace("__RS__", str(d.get("registry_status") or "UNAVAILABLE")) \
|
| 1057 |
.replace("__SLSA__", d["slsa"])
|
| 1058 |
|
| 1059 |
|
|
@@ -1147,10 +1489,11 @@ def _selftest() -> dict:
|
|
| 1147 |
assert t["sovereign"] == tp["gpu_reachable"], t
|
| 1148 |
out["tiers_sovereign_honest"] = True
|
| 1149 |
|
| 1150 |
-
# (f) Verify-claims:
|
| 1151 |
vc = verify_claims_panel()
|
| 1152 |
-
|
| 1153 |
-
|
|
|
|
| 1154 |
|
| 1155 |
# (g) HTML renders, non-trivial, no forbidden raw claims.
|
| 1156 |
h = _html(pipe, tp, vc)
|
|
|
|
| 30 |
(cuML LedoitWolf + cuPy eigh + giotto-tda / Ripser++) is labeled ROADMAP. GPU
|
| 31 |
reachability and dependency imports are readiness only; MEASURED requires a distinct
|
| 32 |
accelerated path plus device/kernel/timing execution evidence.
|
| 33 |
+
* Every receipt is wrapped by szl_dsse.sign_payload (verified ECDSA when the cosign key
|
| 34 |
+
is present in the runtime; explicitly UNSIGNED otherwise — never a fabricated
|
| 35 |
+
signature). The label SAMPLE_SIGNAL | NOT_LIVE | NO_BACKTEST_VALIDATED is embedded
|
| 36 |
+
in the content-addressed payload and its signature state is reported separately.
|
| 37 |
* No fabricated metric. No live-trading claim. No backtest claim. cuML speedups are
|
| 38 |
cited to NVIDIA/STAC docs, never asserted as SZL-measured.
|
| 39 |
|
|
|
|
| 41 |
GET /api/{ns}/v1/quant/pca — Layer 1 PCA-Risk (LW + MP) on a SAMPLE universe
|
| 42 |
GET /api/{ns}/v1/quant/tda — Layer 2 TDA fracture score f_t, z_t, Betti β0/β1
|
| 43 |
GET /api/{ns}/v1/quant/kelly — Layer 3 HJB-Kelly weights w* with σ²_eff
|
| 44 |
+
GET /api/{ns}/v1/quant/pipeline — full 3-layer pass + ONE DSSE-bearing SAMPLE receipt
|
| 45 |
GET /api/{ns}/v1/quant/tiers — 2-GPU serve tier panel (TP=2 / role-split / NIM cloud)
|
| 46 |
+
GET /api/{ns}/v1/quant/verify-claims — NVIDIA datasheet vs SZL-MEASURED (honest, empty/ROADMAP)
|
| 47 |
GET /quant — unified mobile-first "Quant Engine" tab (0 CDN)
|
| 48 |
|
| 49 |
Pure stdlib. Defensive: a compute failure NEVER raises out of a handler.
|
| 50 |
"""
|
| 51 |
from __future__ import annotations
|
| 52 |
|
| 53 |
+
import base64 as _base64
|
| 54 |
import hashlib as _hashlib
|
|
|
|
| 55 |
import json as _json
|
| 56 |
import math as _math
|
| 57 |
import os as _os
|
| 58 |
+
from pathlib import Path as _Path
|
| 59 |
import random as _random
|
| 60 |
import time as _time
|
| 61 |
from datetime import datetime, timezone
|
| 62 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
# --- signed receipts: the SINGLE source of truth (never fabricate a signature) ----
|
| 64 |
try:
|
| 65 |
from szl_dsse import sign_payload as _sign_payload # REAL ECDSA when key present
|
| 66 |
+
from szl_dsse import verify_envelope as _verify_envelope
|
| 67 |
_SIGN_AVAILABLE = True
|
| 68 |
except Exception: # pragma: no cover — defensive; honest unsigned fallback below
|
| 69 |
_SIGN_AVAILABLE = False
|
|
|
|
| 82 |
"no signature fabricated."),
|
| 83 |
}
|
| 84 |
|
| 85 |
+
def _verify_envelope(_envelope): # type: ignore
|
| 86 |
+
return {"verified": False, "reason": "szl_dsse verifier is unavailable"}
|
| 87 |
+
|
| 88 |
_QUANT_PAYLOAD_TYPE = "application/vnd.szl.quant.receipt+json"
|
| 89 |
|
| 90 |
# --- optional acceleration probes (honest GPU-path labels) ------------------------
|
|
|
|
| 164 |
}
|
| 165 |
|
| 166 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
DOCTRINE = {
|
| 168 |
"version": "v11",
|
| 169 |
+
"locked_proven": ["F1", "F4", "F7", "F11", "F12", "F18", "F19", "F22"],
|
| 170 |
+
"locked_count": 8,
|
| 171 |
+
"corpus": "749/14/163",
|
| 172 |
+
"kernel_commit": "c7c0ba17",
|
| 173 |
"lambda": "Conjecture 1 (advisory floor; uniqueness machine-checked FALSE unconditionally; NOT a theorem)",
|
| 174 |
"slsa": "L1 honest / L2 attested (.att emitted, not independently verified) / L3 roadmap",
|
| 175 |
}
|
|
|
|
| 670 |
|
| 671 |
|
| 672 |
# =====================================================================================
|
| 673 |
+
# FULL PIPELINE -> ONE DSSE-bearing SAMPLE receipt.
|
| 674 |
# =====================================================================================
|
| 675 |
def run_pipeline(stress=False, gamma=0.5, kappa=1.0) -> dict:
|
| 676 |
+
"""Full 3-layer pass plus a DSSE envelope whose signature state is explicit."""
|
| 677 |
returns = _sample_returns(stress=stress)
|
| 678 |
l1 = layer1_pca_risk(returns=returns, stress=stress)
|
| 679 |
l2 = layer2_tda_fracture(returns=returns, stress=stress)
|
|
|
|
| 819 |
|
| 820 |
|
| 821 |
# =====================================================================================
|
| 822 |
+
# VERIFY-THE-CLAIMS panel: NVIDIA datasheet vs SZL-MEASURED (honest; empty/ROADMAP).
|
| 823 |
+
# =====================================================================================
|
| 824 |
+
def _legacy_verify_claims_panel() -> dict:
|
| 825 |
+
"""Side-by-side NVIDIA datasheet numbers vs SZL-MEASURED (signed). Honest: SZL columns
|
| 826 |
+
are empty/ROADMAP until we actually measure on OUR harness. NEVER print the datasheet
|
| 827 |
+
number as if it were ours."""
|
| 828 |
+
reachable = _gpu_reachable()
|
| 829 |
+
rows = [
|
| 830 |
+
{"claim": "Nemotron speedup vs prior frontier", "nvidia_datasheet": "up to 5×",
|
| 831 |
+
"szl_measured": None, "szl_label": "ROADMAP",
|
| 832 |
+
"how": "OUR τ-bench + J/token harness on the NIM-routed Ultra tier"},
|
| 833 |
+
{"claim": "Reasoning/accuracy uplift", "nvidia_datasheet": "+30%",
|
| 834 |
+
"szl_measured": None, "szl_label": "ROADMAP",
|
| 835 |
+
"how": "OUR τ-bench score (MEASURED-by-SZL), signed receipt"},
|
| 836 |
+
{"claim": "Benchmark accuracy", "nvidia_datasheet": "91%",
|
| 837 |
+
"szl_measured": None, "szl_label": "ROADMAP",
|
| 838 |
+
"how": "OUR eval set, ECE/Brier calibrated"},
|
| 839 |
+
{"claim": "Long-context retrieval", "nvidia_datasheet": "1M-token retrieval",
|
| 840 |
+
"szl_measured": None, "szl_label": "ROADMAP",
|
| 841 |
+
"how": "OUR needle-in-haystack probe, signed"},
|
| 842 |
+
{"claim": "cuML PCA speedup (quant Layer 1)", "nvidia_datasheet": "10–50× (S&P 500 scale); ~100× genomic",
|
| 843 |
+
"szl_measured": None, "szl_label": "ROADMAP",
|
| 844 |
+
"how": "OUR Layer-1 LedoitWolf on the sovereign GPU vs CPU fallback, signed J/bar"},
|
| 845 |
+
{"claim": "Ripser++ persistence (quant Layer 2)", "nvidia_datasheet": "up to 30× vs CPU Ripser",
|
| 846 |
+
"szl_measured": None, "szl_label": "ROADMAP",
|
| 847 |
+
"how": "OUR Layer-2 VR persistence on the sovereign GPU, signed bar latency"},
|
| 848 |
+
]
|
| 849 |
+
return {
|
| 850 |
+
"service": "verify-the-claims",
|
| 851 |
+
"doctrine": DOCTRINE["version"],
|
| 852 |
+
"summary": ("EMPTY / ROADMAP until SZL measures on its own harness — this is the differentiator: "
|
| 853 |
+
"we publish SZL-MEASURED (signed), never the datasheet number."),
|
| 854 |
+
"gpu_reachable": reachable,
|
| 855 |
+
"rows": rows,
|
| 856 |
+
"honesty": ("The 'NVIDIA datasheet' column is the vendor's published claim (cited, not endorsed). "
|
| 857 |
+
"The 'SZL-MEASURED' column stays null/ROADMAP until we run OUR τ-bench + J/token + "
|
| 858 |
+
"J/bar harness and SIGN the result. measured > datasheet, always. Never fabricated."),
|
| 859 |
+
"citations": [CITATIONS["rapids_cuml"], CITATIONS["ripserpp"]],
|
| 860 |
+
"computed_at": _now_iso(),
|
| 861 |
+
}
|
| 862 |
+
|
| 863 |
+
|
| 864 |
+
# =====================================================================================
|
| 865 |
+
# Receipt-gated local verification. The legacy static panel above is retained only as
|
| 866 |
+
# historical code; this definition is authoritative for routes and the UI.
|
| 867 |
# =====================================================================================
|
| 868 |
+
_QUANT_RECEIPT_SCHEMA = "szl.quant-live-benchmark-receipt.v1"
|
| 869 |
+
_QUANT_RECEIPT_SCOPE = "bounded local execution; not a replication of vendor-scale claims"
|
| 870 |
+
_QUANT_RECEIPT_PAYLOAD_TYPE = "application/vnd.szl.quant-live-benchmark+json"
|
| 871 |
+
|
| 872 |
+
|
| 873 |
+
def _dsse_signature_state(dsse):
|
| 874 |
+
"""Classify a DSSE envelope from cryptographic evidence, not its flag."""
|
| 875 |
+
if not isinstance(dsse, dict):
|
| 876 |
+
return "INVALID_SIGNATURE"
|
| 877 |
+
signatures = dsse.get("signatures")
|
| 878 |
+
if not isinstance(signatures, list):
|
| 879 |
+
return "INVALID_SIGNATURE"
|
| 880 |
+
if dsse.get("signed") is True:
|
| 881 |
+
verdict = _verify_envelope(dsse)
|
| 882 |
+
if isinstance(verdict, dict) and verdict.get("verified") is True:
|
| 883 |
+
return "SIGNED_VERIFIED"
|
| 884 |
+
return "INVALID_SIGNATURE"
|
| 885 |
+
if signatures:
|
| 886 |
+
return "INVALID_SIGNATURE"
|
| 887 |
+
return "UNSIGNED_CONTENT_ADDRESSED"
|
| 888 |
+
|
| 889 |
+
|
| 890 |
+
def _finite_number(value, field, minimum=None, maximum=None):
|
| 891 |
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or not _math.isfinite(float(value)):
|
| 892 |
+
raise ValueError("%s must be a finite number" % field)
|
| 893 |
+
number = float(value)
|
| 894 |
+
if minimum is not None and number < minimum:
|
| 895 |
+
raise ValueError("%s is below its allowed minimum" % field)
|
| 896 |
+
if maximum is not None and number > maximum:
|
| 897 |
+
raise ValueError("%s exceeds its allowed maximum" % field)
|
| 898 |
+
return number
|
| 899 |
+
|
| 900 |
+
|
| 901 |
+
def _bounded_int(value, field, minimum=0, maximum=1_000_000):
|
| 902 |
+
if isinstance(value, bool) or not isinstance(value, int) or not minimum <= value <= maximum:
|
| 903 |
+
raise ValueError("%s must be an integer between %s and %s" % (field, minimum, maximum))
|
| 904 |
+
return value
|
| 905 |
+
|
| 906 |
+
|
| 907 |
+
def _aware_timestamp(value, field):
|
| 908 |
+
if not isinstance(value, str) or not value.strip():
|
| 909 |
+
raise ValueError("%s missing" % field)
|
| 910 |
+
try:
|
| 911 |
+
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
| 912 |
+
except ValueError as exc:
|
| 913 |
+
raise ValueError("%s is not an ISO-8601 timestamp" % field) from exc
|
| 914 |
+
if parsed.tzinfo is None or parsed.utcoffset() is None:
|
| 915 |
+
raise ValueError("%s must include a timezone" % field)
|
| 916 |
+
return parsed.astimezone(timezone.utc)
|
| 917 |
+
|
| 918 |
+
|
| 919 |
+
def _validate_model_identity(identity, measurement, role):
|
| 920 |
+
if not isinstance(identity, dict):
|
| 921 |
+
raise ValueError("%s identity missing" % role)
|
| 922 |
+
if not isinstance(measurement, dict):
|
| 923 |
+
raise ValueError("%s measurement missing" % role)
|
| 924 |
+
requested = identity.get("requested_model")
|
| 925 |
+
if not isinstance(requested, str) or not requested.strip() or requested != measurement.get("model"):
|
| 926 |
+
raise ValueError("%s identity does not match measured model" % role)
|
| 927 |
+
manifest_hash = identity.get("show_response_sha256")
|
| 928 |
+
if not isinstance(manifest_hash, str) or len(manifest_hash) != 64:
|
| 929 |
+
raise ValueError("%s identity manifest hash missing" % role)
|
| 930 |
+
try:
|
| 931 |
+
int(manifest_hash, 16)
|
| 932 |
+
except ValueError as exc:
|
| 933 |
+
raise ValueError("%s identity manifest hash is not SHA-256" % role) from exc
|
| 934 |
+
lineage = identity.get("base_lineage")
|
| 935 |
+
if not isinstance(lineage, dict) or not any(
|
| 936 |
+
isinstance(lineage.get(key), str) and lineage.get(key).strip()
|
| 937 |
+
for key in ("base_ref", "parent_model", "base_digest")
|
| 938 |
+
):
|
| 939 |
+
raise ValueError("%s base lineage missing" % role)
|
| 940 |
+
wall_ms = identity.get("show_wall_ms")
|
| 941 |
+
if wall_ms is not None:
|
| 942 |
+
_finite_number(wall_ms, "%s identity show_wall_ms" % role, 0.0)
|
| 943 |
+
return manifest_hash.lower()
|
| 944 |
+
|
| 945 |
+
|
| 946 |
+
def _validate_model_measurement(measurement, role):
|
| 947 |
+
if not isinstance(measurement, dict):
|
| 948 |
+
raise ValueError("%s measurement missing" % role)
|
| 949 |
+
exact = measurement.get("exact_match")
|
| 950 |
+
retrieval = measurement.get("bounded_retrieval")
|
| 951 |
+
runtime = measurement.get("runtime")
|
| 952 |
+
if not isinstance(exact, dict) or not isinstance(retrieval, dict) or not isinstance(runtime, dict):
|
| 953 |
+
raise ValueError("%s semantic measurement sections missing" % role)
|
| 954 |
+
total = _bounded_int(exact.get("tasks_total"), "%s tasks_total" % role, 1, 10_000)
|
| 955 |
+
passed = _bounded_int(exact.get("tasks_passed"), "%s tasks_passed" % role, 0, total)
|
| 956 |
+
accuracy = _finite_number(exact.get("accuracy_pct"), "%s accuracy_pct" % role, 0.0, 100.0)
|
| 957 |
+
expected_accuracy = 100.0 * passed / total
|
| 958 |
+
if abs(accuracy - expected_accuracy) > 0.001:
|
| 959 |
+
raise ValueError("%s accuracy_pct is inconsistent with pass counts" % role)
|
| 960 |
+
probes_total = _bounded_int(retrieval.get("probes_total"), "%s probes_total" % role, 1, 10_000)
|
| 961 |
+
_bounded_int(retrieval.get("probes_passed"), "%s probes_passed" % role, 0, probes_total)
|
| 962 |
+
_bounded_int(
|
| 963 |
+
retrieval.get("max_prompt_eval_tokens"), "%s max_prompt_eval_tokens" % role, 0, 10_000_000
|
| 964 |
+
)
|
| 965 |
+
_bounded_int(runtime.get("requests"), "%s runtime requests" % role, 1, 100_000)
|
| 966 |
+
latency = _finite_number(runtime.get("p50_wall_ms"), "%s p50_wall_ms" % role, 0.000001)
|
| 967 |
+
tps = runtime.get("p50_tokens_per_second")
|
| 968 |
+
if tps is not None:
|
| 969 |
+
_finite_number(tps, "%s p50_tokens_per_second" % role, 0.000001)
|
| 970 |
+
return {"accuracy": accuracy, "latency": latency}
|
| 971 |
+
|
| 972 |
+
|
| 973 |
+
def _validate_cpu_reference(reference, field):
|
| 974 |
+
if not isinstance(reference, dict):
|
| 975 |
+
raise ValueError("%s missing" % field)
|
| 976 |
+
_bounded_int(reference.get("repeats"), "%s repeats" % field, 1, 20)
|
| 977 |
+
minimum = _finite_number(reference.get("min_ms"), "%s min_ms" % field, 0.0)
|
| 978 |
+
p50 = _finite_number(reference.get("p50_ms"), "%s p50_ms" % field, 0.0)
|
| 979 |
+
maximum = _finite_number(reference.get("max_ms"), "%s max_ms" % field, 0.0)
|
| 980 |
+
if minimum > p50 or p50 > maximum:
|
| 981 |
+
raise ValueError("%s latency order is inconsistent" % field)
|
| 982 |
+
if reference.get("compute_path") != "CPU_REFERENCE":
|
| 983 |
+
raise ValueError("%s is not an explicit CPU reference" % field)
|
| 984 |
+
return p50
|
| 985 |
+
|
| 986 |
+
|
| 987 |
+
def _validate_quant_receipt(envelope):
|
| 988 |
+
if not isinstance(envelope, dict):
|
| 989 |
+
raise ValueError("receipt envelope missing")
|
| 990 |
+
receipt = envelope.get("receipt")
|
| 991 |
+
if not isinstance(receipt, dict):
|
| 992 |
+
raise ValueError("receipt object missing")
|
| 993 |
+
if receipt.get("schema_version") != _QUANT_RECEIPT_SCHEMA:
|
| 994 |
+
raise ValueError("unsupported receipt schema")
|
| 995 |
+
if receipt.get("measurement_class") != "MEASURED":
|
| 996 |
+
raise ValueError("receipt is not a completed MEASURED execution")
|
| 997 |
+
if receipt.get("scope") != _QUANT_RECEIPT_SCOPE:
|
| 998 |
+
raise ValueError("receipt scope is not the bounded local harness")
|
| 999 |
+
|
| 1000 |
+
claimed_digest = receipt.get("content_sha256")
|
| 1001 |
+
unsigned_body = dict(receipt)
|
| 1002 |
+
unsigned_body.pop("content_sha256", None)
|
| 1003 |
+
observed_digest = _hashlib.sha256(
|
| 1004 |
+
_json.dumps(unsigned_body, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
| 1005 |
+
).hexdigest()
|
| 1006 |
+
if claimed_digest != observed_digest:
|
| 1007 |
+
raise ValueError("content digest mismatch")
|
| 1008 |
+
|
| 1009 |
+
started = _aware_timestamp(receipt.get("started_at"), "started_at")
|
| 1010 |
+
completed = _aware_timestamp(receipt.get("completed_at"), "completed_at")
|
| 1011 |
+
now = datetime.now(timezone.utc)
|
| 1012 |
+
if completed < started:
|
| 1013 |
+
raise ValueError("completed_at precedes started_at")
|
| 1014 |
+
if completed.timestamp() > now.timestamp() + 300:
|
| 1015 |
+
raise ValueError("completed_at is implausibly in the future")
|
| 1016 |
+
|
| 1017 |
+
ollama = receipt.get("ollama")
|
| 1018 |
+
if not isinstance(ollama, dict) or ollama.get("base_url_class") != "loopback-local":
|
| 1019 |
+
raise ValueError("receipt is not bound to a loopback-local Ollama endpoint")
|
| 1020 |
+
candidate = ollama.get("candidate")
|
| 1021 |
+
baseline = ollama.get("baseline")
|
| 1022 |
+
c_identity = _validate_model_identity(ollama.get("candidate_identity"), candidate, "candidate")
|
| 1023 |
+
b_identity = _validate_model_identity(ollama.get("baseline_identity"), baseline, "baseline")
|
| 1024 |
+
if c_identity == b_identity:
|
| 1025 |
+
raise ValueError("candidate and baseline resolve to the same manifest")
|
| 1026 |
+
stability = ollama.get("identity_stability")
|
| 1027 |
+
if not isinstance(stability, dict) or stability.get("stable") is not True:
|
| 1028 |
+
raise ValueError("model identity stability is not proven")
|
| 1029 |
+
if not (
|
| 1030 |
+
stability.get("candidate_before_sha256") == c_identity
|
| 1031 |
+
and stability.get("candidate_after_sha256") == c_identity
|
| 1032 |
+
and stability.get("baseline_before_sha256") == b_identity
|
| 1033 |
+
and stability.get("baseline_after_sha256") == b_identity
|
| 1034 |
+
):
|
| 1035 |
+
raise ValueError("model identity drift detected in receipt")
|
| 1036 |
+
|
| 1037 |
+
candidate_metrics = _validate_model_measurement(candidate, "candidate")
|
| 1038 |
+
baseline_metrics = _validate_model_measurement(baseline, "baseline")
|
| 1039 |
+
comparisons = receipt.get("comparisons")
|
| 1040 |
+
if not isinstance(comparisons, dict):
|
| 1041 |
+
raise ValueError("comparison metrics missing")
|
| 1042 |
+
speed = _finite_number(
|
| 1043 |
+
comparisons.get("candidate_vs_baseline_wall_speed_ratio"), "wall speed ratio", 0.000001
|
| 1044 |
+
)
|
| 1045 |
+
expected_speed = baseline_metrics["latency"] / candidate_metrics["latency"]
|
| 1046 |
+
if abs(speed - expected_speed) > 0.0001:
|
| 1047 |
+
raise ValueError("wall speed ratio is inconsistent with measured latency")
|
| 1048 |
+
uplift = _finite_number(
|
| 1049 |
+
comparisons.get("candidate_minus_baseline_exact_match_points"), "accuracy uplift", -100.0, 100.0
|
| 1050 |
+
)
|
| 1051 |
+
expected_uplift = candidate_metrics["accuracy"] - baseline_metrics["accuracy"]
|
| 1052 |
+
if abs(uplift - expected_uplift) > 0.001:
|
| 1053 |
+
raise ValueError("accuracy uplift is inconsistent with measured accuracy")
|
| 1054 |
+
|
| 1055 |
+
quant_reference = receipt.get("quant_reference")
|
| 1056 |
+
if not isinstance(quant_reference, dict):
|
| 1057 |
+
raise ValueError("quant reference section missing")
|
| 1058 |
+
_validate_cpu_reference(quant_reference.get("pca_pipeline"), "pca_pipeline")
|
| 1059 |
+
_validate_cpu_reference(quant_reference.get("tda_stress_pipeline"), "tda_stress_pipeline")
|
| 1060 |
+
gpu_comparison = quant_reference.get("gpu_acceleration_comparison")
|
| 1061 |
+
if not isinstance(gpu_comparison, str) or not gpu_comparison.startswith("UNAVAILABLE:"):
|
| 1062 |
+
raise ValueError("GPU acceleration status is not an explicit structured refusal")
|
| 1063 |
+
|
| 1064 |
+
dsse = envelope.get("dsse")
|
| 1065 |
+
if not isinstance(dsse, dict):
|
| 1066 |
+
raise ValueError("DSSE status missing")
|
| 1067 |
+
signatures = dsse.get("signatures")
|
| 1068 |
+
if not isinstance(signatures, list):
|
| 1069 |
+
raise ValueError("DSSE signatures must be a list")
|
| 1070 |
+
embedded = dsse.get("payload")
|
| 1071 |
+
if embedded is not None:
|
| 1072 |
+
if dsse.get("payloadType") != _QUANT_RECEIPT_PAYLOAD_TYPE:
|
| 1073 |
+
raise ValueError("DSSE payload type mismatch")
|
| 1074 |
+
try:
|
| 1075 |
+
decoded = _base64.b64decode(embedded, validate=True)
|
| 1076 |
+
except Exception as exc:
|
| 1077 |
+
raise ValueError("DSSE payload is not valid base64") from exc
|
| 1078 |
+
expected = _json.dumps(receipt, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
| 1079 |
+
if decoded != expected:
|
| 1080 |
+
raise ValueError("DSSE payload does not match receipt")
|
| 1081 |
+
if dsse.get("signed") is True:
|
| 1082 |
+
if not signatures or embedded is None:
|
| 1083 |
+
raise ValueError("DSSE claims signed without signatures and payload")
|
| 1084 |
+
verdict = _verify_envelope(dsse)
|
| 1085 |
+
if not isinstance(verdict, dict) or verdict.get("verified") is not True:
|
| 1086 |
+
reason = verdict.get("reason") if isinstance(verdict, dict) else None
|
| 1087 |
+
suffix = ": " + str(reason) if reason else ""
|
| 1088 |
+
raise ValueError("DSSE signature verification failed" + suffix)
|
| 1089 |
+
signature_state = "SIGNED_VERIFIED"
|
| 1090 |
+
elif signatures:
|
| 1091 |
+
raise ValueError("unsigned DSSE contains signatures")
|
| 1092 |
+
else:
|
| 1093 |
+
signature_state = "UNSIGNED_CONTENT_ADDRESSED"
|
| 1094 |
+
|
| 1095 |
+
raw_fresh_seconds = _os.environ.get("SZL_QUANT_BENCH_FRESH_SECONDS", "604800")
|
| 1096 |
+
try:
|
| 1097 |
+
fresh_seconds = int(raw_fresh_seconds)
|
| 1098 |
+
except ValueError as exc:
|
| 1099 |
+
raise ValueError("SZL_QUANT_BENCH_FRESH_SECONDS must be an integer") from exc
|
| 1100 |
+
if not 60 <= fresh_seconds <= 2_678_400:
|
| 1101 |
+
raise ValueError("SZL_QUANT_BENCH_FRESH_SECONDS is outside the allowed range")
|
| 1102 |
+
age_seconds = max(0, int((now - completed).total_seconds()))
|
| 1103 |
+
return {
|
| 1104 |
+
"envelope": envelope,
|
| 1105 |
+
"age_seconds": age_seconds,
|
| 1106 |
+
"freshness_state": "CURRENT" if age_seconds <= fresh_seconds else "HISTORICAL",
|
| 1107 |
+
"candidate_manifest_sha256": c_identity,
|
| 1108 |
+
"baseline_manifest_sha256": b_identity,
|
| 1109 |
+
"signature_state": signature_state,
|
| 1110 |
+
}
|
| 1111 |
+
|
| 1112 |
+
|
| 1113 |
def verify_claims_panel() -> dict:
|
| 1114 |
+
"""Read a bounded local benchmark receipt without producing side effects.
|
| 1115 |
|
| 1116 |
+
Missing, semantically inconsistent, stale-looking, or tampered data never
|
| 1117 |
+
becomes a live claim. Valid old receipts remain visible as HISTORICAL.
|
| 1118 |
"""
|
| 1119 |
+
configured_path = _os.environ.get("SZL_QUANT_BENCH_RECEIPT", "").strip()
|
| 1120 |
+
receipt_candidates = ([_Path(configured_path)] if configured_path else [
|
| 1121 |
+
_Path.home() / ".a11oy" / "receipts" / "quant-live-benchmark.json",
|
| 1122 |
+
_Path(__file__).resolve().parent / "benchmarks" / "quant_live" / "receipts" / "latest.json",
|
| 1123 |
+
])
|
| 1124 |
+
receipt_path = next((path for path in receipt_candidates if path.is_file()), receipt_candidates[0])
|
| 1125 |
+
measured = None
|
| 1126 |
+
validation = None
|
| 1127 |
+
receipt_error = None
|
| 1128 |
+
try:
|
| 1129 |
+
if receipt_path.is_file() and receipt_path.stat().st_size <= 2_000_000:
|
| 1130 |
+
envelope = _json.loads(receipt_path.read_text(encoding="utf-8"))
|
| 1131 |
+
validation = _validate_quant_receipt(envelope)
|
| 1132 |
+
measured = validation["envelope"]
|
| 1133 |
+
else:
|
| 1134 |
+
receipt_error = "measurement receipt absent"
|
| 1135 |
+
except (OSError, ValueError, TypeError, _json.JSONDecodeError) as exc:
|
| 1136 |
+
receipt_error = "%s: %s" % (type(exc).__name__, exc)
|
| 1137 |
+
|
| 1138 |
+
local = measured.get("receipt") if measured else {}
|
| 1139 |
+
ollama = local.get("ollama", {})
|
| 1140 |
+
candidate = ollama.get("candidate", {})
|
| 1141 |
+
baseline = ollama.get("baseline", {})
|
| 1142 |
+
comparisons = local.get("comparisons", {})
|
| 1143 |
+
quant_reference = local.get("quant_reference", {})
|
| 1144 |
+
freshness = (validation or {}).get("freshness_state", "NO_RECEIPT")
|
| 1145 |
+
signature_state = (validation or {}).get("signature_state", "NO_RECEIPT")
|
| 1146 |
+
signed = signature_state == "SIGNED_VERIFIED"
|
| 1147 |
+
|
| 1148 |
+
def cell(value, how):
|
| 1149 |
+
if measured is None:
|
| 1150 |
+
return {"szl_measured": None, "szl_label": "NOT_MEASURED", "how": how,
|
| 1151 |
+
"comparison_status": "NO_RECEIPT", "freshness_label": freshness}
|
| 1152 |
+
return {"szl_measured": value, "szl_label": "MEASURED", "how": how,
|
| 1153 |
+
"comparison_status": "BOUNDED_LOCAL_NOT_VENDOR_REPLICATION",
|
| 1154 |
+
"freshness_label": freshness}
|
| 1155 |
+
|
| 1156 |
+
def no_gpu_claim(local_reference, how):
|
| 1157 |
+
return {
|
| 1158 |
+
"szl_measured": None,
|
| 1159 |
+
"szl_label": "NOT_MEASURED",
|
| 1160 |
+
"local_reference": local_reference if measured else None,
|
| 1161 |
+
"local_reference_label": "MEASURED" if measured else "NOT_MEASURED",
|
| 1162 |
+
"how": how,
|
| 1163 |
+
"comparison_status": "NO_GPU_COMPARISON_RECEIPT" if measured else "NO_RECEIPT",
|
| 1164 |
+
"freshness_label": freshness,
|
| 1165 |
+
}
|
| 1166 |
+
|
| 1167 |
+
def vendor_row(claim, reported, values):
|
| 1168 |
+
return {"claim": claim, "nvidia_datasheet": reported, "nvidia_label": "REPORTED", **values}
|
| 1169 |
+
|
| 1170 |
+
c_acc = candidate.get("exact_match", {})
|
| 1171 |
+
c_ret = candidate.get("bounded_retrieval", {})
|
| 1172 |
+
speed = comparisons.get("candidate_vs_baseline_wall_speed_ratio")
|
| 1173 |
+
uplift = comparisons.get("candidate_minus_baseline_exact_match_points")
|
| 1174 |
+
pca = quant_reference.get("pca_pipeline", {})
|
| 1175 |
+
tda = quant_reference.get("tda_stress_pipeline", {})
|
| 1176 |
+
rows = [
|
| 1177 |
+
vendor_row("Nemotron speedup vs prior frontier", "up to 5x", no_gpu_claim(
|
| 1178 |
+
("%sx local Ollama wall-speed ratio vs %s" % (speed, baseline.get("model"))) if speed is not None else None,
|
| 1179 |
+
"Local Ollama p50 wall latency is separate evidence; no vendor-frontier or GPU comparison receipt exists.")),
|
| 1180 |
+
vendor_row("Reasoning/accuracy uplift", "+30%", cell(
|
| 1181 |
+
("%s percentage points vs local baseline" % uplift) if uplift is not None else None,
|
| 1182 |
+
"Six preregistered deterministic exact-match operational probes; not a general reasoning benchmark.")),
|
| 1183 |
+
vendor_row("Benchmark accuracy", "91%", cell(
|
| 1184 |
+
("%s%% (%s/%s exact match)" % (c_acc.get("accuracy_pct"), c_acc.get("tasks_passed"), c_acc.get("tasks_total"))) if c_acc else None,
|
| 1185 |
+
"Bounded SZL exact-match operational suite; not NVIDIA's benchmark.")),
|
| 1186 |
+
vendor_row("Long-context retrieval", "1M-token retrieval", cell(
|
| 1187 |
+
("%s/%s needles; max %s evaluated prompt tokens" % (c_ret.get("probes_passed"), c_ret.get("probes_total"), c_ret.get("max_prompt_eval_tokens"))) if c_ret else None,
|
| 1188 |
+
"Bounded local needle probes; no one-million-token claim.")),
|
| 1189 |
+
vendor_row("cuML PCA speedup (quant Layer 1)", "10-50x (S&P 500 scale); about 100x genomic", no_gpu_claim(
|
| 1190 |
+
("CPU reference p50 %s ms; GPU comparison UNAVAILABLE" % pca.get("p50_ms")) if pca else None,
|
| 1191 |
+
"Measured CPU reference only; no distinct cuML execution receipt exists.")),
|
| 1192 |
+
vendor_row("Ripser++ persistence (quant Layer 2)", "up to 30x vs CPU Ripser", no_gpu_claim(
|
| 1193 |
+
("CPU stress reference p50 %s ms; GPU comparison UNAVAILABLE" % tda.get("p50_ms")) if tda else None,
|
| 1194 |
+
"Measured CPU reference only; no distinct Ripser++ execution receipt exists.")),
|
| 1195 |
+
]
|
| 1196 |
+
for row in rows:
|
| 1197 |
+
row.setdefault("local_reference", None)
|
| 1198 |
+
row.setdefault("local_reference_label", "NOT_MEASURED")
|
| 1199 |
return {
|
| 1200 |
"service": "verify-the-claims",
|
| 1201 |
"doctrine": DOCTRINE["version"],
|
| 1202 |
+
"summary": (("Current" if freshness == "CURRENT" else "Historical")
|
| 1203 |
+
+ " bounded %s receipt loaded; vendor-scale and GPU comparisons remain out of scope."
|
| 1204 |
+
% ("cryptographically verified DSSE" if signed else "unsigned content-addressed")
|
| 1205 |
+
if measured else "No valid local measurement receipt is available; no number is invented."),
|
| 1206 |
+
"gpu_reachable": _gpu_reachable(),
|
| 1207 |
"rows": rows,
|
| 1208 |
+
"receipt": {"path_class": "operator-local", "loaded": bool(measured), "error": receipt_error,
|
| 1209 |
+
"content_sha256": local.get("content_sha256"), "completed_at": local.get("completed_at"),
|
| 1210 |
+
"dsse_signed": signed,
|
| 1211 |
+
"signature_state": signature_state,
|
| 1212 |
+
"freshness_state": freshness, "age_seconds": (validation or {}).get("age_seconds"),
|
| 1213 |
+
"candidate_manifest_sha256": (validation or {}).get("candidate_manifest_sha256"),
|
| 1214 |
+
"baseline_manifest_sha256": (validation or {}).get("baseline_manifest_sha256")},
|
| 1215 |
+
"honesty": ("The NVIDIA column is a cited vendor claim, not an endorsement. The SZL column comes from a "
|
| 1216 |
+
"bounded local execution receipt and is not presented as a vendor-scale replication. Signature "
|
| 1217 |
+
"state is derived from cryptographic verification; unsigned content-addressed evidence is never "
|
| 1218 |
+
"displayed as signed."),
|
| 1219 |
"citations": [CITATIONS["rapids_cuml"], CITATIONS["ripserpp"]],
|
| 1220 |
"computed_at": _now_iso(),
|
| 1221 |
}
|
|
|
|
| 1256 |
+ row("de-risk ratio", fmt(l3["derisk_ratio_vs_uninflated"]))
|
| 1257 |
+ row("γ, κ", "%s, %s <small>(uncalibrated)</small>" % (l3["gamma"], l3["kappa"])))
|
| 1258 |
dsse = pipe["signed_receipt"]["dsse"]
|
| 1259 |
+
pipeline_signature_state = _dsse_signature_state(dsse)
|
| 1260 |
+
pipeline_signed = pipeline_signature_state == "SIGNED_VERIFIED"
|
| 1261 |
+
pipeline_receipt_title = (
|
| 1262 |
+
"Verified Signed SAMPLE Receipt" if pipeline_signed else
|
| 1263 |
+
"Unsigned SAMPLE Receipt" if pipeline_signature_state == "UNSIGNED_CONTENT_ADDRESSED" else
|
| 1264 |
+
"Invalid DSSE SAMPLE Receipt"
|
| 1265 |
+
)
|
| 1266 |
+
pipeline_receipt_note = (
|
| 1267 |
+
"DSSE signature verified against the configured SZL public key."
|
| 1268 |
+
if pipeline_signed else
|
| 1269 |
+
"Content-addressed DSSE envelope; no verified signature is present."
|
| 1270 |
+
if pipeline_signature_state == "UNSIGNED_CONTENT_ADDRESSED" else
|
| 1271 |
+
"DSSE signature is invalid or unverifiable; this receipt is not presented as signed."
|
| 1272 |
+
)
|
| 1273 |
rc_body = (row("data source", "SAMPLE_SYNTHETIC")
|
| 1274 |
+ row("pipeline", "<code>szl-gpu-quant-v0.1</code>")
|
| 1275 |
+
+ row("signature state", pipeline_signature_state)
|
| 1276 |
+ row("PAE sha256", "<code>%s…</code>" % str(dsse.get("_pae_sha256", ""))[:16])
|
| 1277 |
+ row("label", "<small>%s</small>" % SAMPLE_LABEL))
|
| 1278 |
|
|
|
|
| 1288 |
+ gpus)
|
| 1289 |
tier_cards += card(t["tier"], t["label"], body, t.get("fits", ""))
|
| 1290 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1291 |
vrows = ""
|
| 1292 |
for r in verify["rows"]:
|
| 1293 |
+
vrows += ('<tr><td>%s</td><td class="ds"><span class="pill-slot" data-label="%s"></span> %s</td>'
|
| 1294 |
+
'<td class="ms"><span class="pill-slot" data-label="%s"></span> %s<br><small>%s</small></td>'
|
| 1295 |
+
'<td class="ms"><span class="pill-slot" data-label="%s"></span> %s</td></tr>' % (
|
| 1296 |
+
r["claim"], r["nvidia_label"], r["nvidia_datasheet"],
|
| 1297 |
+
r["szl_label"], fmt(r["szl_measured"]), r.get("freshness_label", "NO_RECEIPT"),
|
| 1298 |
+
r["local_reference_label"], fmt(r["local_reference"])))
|
| 1299 |
+
verify_tbl = ('<table class="vt"><thead><tr><th>Claim</th><th>NVIDIA published</th>'
|
| 1300 |
+
'<th>SZL comparison</th><th>Separate local evidence</th></tr></thead>'
|
| 1301 |
+
'<tbody>%s</tbody></table>' % vrows)
|
| 1302 |
+
receipt_view = verify.get("receipt", {})
|
| 1303 |
+
receipt_line = ("loaded=%s · completed_at=%s · signature=%s · content_sha256=%s" % (
|
| 1304 |
+
receipt_view.get("loaded"), receipt_view.get("completed_at") or "—",
|
| 1305 |
+
receipt_view.get("signature_state") or "UNKNOWN",
|
| 1306 |
+
(str(receipt_view.get("content_sha256") or "—")[:20] + "…")
|
| 1307 |
+
if receipt_view.get("content_sha256") else "—"))
|
| 1308 |
|
| 1309 |
cards = "".join([
|
| 1310 |
card("Layer 1 · PCA Risk (LW + MP)", l1["label"].split(" | ")[0].replace("_SIGNAL", ""), l1_body, l1["honest_note"]),
|
| 1311 |
card("Layer 2 · TDA Fracture (β0/β1)", "SAMPLE", l2_body, l2["honest_note"]),
|
| 1312 |
card("Layer 3 · HJB-Kelly Sizing", "MODELED", l3_body, l3["honest_note"]),
|
| 1313 |
+
card(pipeline_receipt_title, "SAMPLE", rc_body, pipeline_receipt_note),
|
|
|
|
|
|
|
| 1314 |
])
|
| 1315 |
|
| 1316 |
return """<!doctype html>
|
|
|
|
| 1346 |
<header>
|
| 1347 |
<h1>Sovereign Quant Engine</h1>
|
| 1348 |
<p class="summary">__SUMMARY__</p>
|
| 1349 |
+
<p class="sub">Three orthogonal risk signals per bar — PCA-Risk · TDA-Fracture · HJB-Kelly — with receipt state <b>__PIPE_SIG__</b>, honestly labeled <b>SAMPLE_SIGNAL · NOT_LIVE · NO_BACKTEST_VALIDATED</b>. Not a trading instruction.</p>
|
| 1350 |
<p class="state">backend=__BACKEND__ · gpu_reachable=__REACH__ · scenario=__SCEN__</p>
|
| 1351 |
</header>
|
| 1352 |
+
<h2>3-Layer Pipeline (DSSE receipt: __PIPE_SIG__)</h2>
|
| 1353 |
<section class="grid">__CARDS__</section>
|
| 1354 |
<h2>2-GPU Sovereign Serve · Throttle Both</h2>
|
| 1355 |
<section class="grid">__TIERS__</section>
|
| 1356 |
+
<h2>Verify the Claims — vendor statement vs bounded local receipt</h2>
|
| 1357 |
+
<section>__VERIFY__<p class="state">__VRECEIPT__</p><p class="note">__VNOTE__</p></section>
|
| 1358 |
<footer>
|
| 1359 |
+
<p class="lock">Doctrine __DV__ LOCKED · locked-proven=__LC__ {__LP__} · __CORPUS__ @ __KC__ · Λ = Conjecture 1 (NOT a theorem) · __SLSA__</p>
|
| 1360 |
+
<p>SAMPLE = honest synthetic fixture (not live) · MODELED = labeled model output (uncalibrated) · ROADMAP = wiring ready, not measured yet (never faked). Cites: Brodetsky (LinkedIn) · Ledoit-Wolf (honey.pdf) · Laloux/Bouchaud/Potters · Gidea-Katz arXiv:1703.04385 · RAPIDS/cuML · giotto-tda · Ripser++ arXiv:2003.07989.</p>
|
| 1361 |
</footer>
|
| 1362 |
<script src="/static/shared/szl_label_engine.js"></script>
|
| 1363 |
<script>
|
|
|
|
| 1370 |
title: (label === "SAMPLE") ? "Honest synthetic fixture — not a live feed, no backtest." :
|
| 1371 |
(label === "MODELED") ? "Labeled model output — uncalibrated, not measured." :
|
| 1372 |
(label === "LIVE") ? "Real backend wired and live." :
|
| 1373 |
+
(label === "NOT_MEASURED") ? "No valid execution receipt is loaded; no value is invented." :
|
| 1374 |
+
"Capability state reported by the live surface."});
|
| 1375 |
}
|
| 1376 |
return '<span>' + label + '</span>';
|
| 1377 |
}
|
|
|
|
| 1381 |
})();
|
| 1382 |
</script>
|
| 1383 |
</body></html>""" \
|
| 1384 |
+
.replace("__SUMMARY__", "Operational bounded quant pipeline; CPU reference measured, GPU comparison requires a kernel receipt") \
|
| 1385 |
.replace("__BACKEND__", str(backend["backend"])) \
|
| 1386 |
.replace("__REACH__", str(backend["gpu_reachable"])) \
|
| 1387 |
.replace("__SCEN__", str(pipe["scenario"])) \
|
| 1388 |
+
.replace("__PIPE_SIG__", pipeline_signature_state) \
|
| 1389 |
.replace("__CARDS__", cards) \
|
| 1390 |
.replace("__TIERS__", tier_cards) \
|
| 1391 |
.replace("__VERIFY__", verify_tbl) \
|
| 1392 |
+
.replace("__VRECEIPT__", receipt_line) \
|
| 1393 |
.replace("__VNOTE__", verify["honesty"]) \
|
| 1394 |
.replace("__DV__", d["version"]) \
|
| 1395 |
.replace("__LC__", str(d["locked_count"])) \
|
| 1396 |
.replace("__LP__", ", ".join(d["locked_proven"])) \
|
| 1397 |
.replace("__CORPUS__", d["corpus"]) \
|
| 1398 |
.replace("__KC__", d["kernel_commit"]) \
|
|
|
|
|
|
|
| 1399 |
.replace("__SLSA__", d["slsa"])
|
| 1400 |
|
| 1401 |
|
|
|
|
| 1489 |
assert t["sovereign"] == tp["gpu_reachable"], t
|
| 1490 |
out["tiers_sovereign_honest"] = True
|
| 1491 |
|
| 1492 |
+
# (f) Verify-claims: without a receipt no measured number is invented.
|
| 1493 |
vc = verify_claims_panel()
|
| 1494 |
+
if not vc["receipt"]["loaded"]:
|
| 1495 |
+
assert all(r["szl_measured"] is None and r["szl_label"] == "NOT_MEASURED" for r in vc["rows"]), vc
|
| 1496 |
+
out["verify_claims_receipt_gate"] = True
|
| 1497 |
|
| 1498 |
# (g) HTML renders, non-trivial, no forbidden raw claims.
|
| 1499 |
h = _html(pipe, tp, vc)
|
szl_involution_probe.py
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
# Copyright 2026 Stephen P. Lutar Jr. / SZL Holdings
|
| 4 |
+
"""Pure, bounded decomposition of paired observations under an involution.
|
| 5 |
+
|
| 6 |
+
Taxonomy home: provenance / EvidenceOS analysis.
|
| 7 |
+
|
| 8 |
+
This module is a clean-room systems adaptation of a general symmetry idea used in
|
| 9 |
+
the cited transport study. It copies no article prose, figure, or implementation.
|
| 10 |
+
The caller declares a permutation ``P`` and supplies a left observation ``x`` and
|
| 11 |
+
an observation ``y`` collected on the transformed surface. With the convention
|
| 12 |
+
``(P v)[i] = v[P[i]]`` and a required involution ``P(P(i)) = i``, the probe aligns
|
| 13 |
+
the transformed observation and computes::
|
| 14 |
+
|
| 15 |
+
y_aligned = P^-1 y
|
| 16 |
+
S = (x + y_aligned) / 2
|
| 17 |
+
A = (x - y_aligned) / 2
|
| 18 |
+
|
| 19 |
+
The algebraic reconstruction identities are labelled PROVEN. A concrete result
|
| 20 |
+
is MODELED because it is derived from caller-supplied observations, not measured
|
| 21 |
+
by this module. The motivating experimental findings remain REPORTED.
|
| 22 |
+
|
| 23 |
+
Primary-source citations:
|
| 24 |
+
* https://doi.org/10.1038/s41467-026-75369-y
|
| 25 |
+
* https://doi.org/10.5281/zenodo.17050703
|
| 26 |
+
|
| 27 |
+
The probe is deliberately pure: it performs no file or network I/O, emits no
|
| 28 |
+
signature, writes no receipt, and invokes no effector.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
import hashlib
|
| 32 |
+
import json
|
| 33 |
+
import math
|
| 34 |
+
import numbers
|
| 35 |
+
from collections.abc import Sequence
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
SCHEMA = "szl.evidenceos.involution-probe.v1"
|
| 39 |
+
MAX_DIMENSION = 4096
|
| 40 |
+
MAX_ABS_VALUE = 1.0e12
|
| 41 |
+
MAX_PAIR_ID_BYTES = 256
|
| 42 |
+
|
| 43 |
+
LABEL_PROVEN = "PROVEN"
|
| 44 |
+
LABEL_MODELED = "MODELED"
|
| 45 |
+
LABEL_REPORTED = "REPORTED"
|
| 46 |
+
|
| 47 |
+
VERDICT_DECOMPOSED = "DECOMPOSED"
|
| 48 |
+
VERDICT_REFUSED = "REFUSED"
|
| 49 |
+
|
| 50 |
+
ARTICLE_DOI = "10.1038/s41467-026-75369-y"
|
| 51 |
+
DATA_CODE_DOI = "10.5281/zenodo.17050703"
|
| 52 |
+
|
| 53 |
+
_CITATIONS = (
|
| 54 |
+
{
|
| 55 |
+
"kind": "article",
|
| 56 |
+
"doi": ARTICLE_DOI,
|
| 57 |
+
"url": "https://doi.org/" + ARTICLE_DOI,
|
| 58 |
+
"evidence_label": LABEL_REPORTED,
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
"kind": "data-and-code",
|
| 62 |
+
"doi": DATA_CODE_DOI,
|
| 63 |
+
"url": "https://doi.org/" + DATA_CODE_DOI,
|
| 64 |
+
"evidence_label": LABEL_REPORTED,
|
| 65 |
+
},
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class _Refusal(ValueError):
|
| 70 |
+
"""Internal, bounded validation refusal converted to a public result."""
|
| 71 |
+
|
| 72 |
+
def __init__(self, code: str, reason: str):
|
| 73 |
+
super().__init__(reason)
|
| 74 |
+
self.code = code
|
| 75 |
+
self.reason = reason
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _canonical_for_digest(value):
|
| 79 |
+
"""Return a JSON-safe projection with platform-stable finite-float encoding."""
|
| 80 |
+
if isinstance(value, float):
|
| 81 |
+
# Validation guarantees finiteness. Normalizing negative zero prevents two
|
| 82 |
+
# numerically identical decompositions from receiving different digests.
|
| 83 |
+
normalized = 0.0 if value == 0.0 else value
|
| 84 |
+
return {"float_hex": normalized.hex()}
|
| 85 |
+
if isinstance(value, dict):
|
| 86 |
+
return {str(key): _canonical_for_digest(item)
|
| 87 |
+
for key, item in sorted(value.items(), key=lambda pair: str(pair[0]))}
|
| 88 |
+
if isinstance(value, (list, tuple)):
|
| 89 |
+
return [_canonical_for_digest(item) for item in value]
|
| 90 |
+
return value
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _stable_digest(payload: dict) -> str:
|
| 94 |
+
canonical = json.dumps(
|
| 95 |
+
_canonical_for_digest(payload),
|
| 96 |
+
sort_keys=True,
|
| 97 |
+
separators=(",", ":"),
|
| 98 |
+
ensure_ascii=False,
|
| 99 |
+
allow_nan=False,
|
| 100 |
+
)
|
| 101 |
+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _utf8_size(value: str) -> int:
|
| 105 |
+
try:
|
| 106 |
+
return len(value.encode("utf-8"))
|
| 107 |
+
except UnicodeEncodeError as exc:
|
| 108 |
+
raise _Refusal("PAIR_ID_INVALID", "pair_id must be valid UTF-8 text") from exc
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _validate_pair_id(pair_id) -> str:
|
| 112 |
+
if not isinstance(pair_id, str) or not pair_id.strip():
|
| 113 |
+
raise _Refusal("PAIR_ID_REQUIRED", "pair_id must be a non-blank string")
|
| 114 |
+
if _utf8_size(pair_id) > MAX_PAIR_ID_BYTES:
|
| 115 |
+
raise _Refusal("PAIR_ID_TOO_LARGE", "pair_id exceeds the byte bound")
|
| 116 |
+
return pair_id
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _as_bounded_vector(name: str, value) -> tuple[float, ...]:
|
| 120 |
+
if value is None:
|
| 121 |
+
raise _Refusal("PAIR_MISSING", f"{name} is required")
|
| 122 |
+
if isinstance(value, (str, bytes, bytearray)) or not isinstance(value, Sequence):
|
| 123 |
+
raise _Refusal("VECTOR_INVALID", f"{name} must be a finite numeric sequence")
|
| 124 |
+
size = len(value)
|
| 125 |
+
if size < 1 or size > MAX_DIMENSION:
|
| 126 |
+
raise _Refusal("DIMENSION_OUT_OF_BOUNDS", f"{name} dimension is outside bounds")
|
| 127 |
+
|
| 128 |
+
out: list[float] = []
|
| 129 |
+
for item in value:
|
| 130 |
+
if isinstance(item, bool) or not isinstance(item, numbers.Real):
|
| 131 |
+
raise _Refusal("VECTOR_INVALID", f"{name} contains a non-real value")
|
| 132 |
+
number = float(item)
|
| 133 |
+
if not math.isfinite(number):
|
| 134 |
+
raise _Refusal("VECTOR_NONFINITE", f"{name} contains a non-finite value")
|
| 135 |
+
if abs(number) > MAX_ABS_VALUE:
|
| 136 |
+
raise _Refusal("VALUE_OUT_OF_BOUNDS", f"{name} exceeds the magnitude bound")
|
| 137 |
+
out.append(0.0 if number == 0.0 else number)
|
| 138 |
+
return tuple(out)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def _as_involution(permutation, dimension: int) -> tuple[int, ...]:
|
| 142 |
+
if permutation is None:
|
| 143 |
+
raise _Refusal("PERMUTATION_REQUIRED", "a declared permutation is required")
|
| 144 |
+
if (isinstance(permutation, (str, bytes, bytearray))
|
| 145 |
+
or not isinstance(permutation, Sequence)):
|
| 146 |
+
raise _Refusal("PERMUTATION_INVALID", "permutation must be an integer sequence")
|
| 147 |
+
if len(permutation) != dimension:
|
| 148 |
+
raise _Refusal("DIMENSION_MISMATCH", "permutation and vectors must share a dimension")
|
| 149 |
+
if any(isinstance(index, bool) or not isinstance(index, int)
|
| 150 |
+
for index in permutation):
|
| 151 |
+
raise _Refusal("PERMUTATION_INVALID", "permutation indices must be integers")
|
| 152 |
+
|
| 153 |
+
result = tuple(permutation)
|
| 154 |
+
if any(index < 0 or index >= dimension for index in result):
|
| 155 |
+
raise _Refusal("PERMUTATION_OUT_OF_RANGE", "permutation index is outside the vector")
|
| 156 |
+
if len(set(result)) != dimension:
|
| 157 |
+
raise _Refusal("PERMUTATION_NOT_BIJECTIVE", "permutation must be bijective")
|
| 158 |
+
if any(result[result[index]] != index for index in range(dimension)):
|
| 159 |
+
raise _Refusal("PERMUTATION_NOT_INVOLUTION", "declared permutation does not satisfy P^2=I")
|
| 160 |
+
return result
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def _apply_permutation(vector: tuple[float, ...], permutation: tuple[int, ...]) -> tuple[float, ...]:
|
| 164 |
+
return tuple(vector[index] for index in permutation)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def _linf(values) -> float:
|
| 168 |
+
return max((abs(value) for value in values), default=0.0)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def _labels() -> dict:
|
| 172 |
+
return {
|
| 173 |
+
"algebraic_contract": LABEL_PROVEN,
|
| 174 |
+
"computed_observation": LABEL_MODELED,
|
| 175 |
+
"external_findings": LABEL_REPORTED,
|
| 176 |
+
"note": (
|
| 177 |
+
"PROVEN is limited to the finite-vector identities checked here; "
|
| 178 |
+
"MODELED is a deterministic transform of caller-supplied observations; "
|
| 179 |
+
"REPORTED identifies claims made by the cited primary sources."
|
| 180 |
+
),
|
| 181 |
+
"adds_to_locked_8": 0,
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def _refusal(pair_id, code: str, reason: str) -> dict:
|
| 186 |
+
safe_pair_id = None
|
| 187 |
+
if isinstance(pair_id, str):
|
| 188 |
+
try:
|
| 189 |
+
if _utf8_size(pair_id) <= MAX_PAIR_ID_BYTES:
|
| 190 |
+
safe_pair_id = pair_id
|
| 191 |
+
except _Refusal:
|
| 192 |
+
pass
|
| 193 |
+
core = {
|
| 194 |
+
"schema": SCHEMA,
|
| 195 |
+
"ok": False,
|
| 196 |
+
"verdict": VERDICT_REFUSED,
|
| 197 |
+
"pair_id": safe_pair_id,
|
| 198 |
+
"refusal": {"code": code, "reason": reason},
|
| 199 |
+
"labels": _labels(),
|
| 200 |
+
"citations": [dict(citation) for citation in _CITATIONS],
|
| 201 |
+
}
|
| 202 |
+
core["digest"] = {
|
| 203 |
+
"algorithm": "sha256",
|
| 204 |
+
"stable_content_sha256": _stable_digest(core),
|
| 205 |
+
"signed": False,
|
| 206 |
+
}
|
| 207 |
+
return core
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def evaluate_involution_pair(*, pair_id, left_observation, transformed_observation,
|
| 211 |
+
permutation) -> dict:
|
| 212 |
+
"""Validate and decompose one declared involution pair.
|
| 213 |
+
|
| 214 |
+
Returns a deterministic ``DECOMPOSED`` result or a deterministic ``REFUSED``
|
| 215 |
+
result for an incomplete, unbounded, non-finite, mismatched, non-bijective, or
|
| 216 |
+
non-involutive input. Programmer faults are not hidden by a broad exception.
|
| 217 |
+
"""
|
| 218 |
+
try:
|
| 219 |
+
validated_pair_id = _validate_pair_id(pair_id)
|
| 220 |
+
left = _as_bounded_vector("left_observation", left_observation)
|
| 221 |
+
transformed = _as_bounded_vector("transformed_observation", transformed_observation)
|
| 222 |
+
if len(left) != len(transformed):
|
| 223 |
+
raise _Refusal("PAIR_DIMENSION_MISMATCH", "paired vectors must share a dimension")
|
| 224 |
+
involution = _as_involution(permutation, len(left))
|
| 225 |
+
except _Refusal as refusal:
|
| 226 |
+
return _refusal(pair_id, refusal.code, refusal.reason)
|
| 227 |
+
|
| 228 |
+
# P^-1 is P because validation established P^2=I.
|
| 229 |
+
aligned = _apply_permutation(transformed, involution)
|
| 230 |
+
symmetric = tuple((a + b) / 2.0 for a, b in zip(left, aligned))
|
| 231 |
+
antisymmetric = tuple((a - b) / 2.0 for a, b in zip(left, aligned))
|
| 232 |
+
|
| 233 |
+
reconstructed_left = tuple(s + a for s, a in zip(symmetric, antisymmetric))
|
| 234 |
+
reconstructed_aligned = tuple(s - a for s, a in zip(symmetric, antisymmetric))
|
| 235 |
+
reconstructed_transformed = _apply_permutation(reconstructed_aligned, involution)
|
| 236 |
+
|
| 237 |
+
permutation_closure_residual = max(
|
| 238 |
+
(abs(involution[involution[index]] - index) for index in range(len(involution))),
|
| 239 |
+
default=0,
|
| 240 |
+
)
|
| 241 |
+
reconstruction_residual = _linf(
|
| 242 |
+
[actual - reconstructed for actual, reconstructed in zip(left, reconstructed_left)]
|
| 243 |
+
+ [actual - reconstructed
|
| 244 |
+
for actual, reconstructed in zip(transformed, reconstructed_transformed)]
|
| 245 |
+
)
|
| 246 |
+
paired_delta = _linf(a - b for a, b in zip(left, aligned))
|
| 247 |
+
|
| 248 |
+
input_contract = {
|
| 249 |
+
"pair_id": validated_pair_id,
|
| 250 |
+
"dimension": len(left),
|
| 251 |
+
"permutation": list(involution),
|
| 252 |
+
"left_observation": list(left),
|
| 253 |
+
"transformed_observation": list(transformed),
|
| 254 |
+
"permutation_convention": "(P v)[i] = v[P[i]]",
|
| 255 |
+
}
|
| 256 |
+
result_core = {
|
| 257 |
+
"schema": SCHEMA,
|
| 258 |
+
"ok": True,
|
| 259 |
+
"verdict": VERDICT_DECOMPOSED,
|
| 260 |
+
"pair_id": validated_pair_id,
|
| 261 |
+
"bounds": {
|
| 262 |
+
"max_dimension": MAX_DIMENSION,
|
| 263 |
+
"max_abs_value": MAX_ABS_VALUE,
|
| 264 |
+
"max_pair_id_bytes": MAX_PAIR_ID_BYTES,
|
| 265 |
+
},
|
| 266 |
+
"contract": {
|
| 267 |
+
"permutation_convention": "(P v)[i] = v[P[i]]",
|
| 268 |
+
"requires_involution": True,
|
| 269 |
+
"aligned_transformed": "P^-1(transformed_observation)",
|
| 270 |
+
"symmetric": "(left + aligned_transformed) / 2",
|
| 271 |
+
"antisymmetric": "(left - aligned_transformed) / 2",
|
| 272 |
+
},
|
| 273 |
+
"input": {
|
| 274 |
+
"dimension": len(left),
|
| 275 |
+
"permutation": list(involution),
|
| 276 |
+
},
|
| 277 |
+
"decomposition": {
|
| 278 |
+
"aligned_transformed": list(aligned),
|
| 279 |
+
"symmetric": list(symmetric),
|
| 280 |
+
"antisymmetric": list(antisymmetric),
|
| 281 |
+
},
|
| 282 |
+
"closure": {
|
| 283 |
+
"permutation_squared_identity": permutation_closure_residual == 0,
|
| 284 |
+
"permutation_closure_residual": permutation_closure_residual,
|
| 285 |
+
"pair_reconstruction_residual_linf": reconstruction_residual,
|
| 286 |
+
"paired_delta_linf": paired_delta,
|
| 287 |
+
},
|
| 288 |
+
"labels": _labels(),
|
| 289 |
+
"citations": [dict(citation) for citation in _CITATIONS],
|
| 290 |
+
"effects": {
|
| 291 |
+
"writes": 0,
|
| 292 |
+
"signatures": 0,
|
| 293 |
+
"effectors": 0,
|
| 294 |
+
"network_calls": 0,
|
| 295 |
+
},
|
| 296 |
+
}
|
| 297 |
+
result_core["digests"] = {
|
| 298 |
+
"algorithm": "sha256",
|
| 299 |
+
"input_sha256": _stable_digest({"schema": SCHEMA, "input": input_contract}),
|
| 300 |
+
"result_sha256": _stable_digest(result_core),
|
| 301 |
+
"signed": False,
|
| 302 |
+
}
|
| 303 |
+
return result_core
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
__all__ = [
|
| 307 |
+
"ARTICLE_DOI",
|
| 308 |
+
"DATA_CODE_DOI",
|
| 309 |
+
"LABEL_MODELED",
|
| 310 |
+
"LABEL_PROVEN",
|
| 311 |
+
"LABEL_REPORTED",
|
| 312 |
+
"MAX_ABS_VALUE",
|
| 313 |
+
"MAX_DIMENSION",
|
| 314 |
+
"MAX_PAIR_ID_BYTES",
|
| 315 |
+
"SCHEMA",
|
| 316 |
+
"VERDICT_DECOMPOSED",
|
| 317 |
+
"VERDICT_REFUSED",
|
| 318 |
+
"evaluate_involution_pair",
|
| 319 |
+
]
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def register(app, ns="a11oy"):
|
| 323 |
+
"""Register the read-only contract view and bounded evaluation endpoint."""
|
| 324 |
+
from fastapi import Request
|
| 325 |
+
from fastapi.responses import JSONResponse
|
| 326 |
+
|
| 327 |
+
base = "/api/%s/v1/evidenceos/involution" % ns
|
| 328 |
+
|
| 329 |
+
def _json_response(body, status_code=200):
|
| 330 |
+
response = JSONResponse(body, status_code=status_code)
|
| 331 |
+
response.headers["Cache-Control"] = "no-store"
|
| 332 |
+
response.headers["X-Content-Type-Options"] = "nosniff"
|
| 333 |
+
return response
|
| 334 |
+
|
| 335 |
+
@app.get(base + "/info")
|
| 336 |
+
async def _involution_info(): # noqa: ANN202
|
| 337 |
+
return _json_response({
|
| 338 |
+
"schema": SCHEMA,
|
| 339 |
+
"service_state": "LIVE",
|
| 340 |
+
"effectors": 0,
|
| 341 |
+
"writes": 0,
|
| 342 |
+
"max_dimension": MAX_DIMENSION,
|
| 343 |
+
"permutation_contract": "(P v)[i] = v[P[i]] and P^2 = I",
|
| 344 |
+
"labels": _labels(),
|
| 345 |
+
"citations": [dict(citation) for citation in _CITATIONS],
|
| 346 |
+
"receipt_policy": "pure computation; content digest returned; no state write and no signature minted",
|
| 347 |
+
})
|
| 348 |
+
|
| 349 |
+
@app.post(base + "/evaluate")
|
| 350 |
+
async def _involution_evaluate(request: Request): # noqa: ANN202
|
| 351 |
+
raw = await request.body()
|
| 352 |
+
if len(raw) > 200_000:
|
| 353 |
+
return _json_response({"ok": False, "verdict": VERDICT_REFUSED,
|
| 354 |
+
"refusal": {"code": "BODY_TOO_LARGE", "reason": "request exceeds 200000 bytes"}},
|
| 355 |
+
status_code=413)
|
| 356 |
+
try:
|
| 357 |
+
body = json.loads(raw.decode("utf-8"))
|
| 358 |
+
except (UnicodeDecodeError, json.JSONDecodeError):
|
| 359 |
+
return _json_response({"ok": False, "verdict": VERDICT_REFUSED,
|
| 360 |
+
"refusal": {"code": "INVALID_JSON", "reason": "request body must be JSON"}},
|
| 361 |
+
status_code=400)
|
| 362 |
+
if not isinstance(body, dict):
|
| 363 |
+
return _json_response({"ok": False, "verdict": VERDICT_REFUSED,
|
| 364 |
+
"refusal": {"code": "INVALID_BODY", "reason": "request body must be an object"}},
|
| 365 |
+
status_code=400)
|
| 366 |
+
allowed = {"pair_id", "left_observation", "transformed_observation", "permutation"}
|
| 367 |
+
unknown = sorted(str(key) for key in body if key not in allowed)
|
| 368 |
+
if unknown:
|
| 369 |
+
return _json_response({"ok": False, "verdict": VERDICT_REFUSED,
|
| 370 |
+
"refusal": {"code": "UNKNOWN_FIELDS", "reason": "unexpected fields", "fields": unknown}},
|
| 371 |
+
status_code=400)
|
| 372 |
+
result = evaluate_involution_pair(
|
| 373 |
+
pair_id=body.get("pair_id"),
|
| 374 |
+
left_observation=body.get("left_observation"),
|
| 375 |
+
transformed_observation=body.get("transformed_observation"),
|
| 376 |
+
permutation=body.get("permutation"),
|
| 377 |
+
)
|
| 378 |
+
return _json_response(result, status_code=200 if result["ok"] else 422)
|
| 379 |
+
|
| 380 |
+
return {"ok": True, "routes": [base + "/info", base + "/evaluate"]}
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
__all__.append("register")
|
szl_runtime_contracts.py
ADDED
|
@@ -0,0 +1,421 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# Copyright 2026 Stephen P. Lutar Jr. / SZL Holdings
|
| 3 |
+
"""Bounded runtime contracts for the a11oy service layer.
|
| 4 |
+
|
| 5 |
+
Taxonomy home: services/ (runtime health, identity, and observability posture).
|
| 6 |
+
|
| 7 |
+
The four read-only endpoints deliberately answer different questions:
|
| 8 |
+
|
| 9 |
+
* ``/api/livez`` proves only that this Python process can answer a request.
|
| 10 |
+
* ``/api/readyz`` re-walks the configured Khipu chain and folds in the existing
|
| 11 |
+
boot-preflight signal. Missing or non-durable chain state fails closed.
|
| 12 |
+
* ``/api/build-info`` emits only observable, allowlisted build metadata.
|
| 13 |
+
* ``/api/<ns>/v1/otel/status`` separates in-process propagation, exporter
|
| 14 |
+
configuration, and fresh collector delivery evidence.
|
| 15 |
+
|
| 16 |
+
GETs never mint receipts, sign data, contact an upstream, or write to disk.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import os
|
| 20 |
+
import platform
|
| 21 |
+
import re
|
| 22 |
+
import subprocess
|
| 23 |
+
import sys
|
| 24 |
+
import time
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
from typing import Any, Optional
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
_STARTED_MONOTONIC = time.monotonic()
|
| 30 |
+
_SHA_RE = re.compile(r"(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})\Z")
|
| 31 |
+
_VERSION_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._+\-]{0,63}\Z")
|
| 32 |
+
_ENV_SHA_NAMES = (
|
| 33 |
+
"A11OY_GIT_SHA",
|
| 34 |
+
"GITHUB_SHA",
|
| 35 |
+
"VERCEL_GIT_COMMIT_SHA",
|
| 36 |
+
"SOURCE_VERSION",
|
| 37 |
+
"GIT_COMMIT",
|
| 38 |
+
)
|
| 39 |
+
_ENV_VERSION_NAMES = ("A11OY_VERSION", "APP_VERSION", "RELEASE_VERSION")
|
| 40 |
+
_DURABLE_BACKENDS = {"sqlite", "json", "postgres", "postgresql", "lmdb"}
|
| 41 |
+
_FRESH_COLLECTOR_EVIDENCE_S = 120.0
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _no_store_json(content: dict[str, Any], status_code: int = 200):
|
| 45 |
+
from fastapi.responses import JSONResponse
|
| 46 |
+
|
| 47 |
+
response = JSONResponse(content=content, status_code=status_code)
|
| 48 |
+
response.headers["Cache-Control"] = "no-store"
|
| 49 |
+
response.headers["X-Content-Type-Options"] = "nosniff"
|
| 50 |
+
return response
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _safe_env_sha() -> tuple[Optional[str], Optional[str]]:
|
| 54 |
+
for name in _ENV_SHA_NAMES:
|
| 55 |
+
value = str(os.environ.get(name, "")).strip()
|
| 56 |
+
if _SHA_RE.fullmatch(value):
|
| 57 |
+
return value.lower(), f"env:{name}"
|
| 58 |
+
return None, None
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _safe_git(args: list[str]) -> Optional[subprocess.CompletedProcess[str]]:
|
| 62 |
+
"""Run one bounded, read-only git query; never uses a shell."""
|
| 63 |
+
try:
|
| 64 |
+
return subprocess.run(
|
| 65 |
+
["git", *args],
|
| 66 |
+
cwd=Path(__file__).resolve().parent,
|
| 67 |
+
capture_output=True,
|
| 68 |
+
text=True,
|
| 69 |
+
timeout=0.75,
|
| 70 |
+
check=False,
|
| 71 |
+
)
|
| 72 |
+
except (FileNotFoundError, OSError, subprocess.SubprocessError):
|
| 73 |
+
return None
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _build_identity() -> dict[str, Any]:
|
| 77 |
+
sha, source = _safe_env_sha()
|
| 78 |
+
if sha is None:
|
| 79 |
+
result = _safe_git(["rev-parse", "HEAD"])
|
| 80 |
+
candidate = result.stdout.strip() if result and result.returncode == 0 else ""
|
| 81 |
+
if _SHA_RE.fullmatch(candidate):
|
| 82 |
+
sha, source = candidate.lower(), "git:HEAD"
|
| 83 |
+
|
| 84 |
+
version = None
|
| 85 |
+
version_source = None
|
| 86 |
+
for name in _ENV_VERSION_NAMES:
|
| 87 |
+
candidate = str(os.environ.get(name, "")).strip()
|
| 88 |
+
if _VERSION_RE.fullmatch(candidate):
|
| 89 |
+
version, version_source = candidate, f"env:{name}"
|
| 90 |
+
break
|
| 91 |
+
|
| 92 |
+
dirty: Optional[bool] = None
|
| 93 |
+
status = _safe_git(["status", "--porcelain", "--untracked-files=normal"])
|
| 94 |
+
if status and status.returncode == 0:
|
| 95 |
+
dirty = bool(status.stdout.strip())
|
| 96 |
+
|
| 97 |
+
return {
|
| 98 |
+
"state": "OBSERVED" if sha else "UNKNOWN",
|
| 99 |
+
"revision": sha,
|
| 100 |
+
"revision_source": source or "UNKNOWN",
|
| 101 |
+
"version": version,
|
| 102 |
+
"version_source": version_source or "UNKNOWN",
|
| 103 |
+
"working_tree": (
|
| 104 |
+
"DIRTY" if dirty is True else "CLEAN" if dirty is False else "UNKNOWN"
|
| 105 |
+
),
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _verify_khipu_store(app: Any) -> dict[str, Any]:
|
| 110 |
+
state = getattr(app, "state", None)
|
| 111 |
+
store = getattr(state, "be_khipu", None) if state is not None else None
|
| 112 |
+
if store is not None and callable(getattr(store, "verify", None)):
|
| 113 |
+
backend = str(getattr(store, "backend", "UNKNOWN"))
|
| 114 |
+
try:
|
| 115 |
+
result = store.verify()
|
| 116 |
+
if not isinstance(result, tuple) or len(result) != 3:
|
| 117 |
+
raise ValueError("verify() returned an unsupported contract")
|
| 118 |
+
intact, depth, first_break = result
|
| 119 |
+
durable = backend.lower() in _DURABLE_BACKENDS
|
| 120 |
+
ready = bool(intact) and durable
|
| 121 |
+
return {
|
| 122 |
+
"state": "READY" if ready else "NOT_READY",
|
| 123 |
+
"source": "app.state.be_khipu",
|
| 124 |
+
"chain_intact": bool(intact),
|
| 125 |
+
"depth": int(depth),
|
| 126 |
+
"first_break_seq": int(first_break),
|
| 127 |
+
"backend": backend,
|
| 128 |
+
"durable": durable,
|
| 129 |
+
"blocking": not ready,
|
| 130 |
+
}
|
| 131 |
+
except Exception as exc:
|
| 132 |
+
return {
|
| 133 |
+
"state": "UNAVAILABLE",
|
| 134 |
+
"source": "app.state.be_khipu",
|
| 135 |
+
"backend": backend,
|
| 136 |
+
"durable": backend.lower() in _DURABLE_BACKENDS,
|
| 137 |
+
"blocking": True,
|
| 138 |
+
"error_type": type(exc).__name__,
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
# Some small deployments use the shared in-process DAG registry without
|
| 142 |
+
# szl_be_hardening. Re-walk it for diagnostic evidence, but never promote
|
| 143 |
+
# an in-memory registry to readiness: intact links do not prove durable
|
| 144 |
+
# receipt persistence.
|
| 145 |
+
try:
|
| 146 |
+
import szl_khipu_verify
|
| 147 |
+
|
| 148 |
+
report = szl_khipu_verify.list_organs()
|
| 149 |
+
organs = list(report.get("organs") or [])
|
| 150 |
+
if not organs:
|
| 151 |
+
return {
|
| 152 |
+
"state": "UNKNOWN",
|
| 153 |
+
"source": "szl_khipu_verify.list_organs",
|
| 154 |
+
"organ_count": 0,
|
| 155 |
+
"blocking": True,
|
| 156 |
+
"reason": "no observed Khipu DAG in this process",
|
| 157 |
+
}
|
| 158 |
+
intact_values = [row.get("links_intact") for row in organs]
|
| 159 |
+
all_intact = all(value is True for value in intact_values)
|
| 160 |
+
return {
|
| 161 |
+
"state": "NOT_READY",
|
| 162 |
+
"source": "szl_khipu_verify.list_organs",
|
| 163 |
+
"organ_count": len(organs),
|
| 164 |
+
"chains_intact": all_intact,
|
| 165 |
+
"backend": "in-process-registry",
|
| 166 |
+
"durable": False,
|
| 167 |
+
"blocking": True,
|
| 168 |
+
"reason": (
|
| 169 |
+
"in-process DAG links are intact but durable persistence is not observed"
|
| 170 |
+
if all_intact
|
| 171 |
+
else "in-process DAG links are not intact and durable persistence is not observed"
|
| 172 |
+
),
|
| 173 |
+
}
|
| 174 |
+
except Exception as exc:
|
| 175 |
+
return {
|
| 176 |
+
"state": "UNAVAILABLE",
|
| 177 |
+
"source": "szl_khipu_verify.list_organs",
|
| 178 |
+
"blocking": True,
|
| 179 |
+
"error_type": type(exc).__name__,
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def _boot_preflight() -> dict[str, Any]:
|
| 184 |
+
try:
|
| 185 |
+
import szl_boot_preflight
|
| 186 |
+
|
| 187 |
+
report = szl_boot_preflight.readiness()
|
| 188 |
+
overall = str(report.get("overall", "UNKNOWN")).upper()
|
| 189 |
+
# Missing optional cloud credentials are explicitly DEGRADED, not a
|
| 190 |
+
# failure of the local core. A hard-required dependency is UNAVAILABLE.
|
| 191 |
+
blocking = overall not in {"LIVE", "DEGRADED"}
|
| 192 |
+
return {
|
| 193 |
+
"state": overall,
|
| 194 |
+
"source": "szl_boot_preflight.readiness",
|
| 195 |
+
"subsystem_count": len(report.get("subsystems") or []),
|
| 196 |
+
"blocking": blocking,
|
| 197 |
+
}
|
| 198 |
+
except Exception as exc:
|
| 199 |
+
return {
|
| 200 |
+
"state": "UNAVAILABLE",
|
| 201 |
+
"source": "szl_boot_preflight.readiness",
|
| 202 |
+
"blocking": True,
|
| 203 |
+
"error_type": type(exc).__name__,
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def _readiness(app: Any) -> tuple[dict[str, Any], int]:
|
| 208 |
+
components = {
|
| 209 |
+
"khipu": _verify_khipu_store(app),
|
| 210 |
+
"boot_preflight": _boot_preflight(),
|
| 211 |
+
}
|
| 212 |
+
blockers = [name for name, value in components.items() if value.get("blocking")]
|
| 213 |
+
ready = not blockers
|
| 214 |
+
body = {
|
| 215 |
+
"status": "READY" if ready else "NOT_READY",
|
| 216 |
+
"ready": ready,
|
| 217 |
+
"components": components,
|
| 218 |
+
"blocking_components": blockers,
|
| 219 |
+
"receipt_minted": False,
|
| 220 |
+
}
|
| 221 |
+
return body, 200 if ready else 503
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def _collector_evidence(app: Any, exporter_configured: bool) -> dict[str, Any]:
|
| 225 |
+
state = getattr(app, "state", None)
|
| 226 |
+
evidence = getattr(state, "otel_collector_evidence", None) if state is not None else None
|
| 227 |
+
if isinstance(evidence, dict):
|
| 228 |
+
try:
|
| 229 |
+
observed = float(evidence["observed_at_unix"])
|
| 230 |
+
age = max(0.0, time.time() - observed)
|
| 231 |
+
if age <= _FRESH_COLLECTOR_EVIDENCE_S and isinstance(
|
| 232 |
+
evidence.get("reachable"), bool
|
| 233 |
+
):
|
| 234 |
+
reachable = bool(evidence["reachable"])
|
| 235 |
+
return {
|
| 236 |
+
"state": "REACHABLE" if reachable else "UNREACHABLE",
|
| 237 |
+
"evidence": "FRESH_PROBE",
|
| 238 |
+
"age_s": round(age, 3),
|
| 239 |
+
}
|
| 240 |
+
return {
|
| 241 |
+
"state": "UNKNOWN",
|
| 242 |
+
"evidence": "STALE_OR_INVALID_PROBE",
|
| 243 |
+
"age_s": round(age, 3),
|
| 244 |
+
}
|
| 245 |
+
except (KeyError, TypeError, ValueError, OverflowError):
|
| 246 |
+
pass
|
| 247 |
+
return {
|
| 248 |
+
"state": "UNKNOWN" if exporter_configured else "UNAVAILABLE",
|
| 249 |
+
"evidence": "NO_FRESH_DELIVERY_PROBE",
|
| 250 |
+
"age_s": None,
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def _otel_posture(app: Any) -> dict[str, Any]:
|
| 255 |
+
installed = bool(getattr(app, "_vsp_otel_installed", False))
|
| 256 |
+
exporter_raw = str(getattr(app, "_vsp_otel_exporter", "UNAVAILABLE"))
|
| 257 |
+
policy = dict(getattr(app, "_vsp_otel_endpoint_policy", {}) or {})
|
| 258 |
+
|
| 259 |
+
# Prefer the existing VSP status object when it is available, but recompute
|
| 260 |
+
# maturity below: VSP propagation is not proof of collector delivery.
|
| 261 |
+
try:
|
| 262 |
+
import vsp_otel.middleware as vsp_otel
|
| 263 |
+
|
| 264 |
+
existing = vsp_otel.status(app)
|
| 265 |
+
installed = existing.get("propagation") == "READY"
|
| 266 |
+
exporter_raw = str(existing.get("exporter", exporter_raw))
|
| 267 |
+
endpoint = existing.get("endpoint")
|
| 268 |
+
if isinstance(endpoint, dict):
|
| 269 |
+
policy = endpoint
|
| 270 |
+
except Exception:
|
| 271 |
+
pass
|
| 272 |
+
|
| 273 |
+
exporter_configured = exporter_raw.startswith("otlp-grpc:configured:")
|
| 274 |
+
collector = _collector_evidence(app, exporter_configured)
|
| 275 |
+
if collector["state"] == "REACHABLE":
|
| 276 |
+
overall = "LIVE"
|
| 277 |
+
elif installed:
|
| 278 |
+
overall = "DEGRADED"
|
| 279 |
+
else:
|
| 280 |
+
overall = "UNAVAILABLE"
|
| 281 |
+
return {
|
| 282 |
+
"status": overall,
|
| 283 |
+
"in_process": {
|
| 284 |
+
"state": "LIVE" if installed else "UNAVAILABLE",
|
| 285 |
+
"trace_propagation": "READY" if installed else "UNAVAILABLE",
|
| 286 |
+
},
|
| 287 |
+
"exporter": {
|
| 288 |
+
"state": "CONFIGURED_UNVERIFIED" if exporter_configured else "UNAVAILABLE",
|
| 289 |
+
"endpoint_policy": str(policy.get("state", "UNKNOWN")),
|
| 290 |
+
"endpoint_fingerprint": policy.get("fingerprint"),
|
| 291 |
+
"delivery_asserted": False,
|
| 292 |
+
},
|
| 293 |
+
"collector": collector,
|
| 294 |
+
"receipt_minted": False,
|
| 295 |
+
"note": "in-process trace propagation is separate from exporter configuration and collector delivery",
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def _looks_like_file_or_well_known(path: str) -> bool:
|
| 300 |
+
if path == "/.well-known" or path.startswith("/.well-known/"):
|
| 301 |
+
return True
|
| 302 |
+
last = path.rsplit("/", 1)[-1]
|
| 303 |
+
return bool(last and "." in last and last not in {".", ".."})
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def _matched_by_path_catchall(app: Any, scope: dict[str, Any]) -> bool:
|
| 307 |
+
"""Return True only when the first matching route is a ``:path`` wildcard."""
|
| 308 |
+
try:
|
| 309 |
+
from starlette.routing import Match
|
| 310 |
+
|
| 311 |
+
for route in app.router.routes:
|
| 312 |
+
matches = getattr(route, "matches", None)
|
| 313 |
+
if not callable(matches):
|
| 314 |
+
continue
|
| 315 |
+
match, _ = matches(scope)
|
| 316 |
+
if match == Match.FULL:
|
| 317 |
+
template = str(getattr(route, "path", ""))
|
| 318 |
+
return ":path}" in template
|
| 319 |
+
except Exception:
|
| 320 |
+
return False
|
| 321 |
+
return False
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def _install_soft_404_guard(app: Any) -> None:
|
| 325 |
+
if getattr(app.state, "szl_runtime_soft_404_guard", False):
|
| 326 |
+
return
|
| 327 |
+
|
| 328 |
+
@app.middleware("http")
|
| 329 |
+
async def _runtime_soft_404_guard(request, call_next):
|
| 330 |
+
suspicious = request.method in {"GET", "HEAD"} and _looks_like_file_or_well_known(
|
| 331 |
+
request.url.path
|
| 332 |
+
)
|
| 333 |
+
catchall_match = suspicious and _matched_by_path_catchall(app, request.scope)
|
| 334 |
+
response = await call_next(request)
|
| 335 |
+
content_type = str(response.headers.get("content-type", "")).lower()
|
| 336 |
+
if catchall_match and response.status_code == 200 and "text/html" in content_type:
|
| 337 |
+
return _no_store_json(
|
| 338 |
+
{
|
| 339 |
+
"status": "NOT_FOUND",
|
| 340 |
+
"path": request.url.path,
|
| 341 |
+
"reason": "unknown file-like path refused SPA fallback",
|
| 342 |
+
},
|
| 343 |
+
status_code=404,
|
| 344 |
+
)
|
| 345 |
+
return response
|
| 346 |
+
|
| 347 |
+
app.state.szl_runtime_soft_404_guard = True
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def _front_move_new_routes(app: Any, previous_ids: set[int]) -> None:
|
| 351 |
+
"""Ensure exact contracts win even when register() follows a SPA catch-all."""
|
| 352 |
+
added = [route for route in app.router.routes if id(route) not in previous_ids]
|
| 353 |
+
if not added:
|
| 354 |
+
return
|
| 355 |
+
old = [route for route in app.router.routes if id(route) in previous_ids]
|
| 356 |
+
app.router.routes[:] = added + old
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def register(app: Any, ns: str = "a11oy") -> dict[str, Any]:
|
| 360 |
+
"""Register idempotent, read-only runtime endpoints and the soft-404 guard."""
|
| 361 |
+
if getattr(app.state, "szl_runtime_contracts_registered", False):
|
| 362 |
+
return {"registered": False, "reason": "already_registered"}
|
| 363 |
+
|
| 364 |
+
previous_ids = {id(route) for route in app.router.routes}
|
| 365 |
+
# Git inspection is a bounded startup observation, not request work. Keep
|
| 366 |
+
# the immutable snapshot in this registration closure so public GETs never
|
| 367 |
+
# spawn child processes or re-read the working tree.
|
| 368 |
+
build_identity = _build_identity()
|
| 369 |
+
|
| 370 |
+
@app.get("/api/livez", tags=["runtime"], include_in_schema=True)
|
| 371 |
+
async def _livez():
|
| 372 |
+
return _no_store_json(
|
| 373 |
+
{
|
| 374 |
+
"status": "LIVE",
|
| 375 |
+
"process": {
|
| 376 |
+
"pid": os.getpid(),
|
| 377 |
+
"uptime_s": round(time.monotonic() - _STARTED_MONOTONIC, 3),
|
| 378 |
+
"python_implementation": platform.python_implementation(),
|
| 379 |
+
},
|
| 380 |
+
"scope": "process liveness only; no dependency readiness asserted",
|
| 381 |
+
"receipt_minted": False,
|
| 382 |
+
}
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
@app.get("/api/readyz", tags=["runtime"], include_in_schema=True)
|
| 386 |
+
async def _readyz():
|
| 387 |
+
body, status = _readiness(app)
|
| 388 |
+
return _no_store_json(body, status_code=status)
|
| 389 |
+
|
| 390 |
+
@app.get("/api/build-info", tags=["runtime"], include_in_schema=True)
|
| 391 |
+
async def _build_info():
|
| 392 |
+
return _no_store_json(
|
| 393 |
+
{
|
| 394 |
+
"status": "OBSERVED",
|
| 395 |
+
"service": ns,
|
| 396 |
+
"build": build_identity,
|
| 397 |
+
"runtime": {
|
| 398 |
+
"python": platform.python_version(),
|
| 399 |
+
"platform": sys.platform,
|
| 400 |
+
},
|
| 401 |
+
"receipt_minted": False,
|
| 402 |
+
}
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
@app.get(f"/api/{ns}/v1/otel/status", tags=["runtime"], include_in_schema=True)
|
| 406 |
+
async def _otel_status():
|
| 407 |
+
return _no_store_json(_otel_posture(app))
|
| 408 |
+
|
| 409 |
+
_front_move_new_routes(app, previous_ids)
|
| 410 |
+
_install_soft_404_guard(app)
|
| 411 |
+
app.state.szl_runtime_contracts_registered = True
|
| 412 |
+
return {
|
| 413 |
+
"registered": True,
|
| 414 |
+
"routes": [
|
| 415 |
+
"/api/livez",
|
| 416 |
+
"/api/readyz",
|
| 417 |
+
"/api/build-info",
|
| 418 |
+
f"/api/{ns}/v1/otel/status",
|
| 419 |
+
],
|
| 420 |
+
"external_writes": False,
|
| 421 |
+
}
|