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, szl_energy_live.py, szl_energy_measured.py, szl_energy_operator.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 +1 -1
- szl_energy_live.py +92 -4
- szl_energy_measured.py +408 -0
- szl_energy_operator.py +14 -1
Dockerfile
CHANGED
|
@@ -649,7 +649,7 @@ COPY web/formulas.html web/v4_fleet_panel.html web/operator.html web/fleet-c2.ht
|
|
| 649 |
# physical-bounds) and szl_governed_api.py (govern/infer energy reference). Per-file
|
| 650 |
# COPY (this Dockerfile uses no `COPY . .`) or the guarded import falls back and the
|
| 651 |
# endpoint 404s / the govern receipt cannot cite the MEASURED reference.
|
| 652 |
-
COPY knowledge.json szl_parity_gaps.py compliance_crosswalk.py szl_compliance_mesh.py a11oy_warhacker_obs.py serve.py szl_governed_api.py szl_demo_tier1.py szl_assurance.py govern_showcase.html a11oy_wireA_metrics.py cathedral.html a11oy_operator_organ.py a11oy_hf_assets.py szl_b2_secdata.py gates_manifest.json a11oy_code_orchestrator.py a11oy_agent_loop.py a11oy_org_rag.py a11oy_mcp_client.py szl_rag.py a11oy_code_ide.html wayra_serve.py wayra_snapshot.json wayra_digests_7d.json szl_khipu_os_routes.py szl_spaces_proxy.py szl_spaces_surface.py szl_khipu_consensus.py szl_puriq_formulas.py ayni_os_serve.py szl_live_wires.py live_wires.html live_wires_3d.js szl_intoto.py szl_intoto_routes.py szl_scitt.py szl_dsse.py szl_provenance.py szl_be_hardening.py szl_unay.py szl_khipu_lmdb.py szl_khipu_replicate.py szl_unay_routes.py szl_warhacker_aliases.py a11oy_v4_hickok.py szl_khipu.py szl_formulas.py a11oy_v4_formulas.py szl_anatomy_3d.py szl_anatomy_routes.py _vendor_blobs.py szl_v4_fleet.py operator_shell_v4.py szl_bridge.py szl_bridge_schemas.py agent.html a11oy_bridge_cli.py szl_ken.py a11oy_formula_endpoints.py a11oy_formula_registry_guard.py a11oy_formulas_page.py a11oy_frontier_patch.py a11oy_v4_agent.py szl_brain.py szl_wire.py szl_hub.py szl_rosie_companion.py szl_receipt_substrate.py szl_alloy_embed_fabric.py szl_ayni_quorum.py szl_agentic_loop.py szl_ltc_dynamics.py szl_sgh_scheduler.py szl_formula_wiring.py szl_formula_surfaces.py a11oy_code_engine.py a11oy_code_runloop.py a11oy_code.py a11oy_seismic.py szl_warhacker_real.py szl_warhacker_demos.py NOTICE_warhacker_demos.txt szl_llm_registry.py szl_elite_console.py szl_alloy_models.py szl_scaling.py szl_allodial.py szl_entanglement.py szl_neuroplasticity.py szl_neuromorphic.py szl_kan.py szl_titans.py szl_mor.py szl_ternary.py szl_agentmem.py szl_edgefusion.py szl_hybridssm.py szl_aigov.py szl_chain_of_title.py szl_sovereign_compute.py szl_a11oy_interpretability.py a11oy_active_flux_router.py szl_energy_budget.py szl_energy_sovereign.py szl_energy_provenance.py szl_heart_blood.py szl_engine_status.py szl_backend_hardening.py revenue_endpoints.py a11oy_harvest_endpoints.py joule_billing.py szl_durable_ledger.py szl_energy_ledger.py szl_energy_operator.py szl_energy_projection.py szl_cheapest_watt.py szl_energy_live.py szl_orbital_topology.py szl_orbital_projection.py a11oy_orbital_page.py a11oy_frontier_page.py szl_frontier_manifest.py szl_frontier_zkinfer.py szl_frontier_fmverif.py szl_frontier_supplychain.py a11oy_code_as_action.py a11oy_governed_kernel.py szl_lambda_tripwire.py szl_provenance_receipt.py szl_khipu_verify.py szl_attest_stack.py szl_demo_sign.py szl_sda.py szl_fabric_surface.py szl_nemo_agents.py szl_kverify.py szl_specdec.py szl_immune.py szl_quant_qbio_holo.py szl_materials.py szl_materials_predict.py a11oy_factory.py a11oy_constitution.py a11oy_nav_wireup.py szl_mbse_cosim.py szl_mbse_nav.py szl_mbse.py szl_factory.py szl_willay_gateway.py a11oy_willay_nav.py szl_waqay.py a11oy_waqay_nav.py szl_yupay.py a11oy_yupay_nav.py a11oy_uds_portability_nav.py szl_pinn_bounds.py szl_pinn_residual.py physical_bounds_certificate.json agentic_decision_trail.json physical_bounds_certificate.dsse.json szl_pinn_inverse.py szl_governed_ipinn.py szl_calphad_inverse.py szl_pnt_mesh.py quantum_sensing_limits.py pnt_resilience.py nav_coasting.py fundamental_limits.py szl_counter_uas_proxy.py szl_gpu_quant.py szl_joules_truth.py revenue_model.py szl_prod_hardening.py szl_resilience.py szl_observability.py szl_corpus_publish.py szl_lake_store.py szl_lake_ingest.py szl_e8.py szl_trajectory_sign.py szl_nemotron_ingest.py szl_nemotron_corpus.py szl_nemo_verify.py a11oy_nemo_core.py szl_restraint.py szl_sapa.py szl_sapa_patch.py szl_restraint_energy.py a11oy_react_core.py szl_org_lambda.py a11oy_canonical_domain.py a11oy_formula_tiers.py szl_physical_bounds.py szl_kc_loop_forge.py szl_kc_loop_forge_metrics.py szl_kc_atlas.py szl_eval_arena.py szl_vqc.py szl_kc_jpt.py ./
|
| 653 |
|
| 654 |
# DEV2 Build 1: TEE/TDX attestation hook (2026-06-30) — imported by serve.py (guarded);
|
| 655 |
# MUST be per-file COPY'd or /api/a11oy/v1/tee/status + tee_attestation receipt field
|
|
|
|
| 649 |
# physical-bounds) and szl_governed_api.py (govern/infer energy reference). Per-file
|
| 650 |
# COPY (this Dockerfile uses no `COPY . .`) or the guarded import falls back and the
|
| 651 |
# endpoint 404s / the govern receipt cannot cite the MEASURED reference.
|
| 652 |
+
COPY knowledge.json szl_parity_gaps.py compliance_crosswalk.py szl_compliance_mesh.py a11oy_warhacker_obs.py serve.py szl_governed_api.py szl_demo_tier1.py szl_assurance.py govern_showcase.html a11oy_wireA_metrics.py cathedral.html a11oy_operator_organ.py a11oy_hf_assets.py szl_b2_secdata.py gates_manifest.json a11oy_code_orchestrator.py a11oy_agent_loop.py a11oy_org_rag.py a11oy_mcp_client.py szl_rag.py a11oy_code_ide.html wayra_serve.py wayra_snapshot.json wayra_digests_7d.json szl_khipu_os_routes.py szl_spaces_proxy.py szl_spaces_surface.py szl_khipu_consensus.py szl_puriq_formulas.py ayni_os_serve.py szl_live_wires.py live_wires.html live_wires_3d.js szl_intoto.py szl_intoto_routes.py szl_scitt.py szl_dsse.py szl_provenance.py szl_be_hardening.py szl_unay.py szl_khipu_lmdb.py szl_khipu_replicate.py szl_unay_routes.py szl_warhacker_aliases.py a11oy_v4_hickok.py szl_khipu.py szl_formulas.py a11oy_v4_formulas.py szl_anatomy_3d.py szl_anatomy_routes.py _vendor_blobs.py szl_v4_fleet.py operator_shell_v4.py szl_bridge.py szl_bridge_schemas.py agent.html a11oy_bridge_cli.py szl_ken.py a11oy_formula_endpoints.py a11oy_formula_registry_guard.py a11oy_formulas_page.py a11oy_frontier_patch.py a11oy_v4_agent.py szl_brain.py szl_wire.py szl_hub.py szl_rosie_companion.py szl_receipt_substrate.py szl_alloy_embed_fabric.py szl_ayni_quorum.py szl_agentic_loop.py szl_ltc_dynamics.py szl_sgh_scheduler.py szl_formula_wiring.py szl_formula_surfaces.py a11oy_code_engine.py a11oy_code_runloop.py a11oy_code.py a11oy_seismic.py szl_warhacker_real.py szl_warhacker_demos.py NOTICE_warhacker_demos.txt szl_llm_registry.py szl_elite_console.py szl_alloy_models.py szl_scaling.py szl_allodial.py szl_entanglement.py szl_neuroplasticity.py szl_neuromorphic.py szl_kan.py szl_titans.py szl_mor.py szl_ternary.py szl_agentmem.py szl_edgefusion.py szl_hybridssm.py szl_aigov.py szl_chain_of_title.py szl_sovereign_compute.py szl_a11oy_interpretability.py a11oy_active_flux_router.py szl_energy_budget.py szl_energy_sovereign.py szl_energy_provenance.py szl_heart_blood.py szl_engine_status.py szl_backend_hardening.py revenue_endpoints.py a11oy_harvest_endpoints.py szl_energy_measured.py joule_billing.py szl_durable_ledger.py szl_energy_ledger.py szl_energy_operator.py szl_energy_projection.py szl_cheapest_watt.py szl_energy_live.py szl_orbital_topology.py szl_orbital_projection.py a11oy_orbital_page.py a11oy_frontier_page.py szl_frontier_manifest.py szl_frontier_zkinfer.py szl_frontier_fmverif.py szl_frontier_supplychain.py a11oy_code_as_action.py a11oy_governed_kernel.py szl_lambda_tripwire.py szl_provenance_receipt.py szl_khipu_verify.py szl_attest_stack.py szl_demo_sign.py szl_sda.py szl_fabric_surface.py szl_nemo_agents.py szl_kverify.py szl_specdec.py szl_immune.py szl_quant_qbio_holo.py szl_materials.py szl_materials_predict.py a11oy_factory.py a11oy_constitution.py a11oy_nav_wireup.py szl_mbse_cosim.py szl_mbse_nav.py szl_mbse.py szl_factory.py szl_willay_gateway.py a11oy_willay_nav.py szl_waqay.py a11oy_waqay_nav.py szl_yupay.py a11oy_yupay_nav.py a11oy_uds_portability_nav.py szl_pinn_bounds.py szl_pinn_residual.py physical_bounds_certificate.json agentic_decision_trail.json physical_bounds_certificate.dsse.json szl_pinn_inverse.py szl_governed_ipinn.py szl_calphad_inverse.py szl_pnt_mesh.py quantum_sensing_limits.py pnt_resilience.py nav_coasting.py fundamental_limits.py szl_counter_uas_proxy.py szl_gpu_quant.py szl_joules_truth.py revenue_model.py szl_prod_hardening.py szl_resilience.py szl_observability.py szl_corpus_publish.py szl_lake_store.py szl_lake_ingest.py szl_e8.py szl_trajectory_sign.py szl_nemotron_ingest.py szl_nemotron_corpus.py szl_nemo_verify.py a11oy_nemo_core.py szl_restraint.py szl_sapa.py szl_sapa_patch.py szl_restraint_energy.py a11oy_react_core.py szl_org_lambda.py a11oy_canonical_domain.py a11oy_formula_tiers.py szl_physical_bounds.py szl_kc_loop_forge.py szl_kc_loop_forge_metrics.py szl_kc_atlas.py szl_eval_arena.py szl_vqc.py szl_kc_jpt.py ./
|
| 653 |
|
| 654 |
# DEV2 Build 1: TEE/TDX attestation hook (2026-06-30) — imported by serve.py (guarded);
|
| 655 |
# MUST be per-file COPY'd or /api/a11oy/v1/tee/status + tee_attestation receipt field
|
szl_energy_live.py
CHANGED
|
@@ -41,6 +41,10 @@ from starlette.responses import JSONResponse
|
|
| 41 |
# Honest labels (mirror szl_governed_api / szl_joules_truth vocabulary).
|
| 42 |
LABEL_MEASURED = "MEASURED"
|
| 43 |
LABEL_UNAVAILABLE = "UNAVAILABLE"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
# The NVML exporter URL — SAME env the governed-inference GLM engine meters off.
|
| 46 |
METER_URL = os.environ.get("SZL_GLM_METER", "https://meter2.a-11-oy.com").rstrip("/")
|
|
@@ -377,6 +381,29 @@ def _merged_engine_readings() -> dict:
|
|
| 377 |
return out
|
| 378 |
|
| 379 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 380 |
def build_mesh() -> dict:
|
| 381 |
snap = meter_snapshot()
|
| 382 |
reachable = bool(snap.get("reachable"))
|
|
@@ -386,6 +413,9 @@ def build_mesh() -> dict:
|
|
| 386 |
# and the laptop's meters). This is what lets the laptop node pull its own engine's
|
| 387 |
# watts/joules instead of showing null when its meter is a SEPARATE URL from METER_URL.
|
| 388 |
engine_map = _merged_engine_readings()
|
|
|
|
|
|
|
|
|
|
| 389 |
|
| 390 |
# Fallback attribution: match a meter GPU to a mesh node by GPU model token (e.g. the
|
| 391 |
# node "…RTX 4060 Ti…" gets the meter GPU whose name label contains "RTX 4060 Ti").
|
|
@@ -418,7 +448,7 @@ def build_mesh() -> dict:
|
|
| 418 |
source = "NVML" if g else "mesh-posture"
|
| 419 |
if isinstance(watts, (int, float)):
|
| 420 |
watt_vals.append(watts)
|
| 421 |
-
|
| 422 |
"name": n.get("name"),
|
| 423 |
"role": n.get("role"),
|
| 424 |
"live": n.get("live"),
|
|
@@ -426,7 +456,28 @@ def build_mesh() -> dict:
|
|
| 426 |
"joules": joules,
|
| 427 |
"joules_label": LABEL_MEASURED if isinstance(joules, (int, float)) else LABEL_UNAVAILABLE,
|
| 428 |
"source": source,
|
| 429 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 430 |
|
| 431 |
# Normalized 0..1 draw for visualization (relative to the busiest live node this tick).
|
| 432 |
max_w = max(watt_vals) if watt_vals else 0.0
|
|
@@ -853,17 +904,24 @@ def _selftest() -> dict:
|
|
| 853 |
# UNAVAILABLE, never fabricated. This is the regression this fix guards.
|
| 854 |
_lap = "Sovereign GPU 1 (laptop · RTX 5050 · Blackwell)"
|
| 855 |
_tow = "Sovereign GPU 2 (tower · RTX 4060 Ti · anchor)"
|
|
|
|
| 856 |
_prev_posture = globals()["govern_posture"]
|
| 857 |
_prev_readings = globals()["_merged_engine_readings"]
|
|
|
|
| 858 |
try:
|
| 859 |
-
# Deterministic posture (no network) with both nodes' engine labels wired
|
|
|
|
| 860 |
globals()["govern_posture"] = lambda *a, **k: {
|
| 861 |
-
"available": True, "live_count":
|
| 862 |
{"name": _tow, "role": "anchor", "gpu_model": "RTX 4060 Ti",
|
| 863 |
"exporter": "omen", "is_glm": False, "live": True},
|
| 864 |
{"name": _lap, "role": "blackwell", "gpu_model": "RTX 5050",
|
| 865 |
"exporter": "betterwithage", "is_glm": False, "live": True},
|
|
|
|
|
|
|
| 866 |
]}
|
|
|
|
|
|
|
| 867 |
# Reachable-but-empty single meter so the GPU-model fallback yields nothing
|
| 868 |
# (proves attribution comes from the engine map, and null is honest when absent).
|
| 869 |
with _snap_lock:
|
|
@@ -881,6 +939,9 @@ def _selftest() -> dict:
|
|
| 881 |
assert by[_lap]["watts"] == 8.0 and by[_lap]["joules"] == 37000.0, by[_lap]
|
| 882 |
assert by[_lap]["joules_label"] == LABEL_MEASURED and by[_lap]["source"] == "NVML", by[_lap]
|
| 883 |
assert by[_tow]["watts"] == 13.53 and by[_tow]["joules"] == 15896.0, by[_tow]
|
|
|
|
|
|
|
|
|
|
| 884 |
|
| 885 |
# Laptop engine absent (meter2 unreachable) → null, NEVER fabricated; tower unaffected.
|
| 886 |
globals()["_merged_engine_readings"] = lambda: {"omen": {"watts": 13.53, "joules": 15896.0}}
|
|
@@ -889,13 +950,40 @@ def _selftest() -> dict:
|
|
| 889 |
assert by3[_lap]["watts"] is None and by3[_lap]["joules"] is None, by3[_lap]
|
| 890 |
assert by3[_lap]["joules_label"] == LABEL_UNAVAILABLE, by3[_lap]
|
| 891 |
assert by3[_tow]["watts"] == 13.53, by3[_tow]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 892 |
finally:
|
| 893 |
globals()["govern_posture"] = _prev_posture
|
| 894 |
globals()["_merged_engine_readings"] = _prev_readings
|
|
|
|
| 895 |
with _snap_lock:
|
| 896 |
_snap_cache["data"] = None
|
| 897 |
_snap_cache["ts"] = 0.0
|
| 898 |
out["mesh_laptop_attribution"] = True
|
|
|
|
| 899 |
|
| 900 |
out["ok"] = all(v is True for v in out.values())
|
| 901 |
return out
|
|
|
|
| 41 |
# Honest labels (mirror szl_governed_api / szl_joules_truth vocabulary).
|
| 42 |
LABEL_MEASURED = "MEASURED"
|
| 43 |
LABEL_UNAVAILABLE = "UNAVAILABLE"
|
| 44 |
+
# Per-inference GPU energy where the meter counts the WHOLE GPU and exclusivity is NOT
|
| 45 |
+
# asserted: a real counter delta that may include co-tenant energy (an upper bound).
|
| 46 |
+
# Emitted verbatim by ollama_energy_probe.py; NEVER upgraded to MEASURED here.
|
| 47 |
+
LABEL_BOUNDED = "MEASURED_SHARED_BOUNDED"
|
| 48 |
|
| 49 |
# The NVML exporter URL — SAME env the governed-inference GLM engine meters off.
|
| 50 |
METER_URL = os.environ.get("SZL_GLM_METER", "https://meter2.a-11-oy.com").rstrip("/")
|
|
|
|
| 381 |
return out
|
| 382 |
|
| 383 |
|
| 384 |
+
def _merged_model_readings() -> dict:
|
| 385 |
+
"""Per-inference model energy from the MERGED multi-meter scrape, keyed by the model's
|
| 386 |
+
BASE name (tag stripped, lower-cased) → the probe's reading dict.
|
| 387 |
+
|
| 388 |
+
Populated by ollama_energy_probe.py → omen_joule_exporter.py models[] → the operator's
|
| 389 |
+
merged meter. Lets the GLM mesh node show its own MEASURED joules/token. Honest
|
| 390 |
+
(Doctrine v11): no models[] in the meter => empty map => the GLM node keeps its
|
| 391 |
+
UNAVAILABLE empty-state; a reading's label is carried VERBATIM (never upgraded)."""
|
| 392 |
+
try:
|
| 393 |
+
import szl_energy_operator as _op
|
| 394 |
+
meter = _op._fetch_joule_meter()
|
| 395 |
+
except Exception: # noqa: BLE001 — operator/meter absent => empty map, honest fallback
|
| 396 |
+
return {}
|
| 397 |
+
out: dict = {}
|
| 398 |
+
for m in (meter or {}).get("models", []) or []:
|
| 399 |
+
raw = str(m.get("name") or "").strip().lower()
|
| 400 |
+
if not raw:
|
| 401 |
+
continue
|
| 402 |
+
base = raw.split(":", 1)[0] # 'glm-4.7-flash:latest' → 'glm-4.7-flash'
|
| 403 |
+
out.setdefault(base, m) # first-seen wins, mirrors engine merge
|
| 404 |
+
return out
|
| 405 |
+
|
| 406 |
+
|
| 407 |
def build_mesh() -> dict:
|
| 408 |
snap = meter_snapshot()
|
| 409 |
reachable = bool(snap.get("reachable"))
|
|
|
|
| 413 |
# and the laptop's meters). This is what lets the laptop node pull its own engine's
|
| 414 |
# watts/joules instead of showing null when its meter is a SEPARATE URL from METER_URL.
|
| 415 |
engine_map = _merged_engine_readings()
|
| 416 |
+
# Per-inference model energy (keyed by base model name) for the GLM node — from the
|
| 417 |
+
# same merged meter scrape. Absent => GLM keeps its honest UNAVAILABLE empty-state.
|
| 418 |
+
model_map = _merged_model_readings()
|
| 419 |
|
| 420 |
# Fallback attribution: match a meter GPU to a mesh node by GPU model token (e.g. the
|
| 421 |
# node "…RTX 4060 Ti…" gets the meter GPU whose name label contains "RTX 4060 Ti").
|
|
|
|
| 448 |
source = "NVML" if g else "mesh-posture"
|
| 449 |
if isinstance(watts, (int, float)):
|
| 450 |
watt_vals.append(watts)
|
| 451 |
+
node = {
|
| 452 |
"name": n.get("name"),
|
| 453 |
"role": n.get("role"),
|
| 454 |
"live": n.get("live"),
|
|
|
|
| 456 |
"joules": joules,
|
| 457 |
"joules_label": LABEL_MEASURED if isinstance(joules, (int, float)) else LABEL_UNAVAILABLE,
|
| 458 |
"source": source,
|
| 459 |
+
}
|
| 460 |
+
# GLM node: attribute REAL per-inference energy from the probe's models[] entry.
|
| 461 |
+
# Matched by base model name. The probe's honest label (MEASURED /
|
| 462 |
+
# MEASURED_SHARED_BOUNDED / UNAVAILABLE) is carried VERBATIM — never upgraded.
|
| 463 |
+
# No fresh reading => the node keeps its UNAVAILABLE empty-state (null number).
|
| 464 |
+
if n.get("is_glm"):
|
| 465 |
+
base = str(n.get("model") or "").strip().lower().split(":", 1)[0]
|
| 466 |
+
m = model_map.get(base) if base else None
|
| 467 |
+
jpt = m.get("joules_per_token") if m else None
|
| 468 |
+
mlabel = (m.get("label") if m else None) or LABEL_UNAVAILABLE
|
| 469 |
+
if isinstance(jpt, (int, float)) and mlabel != LABEL_UNAVAILABLE:
|
| 470 |
+
node["joules_per_token"] = jpt
|
| 471 |
+
node["joules_per_token_label"] = mlabel # verbatim, never upgraded
|
| 472 |
+
node["measurement_method"] = m.get("measurement_method")
|
| 473 |
+
node["exclusive"] = m.get("exclusive")
|
| 474 |
+
node["energy_joules"] = m.get("energy_joules")
|
| 475 |
+
node["output_tokens"] = m.get("output_tokens")
|
| 476 |
+
node["inference_source"] = m.get("source")
|
| 477 |
+
else:
|
| 478 |
+
node["joules_per_token"] = None
|
| 479 |
+
node["joules_per_token_label"] = LABEL_UNAVAILABLE
|
| 480 |
+
nodes.append(node)
|
| 481 |
|
| 482 |
# Normalized 0..1 draw for visualization (relative to the busiest live node this tick).
|
| 483 |
max_w = max(watt_vals) if watt_vals else 0.0
|
|
|
|
| 904 |
# UNAVAILABLE, never fabricated. This is the regression this fix guards.
|
| 905 |
_lap = "Sovereign GPU 1 (laptop · RTX 5050 · Blackwell)"
|
| 906 |
_tow = "Sovereign GPU 2 (tower · RTX 4060 Ti · anchor)"
|
| 907 |
+
_glm = "GLM-4.7-Flash (sovereign · MIT · glm-4.7-flash)"
|
| 908 |
_prev_posture = globals()["govern_posture"]
|
| 909 |
_prev_readings = globals()["_merged_engine_readings"]
|
| 910 |
+
_prev_models = globals()["_merged_model_readings"]
|
| 911 |
try:
|
| 912 |
+
# Deterministic posture (no network) with both nodes' engine labels wired,
|
| 913 |
+
# plus the GLM node (no exporter, is_glm=True, model tag for models[] match).
|
| 914 |
globals()["govern_posture"] = lambda *a, **k: {
|
| 915 |
+
"available": True, "live_count": 3, "nodes": [
|
| 916 |
{"name": _tow, "role": "anchor", "gpu_model": "RTX 4060 Ti",
|
| 917 |
"exporter": "omen", "is_glm": False, "live": True},
|
| 918 |
{"name": _lap, "role": "blackwell", "gpu_model": "RTX 5050",
|
| 919 |
"exporter": "betterwithage", "is_glm": False, "live": True},
|
| 920 |
+
{"name": _glm, "role": "inference", "model": "glm-4.7-flash",
|
| 921 |
+
"exporter": None, "is_glm": True, "live": True},
|
| 922 |
]}
|
| 923 |
+
# No probe reading by default → GLM node stays UNAVAILABLE (honest empty-state).
|
| 924 |
+
globals()["_merged_model_readings"] = lambda: {}
|
| 925 |
# Reachable-but-empty single meter so the GPU-model fallback yields nothing
|
| 926 |
# (proves attribution comes from the engine map, and null is honest when absent).
|
| 927 |
with _snap_lock:
|
|
|
|
| 939 |
assert by[_lap]["watts"] == 8.0 and by[_lap]["joules"] == 37000.0, by[_lap]
|
| 940 |
assert by[_lap]["joules_label"] == LABEL_MEASURED and by[_lap]["source"] == "NVML", by[_lap]
|
| 941 |
assert by[_tow]["watts"] == 13.53 and by[_tow]["joules"] == 15896.0, by[_tow]
|
| 942 |
+
# GLM node with no probe reading → honest UNAVAILABLE, joules_per_token null.
|
| 943 |
+
assert by[_glm]["joules_per_token"] is None, by[_glm]
|
| 944 |
+
assert by[_glm]["joules_per_token_label"] == LABEL_UNAVAILABLE, by[_glm]
|
| 945 |
|
| 946 |
# Laptop engine absent (meter2 unreachable) → null, NEVER fabricated; tower unaffected.
|
| 947 |
globals()["_merged_engine_readings"] = lambda: {"omen": {"watts": 13.53, "joules": 15896.0}}
|
|
|
|
| 950 |
assert by3[_lap]["watts"] is None and by3[_lap]["joules"] is None, by3[_lap]
|
| 951 |
assert by3[_lap]["joules_label"] == LABEL_UNAVAILABLE, by3[_lap]
|
| 952 |
assert by3[_tow]["watts"] == 13.53, by3[_tow]
|
| 953 |
+
|
| 954 |
+
# (g) GLM per-inference energy: a fresh MEASURED_SHARED_BOUNDED reading in models[]
|
| 955 |
+
# is surfaced on the GLM node with the label carried VERBATIM (never upgraded).
|
| 956 |
+
globals()["_merged_model_readings"] = lambda: {
|
| 957 |
+
"glm-4.7-flash": {
|
| 958 |
+
"name": "glm-4.7-flash:latest", "joules_per_token": 0.42,
|
| 959 |
+
"energy_joules": 84.0, "output_tokens": 200,
|
| 960 |
+
"measurement_method": "counter-delta", "exclusive": False,
|
| 961 |
+
"label": LABEL_BOUNDED, "source": "pynvml.nvmlDeviceGetTotalEnergyConsumption",
|
| 962 |
+
}}
|
| 963 |
+
m4 = build_mesh()
|
| 964 |
+
by4 = {nd["name"]: nd for nd in m4["nodes"]}
|
| 965 |
+
assert by4[_glm]["joules_per_token"] == 0.42, by4[_glm]
|
| 966 |
+
assert by4[_glm]["joules_per_token_label"] == LABEL_BOUNDED, by4[_glm]
|
| 967 |
+
assert by4[_glm]["measurement_method"] == "counter-delta", by4[_glm]
|
| 968 |
+
assert by4[_glm]["exclusive"] is False, by4[_glm]
|
| 969 |
+
|
| 970 |
+
# A models[] entry whose own label is UNAVAILABLE is NOT surfaced as a number.
|
| 971 |
+
globals()["_merged_model_readings"] = lambda: {
|
| 972 |
+
"glm-4.7-flash": {"name": "glm-4.7-flash:latest", "joules_per_token": None,
|
| 973 |
+
"label": LABEL_UNAVAILABLE}}
|
| 974 |
+
m5 = build_mesh()
|
| 975 |
+
by5 = {nd["name"]: nd for nd in m5["nodes"]}
|
| 976 |
+
assert by5[_glm]["joules_per_token"] is None, by5[_glm]
|
| 977 |
+
assert by5[_glm]["joules_per_token_label"] == LABEL_UNAVAILABLE, by5[_glm]
|
| 978 |
finally:
|
| 979 |
globals()["govern_posture"] = _prev_posture
|
| 980 |
globals()["_merged_engine_readings"] = _prev_readings
|
| 981 |
+
globals()["_merged_model_readings"] = _prev_models
|
| 982 |
with _snap_lock:
|
| 983 |
_snap_cache["data"] = None
|
| 984 |
_snap_cache["ts"] = 0.0
|
| 985 |
out["mesh_laptop_attribution"] = True
|
| 986 |
+
out["mesh_glm_inference_energy"] = True
|
| 987 |
|
| 988 |
out["ok"] = all(v is True for v in out.values())
|
| 989 |
return out
|
szl_energy_measured.py
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# © 2026 Lutar, Stephen P. — SZL Holdings · ORCID 0009-0001-0110-4173
|
| 3 |
+
# Doctrine v11 LOCKED: locked-proven=8 · Λ=Conjecture 1 · provenance 1.0
|
| 4 |
+
# Co-Authored-By: Perplexity Computer Agent
|
| 5 |
+
"""szl_energy_measured.py — the ENERGY surface's MEASURED channel.
|
| 6 |
+
|
| 7 |
+
The `energy` (Energy · Harvest) surface was live-labelled STRUCTURAL-ONLY: its
|
| 8 |
+
joules HUD never carried a real MEASURED reading because the served
|
| 9 |
+
/api/a11oy/v1/harvest/posture endpoint had NO exporter sample off-box, so
|
| 10 |
+
szl_joules_truth honestly returned label "sample" / STRUCTURAL-ONLY.
|
| 11 |
+
|
| 12 |
+
This organ gives that surface a REAL MEASURED channel by reading the LIVE NVML
|
| 13 |
+
joule meter (meter.a-11-oy.com, engine 'omen', ~6-20 W, joules climbing) the
|
| 14 |
+
SAME way the JPT organ (szl_kc_jpt.py) and the One-Bit organ (szl_kc_onebit.py)
|
| 15 |
+
do — via the env A11OY_JOULE_METER_URLS (comma-separated meter list, aggregated),
|
| 16 |
+
with a browser-like UA + short timeout, fully guarded.
|
| 17 |
+
|
| 18 |
+
HONESTY SPINE (Doctrine v11 — NON-NEGOTIABLE):
|
| 19 |
+
* MEASURED only from a REAL live meter reading THIS request. If NO meter env is
|
| 20 |
+
set or NO meter responds live this request, the channel is honest
|
| 21 |
+
STRUCTURAL-ONLY with a clear machine-readable `reason` — NEVER a fabricated joule.
|
| 22 |
+
* MONOTONIC-RESET DETECTION: this organ takes a joule reading BEFORE and AFTER a
|
| 23 |
+
tiny bounded settle window (or across two reads). If meter_after < meter_before
|
| 24 |
+
(tower reboot / NVML counter reset) we SKIP the reading, flag `meter_reset`, and
|
| 25 |
+
fall back to STRUCTURAL-ONLY — we never log a negative or fabricated delta.
|
| 26 |
+
* PROVENANCE on EVERY number: meter url, engine, exporter, meter ts, fetched-at.
|
| 27 |
+
* The honesty LABEL is decided SOLELY by szl_joules_truth (the single source of
|
| 28 |
+
truth shared with the operator / billing / kernel) — never off a flag. We only
|
| 29 |
+
build the exporter_sample; szl_joules_truth gates it MEASURED vs sample.
|
| 30 |
+
* Λ = Conjecture 1 — untouched (this organ never emits it).
|
| 31 |
+
* Pure stdlib only (urllib, json, os, time). Cite the meter/exporter, never ours.
|
| 32 |
+
|
| 33 |
+
Public surface (consumed by a11oy_harvest_endpoints.handle_posture):
|
| 34 |
+
measured_channel(now=None) -> dict
|
| 35 |
+
Always returns a dict with a doctrine-stable schema:
|
| 36 |
+
{
|
| 37 |
+
"joules_label": "measured" | "sample", # from szl_joules_truth
|
| 38 |
+
"measured": bool, # True only when live this request
|
| 39 |
+
"joules_evidence": dict, # {} unless measured
|
| 40 |
+
"exporter_sample": dict | None, # the sample handed to joules_truth
|
| 41 |
+
"reason": str, # WHY structural/measured (honest)
|
| 42 |
+
"provenance": {meter_url, engine, exporter, meter_ts, fetched_at, method},
|
| 43 |
+
"power_w": float | None,
|
| 44 |
+
"joules_before": float | None,
|
| 45 |
+
"joules_after": float | None,
|
| 46 |
+
"meter_urls": [str, ...],
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
A number here is MEASURED because it came from a live meter read with live=true
|
| 50 |
+
NVML this request; it is NEVER a stale or fabricated constant.
|
| 51 |
+
"""
|
| 52 |
+
from __future__ import annotations
|
| 53 |
+
|
| 54 |
+
import json as _json
|
| 55 |
+
import os as _os
|
| 56 |
+
import time as _time
|
| 57 |
+
import urllib.request as _urllib_request
|
| 58 |
+
from typing import Any, Dict, List, Optional
|
| 59 |
+
|
| 60 |
+
DOCTRINE_VERSION = "v11"
|
| 61 |
+
|
| 62 |
+
# The default omen meter (Cloudflare-fronted). Overridden by A11OY_JOULE_METER_URLS
|
| 63 |
+
# (comma-separated) — the SAME env the JPT + One-Bit organs harness. Never hardcodes
|
| 64 |
+
# a wattage; only selects WHERE to read a real reading from.
|
| 65 |
+
_METER_URL_DEFAULT = "https://meter.a-11-oy.com/"
|
| 66 |
+
|
| 67 |
+
_METER_PROBE_UA = _os.environ.get(
|
| 68 |
+
"SZL_PROBE_USER_AGENT",
|
| 69 |
+
"Mozilla/5.0 (compatible; szl-energy-measured/1.0; +https://a-11-oy.com)")
|
| 70 |
+
try:
|
| 71 |
+
_METER_TIMEOUT_S = float(_os.environ.get("SZL_ENERGY_METER_TIMEOUT", "4.0"))
|
| 72 |
+
except (TypeError, ValueError):
|
| 73 |
+
_METER_TIMEOUT_S = 4.0
|
| 74 |
+
|
| 75 |
+
CITATIONS: Dict[str, str] = {
|
| 76 |
+
"meter": "meter.a-11-oy.com — omen-joule-exporter (real NVML via nvidia-smi)",
|
| 77 |
+
"exporter": "omen_joule_exporter.py (SZL fleet) reads NVIDIA NVML power via nvidia-smi",
|
| 78 |
+
"doctrine": "SZL joules doctrine v11 — MEASURED only from a live meter reading this request",
|
| 79 |
+
"joules_truth": "szl_joules_truth.py — the single source of truth for the joules honesty label",
|
| 80 |
+
"harness": ("A11OY_JOULE_METER_URLS — the comma-separated meter list the JPT (szl_kc_jpt.py) "
|
| 81 |
+
"and One-Bit (szl_kc_onebit.py) organs harness; adding a meter = adding a URL"),
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _joule_meter_urls() -> List[str]:
|
| 86 |
+
"""Resolve the harnessed meter URL list at call time — the JPT/One-Bit way.
|
| 87 |
+
|
| 88 |
+
Priority:
|
| 89 |
+
1. A11OY_JOULE_METER_URLS (comma-separated) — the multi-meter harness form.
|
| 90 |
+
2. A11OY_JOULE_METER_URL (single) — the operator/One-Bit single-meter env.
|
| 91 |
+
3. Empty list when NEITHER is set (the sandbox default) — the organ then
|
| 92 |
+
honestly reports STRUCTURAL-ONLY (never fabricates a default reading).
|
| 93 |
+
Never fabricates a meter; only selects WHERE to read a real reading from.
|
| 94 |
+
"""
|
| 95 |
+
multi = (_os.environ.get("A11OY_JOULE_METER_URLS") or "").strip()
|
| 96 |
+
urls = [u.strip() for u in multi.split(",") if u.strip()]
|
| 97 |
+
if urls:
|
| 98 |
+
return urls
|
| 99 |
+
single = (_os.environ.get("A11OY_JOULE_METER_URL") or "").strip()
|
| 100 |
+
if single:
|
| 101 |
+
return [single]
|
| 102 |
+
return []
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _read_meter_raw(url: str, timeout: float) -> Optional[Dict[str, Any]]:
|
| 106 |
+
"""GET the live joule-meter JSON, or None on ANY failure (unreachable/timeout/
|
| 107 |
+
non-200/malformed). Guarded — NEVER raises, NEVER fabricates. Browser-like UA so
|
| 108 |
+
the Cloudflare-fronted meter does not 403. Mirrors szl_kc_jpt._read_meter_raw /
|
| 109 |
+
szl_kc_onebit.read_live_meter transport."""
|
| 110 |
+
target = (url or _METER_URL_DEFAULT).strip()
|
| 111 |
+
try:
|
| 112 |
+
req = _urllib_request.Request(target, headers={"User-Agent": _METER_PROBE_UA})
|
| 113 |
+
with _urllib_request.urlopen(req, timeout=timeout) as r: # noqa: S310
|
| 114 |
+
status = getattr(r, "status", None) or 200
|
| 115 |
+
if not (200 <= int(status) < 300):
|
| 116 |
+
return None
|
| 117 |
+
raw = r.read().decode("utf-8", "replace")
|
| 118 |
+
doc = _json.loads(raw)
|
| 119 |
+
except Exception: # noqa: BLE001 — degrade honestly
|
| 120 |
+
return None
|
| 121 |
+
return doc if isinstance(doc, dict) else None
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _live_engine(doc: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
|
| 125 |
+
"""Return the FIRST engine that carries a live=true GPU with a numeric power_w,
|
| 126 |
+
or None. HARD honesty gate (mirrors szl_kc_onebit): an engine with no live=true
|
| 127 |
+
real GPU reading is not a live reading and is dropped."""
|
| 128 |
+
if not isinstance(doc, dict):
|
| 129 |
+
return None
|
| 130 |
+
for e in (doc.get("engines") or []):
|
| 131 |
+
if not isinstance(e, dict):
|
| 132 |
+
continue
|
| 133 |
+
for g in (e.get("gpus") or []):
|
| 134 |
+
if isinstance(g, dict) and g.get("live") is True and isinstance(g.get("power_w"), (int, float)):
|
| 135 |
+
return e
|
| 136 |
+
return None
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _engine_joules(engine: Optional[Dict[str, Any]], doc: Optional[Dict[str, Any]]) -> Optional[float]:
|
| 140 |
+
"""Cumulative joules for the live engine (prefer engine.joules; fall back to
|
| 141 |
+
totals.joules). None if neither is numeric."""
|
| 142 |
+
if isinstance(engine, dict) and isinstance(engine.get("joules"), (int, float)):
|
| 143 |
+
return float(engine["joules"])
|
| 144 |
+
if isinstance(doc, dict):
|
| 145 |
+
totals = doc.get("totals") if isinstance(doc.get("totals"), dict) else {}
|
| 146 |
+
tj = totals.get("joules")
|
| 147 |
+
if isinstance(tj, (int, float)):
|
| 148 |
+
return float(tj)
|
| 149 |
+
return None
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _engine_power_w(engine: Optional[Dict[str, Any]]) -> Optional[float]:
|
| 153 |
+
"""First live GPU power_w on the engine (for the believable-envelope note)."""
|
| 154 |
+
if not isinstance(engine, dict):
|
| 155 |
+
return None
|
| 156 |
+
for g in (engine.get("gpus") or []):
|
| 157 |
+
if isinstance(g, dict) and g.get("live") is True and isinstance(g.get("power_w"), (int, float)):
|
| 158 |
+
return float(g["power_w"])
|
| 159 |
+
return None
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def _structural(reason: str, meter_urls: List[str], *,
|
| 163 |
+
provenance: Optional[Dict[str, Any]] = None,
|
| 164 |
+
joules_before: Optional[float] = None,
|
| 165 |
+
joules_after: Optional[float] = None) -> Dict[str, Any]:
|
| 166 |
+
"""Build the honest STRUCTURAL-ONLY channel: joules_label 'sample', NO evidence,
|
| 167 |
+
NO fabricated joule — just a clear machine-readable reason + what provenance we
|
| 168 |
+
have. joules_truth is the single source of truth: with exporter_sample None it
|
| 169 |
+
returns ('sample', {}), so this stays doctrine-clean and self-verifying."""
|
| 170 |
+
label, evidence = _label_and_evidence(None)
|
| 171 |
+
return {
|
| 172 |
+
"joules_label": label, # "sample" (STRUCTURAL-ONLY on the surface)
|
| 173 |
+
"measured": False,
|
| 174 |
+
"joules_evidence": evidence, # {} — never fabricated
|
| 175 |
+
"exporter_sample": None,
|
| 176 |
+
"reason": reason,
|
| 177 |
+
"provenance": provenance or {
|
| 178 |
+
"meter_url": None, "engine": None, "exporter": None,
|
| 179 |
+
"meter_ts": None, "fetched_at": _time.time(),
|
| 180 |
+
"method": ("read live NVML joule meter (engine live=true) THIS request; "
|
| 181 |
+
"measured only when the meter responds live"),
|
| 182 |
+
},
|
| 183 |
+
"power_w": None,
|
| 184 |
+
"joules_before": joules_before,
|
| 185 |
+
"joules_after": joules_after,
|
| 186 |
+
"meter_urls": list(meter_urls),
|
| 187 |
+
"doctrine": DOCTRINE_VERSION,
|
| 188 |
+
"citations": {k: CITATIONS[k] for k in ("meter", "exporter", "joules_truth", "harness")},
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def _label_and_evidence(exporter_sample: Optional[Dict[str, Any]],
|
| 193 |
+
now: Optional[float] = None):
|
| 194 |
+
"""Decide the honesty label + evidence via szl_joules_truth (the single source
|
| 195 |
+
of truth). Guarded fallback returns ('sample', {}) if the module is absent —
|
| 196 |
+
NEVER fabricates a measured claim."""
|
| 197 |
+
try:
|
| 198 |
+
from szl_joules_truth import joules_label as _jl, joules_evidence as _je
|
| 199 |
+
return _jl(exporter_sample, now=now), _je(exporter_sample, now=now)
|
| 200 |
+
except Exception: # noqa: BLE001 — doctrine default is always sample
|
| 201 |
+
return "sample", {}
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def measured_channel(now: Optional[float] = None,
|
| 205 |
+
meter_urls: Optional[List[str]] = None,
|
| 206 |
+
timeout: Optional[float] = None) -> Dict[str, Any]:
|
| 207 |
+
"""Read the LIVE NVML joule meter(s) and build the ENERGY surface's MEASURED
|
| 208 |
+
channel. Doctrine-stable schema (see module docstring). MEASURED only when a
|
| 209 |
+
meter responds live THIS request with a live=true NVML engine; otherwise honest
|
| 210 |
+
STRUCTURAL-ONLY with a reason. NEVER fabricates a joule; NEVER raises."""
|
| 211 |
+
now = _time.time() if now is None else float(now)
|
| 212 |
+
to = _METER_TIMEOUT_S if timeout is None else float(timeout)
|
| 213 |
+
urls = meter_urls if meter_urls is not None else _joule_meter_urls()
|
| 214 |
+
|
| 215 |
+
if not urls:
|
| 216 |
+
return _structural(
|
| 217 |
+
"no live meter env set (A11OY_JOULE_METER_URLS / A11OY_JOULE_METER_URL) — "
|
| 218 |
+
"STRUCTURAL-ONLY; no joule fabricated", urls)
|
| 219 |
+
|
| 220 |
+
# Iterate the harnessed meters; the FIRST that responds live wins (the omen anchor
|
| 221 |
+
# is first by default). A dead meter is skipped, never faked — others continue.
|
| 222 |
+
for url in urls:
|
| 223 |
+
before_doc = _read_meter_raw(url, to)
|
| 224 |
+
engine_b = _live_engine(before_doc)
|
| 225 |
+
if engine_b is None:
|
| 226 |
+
continue # this meter is unreachable / has no live NVML reading — try next
|
| 227 |
+
j_before = _engine_joules(engine_b, before_doc)
|
| 228 |
+
|
| 229 |
+
# MONOTONIC-RESET DETECTION: read the meter a SECOND time and compare the
|
| 230 |
+
# cumulative counter. A tower reboot / NVML reset makes after < before; we
|
| 231 |
+
# then SKIP this meter honestly (flag meter_reset), never logging a negative
|
| 232 |
+
# or fabricated delta. When before is unavailable we cannot form a delta but
|
| 233 |
+
# a single live reading is still a real MEASURED reading (the counter is
|
| 234 |
+
# cumulative), so we proceed with the live reading and NO delta claim.
|
| 235 |
+
after_doc = _read_meter_raw(url, to)
|
| 236 |
+
engine_a = _live_engine(after_doc)
|
| 237 |
+
j_after = _engine_joules(engine_a, after_doc) if engine_a is not None else None
|
| 238 |
+
|
| 239 |
+
if (isinstance(j_before, (int, float)) and isinstance(j_after, (int, float))
|
| 240 |
+
and j_after < j_before):
|
| 241 |
+
# counter went backwards between two live reads this request -> reset.
|
| 242 |
+
return _structural(
|
| 243 |
+
("meter_reset_detected: after (%.3f J) < before (%.3f J) — tower reboot / "
|
| 244 |
+
"NVML counter reset; STRUCTURAL-ONLY, no delta logged"
|
| 245 |
+
% (float(j_after), float(j_before))),
|
| 246 |
+
urls, joules_before=j_before, joules_after=j_after,
|
| 247 |
+
provenance={
|
| 248 |
+
"meter_url": url,
|
| 249 |
+
"engine": (engine_b.get("engine") if isinstance(engine_b, dict) else None),
|
| 250 |
+
"exporter": (before_doc.get("exporter") if isinstance(before_doc, dict) else None),
|
| 251 |
+
"meter_ts": (before_doc.get("ts") if isinstance(before_doc, dict) else None),
|
| 252 |
+
"fetched_at": now,
|
| 253 |
+
"method": "two live reads this request; after<before => reset => STRUCTURAL-ONLY",
|
| 254 |
+
})
|
| 255 |
+
|
| 256 |
+
# LIVE this request — build the exporter_sample and let szl_joules_truth gate it.
|
| 257 |
+
engine_name = str(engine_b.get("engine") or "unknown-engine")
|
| 258 |
+
power_w = _engine_power_w(engine_a) or _engine_power_w(engine_b)
|
| 259 |
+
# The cumulative joules to report: prefer the fresher AFTER reading; the
|
| 260 |
+
# counter is monotonic so after>=before here.
|
| 261 |
+
joules_now = j_after if isinstance(j_after, (int, float)) else j_before
|
| 262 |
+
exporter = None
|
| 263 |
+
for d in (after_doc, before_doc):
|
| 264 |
+
if isinstance(d, dict) and d.get("exporter") is not None:
|
| 265 |
+
exporter = str(d.get("exporter"))
|
| 266 |
+
break
|
| 267 |
+
meter_ts = None
|
| 268 |
+
for d in (after_doc, before_doc):
|
| 269 |
+
if isinstance(d, dict) and isinstance(d.get("ts"), (int, float)):
|
| 270 |
+
meter_ts = float(d.get("ts"))
|
| 271 |
+
break
|
| 272 |
+
|
| 273 |
+
# exporter_sample shape szl_joules_truth expects. exporter_last_seen_ts = now
|
| 274 |
+
# (we JUST read it live this request -> fresh by construction), so the single
|
| 275 |
+
# source of truth resolves this to MEASURED. If it is somehow judged stale, the
|
| 276 |
+
# helper honestly downgrades to sample and we surface STRUCTURAL-ONLY below.
|
| 277 |
+
exporter_sample = {
|
| 278 |
+
"joules_measured_total": joules_now,
|
| 279 |
+
"exporter_node": engine_name,
|
| 280 |
+
"exporter_last_seen_ts": now,
|
| 281 |
+
"power_w_sample": power_w,
|
| 282 |
+
}
|
| 283 |
+
label, evidence = _label_and_evidence(exporter_sample, now=now)
|
| 284 |
+
provenance = {
|
| 285 |
+
"meter_url": url,
|
| 286 |
+
"engine": engine_name,
|
| 287 |
+
"exporter": exporter,
|
| 288 |
+
"meter_ts": meter_ts,
|
| 289 |
+
"fetched_at": now,
|
| 290 |
+
"method": ("read live NVML joule meter (engine live=true) THIS request "
|
| 291 |
+
"with monotonic-reset detection; measured only when live"),
|
| 292 |
+
}
|
| 293 |
+
if label != "measured":
|
| 294 |
+
# joules_truth judged it not fresh/real — honest STRUCTURAL-ONLY, no fabrication.
|
| 295 |
+
return _structural(
|
| 296 |
+
"meter responded but joules_truth judged the reading not fresh/real — "
|
| 297 |
+
"STRUCTURAL-ONLY (honest downgrade, no joule fabricated)",
|
| 298 |
+
urls, provenance=provenance,
|
| 299 |
+
joules_before=j_before, joules_after=j_after)
|
| 300 |
+
|
| 301 |
+
return {
|
| 302 |
+
"joules_label": label, # "measured"
|
| 303 |
+
"measured": True,
|
| 304 |
+
"joules_evidence": evidence, # real NVML evidence with provenance
|
| 305 |
+
"exporter_sample": exporter_sample,
|
| 306 |
+
"reason": ("MEASURED — live NVML meter responded with a live=true engine (%s) "
|
| 307 |
+
"THIS request; cumulative joules climbing, monotonic-reset checked"
|
| 308 |
+
% engine_name),
|
| 309 |
+
"provenance": provenance,
|
| 310 |
+
"power_w": power_w,
|
| 311 |
+
"joules_before": j_before,
|
| 312 |
+
"joules_after": j_after,
|
| 313 |
+
"meter_urls": list(urls),
|
| 314 |
+
"doctrine": DOCTRINE_VERSION,
|
| 315 |
+
"citations": {k: CITATIONS[k] for k in ("meter", "exporter", "joules_truth", "harness")},
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
# No harnessed meter responded live this request.
|
| 319 |
+
return _structural(
|
| 320 |
+
"no harnessed meter responded live this request (all unreachable / no live=true "
|
| 321 |
+
"NVML reading) — STRUCTURAL-ONLY; no joule fabricated", urls)
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
# ======================================================================================
|
| 325 |
+
# Self-test — MUST print ALL OK network-free.
|
| 326 |
+
# * No meter env => STRUCTURAL-ONLY, joules_label 'sample', evidence {}, no fabrication.
|
| 327 |
+
# * Synthetic live snapshot (omen) via injected reader => MEASURED with provenance.
|
| 328 |
+
# * Monotonic reset (after<before) => STRUCTURAL-ONLY meter_reset, no delta logged.
|
| 329 |
+
# ======================================================================================
|
| 330 |
+
if __name__ == "__main__":
|
| 331 |
+
import sys as _sys
|
| 332 |
+
|
| 333 |
+
# ---- (a) network-free: no meter env, unreachable url => honest STRUCTURAL-ONLY ----
|
| 334 |
+
ch = measured_channel(meter_urls=["http://127.0.0.1:1/nope"], timeout=0.2)
|
| 335 |
+
assert ch["measured"] is False, ch
|
| 336 |
+
assert ch["joules_label"] == "sample", ch["joules_label"]
|
| 337 |
+
assert ch["joules_evidence"] == {}, "STRUCTURAL-ONLY must carry NO evidence"
|
| 338 |
+
assert ch["reason"], "STRUCTURAL-ONLY must carry a reason"
|
| 339 |
+
print("(a) unreachable meter => STRUCTURAL-ONLY:", ch["reason"][:70])
|
| 340 |
+
|
| 341 |
+
ch0 = measured_channel(meter_urls=[])
|
| 342 |
+
assert ch0["measured"] is False and ch0["joules_label"] == "sample", ch0
|
| 343 |
+
assert "no live meter env" in ch0["reason"], ch0["reason"]
|
| 344 |
+
print("(a2) no meter env => STRUCTURAL-ONLY:", ch0["reason"][:70])
|
| 345 |
+
|
| 346 |
+
# ---- (b) synthetic live snapshot (matches /home/user/workspace/w27 shape) ----
|
| 347 |
+
# Prove the code path that WOULD produce MEASURED given a live meter delta, by
|
| 348 |
+
# monkeypatching the raw reader to return a live omen snapshot (real NVML shape).
|
| 349 |
+
_SNAP = {
|
| 350 |
+
"engines": [{"engine": "omen", "joules": 6937.669,
|
| 351 |
+
"gpus": [{"index": 0, "name": "NVIDIA GeForce RTX 4060 Ti",
|
| 352 |
+
"power_w": 6.17, "joules": 6937.669, "live": True}]}],
|
| 353 |
+
"totals": {"joules": 6937.669},
|
| 354 |
+
"exporter": "omen-joule-exporter (real NVML via nvidia-smi)",
|
| 355 |
+
"ts": 1783435960.4713373,
|
| 356 |
+
}
|
| 357 |
+
_seq = {"n": 0}
|
| 358 |
+
|
| 359 |
+
def _fake_read(url, timeout): # noqa: ANN001 — climbing counter across two reads
|
| 360 |
+
d = _json.loads(_json.dumps(_SNAP))
|
| 361 |
+
# second read this request: counter climbed a hair (real omen ~6-20W)
|
| 362 |
+
bump = 0.031 * _seq["n"]
|
| 363 |
+
d["engines"][0]["joules"] = round(6937.669 + bump, 3)
|
| 364 |
+
d["engines"][0]["gpus"][0]["joules"] = d["engines"][0]["joules"]
|
| 365 |
+
d["totals"]["joules"] = d["engines"][0]["joules"]
|
| 366 |
+
_seq["n"] += 1
|
| 367 |
+
return d
|
| 368 |
+
|
| 369 |
+
_orig = _read_meter_raw
|
| 370 |
+
globals()["_read_meter_raw"] = _fake_read
|
| 371 |
+
try:
|
| 372 |
+
chm = measured_channel(meter_urls=["https://meter.a-11-oy.com/"])
|
| 373 |
+
finally:
|
| 374 |
+
globals()["_read_meter_raw"] = _orig
|
| 375 |
+
assert chm["measured"] is True, chm
|
| 376 |
+
assert chm["joules_label"] == "measured", chm["joules_label"]
|
| 377 |
+
assert chm["joules_evidence"], "MEASURED must carry NVML evidence"
|
| 378 |
+
assert chm["provenance"]["engine"] == "omen", chm["provenance"]
|
| 379 |
+
assert chm["provenance"]["meter_url"] == "https://meter.a-11-oy.com/"
|
| 380 |
+
assert chm["power_w"] == 6.17, chm["power_w"]
|
| 381 |
+
assert chm["joules_after"] >= chm["joules_before"], "monotonic: after >= before"
|
| 382 |
+
print("(b) synthetic live omen snapshot => MEASURED, power_w=%s J=%s engine=%s"
|
| 383 |
+
% (chm["power_w"], chm["joules_after"], chm["provenance"]["engine"]))
|
| 384 |
+
|
| 385 |
+
# ---- (c) monotonic reset: after < before => STRUCTURAL-ONLY meter_reset ----
|
| 386 |
+
_rseq = {"n": 0}
|
| 387 |
+
|
| 388 |
+
def _fake_reset(url, timeout): # noqa: ANN001 — counter goes BACKWARDS (reboot)
|
| 389 |
+
d = _json.loads(_json.dumps(_SNAP))
|
| 390 |
+
val = 6937.669 if _rseq["n"] == 0 else 12.5 # after << before (reset)
|
| 391 |
+
d["engines"][0]["joules"] = val
|
| 392 |
+
d["engines"][0]["gpus"][0]["joules"] = val
|
| 393 |
+
d["totals"]["joules"] = val
|
| 394 |
+
_rseq["n"] += 1
|
| 395 |
+
return d
|
| 396 |
+
|
| 397 |
+
globals()["_read_meter_raw"] = _fake_reset
|
| 398 |
+
try:
|
| 399 |
+
chr_ = measured_channel(meter_urls=["https://meter.a-11-oy.com/"])
|
| 400 |
+
finally:
|
| 401 |
+
globals()["_read_meter_raw"] = _orig
|
| 402 |
+
assert chr_["measured"] is False, chr_
|
| 403 |
+
assert "meter_reset_detected" in chr_["reason"], chr_["reason"]
|
| 404 |
+
assert chr_["joules_evidence"] == {}, "reset must carry NO fabricated evidence"
|
| 405 |
+
print("(c) counter reset (after<before) => STRUCTURAL-ONLY:", chr_["reason"][:70])
|
| 406 |
+
|
| 407 |
+
print("ALL OK")
|
| 408 |
+
_sys.exit(0)
|
szl_energy_operator.py
CHANGED
|
@@ -561,8 +561,10 @@ def _fetch_joule_meter(timeout: float = 4.0) -> Optional[dict]:
|
|
| 561 |
if len(urls) == 1:
|
| 562 |
return _fetch_one_meter(urls[0], timeout)
|
| 563 |
merged_engines: list[dict] = []
|
|
|
|
| 564 |
total = 0.0
|
| 565 |
seen_names: set = set()
|
|
|
|
| 566 |
any_ok = False
|
| 567 |
for u in urls:
|
| 568 |
d = _fetch_one_meter(u, timeout)
|
|
@@ -577,9 +579,20 @@ def _fetch_joule_meter(timeout: float = 4.0) -> Optional[dict]:
|
|
| 577 |
merged_engines.append(e)
|
| 578 |
if isinstance(e.get("joules"), (int, float)):
|
| 579 |
total += float(e["joules"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 580 |
if not any_ok:
|
| 581 |
return None
|
| 582 |
-
|
|
|
|
|
|
|
|
|
|
| 583 |
|
| 584 |
|
| 585 |
def _exporter_sample_for_node(meter: Optional[dict], exporter_node: str,
|
|
|
|
| 561 |
if len(urls) == 1:
|
| 562 |
return _fetch_one_meter(urls[0], timeout)
|
| 563 |
merged_engines: list[dict] = []
|
| 564 |
+
merged_models: list[dict] = []
|
| 565 |
total = 0.0
|
| 566 |
seen_names: set = set()
|
| 567 |
+
seen_models: set = set()
|
| 568 |
any_ok = False
|
| 569 |
for u in urls:
|
| 570 |
d = _fetch_one_meter(u, timeout)
|
|
|
|
| 579 |
merged_engines.append(e)
|
| 580 |
if isinstance(e.get("joules"), (int, float)):
|
| 581 |
total += float(e["joules"])
|
| 582 |
+
# Preserve per-inference model readings additively (first-seen wins on name,
|
| 583 |
+
# mirroring the engine merge). Honest: an absent models[] contributes nothing.
|
| 584 |
+
for m in (d.get("models") or []):
|
| 585 |
+
mname = str(m.get("name") or "").lower()
|
| 586 |
+
if not mname or mname in seen_models:
|
| 587 |
+
continue
|
| 588 |
+
seen_models.add(mname)
|
| 589 |
+
merged_models.append(m)
|
| 590 |
if not any_ok:
|
| 591 |
return None
|
| 592 |
+
out: dict = {"engines": merged_engines, "totals": {"joules": round(total, 3)}}
|
| 593 |
+
if merged_models:
|
| 594 |
+
out["models"] = merged_models
|
| 595 |
+
return out
|
| 596 |
|
| 597 |
|
| 598 |
def _exporter_sample_for_node(meter: Optional[dict], exporter_node: str,
|