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.
- nvs_runtime/__init__.py +29 -0
- nvs_runtime/__version__.py +3 -0
- nvs_runtime/config/__init__.py +3 -0
- nvs_runtime/config/settings.py +26 -0
- nvs_runtime/core/__init__.py +6 -0
- nvs_runtime/core/clock.py +32 -0
- nvs_runtime/core/composition.py +92 -0
- nvs_runtime/core/errors.py +69 -0
- nvs_runtime/core/hext.py +43 -0
- nvs_runtime/core/models.py +151 -0
- nvs_runtime/core/protocols.py +77 -0
- nvs_runtime/core/runtime.py +373 -0
- nvs_runtime/events/__init__.py +4 -0
- nvs_runtime/events/bus.py +50 -0
- nvs_runtime/events/types.py +35 -0
- nvs_runtime/executors/__init__.py +2 -0
- nvs_runtime/governance/__init__.py +4 -0
- nvs_runtime/governance/engine.py +58 -0
- nvs_runtime/governance/quota.py +48 -0
- nvs_runtime/graph/__init__.py +3 -0
- nvs_runtime/graph/capability_graph.py +100 -0
- nvs_runtime/hidden_trajectory/__init__.py +62 -0
- nvs_runtime/hidden_trajectory/_gate_child.py +375 -0
- nvs_runtime/hidden_trajectory/adapter_loader.py +70 -0
- nvs_runtime/hidden_trajectory/canonical.py +22 -0
- nvs_runtime/hidden_trajectory/capture_archive.py +204 -0
- nvs_runtime/hidden_trajectory/capture_chain.py +319 -0
- nvs_runtime/hidden_trajectory/cli.py +765 -0
- nvs_runtime/hidden_trajectory/envelope.py +303 -0
- nvs_runtime/hidden_trajectory/formal_save.py +499 -0
- nvs_runtime/hidden_trajectory/formal_writer.py +590 -0
- nvs_runtime/hidden_trajectory/gate_client.py +460 -0
- nvs_runtime/hidden_trajectory/item_set.py +317 -0
- nvs_runtime/hidden_trajectory/k_measure.py +145 -0
- nvs_runtime/hidden_trajectory/model_catalog.py +56 -0
- nvs_runtime/hidden_trajectory/payload.py +382 -0
- nvs_runtime/hidden_trajectory/phase2/__init__.py +3 -0
- nvs_runtime/hidden_trajectory/phase2/evaluate.py +319 -0
- nvs_runtime/hidden_trajectory/phase2/geometry.py +80 -0
- nvs_runtime/hidden_trajectory/phase2/labels.py +72 -0
- nvs_runtime/hidden_trajectory/phase4/__init__.py +3 -0
- nvs_runtime/hidden_trajectory/phase4/normalize.py +171 -0
- nvs_runtime/hidden_trajectory/phase4/summary.py +270 -0
- nvs_runtime/hidden_trajectory/phase4b/__init__.py +3 -0
- nvs_runtime/hidden_trajectory/phase4b/load.py +46 -0
- nvs_runtime/hidden_trajectory/phase4b/metrics.py +96 -0
- nvs_runtime/hidden_trajectory/phase4b/scan.py +33 -0
- nvs_runtime/hidden_trajectory/record.py +334 -0
- nvs_runtime/hidden_trajectory/record_schema.py +781 -0
- nvs_runtime/hidden_trajectory/replay/__init__.py +6 -0
- nvs_runtime/hidden_trajectory/replay/risk_control.py +196 -0
- nvs_runtime/hidden_trajectory/rerun.py +302 -0
- nvs_runtime/hidden_trajectory/rsa/__init__.py +6 -0
- nvs_runtime/hidden_trajectory/rsa/analysis.py +248 -0
- nvs_runtime/hidden_trajectory/rsa/calibration.py +659 -0
- nvs_runtime/hidden_trajectory/rsa/compare.py +714 -0
- nvs_runtime/hidden_trajectory/rsa/readout.py +192 -0
- nvs_runtime/hidden_trajectory/run.py +362 -0
- nvs_runtime/hidden_trajectory/token_temporal.py +368 -0
- nvs_runtime/hidden_trajectory/window.py +344 -0
- nvs_runtime/integrations/__init__.py +4 -0
- nvs_runtime/integrations/hekb_formal.py +169 -0
- nvs_runtime/integrations/hekb_vnext.py +302 -0
- nvs_runtime/metrics/__init__.py +3 -0
- nvs_runtime/metrics/collector.py +63 -0
- nvs_runtime/observability/__init__.py +3 -0
- nvs_runtime/observability/store.py +44 -0
- nvs_runtime/planner/__init__.py +3 -0
- nvs_runtime/planner/planner.py +158 -0
- nvs_runtime/providers/__init__.py +19 -0
- nvs_runtime/providers/base.py +43 -0
- nvs_runtime/providers/edge.py +165 -0
- nvs_runtime/providers/grpc.py +58 -0
- nvs_runtime/providers/hekb.py +77 -0
- nvs_runtime/providers/http.py +59 -0
- nvs_runtime/providers/kernel.py +67 -0
- nvs_runtime/providers/local.py +88 -0
- nvs_runtime/providers/mcp.py +84 -0
- nvs_runtime/providers/registry.py +56 -0
- nvs_runtime/providers/replay.py +138 -0
- nvs_runtime/py.typed +0 -0
- nvs_runtime/security/__init__.py +4 -0
- nvs_runtime/security/cbac.py +106 -0
- nvs_runtime/security/signer.py +20 -0
- nvs_runtime/session/__init__.py +4 -0
- nvs_runtime/session/checkpoint.py +108 -0
- nvs_runtime/session/manager.py +149 -0
- nvs_runtime/transport/__init__.py +3 -0
- nvs_runtime/transport/memory.py +36 -0
- nvs_runtime-1.0.0.dist-info/METADATA +234 -0
- nvs_runtime-1.0.0.dist-info/RECORD +94 -0
- nvs_runtime-1.0.0.dist-info/WHEEL +4 -0
- nvs_runtime-1.0.0.dist-info/entry_points.txt +2 -0
- nvs_runtime-1.0.0.dist-info/licenses/LICENSE +190 -0
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
"""Assemble one ``msr.trajectory-window`` 0.10.0 envelope from a stored observation.
|
|
2
|
+
|
|
3
|
+
The rows are the blob named by ``raw_ref.trajectory_id``. The caller passes the
|
|
4
|
+
blob reader, the space id, and the sealer. This module does not call the Gate
|
|
5
|
+
or the Formal Store, and it does not import MSR.
|
|
6
|
+
|
|
7
|
+
``envelope.build_envelope`` seals an ``nvs.hidden-trajectory`` for
|
|
8
|
+
``sensos-inference``. A window is a different schema and producer
|
|
9
|
+
(``nvs-runtime``, parent role ``source_trajectory``), so the envelope is
|
|
10
|
+
assembled here and sealed with the same ``seal(envelope, lookup)`` callback
|
|
11
|
+
that builder uses. IC-00 1.1.0 is ``envelope.IC00_VERSION``.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import hashlib
|
|
17
|
+
import math
|
|
18
|
+
import re
|
|
19
|
+
import struct
|
|
20
|
+
from collections.abc import Callable, Mapping
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from nvs_runtime.__version__ import __version__
|
|
25
|
+
from nvs_runtime.hidden_trajectory.envelope import IC00_VERSION
|
|
26
|
+
from nvs_runtime.hidden_trajectory.payload import MEDIA_TYPE, blob_uri, token_index_bytes
|
|
27
|
+
|
|
28
|
+
SCHEMA_ID = "nvs.hidden-trajectory"
|
|
29
|
+
SCHEMA_VERSION = "0.1.0"
|
|
30
|
+
WINDOW_SCHEMA = {"id": "msr.trajectory-window", "version": "0.10.0"}
|
|
31
|
+
WINDOW_RULE = "rows"
|
|
32
|
+
SPACE_RULE = "nvs.hidden-trajectory.space/1"
|
|
33
|
+
PRODUCER_NAME = "nvs-runtime"
|
|
34
|
+
PARENT_ROLE = "source_trajectory"
|
|
35
|
+
SOURCE = "T-hid"
|
|
36
|
+
|
|
37
|
+
_PLACEHOLDER_CONTENT = "cnt:" + "0" * 64
|
|
38
|
+
_PLACEHOLDER_ARTIFACT = "art:" + "0" * 64
|
|
39
|
+
_HEX64 = re.compile(r"[0-9a-f]{64}")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class WindowInputError(Exception):
|
|
43
|
+
"""A required value is missing or does not match. Nothing is filled in."""
|
|
44
|
+
|
|
45
|
+
def __init__(self, field: str, detail: str) -> None:
|
|
46
|
+
super().__init__(f"{field}: {detail}")
|
|
47
|
+
self.field = field
|
|
48
|
+
self.detail = detail
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True, slots=True)
|
|
52
|
+
class WindowArtifact:
|
|
53
|
+
"""A sealed window, the stored parent the Gate compares, and the bytes it reads.
|
|
54
|
+
|
|
55
|
+
``stored_parent`` is ``artifact_id -> {"envelope": observation}``.
|
|
56
|
+
``lookup`` is the IC-00 parent entry. ``blobs`` maps ``uri`` to bytes.
|
|
57
|
+
``origin`` is ``trajectory_id``, ``position``, ``length``, ``dimension``.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
envelope: dict[str, Any]
|
|
61
|
+
stored_parent: dict[str, Any]
|
|
62
|
+
blobs: dict[str, bytes]
|
|
63
|
+
lookup: dict[str, Any]
|
|
64
|
+
origin: dict[str, Any]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def observation_origin(observation_envelope: Mapping[str, Any]) -> dict[str, Any]:
|
|
68
|
+
"""The parent fields the Gate reads back: trajectory id, length, position, dimension.
|
|
69
|
+
|
|
70
|
+
``dimension`` is the parent's value, the same type the window declares (W-1).
|
|
71
|
+
"""
|
|
72
|
+
payload = _payload(observation_envelope)
|
|
73
|
+
raw_ref = payload.get("raw_ref")
|
|
74
|
+
if not isinstance(raw_ref, Mapping) or "trajectory_id" not in raw_ref:
|
|
75
|
+
raise WindowInputError("raw_ref.trajectory_id", "not in the observation payload")
|
|
76
|
+
for key in ("length", "position", "dimension"):
|
|
77
|
+
if key not in payload:
|
|
78
|
+
raise WindowInputError(key, "not in the observation payload")
|
|
79
|
+
return {
|
|
80
|
+
"trajectory_id": raw_ref["trajectory_id"],
|
|
81
|
+
"length": payload["length"],
|
|
82
|
+
"position": payload["position"],
|
|
83
|
+
"dimension": payload["dimension"],
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def stored_parent_of(observation_envelope: Mapping[str, Any]) -> dict[str, Any]:
|
|
88
|
+
"""The Gate's ``stored`` map for this observation: one ``{"envelope": ...}``."""
|
|
89
|
+
artifact_id = observation_envelope.get("artifact_id")
|
|
90
|
+
if not isinstance(artifact_id, str) or not artifact_id:
|
|
91
|
+
raise WindowInputError("artifact_id", "the observation has no artifact_id")
|
|
92
|
+
return {artifact_id: {"envelope": observation_envelope}}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def build_window_artifact(
|
|
96
|
+
observation_envelope: Mapping[str, Any],
|
|
97
|
+
blob_reader: Callable[[str], bytes],
|
|
98
|
+
*,
|
|
99
|
+
start: int = 0,
|
|
100
|
+
length: int | None = None,
|
|
101
|
+
producer_build: str,
|
|
102
|
+
space_id_of: Callable[[Mapping[str, Any]], str],
|
|
103
|
+
seal: Callable[[dict[str, Any], Mapping[str, Any]], dict[str, Any]],
|
|
104
|
+
) -> WindowArtifact:
|
|
105
|
+
"""The sealed window of ``observation_envelope``.
|
|
106
|
+
|
|
107
|
+
``blob_reader(sha256)`` returns the blob bytes. ``length is None`` takes the
|
|
108
|
+
rows from ``start`` through the end of the origin. ``start + length`` must
|
|
109
|
+
not pass ``origin.length``. ``producer_build`` is the IC-00 build; it is not
|
|
110
|
+
a field of the observation. ``space_id_of(materials)`` and
|
|
111
|
+
``seal(envelope, lookup)`` are the existing sensos operations. The same
|
|
112
|
+
arguments seal the same envelope: no clock and no random value is written.
|
|
113
|
+
"""
|
|
114
|
+
if not isinstance(producer_build, str) or not producer_build:
|
|
115
|
+
raise WindowInputError(
|
|
116
|
+
"producer.build", "IC-00 requires a non-empty build; none was given"
|
|
117
|
+
)
|
|
118
|
+
_require_observation(observation_envelope)
|
|
119
|
+
payload = _payload(observation_envelope)
|
|
120
|
+
origin = observation_origin(observation_envelope)
|
|
121
|
+
origin_length = _integer("length", origin["length"], minimum=1)
|
|
122
|
+
dimension = origin["dimension"]
|
|
123
|
+
if type(dimension) is not int or dimension < 1:
|
|
124
|
+
raise WindowInputError("dimension", f"{dimension!r} is not an integer >= 1")
|
|
125
|
+
start = _integer("start", start, minimum=0)
|
|
126
|
+
if length is None:
|
|
127
|
+
window_length = origin_length - start
|
|
128
|
+
else:
|
|
129
|
+
window_length = _integer("length", length, minimum=1)
|
|
130
|
+
if window_length < 1 or start + window_length > origin_length:
|
|
131
|
+
raise WindowInputError(
|
|
132
|
+
"window",
|
|
133
|
+
f"start {start} + length {window_length} exceeds origin.length {origin_length}",
|
|
134
|
+
)
|
|
135
|
+
_need(
|
|
136
|
+
payload,
|
|
137
|
+
"position",
|
|
138
|
+
"layer",
|
|
139
|
+
"source",
|
|
140
|
+
"model_build_id",
|
|
141
|
+
"compute_environment",
|
|
142
|
+
"row_rule",
|
|
143
|
+
"points",
|
|
144
|
+
"token_index",
|
|
145
|
+
)
|
|
146
|
+
if payload["source"] != SOURCE:
|
|
147
|
+
raise WindowInputError("source", f"observation source is {payload['source']!r}")
|
|
148
|
+
points_ref = payload["points"]
|
|
149
|
+
token_ref = payload["token_index"]
|
|
150
|
+
if not isinstance(points_ref, Mapping) or "unit" not in points_ref:
|
|
151
|
+
raise WindowInputError("points.unit", "not in the observation payload")
|
|
152
|
+
if not isinstance(token_ref, Mapping) or "sha256" not in token_ref or "unit" not in token_ref:
|
|
153
|
+
raise WindowInputError("token_index", "the observation blob ref has no sha256 or unit")
|
|
154
|
+
if points_ref.get("shape") != [origin_length, dimension]:
|
|
155
|
+
raise WindowInputError(
|
|
156
|
+
"dimension",
|
|
157
|
+
f"points.shape {points_ref.get('shape')!r} != [{origin_length}, {dimension}]",
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
trajectory_id = origin["trajectory_id"]
|
|
161
|
+
if not isinstance(trajectory_id, str) or _HEX64.fullmatch(trajectory_id) is None:
|
|
162
|
+
raise WindowInputError("raw_ref.trajectory_id", "not a sha256 hex string")
|
|
163
|
+
points = _read(blob_reader, trajectory_id, "points")
|
|
164
|
+
expected_bytes = origin_length * dimension * 4
|
|
165
|
+
if len(points) != expected_bytes:
|
|
166
|
+
raise WindowInputError(
|
|
167
|
+
"points",
|
|
168
|
+
f"{len(points)} bytes, expected {origin_length} x {dimension} x 4",
|
|
169
|
+
)
|
|
170
|
+
if hashlib.sha256(points).hexdigest() != trajectory_id:
|
|
171
|
+
raise WindowInputError("sha256", "sha256 of the rows is not raw_ref.trajectory_id")
|
|
172
|
+
values = struct.unpack(f"<{origin_length * dimension}f", points)
|
|
173
|
+
if not all(math.isfinite(value) for value in values):
|
|
174
|
+
raise WindowInputError("points", "a NaN or an infinity")
|
|
175
|
+
|
|
176
|
+
token_bytes = _read(blob_reader, token_ref["sha256"], "token_index")
|
|
177
|
+
if len(token_bytes) != origin_length * 8:
|
|
178
|
+
raise WindowInputError(
|
|
179
|
+
"token_index",
|
|
180
|
+
f"{len(token_bytes)} bytes, expected {origin_length * 8}",
|
|
181
|
+
)
|
|
182
|
+
if hashlib.sha256(token_bytes).hexdigest() != token_ref["sha256"]:
|
|
183
|
+
raise WindowInputError("sha256", "sha256 of token_index does not match the reference")
|
|
184
|
+
if token_bytes != token_index_bytes(origin_length):
|
|
185
|
+
raise WindowInputError("token_index", "the stored index is not 0 .. length-1")
|
|
186
|
+
|
|
187
|
+
row = dimension * 4
|
|
188
|
+
window_points = points[start * row : (start + window_length) * row]
|
|
189
|
+
window_tokens = token_bytes[start * 8 : (start + window_length) * 8]
|
|
190
|
+
point_sha = hashlib.sha256(window_points).hexdigest()
|
|
191
|
+
token_sha = hashlib.sha256(window_tokens).hexdigest()
|
|
192
|
+
policy_name = f"rows-{start}+{window_length}/1"
|
|
193
|
+
derived_rule = f"{payload['row_rule']}+rows{start}+{window_length}/1"
|
|
194
|
+
space_id = space_id_of(
|
|
195
|
+
{
|
|
196
|
+
"model_build_id": payload["model_build_id"],
|
|
197
|
+
"layer": payload["layer"],
|
|
198
|
+
"row_rule": derived_rule,
|
|
199
|
+
"compute_environment": payload["compute_environment"],
|
|
200
|
+
"dimension": dimension,
|
|
201
|
+
"space_rule": SPACE_RULE,
|
|
202
|
+
}
|
|
203
|
+
)
|
|
204
|
+
window_payload = {
|
|
205
|
+
"window": {
|
|
206
|
+
"rule": WINDOW_RULE,
|
|
207
|
+
"start": start,
|
|
208
|
+
"length": window_length,
|
|
209
|
+
"content_sha256": point_sha,
|
|
210
|
+
},
|
|
211
|
+
"origin": {
|
|
212
|
+
"trajectory_id": trajectory_id,
|
|
213
|
+
"position": payload["position"],
|
|
214
|
+
"length": origin_length,
|
|
215
|
+
},
|
|
216
|
+
"source": payload["source"],
|
|
217
|
+
"layer": payload["layer"],
|
|
218
|
+
"dimension": dimension,
|
|
219
|
+
"model_build_id": payload["model_build_id"],
|
|
220
|
+
"policy": {
|
|
221
|
+
"name": policy_name,
|
|
222
|
+
"sha256": hashlib.sha256(policy_name.encode("utf-8")).hexdigest(),
|
|
223
|
+
},
|
|
224
|
+
"points": {
|
|
225
|
+
"uri": blob_uri(point_sha),
|
|
226
|
+
"sha256": point_sha,
|
|
227
|
+
"media_type": MEDIA_TYPE,
|
|
228
|
+
"dtype": "float32",
|
|
229
|
+
"shape": [window_length, dimension],
|
|
230
|
+
"byte_order": "little",
|
|
231
|
+
"order": "C",
|
|
232
|
+
"unit": points_ref["unit"],
|
|
233
|
+
},
|
|
234
|
+
"token_index": {
|
|
235
|
+
"uri": blob_uri(token_sha),
|
|
236
|
+
"sha256": token_sha,
|
|
237
|
+
"media_type": MEDIA_TYPE,
|
|
238
|
+
"dtype": "int64",
|
|
239
|
+
"shape": [window_length],
|
|
240
|
+
"byte_order": "little",
|
|
241
|
+
"order": "C",
|
|
242
|
+
"quantization": None,
|
|
243
|
+
"unit": token_ref["unit"],
|
|
244
|
+
},
|
|
245
|
+
}
|
|
246
|
+
lookup = {
|
|
247
|
+
observation_envelope["artifact_id"]: {
|
|
248
|
+
"content_id": observation_envelope["content_id"],
|
|
249
|
+
"seq": observation_envelope["seq"],
|
|
250
|
+
"observation_id": observation_envelope["observation_id"],
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
envelope = {
|
|
254
|
+
"contract": {"id": "IC-00", "version": IC00_VERSION},
|
|
255
|
+
"content_id": _PLACEHOLDER_CONTENT,
|
|
256
|
+
"artifact_id": _PLACEHOLDER_ARTIFACT,
|
|
257
|
+
"kind": "observation",
|
|
258
|
+
"payload_schema": dict(WINDOW_SCHEMA),
|
|
259
|
+
"payload": window_payload,
|
|
260
|
+
"producer": {
|
|
261
|
+
"name": PRODUCER_NAME,
|
|
262
|
+
"version": __version__,
|
|
263
|
+
"build": producer_build,
|
|
264
|
+
},
|
|
265
|
+
"session_id": observation_envelope["session_id"],
|
|
266
|
+
"observation_id": observation_envelope["observation_id"],
|
|
267
|
+
"event_span": None,
|
|
268
|
+
"space_id": space_id,
|
|
269
|
+
"parents": [
|
|
270
|
+
{
|
|
271
|
+
"role": PARENT_ROLE,
|
|
272
|
+
"ordered": False,
|
|
273
|
+
"artifact_ids": [observation_envelope["artifact_id"]],
|
|
274
|
+
}
|
|
275
|
+
],
|
|
276
|
+
"policy_refs": [],
|
|
277
|
+
"calibration_ref": None,
|
|
278
|
+
"rule_refs": [],
|
|
279
|
+
"observed_at": None,
|
|
280
|
+
"seq": observation_envelope["seq"] + 1,
|
|
281
|
+
"produced_at": observation_envelope["produced_at"],
|
|
282
|
+
"extensions": {},
|
|
283
|
+
}
|
|
284
|
+
sealed = seal(dict(envelope), lookup)
|
|
285
|
+
return WindowArtifact(
|
|
286
|
+
envelope=sealed,
|
|
287
|
+
stored_parent=stored_parent_of(observation_envelope),
|
|
288
|
+
blobs={
|
|
289
|
+
window_payload["points"]["uri"]: window_points,
|
|
290
|
+
window_payload["token_index"]["uri"]: window_tokens,
|
|
291
|
+
},
|
|
292
|
+
lookup=lookup,
|
|
293
|
+
origin=origin,
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _payload(observation_envelope: Mapping[str, Any]) -> Mapping[str, Any]:
|
|
298
|
+
payload = observation_envelope.get("payload")
|
|
299
|
+
if not isinstance(payload, Mapping):
|
|
300
|
+
raise WindowInputError("payload", "the observation has no payload")
|
|
301
|
+
return payload
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _require_observation(observation_envelope: Mapping[str, Any]) -> None:
|
|
305
|
+
schema = observation_envelope.get("payload_schema")
|
|
306
|
+
if not isinstance(schema, Mapping) or (
|
|
307
|
+
schema.get("id"),
|
|
308
|
+
schema.get("version"),
|
|
309
|
+
) != (SCHEMA_ID, SCHEMA_VERSION):
|
|
310
|
+
raise WindowInputError(
|
|
311
|
+
"payload_schema", "the observation is not nvs.hidden-trajectory 0.1.0"
|
|
312
|
+
)
|
|
313
|
+
for key in ("artifact_id", "content_id", "session_id", "observation_id", "produced_at"):
|
|
314
|
+
if not observation_envelope.get(key):
|
|
315
|
+
raise WindowInputError(key, "not on the observation envelope")
|
|
316
|
+
seq = observation_envelope.get("seq")
|
|
317
|
+
if type(seq) is not int or seq < 0:
|
|
318
|
+
raise WindowInputError("seq", f"{seq!r} is not an integer >= 0")
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _need(payload: Mapping[str, Any], *keys: str) -> None:
|
|
322
|
+
for key in keys:
|
|
323
|
+
if key not in payload:
|
|
324
|
+
raise WindowInputError(key, "not in the observation payload")
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _integer(field: str, value: Any, *, minimum: int) -> int:
|
|
328
|
+
if type(value) is not int or value < minimum:
|
|
329
|
+
raise WindowInputError(field, f"{value!r} is not an integer >= {minimum}")
|
|
330
|
+
return value
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _read(blob_reader: Callable[[str], bytes], digest: str, field: str) -> bytes:
|
|
334
|
+
if not isinstance(digest, str) or _HEX64.fullmatch(digest) is None:
|
|
335
|
+
raise WindowInputError(field, "sha256 is not 64 hex characters")
|
|
336
|
+
try:
|
|
337
|
+
data = blob_reader(digest)
|
|
338
|
+
except WindowInputError:
|
|
339
|
+
raise
|
|
340
|
+
except Exception as error:
|
|
341
|
+
raise WindowInputError(field, f"the blob could not be read: {error}") from error
|
|
342
|
+
if not isinstance(data, (bytes, bytearray)):
|
|
343
|
+
raise WindowInputError(field, "the reader did not return bytes")
|
|
344
|
+
return bytes(data)
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
"""Adapters that map nvs-runtime's protocol-only boundary onto a specific sibling
|
|
2
|
+
service's real wire format (e.g. ``hekb_vnext.py`` -> hekb-vnext's ``/v3/*`` HTTP API).
|
|
3
|
+
Not providers themselves -- providers (``nvs_runtime.providers``) depend on these only
|
|
4
|
+
through the protocols in ``nvs_runtime.core.protocols`` (e.g. ``ObjectStore``)."""
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""Open a hekb-vnext Formal Store for the save (U6T-2b').
|
|
2
|
+
|
|
3
|
+
nvs-runtime reaches hekb-vnext the way ``hekb_vnext.py`` does: lazily, from a checkout
|
|
4
|
+
(``hekb_vnext_root``), by name. Nothing
|
|
5
|
+
here imports at module load, and nothing of sensos is imported (by design, no cross-imports):
|
|
6
|
+
the Formal Store is a
|
|
7
|
+
hekb-vnext object, and nvs-runtime
|
|
8
|
+
only calls ``put(envelope, blobs, *, gate_verdict, checker_bundle)``, ``get`` and ``gate_status`` on
|
|
9
|
+
it (``formal_save.py``).
|
|
10
|
+
Only ``FormalWriter`` (U6T-2b-b) opens a Formal Store, once, with ``require_formal=True``; the names
|
|
11
|
+
here are internal.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import importlib
|
|
17
|
+
import os
|
|
18
|
+
import sys
|
|
19
|
+
import threading
|
|
20
|
+
from collections.abc import Mapping
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class HekbFormalUnavailable(RuntimeError):
|
|
26
|
+
"""The hekb-vnext checkout has no ``graph.ic04`` with a Formal Store."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
#: The top-level packages of a hekb-vnext checkout that the Formal Store reads. Two checkouts (or
|
|
30
|
+
#: worktrees) have the same names, so
|
|
31
|
+
#: one already loaded from another place has to be dropped before the one asked for is imported.
|
|
32
|
+
_PACKAGES = ("graph", "vendor")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _activate(hekb_vnext_root: Path | str) -> str:
|
|
36
|
+
"""Put the checkout first on ``sys.path`` and drop ``graph`` / ``vendor`` modules loaded from
|
|
37
|
+
any other place."""
|
|
38
|
+
root = Path(hekb_vnext_root).resolve()
|
|
39
|
+
for name in list(sys.modules):
|
|
40
|
+
if name.split(".")[0] not in _PACKAGES:
|
|
41
|
+
continue
|
|
42
|
+
file = getattr(sys.modules[name], "__file__", None) or ""
|
|
43
|
+
paths = [str(p) for p in getattr(sys.modules[name], "__path__", [])]
|
|
44
|
+
places = [file, *paths]
|
|
45
|
+
if places and not any(Path(p).resolve().is_relative_to(root) for p in places if p):
|
|
46
|
+
del sys.modules[name]
|
|
47
|
+
text = str(root)
|
|
48
|
+
if text in sys.path:
|
|
49
|
+
sys.path.remove(text)
|
|
50
|
+
sys.path.insert(0, text)
|
|
51
|
+
return text
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _has_regular_package(entry: str) -> bool:
|
|
55
|
+
try:
|
|
56
|
+
return any((Path(entry) / name / "__init__.py").is_file() for name in _PACKAGES)
|
|
57
|
+
except (OSError, ValueError):
|
|
58
|
+
return False
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _load_hekb_module(hekb_vnext_root: Path | str, name: str) -> Any:
|
|
62
|
+
"""A module of the hekb-vnext checkout by name (``graph.formal``, ``graph.chainlog``...).
|
|
63
|
+
|
|
64
|
+
Another checkout whose ``graph`` has an ``__init__.py`` would win over this one's namespace
|
|
65
|
+
``graph`` while it is on ``sys.path``; so, for the import only, the other entries that hold such
|
|
66
|
+
a package are left out."""
|
|
67
|
+
root = _activate(hekb_vnext_root)
|
|
68
|
+
saved = list(sys.path)
|
|
69
|
+
sys.path[:] = [root, *(p for p in saved if p != root and not _has_regular_package(p))]
|
|
70
|
+
try:
|
|
71
|
+
return importlib.import_module(name)
|
|
72
|
+
except ImportError as error:
|
|
73
|
+
raise HekbFormalUnavailable(
|
|
74
|
+
f"cannot import {name} from the hekb-vnext checkout given: {error}"
|
|
75
|
+
) from error
|
|
76
|
+
finally:
|
|
77
|
+
sys.path[:] = [root, *(p for p in saved if p != root)]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _store_class(hekb_vnext_root: Path | str) -> Any:
|
|
81
|
+
try:
|
|
82
|
+
module = _load_hekb_module(hekb_vnext_root, "graph.ic04")
|
|
83
|
+
cls = module.IC04Store
|
|
84
|
+
if not hasattr(cls, "create_formal"):
|
|
85
|
+
raise AttributeError("IC04Store.create_formal")
|
|
86
|
+
except (HekbFormalUnavailable, AttributeError) as error:
|
|
87
|
+
raise HekbFormalUnavailable(
|
|
88
|
+
f"no Formal Store in the hekb-vnext checkout given: {error}"
|
|
89
|
+
) from error
|
|
90
|
+
return cls
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _create_formal_store(
|
|
94
|
+
hekb_vnext_root: Path | str, data_dir: Path | str, declaration: Mapping[str, Any]
|
|
95
|
+
) -> Any:
|
|
96
|
+
"""``IC04Store.create_formal``: a new Formal Store in an empty folder, opened with
|
|
97
|
+
``require_formal=True``."""
|
|
98
|
+
return _store_class(hekb_vnext_root).create_formal(data_dir, declaration)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _open_formal_store(hekb_vnext_root: Path | str, data_dir: Path | str) -> Any:
|
|
102
|
+
"""``IC04Store(data_dir, require_formal=True)``: an existing Formal Store (it raises
|
|
103
|
+
``IC04Error`` if it is not one)."""
|
|
104
|
+
return _store_class(hekb_vnext_root)(data_dir, require_formal=True)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
# ------------------------------------------------------------
|
|
108
|
+
# One hekb-vnext checkout per process (U6T-2 section 15, condition 2). ``graph`` / ``vendor`` are
|
|
109
|
+
# top-level names: two checkouts cannot both be loaded, and swapping one under an open Formal Store
|
|
110
|
+
# would change the classes it runs on. ``FormalWriter`` claims the checkout it was given before it
|
|
111
|
+
# opens a store and releases it on close.
|
|
112
|
+
# ------------------------------------------------------------
|
|
113
|
+
class CheckoutConflict(RuntimeError):
|
|
114
|
+
"""Another hekb-vnext checkout is in use in this process."""
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
_WATCHED = ("graph", "vendor", "storage") # ``storage`` is what the older hekb_vnext.py imports
|
|
118
|
+
_claim_lock = threading.Lock()
|
|
119
|
+
_claimed_root: str | None = (
|
|
120
|
+
None # the checkout this module loaded from (kept after the last release)
|
|
121
|
+
)
|
|
122
|
+
_claims = 0 # open writers using it
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _module_places(module: Any) -> list[str]:
|
|
126
|
+
places = [getattr(module, "__file__", None) or "", *map(str, getattr(module, "__path__", []))]
|
|
127
|
+
return [p for p in places if p]
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _under(path: str, root: str) -> bool:
|
|
131
|
+
try:
|
|
132
|
+
return Path(path).resolve().is_relative_to(root)
|
|
133
|
+
except (OSError, ValueError):
|
|
134
|
+
return False
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _claim_checkout(hekb_vnext_root: Path | str) -> str:
|
|
138
|
+
"""Claim the checkout for one writer; ``CheckoutConflict`` if another one is in use here, either
|
|
139
|
+
by an open writer or because ``graph`` / ``vendor`` / ``storage`` of another checkout is
|
|
140
|
+
already loaded (for example by the older ``hekb_vnext.py``)."""
|
|
141
|
+
global _claimed_root, _claims
|
|
142
|
+
root = os.path.realpath(str(hekb_vnext_root))
|
|
143
|
+
with _claim_lock:
|
|
144
|
+
if _claims and _claimed_root != root:
|
|
145
|
+
raise CheckoutConflict(
|
|
146
|
+
f"a writer already uses the hekb-vnext checkout {_claimed_root}; this one is {root}"
|
|
147
|
+
)
|
|
148
|
+
for name in _WATCHED:
|
|
149
|
+
module = sys.modules.get(name)
|
|
150
|
+
if module is None:
|
|
151
|
+
continue
|
|
152
|
+
places = _module_places(module)
|
|
153
|
+
ours = bool(_claimed_root) and not _claims # an earlier writer's, all closed: replaced
|
|
154
|
+
# a namespace package can list several checkouts; it is ours if one of them is
|
|
155
|
+
mine = any(_under(p, root) or (ours and _under(p, _claimed_root or "")) for p in places)
|
|
156
|
+
if places and not mine:
|
|
157
|
+
raise CheckoutConflict(
|
|
158
|
+
f"the module {name} is already loaded from {places[0]}, not from the "
|
|
159
|
+
f"checkout {root}"
|
|
160
|
+
)
|
|
161
|
+
_claimed_root = root
|
|
162
|
+
_claims += 1
|
|
163
|
+
return root
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _release_checkout() -> None:
|
|
167
|
+
global _claims
|
|
168
|
+
with _claim_lock:
|
|
169
|
+
_claims = max(0, _claims - 1)
|