nvs-runtime 1.0.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.
Files changed (94) hide show
  1. nvs_runtime/__init__.py +29 -0
  2. nvs_runtime/__version__.py +3 -0
  3. nvs_runtime/config/__init__.py +3 -0
  4. nvs_runtime/config/settings.py +26 -0
  5. nvs_runtime/core/__init__.py +6 -0
  6. nvs_runtime/core/clock.py +32 -0
  7. nvs_runtime/core/composition.py +92 -0
  8. nvs_runtime/core/errors.py +69 -0
  9. nvs_runtime/core/hext.py +43 -0
  10. nvs_runtime/core/models.py +151 -0
  11. nvs_runtime/core/protocols.py +77 -0
  12. nvs_runtime/core/runtime.py +373 -0
  13. nvs_runtime/events/__init__.py +4 -0
  14. nvs_runtime/events/bus.py +50 -0
  15. nvs_runtime/events/types.py +35 -0
  16. nvs_runtime/executors/__init__.py +2 -0
  17. nvs_runtime/governance/__init__.py +4 -0
  18. nvs_runtime/governance/engine.py +58 -0
  19. nvs_runtime/governance/quota.py +48 -0
  20. nvs_runtime/graph/__init__.py +3 -0
  21. nvs_runtime/graph/capability_graph.py +100 -0
  22. nvs_runtime/hidden_trajectory/__init__.py +62 -0
  23. nvs_runtime/hidden_trajectory/_gate_child.py +375 -0
  24. nvs_runtime/hidden_trajectory/adapter_loader.py +70 -0
  25. nvs_runtime/hidden_trajectory/canonical.py +22 -0
  26. nvs_runtime/hidden_trajectory/capture_archive.py +204 -0
  27. nvs_runtime/hidden_trajectory/capture_chain.py +319 -0
  28. nvs_runtime/hidden_trajectory/cli.py +765 -0
  29. nvs_runtime/hidden_trajectory/envelope.py +303 -0
  30. nvs_runtime/hidden_trajectory/formal_save.py +499 -0
  31. nvs_runtime/hidden_trajectory/formal_writer.py +590 -0
  32. nvs_runtime/hidden_trajectory/gate_client.py +460 -0
  33. nvs_runtime/hidden_trajectory/item_set.py +317 -0
  34. nvs_runtime/hidden_trajectory/k_measure.py +145 -0
  35. nvs_runtime/hidden_trajectory/model_catalog.py +56 -0
  36. nvs_runtime/hidden_trajectory/payload.py +382 -0
  37. nvs_runtime/hidden_trajectory/phase2/__init__.py +3 -0
  38. nvs_runtime/hidden_trajectory/phase2/evaluate.py +319 -0
  39. nvs_runtime/hidden_trajectory/phase2/geometry.py +80 -0
  40. nvs_runtime/hidden_trajectory/phase2/labels.py +72 -0
  41. nvs_runtime/hidden_trajectory/phase4/__init__.py +3 -0
  42. nvs_runtime/hidden_trajectory/phase4/normalize.py +171 -0
  43. nvs_runtime/hidden_trajectory/phase4/summary.py +270 -0
  44. nvs_runtime/hidden_trajectory/phase4b/__init__.py +3 -0
  45. nvs_runtime/hidden_trajectory/phase4b/load.py +46 -0
  46. nvs_runtime/hidden_trajectory/phase4b/metrics.py +96 -0
  47. nvs_runtime/hidden_trajectory/phase4b/scan.py +33 -0
  48. nvs_runtime/hidden_trajectory/record.py +334 -0
  49. nvs_runtime/hidden_trajectory/record_schema.py +781 -0
  50. nvs_runtime/hidden_trajectory/replay/__init__.py +6 -0
  51. nvs_runtime/hidden_trajectory/replay/risk_control.py +196 -0
  52. nvs_runtime/hidden_trajectory/rerun.py +302 -0
  53. nvs_runtime/hidden_trajectory/rsa/__init__.py +6 -0
  54. nvs_runtime/hidden_trajectory/rsa/analysis.py +248 -0
  55. nvs_runtime/hidden_trajectory/rsa/calibration.py +659 -0
  56. nvs_runtime/hidden_trajectory/rsa/compare.py +714 -0
  57. nvs_runtime/hidden_trajectory/rsa/readout.py +192 -0
  58. nvs_runtime/hidden_trajectory/run.py +362 -0
  59. nvs_runtime/hidden_trajectory/token_temporal.py +368 -0
  60. nvs_runtime/hidden_trajectory/window.py +344 -0
  61. nvs_runtime/integrations/__init__.py +4 -0
  62. nvs_runtime/integrations/hekb_formal.py +169 -0
  63. nvs_runtime/integrations/hekb_vnext.py +302 -0
  64. nvs_runtime/metrics/__init__.py +3 -0
  65. nvs_runtime/metrics/collector.py +63 -0
  66. nvs_runtime/observability/__init__.py +3 -0
  67. nvs_runtime/observability/store.py +44 -0
  68. nvs_runtime/planner/__init__.py +3 -0
  69. nvs_runtime/planner/planner.py +158 -0
  70. nvs_runtime/providers/__init__.py +19 -0
  71. nvs_runtime/providers/base.py +43 -0
  72. nvs_runtime/providers/edge.py +165 -0
  73. nvs_runtime/providers/grpc.py +58 -0
  74. nvs_runtime/providers/hekb.py +77 -0
  75. nvs_runtime/providers/http.py +59 -0
  76. nvs_runtime/providers/kernel.py +67 -0
  77. nvs_runtime/providers/local.py +88 -0
  78. nvs_runtime/providers/mcp.py +84 -0
  79. nvs_runtime/providers/registry.py +56 -0
  80. nvs_runtime/providers/replay.py +138 -0
  81. nvs_runtime/py.typed +0 -0
  82. nvs_runtime/security/__init__.py +4 -0
  83. nvs_runtime/security/cbac.py +106 -0
  84. nvs_runtime/security/signer.py +20 -0
  85. nvs_runtime/session/__init__.py +4 -0
  86. nvs_runtime/session/checkpoint.py +108 -0
  87. nvs_runtime/session/manager.py +149 -0
  88. nvs_runtime/transport/__init__.py +3 -0
  89. nvs_runtime/transport/memory.py +36 -0
  90. nvs_runtime-1.0.0.dist-info/METADATA +234 -0
  91. nvs_runtime-1.0.0.dist-info/RECORD +94 -0
  92. nvs_runtime-1.0.0.dist-info/WHEEL +4 -0
  93. nvs_runtime-1.0.0.dist-info/entry_points.txt +2 -0
  94. nvs_runtime-1.0.0.dist-info/licenses/LICENSE +190 -0
