governed-inference-meter 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,360 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # © 2026 SZL Holdings · Stephen P. Lutar · ORCID 0009-0001-0110-4173
3
+ """governed_inference_meter — energy-metered, governed inference receipts.
4
+
5
+ A lightweight, dependency-light utility (and Hugging Face *universal* kernel)
6
+ that wraps an inference call and emits a GOVERNED, ENERGY-METERED RECEIPT:
7
+
8
+ * measures GPU energy via NVML (power/energy readback) integrated over
9
+ wall-time -> joules,
10
+ * computes tokens-per-joule,
11
+ * runs a pluggable, advisory policy gate (allow/deny; defaults to allow),
12
+ * and emits a tamper-evident, SHA-256 hash-chained JSON receipt.
13
+
14
+ It is the energy+governance counterpart to SZL Holdings'
15
+ ``SZLHOLDINGS/szl-governed-norm`` — provenance at the inference boundary, in
16
+ the spirit of the a11oy governed-AI platform (https://a-11-oy.com).
17
+
18
+ Load from the Hub::
19
+
20
+ from kernels import get_kernel
21
+ gim = get_kernel("SZLHOLDINGS/governed-inference-meter")
22
+
23
+ print(gim.__version__)
24
+ print(gim.capability_report()) # what energy measurement is possible here
25
+
26
+ # Wrap any inference callable. The callable returns the model output;
27
+ # you tell the meter how many tokens went in/out.
28
+ def run(prompt):
29
+ # ... your real model call here ...
30
+ return "the model's response text"
31
+
32
+ receipt, output = gim.meter(
33
+ run, args=("hello",),
34
+ model="my-llm-7b",
35
+ tokens_in=2, tokens_out=7,
36
+ )
37
+ print(receipt["mode"], receipt["joules"], receipt["tokens_per_joule"])
38
+ print(receipt["digest"]) # tamper-evident over the whole record
39
+ print(gim.receipt_verify()) # (ok, depth, first_break_seq)
40
+
41
+ Or as a decorator / context manager — see ``meter`` and ``metered``.
42
+
43
+ HONESTY (Λ = Conjecture 1, advisory — NOT a theorem):
44
+ * Energy is MEASURED only when NVML is present and grants readback.
45
+ Without it the receipt is ``mode="unmeasured"`` and ``joules=None`` /
46
+ ``tokens_per_joule=None``. We never fabricate joules.
47
+ * The policy gate is ADVISORY and host-enforced. This is a metering +
48
+ receipt utility, NOT a safety guarantee.
49
+ * The receipt digest is an integrity fingerprint (tamper-evidence), not a
50
+ cryptographic signature.
51
+
52
+ Dependencies: Python stdlib + ``pynvml`` (optional; only used when present).
53
+ ``torch`` is optional and only used to opportunistically synchronize the GPU
54
+ so energy is attributed to the right wall-time window.
55
+ """
56
+ import contextlib
57
+ import time
58
+ from typing import Any, Callable, Dict, Optional, Sequence, Tuple
59
+
60
+ from . import _attest, _energy, _policy, _receipt
61
+ from ._attest import (
62
+ IN_TOTO_STATEMENT_TYPE,
63
+ SZL_PREDICATE_TYPE,
64
+ attest,
65
+ compliance_evidence,
66
+ to_intoto_statement,
67
+ verify_statement,
68
+ )
69
+ from ._energy import (
70
+ MODE_ENERGY_COUNTER,
71
+ MODE_POWER_INTEGRAL,
72
+ MODE_UNMEASURED,
73
+ EnergyMeter,
74
+ capability_report,
75
+ nvml_available,
76
+ )
77
+ from ._policy import ALLOW, DENY, PolicyResult, allow_all, deny_all, evaluate
78
+ from ._receipt import ReceiptChain, default_chain
79
+ from ._spine import (
80
+ CANONICAL_KIND,
81
+ ENERGY_UNAVAILABLE,
82
+ PREDICATE_TYPE,
83
+ SPEC_VERSION,
84
+ canonical_receipt_body,
85
+ digest,
86
+ emit_szl_receipt,
87
+ from_meter_receipt,
88
+ meter_szl_receipt,
89
+ to_statement,
90
+ verify_szl_receipt,
91
+ verify_szl_statement,
92
+ )
93
+
94
+ __all__ = [
95
+ "meter",
96
+ "metered",
97
+ "EnergyMeter",
98
+ "ReceiptChain",
99
+ "PolicyResult",
100
+ "allow_all",
101
+ "deny_all",
102
+ "capability_report",
103
+ "nvml_available",
104
+ "receipt_head",
105
+ "receipt_count",
106
+ "receipt_tail",
107
+ "receipt_verify",
108
+ "selfcheck",
109
+ "attest",
110
+ "to_intoto_statement",
111
+ "compliance_evidence",
112
+ "verify_statement",
113
+ "IN_TOTO_STATEMENT_TYPE",
114
+ "SZL_PREDICATE_TYPE",
115
+ "DOCTRINE_FOOTER",
116
+ "MODE_UNMEASURED",
117
+ "MODE_ENERGY_COUNTER",
118
+ "MODE_POWER_INTEGRAL",
119
+ "ALLOW",
120
+ "DENY",
121
+ # PCGI spine fold — canonical szl-receipt for a metered inference.
122
+ "emit_szl_receipt",
123
+ "from_meter_receipt",
124
+ "meter_szl_receipt",
125
+ "canonical_receipt_body",
126
+ "to_statement",
127
+ "verify_szl_receipt",
128
+ "verify_szl_statement",
129
+ "digest",
130
+ "CANONICAL_KIND",
131
+ "PREDICATE_TYPE",
132
+ "SPEC_VERSION",
133
+ "ENERGY_UNAVAILABLE",
134
+ "__version__",
135
+ ]
136
+
137
+ __version__ = "0.2.0"
138
+ DOCTRINE_FOOTER = (
139
+ "SZL Holdings · governed, energy-metered inference receipts · "
140
+ "MEASURED only with NVML · policy gate is advisory (host-enforced) · "
141
+ "Lambda = Conjecture 1 (advisory, NOT a theorem) · trust never 100% · "
142
+ "honesty over checklist"
143
+ )
144
+
145
+
146
+ def _maybe_cuda_sync() -> None:
147
+ """Synchronize CUDA if torch+CUDA are present, so energy maps to the call.
148
+
149
+ Optional and best-effort: import errors or CPU-only torch are ignored.
150
+ """
151
+ try: # pragma: no cover - environment dependent
152
+ import torch # type: ignore
153
+
154
+ if torch.cuda.is_available():
155
+ torch.cuda.synchronize()
156
+ except Exception: # noqa: BLE001
157
+ pass
158
+
159
+
160
+ def meter(
161
+ fn: Callable[..., Any],
162
+ *,
163
+ args: Sequence[Any] = (),
164
+ kwargs: Optional[Dict[str, Any]] = None,
165
+ model: str = "unspecified",
166
+ tokens_in: int = 0,
167
+ tokens_out: int = 0,
168
+ policy: Optional[_policy.PolicyGate] = None,
169
+ chain: Optional[ReceiptChain] = None,
170
+ device_index: int = 0,
171
+ sample_hz: float = 100.0,
172
+ sign_key: Optional[Any] = None,
173
+ organ: str = "governed-inference-meter",
174
+ ) -> Tuple[Dict[str, Any], Any]:
175
+ """Run ``fn(*args, **kwargs)`` under an energy meter + policy gate.
176
+
177
+ Returns ``(receipt, output)``. If the policy gate DENIES, ``fn`` is NOT
178
+ called, ``output`` is ``None``, and the receipt records the denial with
179
+ ``mode="unmeasured"`` (nothing ran, so nothing is measured).
180
+
181
+ The receipt is appended to ``chain`` (or the module default chain) and is
182
+ a plain dict with a SHA-256 ``digest`` over its canonical body.
183
+ """
184
+ kwargs = dict(kwargs or {})
185
+ ch = chain if chain is not None else default_chain()
186
+ gate = policy if policy is not None else allow_all
187
+
188
+ context = {
189
+ "model": model,
190
+ "tokens_in": int(tokens_in),
191
+ "tokens_out": int(tokens_out),
192
+ "args": args,
193
+ "kwargs": kwargs,
194
+ "ts": time.time(),
195
+ }
196
+ decision = evaluate(gate, context)
197
+
198
+ if not decision.allowed:
199
+ # Fail-safe: do not execute on deny. Record an honest unmeasured receipt.
200
+ rec = ch.emit(
201
+ model=model,
202
+ tokens_in=tokens_in,
203
+ tokens_out=tokens_out,
204
+ energy={"mode": MODE_UNMEASURED, "joules": None, "wall_seconds": 0.0},
205
+ policy_decision=decision.decision,
206
+ policy_reason=decision.reason,
207
+ sign_key=sign_key,
208
+ organ=organ,
209
+ )
210
+ return rec, None
211
+
212
+ em = EnergyMeter(device_index=device_index, sample_hz=sample_hz)
213
+ _maybe_cuda_sync()
214
+ em.start()
215
+ try:
216
+ output = fn(*args, **kwargs)
217
+ finally:
218
+ _maybe_cuda_sync()
219
+ energy = em.stop()
220
+
221
+ rec = ch.emit(
222
+ model=model,
223
+ tokens_in=tokens_in,
224
+ tokens_out=tokens_out,
225
+ energy=energy,
226
+ policy_decision=decision.decision,
227
+ policy_reason=decision.reason,
228
+ sign_key=sign_key,
229
+ organ=organ,
230
+ )
231
+ return rec, output
232
+
233
+
234
+ @contextlib.contextmanager
235
+ def metered(
236
+ *,
237
+ model: str = "unspecified",
238
+ tokens_in: int = 0,
239
+ tokens_out: int = 0,
240
+ policy: Optional[_policy.PolicyGate] = None,
241
+ chain: Optional[ReceiptChain] = None,
242
+ device_index: int = 0,
243
+ sample_hz: float = 100.0,
244
+ sign_key: Optional[Any] = None,
245
+ organ: str = "governed-inference-meter",
246
+ ):
247
+ """Context-manager form. Yields a mutable ``state`` dict; on exit it holds
248
+ ``state["receipt"]``. The policy gate is evaluated on entry; on DENY the
249
+ body still runs is the host's choice — for fail-safe semantics use
250
+ :func:`meter`. Here we record the decision and always meter the block.
251
+
252
+ You may update ``state["tokens_out"]`` inside the block (e.g. once you know
253
+ how many tokens were generated) and it will be used in the receipt.
254
+ """
255
+ kwargs_ch = chain if chain is not None else default_chain()
256
+ gate = policy if policy is not None else allow_all
257
+ state: Dict[str, Any] = {
258
+ "model": model,
259
+ "tokens_in": int(tokens_in),
260
+ "tokens_out": int(tokens_out),
261
+ "receipt": None,
262
+ }
263
+ decision = evaluate(gate, dict(state, ts=time.time()))
264
+ em = EnergyMeter(device_index=device_index, sample_hz=sample_hz)
265
+ _maybe_cuda_sync()
266
+ em.start()
267
+ try:
268
+ yield state
269
+ finally:
270
+ _maybe_cuda_sync()
271
+ energy = em.stop()
272
+ state["receipt"] = kwargs_ch.emit(
273
+ model=state["model"],
274
+ tokens_in=int(state["tokens_in"]),
275
+ tokens_out=int(state["tokens_out"]),
276
+ energy=energy,
277
+ policy_decision=decision.decision,
278
+ policy_reason=decision.reason,
279
+ sign_key=sign_key,
280
+ organ=organ,
281
+ )
282
+
283
+
284
+ # --- Convenience accessors over the module default chain -------------------
285
+
286
+ def receipt_head() -> str:
287
+ return default_chain().head()
288
+
289
+
290
+ def receipt_count() -> int:
291
+ return default_chain().count()
292
+
293
+
294
+ def receipt_tail(n: int = 10):
295
+ return default_chain().tail(n)
296
+
297
+
298
+ def receipt_verify():
299
+ return default_chain().verify()
300
+
301
+
302
+ def selfcheck() -> Dict[str, Any]:
303
+ """One-shot end-to-end check on a fresh chain. No GPU required.
304
+
305
+ Exercises: a metered allow call, a denied call, tokens/joule honesty, and
306
+ chain verification + tamper detection. Returns a dict of results; this is
307
+ a *functional* check, NOT a benchmark, and emits NO fabricated energy.
308
+ """
309
+ ch = ReceiptChain()
310
+
311
+ def fake_infer(prompt: str) -> str:
312
+ # A trivial deterministic stand-in. Sleep a hair so the power-integral
313
+ # path (when a real GPU is present) has a window to sample.
314
+ time.sleep(0.002)
315
+ return prompt[::-1]
316
+
317
+ rec1, out1 = meter(
318
+ fake_infer, args=("hello",), model="selfcheck-stub",
319
+ tokens_in=1, tokens_out=5, chain=ch,
320
+ )
321
+ rec2, out2 = meter(
322
+ fake_infer, args=("blocked",), model="selfcheck-stub",
323
+ tokens_in=1, tokens_out=5, chain=ch, policy=deny_all,
324
+ )
325
+
326
+ ok, depth, brk = ch.verify()
327
+
328
+ # Tamper test: mutate a record and confirm verify() catches it.
329
+ tampered = False
330
+ if ch._records: # noqa: SLF001 - intentional white-box self-test
331
+ saved = ch._records[0]["tokens_out"]
332
+ ch._records[0]["tokens_out"] = saved + 1
333
+ bad_ok, _, bad_brk = ch.verify()
334
+ tampered = (not bad_ok) and (bad_brk == 0)
335
+ ch._records[0]["tokens_out"] = saved # restore
336
+
337
+ cap = capability_report()
338
+ return {
339
+ "version": __version__,
340
+ "nvml_available": nvml_available(),
341
+ "energy_mode_first_call": rec1["mode"],
342
+ "joules_honest_when_unmeasured": (
343
+ rec1["joules"] is None if rec1["mode"] == MODE_UNMEASURED else True
344
+ ),
345
+ "tpj_honest_when_unmeasured": (
346
+ rec1["tokens_per_joule"] is None
347
+ if rec1["mode"] == MODE_UNMEASURED else True
348
+ ),
349
+ "allow_call_ran": out1 == "olleh",
350
+ "deny_call_blocked": out2 is None and rec2["policy_decision"] == DENY,
351
+ "chain_ok": ok,
352
+ "chain_depth": depth,
353
+ "tamper_detected": tampered,
354
+ "preferred_energy_mode": cap["preferred_mode"],
355
+ "doctrine": DOCTRINE_FOOTER,
356
+ "passed": bool(
357
+ ok and tampered and out1 == "olleh" and out2 is None
358
+ and (rec1["joules"] is None or rec1["mode"] != MODE_UNMEASURED)
359
+ ),
360
+ }
@@ -0,0 +1,223 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # © 2026 SZL Holdings · Stephen P. Lutar · ORCID 0009-0001-0110-4173
3
+ """Standards-interop + compliance-evidence layer for governed-inference receipts.
4
+
5
+ A governed-inference receipt (see :mod:`._receipt`) is an honest, tamper-evident,
6
+ hash-chained record of one metered inference call. This module lets that record
7
+ *speak the wider ecosystem's language* without changing a single measured value:
8
+
9
+ 1. :func:`to_intoto_statement` renders a receipt as an **in-toto Statement v1**
10
+ — the exact JSON payload that Sigstore / DSSE / IETF SCITT tooling already
11
+ knows how to carry, sign, and store in a transparency log. The predicate is
12
+ laid out in SLSA-v1 provenance shape (``buildDefinition`` / ``runDetails``).
13
+ 2. :func:`compliance_evidence` maps the receipt onto the specific **EU AI Act**
14
+ articles and **NIST AI RMF** functions it provides operational evidence for
15
+ and — per the honesty doctrine — states plainly what it does **NOT** establish.
16
+ 3. :func:`verify_statement` re-derives the receipt body digest and confirms the
17
+ Statement's subject is bound to that exact receipt.
18
+
19
+ CONSOLIDATION (the ecosystem shapes + regulator catalogue live in ONE place):
20
+ The in-toto Statement envelope, the SLSA-shaped predicate skeleton, the
21
+ EU AI Act / NIST AI RMF control catalogue, and the subject-digest verifier are
22
+ the SHARED :mod:`szl_receipt.attest` module — the same library that already
23
+ provides receipt signing. This module is a thin, receipt-schema-specific
24
+ adapter over it: it maps this package's receipt fields onto capability flags
25
+ and predicate parameters, then delegates the ecosystem-facing shapes. That
26
+ keeps a single source of truth so the regulator mapping can never drift
27
+ between SZL packages. Attestation is therefore an interop feature that, like
28
+ signing, requires the shared ``szl-receipt`` library (install extra ``[sign]``);
29
+ the import is lazy so importing this package stays zero-hard-dependency.
30
+
31
+ HONESTY (Λ = Conjecture 1, advisory — NOT a theorem):
32
+ * We emit our OWN predicate type URI. We do NOT claim official SLSA-provenance
33
+ conformance; the shape is SLSA-*inspired* for recognizability only.
34
+ * Energy fields are copied verbatim from the receipt. When the receipt is
35
+ ``mode="unmeasured"`` the energy evidence is reported ``UNAVAILABLE`` — never
36
+ a fabricated joule or efficiency number.
37
+ * A receipt is EVIDENCE toward a control, never a conformity assessment,
38
+ certification, or safety guarantee. Every mapping entry carries an explicit
39
+ ``does_not_establish`` note.
40
+ * Stdlib only in this module. Nothing is written to disk or the network here;
41
+ signing (DSSE/Sigstore) is a separate, out-of-band concern.
42
+ """
43
+ import hashlib
44
+ import json
45
+ from typing import Any, Dict, Optional, Tuple
46
+
47
+ from ._receipt import _BODY_FIELDS, canonical_json
48
+
49
+ # In-toto Statement envelope type — the stable, ecosystem-standard URI. Defined
50
+ # locally (not imported) so importing this package never requires szl-receipt at
51
+ # import time; it mirrors the identical constant in ``szl_receipt.attest``.
52
+ IN_TOTO_STATEMENT_TYPE = "https://in-toto.io/Statement/v1"
53
+
54
+ # Our OWN predicate type. Honest: this is an SZL predicate, SLSA-*shaped* for
55
+ # recognizability — it is NOT a claim of official SLSA-provenance conformance.
56
+ SZL_PREDICATE_TYPE = "https://a-11-oy.com/attest/governed-inference/v0.1"
57
+
58
+ ATTEST_DOCTRINE = (
59
+ "SZL Holdings · in-toto/SLSA-shaped attestation over an honest, hash-chained "
60
+ "governed-inference receipt · MEASURED energy only (else UNAVAILABLE) · "
61
+ "EVIDENCE toward a control, NOT a conformity assessment or safety guarantee · "
62
+ "Lambda = Conjecture 1 (advisory) · trust never 100%"
63
+ )
64
+
65
+
66
+ def _shared():
67
+ """Lazily import the shared :mod:`szl_receipt.attest` layer.
68
+
69
+ Attestation is an interop feature that reuses the ONE canonical home for the
70
+ ecosystem shapes and the regulator catalogue (the same ``szl-receipt`` library
71
+ used for signing). If it is not installed we raise a clear, honest error —
72
+ never a silent, drift-prone local reimplementation.
73
+ """
74
+ try:
75
+ from szl_receipt import attest as _a # type: ignore
76
+ except Exception as exc: # noqa: BLE001
77
+ raise ImportError(
78
+ "governed_inference_meter attestation requires the shared 'szl-receipt' "
79
+ "library (pip install 'governed-inference-meter[sign]', or "
80
+ "pip install szl-receipt). Underlying import error: %r" % (exc,)
81
+ ) from exc
82
+ return _a
83
+
84
+
85
+ def _receipt_body(receipt: Dict[str, Any]) -> Dict[str, Any]:
86
+ """Extract the exact canonical body (the hashed fields) from a receipt."""
87
+ return {k: receipt[k] for k in _BODY_FIELDS}
88
+
89
+
90
+ def _body_digest(body: Dict[str, Any]) -> str:
91
+ return hashlib.sha256(canonical_json(body).encode("utf-8")).hexdigest()
92
+
93
+
94
+ def _measured(receipt: Dict[str, Any]) -> bool:
95
+ """True only when real energy was measured (mode set and joules present)."""
96
+ return receipt.get("mode") != "unmeasured" and receipt.get("joules") is not None
97
+
98
+
99
+ def to_intoto_statement(
100
+ receipt: Dict[str, Any],
101
+ *,
102
+ subject_name: Optional[str] = None,
103
+ ) -> Dict[str, Any]:
104
+ """Render *receipt* as an in-toto Statement v1 with an SLSA-shaped predicate.
105
+
106
+ The Statement's single subject is the receipt itself, bound by its SHA-256
107
+ body digest, so the attestation is inseparable from the exact record it
108
+ describes. All energy fields are copied verbatim (honest ``null`` when the
109
+ receipt was unmeasured). The returned dict is the *unsigned* payload that a
110
+ DSSE/Sigstore signer would then wrap.
111
+ """
112
+ a = _shared()
113
+ body = _receipt_body(receipt)
114
+ digest = receipt.get("digest") or _body_digest(body)
115
+ measured = _measured(receipt)
116
+ name = subject_name or "governed-inference-receipt/seq-{}".format(
117
+ receipt.get("seq", "?")
118
+ )
119
+ predicate = a.slsa_predicate(
120
+ build_type=SZL_PREDICATE_TYPE,
121
+ external_parameters={
122
+ "model": receipt.get("model"),
123
+ "tokens_in": receipt.get("tokens_in"),
124
+ "tokens_out": receipt.get("tokens_out"),
125
+ },
126
+ internal_parameters={
127
+ "policy_decision": receipt.get("policy_decision"),
128
+ "policy_reason": receipt.get("policy_reason"),
129
+ },
130
+ builder_id=SZL_PREDICATE_TYPE,
131
+ metadata={
132
+ "energy_mode": receipt.get("mode"),
133
+ "measured": measured,
134
+ # Verbatim, honest-null when unmeasured. Never fabricated.
135
+ "joules": receipt.get("joules"),
136
+ "wall_seconds": receipt.get("wall_seconds"),
137
+ "tokens_per_joule": receipt.get("tokens_per_joule"),
138
+ },
139
+ extra={"doctrine": ATTEST_DOCTRINE},
140
+ )
141
+ # Bind the receipt's chain position into the run details (product-specific).
142
+ predicate["runDetails"]["receipt"] = {
143
+ "seq": receipt.get("seq"),
144
+ "prev": receipt.get("prev"),
145
+ "digest": digest,
146
+ }
147
+ return a.build_statement(
148
+ subject_name=name,
149
+ subject_digest=digest,
150
+ predicate=predicate,
151
+ predicate_type=SZL_PREDICATE_TYPE,
152
+ )
153
+
154
+
155
+ def compliance_evidence(receipt: Dict[str, Any]) -> Dict[str, Any]:
156
+ """Map *receipt* onto EU AI Act / NIST AI RMF controls it evidences.
157
+
158
+ Returns a dict with per-control ``status`` — ``"supports"`` when the receipt
159
+ provides operational evidence for that control, or ``"UNAVAILABLE"`` for an
160
+ energy-dependent control on an unmeasured receipt. Every entry carries an
161
+ explicit ``does_not_establish`` note. This is EVIDENCE, never a conformity
162
+ assessment or certification.
163
+ """
164
+ a = _shared()
165
+ measured = _measured(receipt)
166
+ # A governed-inference receipt always logs (hash chain), is tamper-evident,
167
+ # and records an advisory governance decision; energy is capability-gated.
168
+ capabilities = {
169
+ "logging": True,
170
+ "integrity": True,
171
+ "governance": True,
172
+ "energy": measured,
173
+ }
174
+ ev = a.compliance_evidence(
175
+ capabilities=capabilities,
176
+ subject_digest=receipt.get("digest"),
177
+ extra={
178
+ "receipt_seq": receipt.get("seq"),
179
+ "receipt_digest": receipt.get("digest"),
180
+ "doctrine": ATTEST_DOCTRINE,
181
+ },
182
+ )
183
+ return ev
184
+
185
+
186
+ def attest(
187
+ receipt: Dict[str, Any],
188
+ *,
189
+ subject_name: Optional[str] = None,
190
+ ) -> Dict[str, Any]:
191
+ """Convenience: the in-toto Statement plus its compliance-evidence mapping."""
192
+ return {
193
+ "statement": to_intoto_statement(receipt, subject_name=subject_name),
194
+ "compliance": compliance_evidence(receipt),
195
+ }
196
+
197
+
198
+ def verify_statement(
199
+ statement: Dict[str, Any],
200
+ receipt: Dict[str, Any],
201
+ ) -> Tuple[bool, str]:
202
+ """Confirm *statement* is bound to *receipt*. Returns ``(ok, reason)``.
203
+
204
+ Re-derives the receipt body digest and checks it matches BOTH the receipt's
205
+ own ``digest`` and the Statement subject digest — so an attestation cannot
206
+ drift from, or be swapped away from, the exact record it claims to describe.
207
+ """
208
+ a = _shared()
209
+ try:
210
+ body = _receipt_body(receipt)
211
+ except KeyError as exc: # receipt missing a hashed field
212
+ return (False, "receipt-missing-field:{}".format(exc.args[0]))
213
+ recomputed = _body_digest(body)
214
+ if receipt.get("digest") != recomputed:
215
+ return (False, "receipt-digest-mismatch")
216
+ return a.verify_statement(
217
+ statement, expected_digest=recomputed, predicate_type=SZL_PREDICATE_TYPE
218
+ )
219
+
220
+
221
+ def to_json(obj: Dict[str, Any]) -> str:
222
+ """Canonical (sorted, compact) JSON — the bytes a DSSE signer would cover."""
223
+ return json.dumps(obj, sort_keys=True, separators=(",", ":"))