@@ -0,0 +1,499 @@
1
+ """The save of one capture into a Formal Store and the capture archive (U6T-2 design 7, U6T-2b').
2
+
3
+ ``CaptureSaver.save`` is the one entry that writes. In order:
4
+
5
+ 1. the contract and the capture are checked (nothing written yet);
6
+ 2. the contract document and the RAW files go to the capture archive (content hashes; never
7
+ rewritten);
8
+ 3. the envelopes are built (the caller's ``space_id_of`` and ``seal``);
9
+ 4. each envelope goes to the Gate (``GateClient.verdict``) and then to the Formal Store (``put``
10
+ with the GateVerdict);
11
+ 5. the capture record is appended to the archive **last**: a record is there only when what it names
12
+ was written before it.
13
+
14
+ **R-9: a record is always written.** A failure of ``space_id_of``, ``seal``, the archive write, the
15
+ Gate or the store does not lose
16
+ the capture: the record says which stage failed and why (see below), and what had been written stays
17
+ (append only). Only a failure
18
+ of the record's own append is raised (nothing may hide it). Not recorded, raised as before
19
+ (``run_capture_session``): a mistake of
20
+ the caller's data -- ``LookupMissing``, ``ParentEnvelopeMissing``, ``ParentMismatch`` -- which is
21
+ found before anything is written.
22
+
23
+ How a failure shows in the record (``outcome`` keeps its five values, see U6T-2 design 14):
24
+
25
+ * before an envelope exists (contract stage, contract check, archive write, ``space_id_of``,
26
+ ``seal``, building): ``outcome``
27
+ ``refused``, every position ``not_built`` with the reason ``<stage>_failed``, and a ``refusals``
28
+ line ``<stage>_failed: <type>: <message>``;
29
+ * the Gate failed for an envelope: the position is ``enveloped``, its ``gate.status`` is
30
+ ``gate_error`` and ``store_refusal`` is
31
+ ``gate_error`` (the store was not asked);
32
+ * the store refused an envelope (a ``code`` of its own, e.g. ``gate_rejected``) or raised: the
33
+ position is ``enveloped``,
34
+ ``stored`` is ``null``, ``store_refusal`` is ``{code, detail}`` (``put_failed`` for anything
35
+ without a code of its own);
36
+ * the store took it: ``stored`` is ``{artifact_id, hekb_seq, hekb_hash}``. ``verdict_sha256`` is
37
+ that of the verdict whenever there is one.
38
+
39
+ A parent: given a ``ParentRef`` and no ``parent_envelope``, the parent's envelope is read from the
40
+ Formal Store (``store.get``); a
41
+ parent the store does not have is ``ParentAbsent`` (a refusal record, nothing sent to the Gate).
42
+
43
+ ``store`` is any object with ``put(envelope, blobs, *, gate_verdict, checker_bundle)`` and
44
+ ``get(artifact_id)`` (a hekb-vnext
45
+ ``IC04Store`` opened with ``require_formal=True``; see ``integrations/hekb_formal.py``). This module
46
+ imports no hekb-vnext and no sensos.
47
+ """
48
+
49
+ from __future__ import annotations
50
+
51
+ import struct
52
+ from collections.abc import Callable, Mapping
53
+ from dataclasses import dataclass, field
54
+ from datetime import datetime
55
+ from typing import Any, Final
56
+
57
+ from nvs_observation.adapter_session import CapturedWithOrigin
58
+ from nvs_observation.contract_build import ContractBuild, contract_from_captured
59
+ from nvs_observation.contract_check import ContractCheck, check_contract_v2, rows_from_raw
60
+
61
+ from nvs_runtime.hidden_trajectory import record as rec
62
+ from nvs_runtime.hidden_trajectory.capture_archive import CaptureArchive
63
+ from nvs_runtime.hidden_trajectory.envelope import (
64
+ BuildResult,
65
+ EnvelopeIds,
66
+ ParentRef,
67
+ build_envelopes,
68
+ )
69
+ from nvs_runtime.hidden_trajectory.gate_client import (
70
+ LookupMissing,
71
+ ParentAbsent,
72
+ ParentEnvelopeMissing,
73
+ ParentMismatch,
74
+ missing_lookup,
75
+ )
76
+ from nvs_runtime.hidden_trajectory.k_measure import (
77
+ KMeasurer,
78
+ default_k_measurer,
79
+ default_key_source,
80
+ )
81
+ from nvs_runtime.hidden_trajectory.payload import POLICY_ALL_ROWS
82
+ from nvs_runtime.hidden_trajectory.record_schema import MAX_REFUSAL_DETAIL_CHARS
83
+ from nvs_runtime.hidden_trajectory.run import (
84
+ GATE_ERROR,
85
+ STAGE_BUILT,
86
+ STAGE_EMPTY_GENERATION,
87
+ STAGE_REFUSED,
88
+ _gate_fields,
89
+ _gate_inputs,
90
+ _now,
91
+ _parent_differences,
92
+ _parent_not_stored_record,
93
+ _without_contract,
94
+ with_capture_extra,
95
+ )
96
+
97
+ #: ``SaveResult.stage`` besides the three of ``run.py``: where a save stopped.
98
+ STAGE_FAILED_PREFIX: Final = "failed:"
99
+ _FETCH: Final = object()
100
+
101
+
102
+ @dataclass(frozen=True)
103
+ class SaveResult:
104
+ """``record`` is what was appended (and ``line`` its chain line). ``receipts``: point -> the
105
+ store's receipt of a stored envelope;
106
+ ``store_refusals``: point -> ``{code, detail}``; ``archived`` says what the archive wrote
107
+ (``written`` false = it was there already)."""
108
+
109
+ record: dict[str, Any]
110
+ line: dict[str, Any]
111
+ stage: str
112
+ envelopes: dict[str, dict[str, Any]] = field(default_factory=dict)
113
+ verdicts: dict[str, Mapping[str, Any]] = field(default_factory=dict)
114
+ receipts: dict[str, dict[str, Any]] = field(default_factory=dict)
115
+ store_refusals: dict[str, dict[str, str]] = field(default_factory=dict)
116
+ gate_errors: dict[str, str] = field(default_factory=dict)
117
+ contract: dict[str, Any] | None = None
118
+ archived: dict[str, Any] = field(default_factory=dict)
119
+ k_paths: dict[str, dict[str, Any]] = field(default_factory=dict)
120
+
121
+
122
+ def _detail(error: BaseException) -> str:
123
+ text = f"{type(error).__name__}: {error}"
124
+ return (
125
+ text
126
+ if len(text) <= MAX_REFUSAL_DETAIL_CHARS
127
+ else text[: MAX_REFUSAL_DETAIL_CHARS - 3] + "..."
128
+ )
129
+
130
+
131
+ class _CaptureSaver:
132
+ """The save order of one capture (internal: ``FormalWriter`` is the only entry that owns a
133
+ Formal Store handle and calls this, under its lock; U6T-2b-b).
134
+
135
+ ``store``: the Formal Store handle; ``archive``: a ``CaptureArchive`` of the same ``data_dir``;
136
+ ``gate``: ``GateClient.verdict``;
137
+ ``checker_bundle``: the bytes of the checker bundle, or a function that makes them (called once,
138
+ when a ``put`` first needs it);
139
+ ``space_id_of`` and ``seal``: the caller's (sensos's, through the door)."""
140
+
141
+ def __init__(
142
+ self,
143
+ *,
144
+ store: Any,
145
+ archive: CaptureArchive,
146
+ gate: Callable[..., Mapping[str, Any]],
147
+ space_id_of: Callable[[Mapping[str, Any]], str],
148
+ seal: Callable[[dict[str, Any], Mapping[str, Any]], dict[str, Any]],
149
+ checker_bundle: bytes | Callable[[], bytes] | None = None,
150
+ clock: Callable[[], datetime] = _now,
151
+ k_path: bool = False,
152
+ key_source: Callable[[], bytes] | None = None,
153
+ k_measurer: KMeasurer | None = None,
154
+ ) -> None:
155
+ """``k_path`` (U6-6a): also keep the id lists and run route K for each position that has a
156
+ RAW file; off, the save is what it was. The measurement is ``k_measurer`` when one was
157
+ passed, and otherwise the measurer found through the ``nvs_runtime.k_measurer`` entry point
158
+ (with none installed K is recorded as not measured). ``key_source`` is for tests. When it is
159
+ omitted, the default key is chosen when K is measured, not when the saver is made."""
160
+ self._k_path = k_path
161
+ self._k_measurer = k_measurer
162
+ self._key_source = key_source
163
+ self._store, self._archive, self._gate = store, archive, gate
164
+ self._space_id_of, self._seal = space_id_of, seal
165
+ self._bundle = checker_bundle
166
+ self._clock = clock
167
+
168
+ # ---- helpers --------------------------------------------------------------------------
169
+ def _bundle_bytes(self) -> bytes | None:
170
+ if callable(self._bundle):
171
+ self._bundle = self._bundle()
172
+ return self._bundle
173
+
174
+ def _finish(self, record: dict[str, Any], stage: str, **parts: Any) -> SaveResult:
175
+ """Append the record (the last write). A failure here is not hidden."""
176
+ line = self._archive.append_record(record)
177
+ return SaveResult(record=record, line=line, stage=stage, **parts)
178
+
179
+ def _failed(
180
+ self,
181
+ code: str,
182
+ error: BaseException,
183
+ ids: EnvelopeIds,
184
+ build: ContractBuild | None,
185
+ check: ContractCheck | None,
186
+ **parts: Any,
187
+ ) -> SaveResult:
188
+ """The record of a save that stopped before an envelope existed."""
189
+ line = f"{code}: {_detail(error)}"
190
+ if build is None:
191
+ capture = rec.capture_block_of_contract(None)
192
+ document: Any = None
193
+ extra = None
194
+ else:
195
+ capture = build.capture_block or rec.capture_block_of_contract(build.contract)
196
+ document = build.contract
197
+ extra = build.capture_extra
198
+ contract_session = document.get("session_id") if isinstance(document, Mapping) else None
199
+ record = rec.build_record(
200
+ session_id=ids.session_id,
201
+ observation_id=ids.observation_id,
202
+ contract_session_id=contract_session if isinstance(contract_session, str) else None,
203
+ capture=capture,
204
+ contract_status=check.status if check is not None else rec.CONTRACT_NONE,
205
+ contract_sha256=check.contract_sha256 if check is not None else None,
206
+ hash_source=check.hash_source if check is not None else rec.CONTRACT_NONE,
207
+ refusals=[line],
208
+ positions={
209
+ point: rec.position_entry(rec.POSITION_NOT_BUILT, (code,))
210
+ for point in dict.fromkeys(capture.get("points") or [])
211
+ },
212
+ )
213
+ if extra is not None:
214
+ record = with_capture_extra(record, extra)
215
+ return self._finish(
216
+ record,
217
+ f"{STAGE_FAILED_PREFIX}{code}",
218
+ contract=document if isinstance(document, dict) else None,
219
+ **parts,
220
+ )
221
+
222
+ def _archive_ids(self, build: ContractBuild, captured: CapturedWithOrigin) -> dict[str, Any]:
223
+ """The id lists, as little-endian int64 (how the contract hashes them), under the contract's
224
+ own hashes. Bytes that do not hash to the contract's value are refused
225
+ (``ArchiveError``)."""
226
+ assert build.contract is not None
227
+ binding = build.contract["binding"]
228
+ done: dict[str, Any] = {}
229
+ for name, hash_key, attribute in (
230
+ ("input", "prompt_ids_sha256", "prompt_ids"),
231
+ ("generated", "gen_token_ids_sha256", "token_ids"),
232
+ ):
233
+ values = [int(v) for v in getattr(captured.capture, attribute)]
234
+ data = struct.pack(f"<{len(values)}q", *values)
235
+ written = self._archive.write_ids(data, binding[hash_key])
236
+ done[name] = {"sha256": binding[hash_key], "written": written}
237
+ return done
238
+
239
+ def _archive_contract(self, build: ContractBuild, check: ContractCheck) -> dict[str, Any]:
240
+ assert build.contract is not None
241
+ if (
242
+ check.contract_sha256 is None
243
+ ): # the contract was not verified: nothing is kept as if it were
244
+ return {"contract_sha256": None, "contract_written": False, "raw": {}}
245
+ document = build.contract
246
+ written = self._archive.write_contract(document, check.contract_sha256)
247
+ trajectory_ids = {p["point"]: p["trajectory_id"] for p in document["positions"]}
248
+ raw = self._archive.write_raw(build.raw_bytes, trajectory_ids)
249
+ return {"contract_sha256": check.contract_sha256, "contract_written": written, "raw": raw}
250
+
251
+ # ---- the save -------------------------------------------------------------------------
252
+ def save(
253
+ self,
254
+ captured: CapturedWithOrigin,
255
+ *,
256
+ contract_session_id: str,
257
+ synthetic: bool,
258
+ ids: EnvelopeIds,
259
+ parent: ParentRef | None = None,
260
+ parent_envelope: Mapping[str, Any] | ParentAbsent | None | object = _FETCH,
261
+ producer_build: str | None = None,
262
+ session_extensions: Mapping[str, Any] | None = None,
263
+ extensions: Mapping[str, Mapping[str, Any]] | None = None,
264
+ copied: bool = False,
265
+ policy_name: str = POLICY_ALL_ROWS,
266
+ ) -> SaveResult:
267
+ """Save one capture; see the module docstring. ``parent_envelope`` left out means "read it
268
+ from the Formal Store"; ``None`` means
269
+ "not fetched" (``ParentEnvelopeMissing``), a ``ParentAbsent`` says the caller asked the
270
+ store and the parent is not there."""
271
+ try:
272
+ build = contract_from_captured(
273
+ captured, session_id=contract_session_id, synthetic=synthetic, clock=self._clock
274
+ )
275
+ except Exception as error: # noqa: BLE001 -- R-9: the capture is not lost
276
+ return self._failed(rec.REASON_CONTRACT_STAGE_FAILED, error, ids, None, None)
277
+ if build.contract is None or build.capture_extra is None:
278
+ record, stage = _without_contract(build, ids)
279
+ return self._finish(record, stage)
280
+ try:
281
+ check = check_contract_v2(
282
+ build.contract,
283
+ raw_bytes=build.raw_bytes,
284
+ instrument_records=build.instrument_records,
285
+ )
286
+ except Exception as error: # noqa: BLE001
287
+ return self._failed(rec.REASON_CONTRACT_CHECK_FAILED, error, ids, build, None)
288
+
289
+ # the caller's mistakes are found before anything is written
290
+ if parent is not None and parent_envelope is _FETCH:
291
+ held = self._store.get(parent.artifact_id)
292
+ parent_envelope = (
293
+ held["envelope"]
294
+ if held is not None
295
+ else ParentAbsent(parent.artifact_id, "formal-store")
296
+ )
297
+ if parent is not None and isinstance(parent_envelope, ParentAbsent):
298
+ if parent_envelope.artifact_id != parent.artifact_id:
299
+ raise ParentMismatch(
300
+ {"artifact_id": (parent.artifact_id, parent_envelope.artifact_id)}
301
+ )
302
+ elif parent is not None:
303
+ if parent_envelope is None:
304
+ raise ParentEnvelopeMissing(parent.artifact_id)
305
+ assert isinstance(parent_envelope, Mapping)
306
+ differences = _parent_differences(parent, parent_envelope)
307
+ if differences:
308
+ raise ParentMismatch(differences)
309
+
310
+ # 1. the contract and the RAW files
311
+ try:
312
+ archived = self._archive_contract(build, check)
313
+ if self._k_path and check.contract_sha256 is not None:
314
+ archived["ids"] = self._archive_ids(build, captured)
315
+ except Exception as error: # noqa: BLE001
316
+ return self._failed(rec.REASON_ARCHIVE_WRITE_FAILED, error, ids, build, check)
317
+ if parent is not None and isinstance(parent_envelope, ParentAbsent):
318
+ record = _parent_not_stored_record(parent_envelope, build, check, ids)
319
+ return self._finish(record, STAGE_REFUSED, contract=build.contract, archived=archived)
320
+
321
+ # 2. the envelopes (the caller's space_id_of and seal; which one failed is told)
322
+ failing: list[str] = []
323
+
324
+ def space_id_of(materials: Mapping[str, Any]) -> str:
325
+ try:
326
+ return self._space_id_of(materials)
327
+ except BaseException:
328
+ failing.append(rec.REASON_SPACE_ID_FAILED)
329
+ raise
330
+
331
+ def seal(envelope: dict[str, Any], lookup: Mapping[str, Any]) -> dict[str, Any]:
332
+ try:
333
+ return self._seal(envelope, lookup)
334
+ except BaseException:
335
+ failing.append(rec.REASON_SEAL_FAILED)
336
+ raise
337
+
338
+ try:
339
+ built: BuildResult = build_envelopes(
340
+ build.contract,
341
+ check,
342
+ ids=ids,
343
+ space_id_of=space_id_of,
344
+ seal=seal,
345
+ rows=rows_from_raw(build.raw_bytes),
346
+ parent=parent,
347
+ producer_build=producer_build,
348
+ session_extensions=session_extensions,
349
+ extensions=extensions,
350
+ copied=copied,
351
+ policy_name=policy_name,
352
+ )
353
+ except Exception as error: # noqa: BLE001
354
+ code = failing[0] if failing else rec.REASON_BUILD_FAILED
355
+ return self._failed(code, error, ids, build, check, archived=archived)
356
+ record = with_capture_extra(built.record, build.capture_extra)
357
+
358
+ # 3. the Gate and the store, envelope by envelope
359
+ stored_parent = parent_envelope if isinstance(parent_envelope, Mapping) else None
360
+ lookup, stored = _gate_inputs(parent, stored_parent)
361
+ verdicts: dict[str, Mapping[str, Any]] = {}
362
+ gate_errors: dict[str, str] = {}
363
+ receipts: dict[str, dict[str, Any]] = {}
364
+ refusals: dict[str, dict[str, str]] = {}
365
+ for envelope in built.envelopes.values():
366
+ if missing_lookup(envelope, lookup):
367
+ raise LookupMissing(missing_lookup(envelope, lookup))
368
+ for point, envelope in built.envelopes.items():
369
+ verdict: Mapping[str, Any] | None = None
370
+ try:
371
+ verdict = self._gate(
372
+ envelope,
373
+ lookup=lookup,
374
+ stored=stored,
375
+ blobs=built.blobs,
376
+ contract_facts=check.facts,
377
+ )
378
+ status, violations, unverifiable = _gate_fields(verdict)
379
+ except Exception as error: # noqa: BLE001
380
+ verdict = None
381
+ gate_errors[point] = f"{type(error).__name__}: {error}"
382
+ status, violations = GATE_ERROR, []
383
+ unverifiable = [{"check": "gate_call", "reason": type(error).__name__}]
384
+ refusals[point] = {"code": rec.STORE_GATE_ERROR, "detail": _detail(error)}
385
+ else:
386
+ verdicts[point] = verdict
387
+ record = rec.with_gate_result(
388
+ record, point, status=status, violations=violations, unverifiable=unverifiable
389
+ )
390
+ stored_entry: dict[str, Any] | None = None
391
+ if verdict is not None:
392
+ try:
393
+ receipt = self._store.put(
394
+ envelope,
395
+ _blobs_of(envelope, built.blobs),
396
+ gate_verdict=verdict,
397
+ checker_bundle=self._bundle_bytes(),
398
+ )
399
+ except Exception as error: # noqa: BLE001 -- a refusal (it has a code) or a failure of the store
400
+ own = getattr(error, "code", None)
401
+ refusals[point] = {
402
+ "code": own if isinstance(own, str) and own else rec.STORE_PUT_FAILED,
403
+ "detail": _detail(error),
404
+ }
405
+ else:
406
+ receipts[point] = receipt
407
+ stored_entry = {
408
+ "artifact_id": receipt["artifact_id"],
409
+ "hekb_seq": receipt["hekb_seq"],
410
+ "hekb_hash": receipt["hekb_hash"],
411
+ }
412
+ record = rec.with_store_result(
413
+ record,
414
+ point,
415
+ stored=stored_entry,
416
+ verdict_sha256=None if verdict is None else verdict.get("verdict_sha256"),
417
+ store_refusal=refusals.get(point),
418
+ )
419
+
420
+ # 3b. route K, position by position (never stops R; a key lives only in ``run_position``)
421
+ k_paths: dict[str, dict[str, Any]] = {}
422
+ if self._k_path and check.contract_sha256 is not None:
423
+ record, k_paths, archived["k"] = self._run_k(record, build, ids)
424
+
425
+ # 4. the record, last
426
+ return self._finish(
427
+ record,
428
+ STAGE_BUILT,
429
+ envelopes=built.envelopes,
430
+ verdicts=verdicts,
431
+ receipts=receipts,
432
+ store_refusals=refusals,
433
+ gate_errors=gate_errors,
434
+ contract=build.contract,
435
+ archived=archived,
436
+ k_paths=k_paths,
437
+ )
438
+
439
+ def _run_k(
440
+ self, record: dict[str, Any], build: ContractBuild, ids: EnvelopeIds
441
+ ) -> tuple[dict[str, Any], dict[str, dict[str, Any]], dict[str, Any]]:
442
+ """K for each position with a RAW file: ``(record with k_path, k_paths, what was kept)``."""
443
+ assert build.contract is not None
444
+ origin = build.contract.get("origin", {})
445
+ trajectory = {p["point"]: p["trajectory_id"] for p in build.contract["positions"]}
446
+ k_paths: dict[str, dict[str, Any]] = {}
447
+ kept: dict[str, Any] = {}
448
+ measurer = self._k_measurer if self._k_measurer is not None else default_k_measurer()
449
+ key_source = self._key_source if self._key_source is not None else default_key_source()
450
+ for point, raw in build.raw_bytes.items():
451
+ outcome = measurer.run_position(
452
+ observation_id=ids.observation_id,
453
+ point=point,
454
+ raw_bytes=raw,
455
+ trajectory_id=trajectory.get(point),
456
+ model_build_id=origin.get("model_build_id"),
457
+ compute_environment=origin.get("compute_environment"),
458
+ key_source=key_source,
459
+ )
460
+ entry = outcome.k_path
461
+ if outcome.board is not None and outcome.causal is not None:
462
+ try:
463
+ board = self._archive.write_k(outcome.board)
464
+ causal = self._archive.write_k(outcome.causal)
465
+ kept[point] = {"board": board, "causal": causal}
466
+ except Exception: # noqa: BLE001 -- nothing of K is claimed that was not kept
467
+ entry = {
468
+ **entry,
469
+ "status": rec.K_NOT_MEASURED,
470
+ "reason": rec.REASON_K_ARCHIVE_WRITE_FAILED,
471
+ "board_records_sha256": None,
472
+ "causal_log_sha256": None,
473
+ "chain_head": None,
474
+ "integrity": None,
475
+ }
476
+ k_paths[point] = entry
477
+ record = rec.with_k_path(record, point, entry)
478
+ return record, k_paths, kept
479
+
480
+
481
+ def _blobs_of(envelope: Mapping[str, Any], blobs: Mapping[str, bytes]) -> dict[str, bytes]:
482
+ """The Blobs this envelope names (its points and token index), from all the Blobs of the
483
+ capture."""
484
+ payload = envelope.get("payload")
485
+ uris = [
486
+ (payload.get(key) or {}).get("uri")
487
+ for key in ("points", "token_index")
488
+ if isinstance(payload, Mapping)
489
+ ]
490
+ return {uri: blobs[uri] for uri in uris if isinstance(uri, str) and uri in blobs}
491
+
492
+
493
+ __all__ = [
494
+ "STAGE_BUILT",
495
+ "STAGE_EMPTY_GENERATION",
496
+ "STAGE_FAILED_PREFIX",
497
+ "STAGE_REFUSED",
498
+ "SaveResult",
499
+ ]