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,590 @@
|
|
|
1
|
+
"""``FormalWriter``: the one entry that writes the Formal Store and the capture archive (U6T-2b-b;
|
|
2
|
+
design U6T-2b v0.1, sections 2-4, W-1 to W-6).
|
|
3
|
+
|
|
4
|
+
* One writer per ``data_dir`` in this process (W-1): a module registry keyed by
|
|
5
|
+
``os.path.realpath(data_dir)``; ``writer_already_open`` for the second one.
|
|
6
|
+
* The writer owns the handles: the Formal Store (hekb-vnext ``IC04Store``, ``require_formal=True``),
|
|
7
|
+
the capture archive and the save order. None is handed out (W-2).
|
|
8
|
+
* Every write is one line in one queue: a lock held for a whole save, so the order contract/RAW ->
|
|
9
|
+
Gate -> put -> record is never interleaved with another capture's writes (W-3). Reads go through
|
|
10
|
+
the writer too, under the same lock (W-4).
|
|
11
|
+
* One hekb-vnext checkout per process (U6T-2 section 15, condition 2): ``hekb_checkout_conflict``.
|
|
12
|
+
* An outside write to a chain is detected before an append (not a lock; U6T-8 closes the window):
|
|
13
|
+
``store_changed_externally``, and the writer never writes again. A half-written last line of an
|
|
14
|
+
archive chain is set aside, evidence first, at open (see ``capture_chain``).
|
|
15
|
+
* An envelope that is in the Formal Store but in no capture record (the save stopped before the
|
|
16
|
+
record) is listed at open (``unrecorded_envelopes``). No record is written for it (N-2).
|
|
17
|
+
|
|
18
|
+
This is detection and convention, not an OS lock (W-5). hekb-vnext's other entries do not write a
|
|
19
|
+
Formal Store (W-6).
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import os
|
|
25
|
+
import threading
|
|
26
|
+
from collections.abc import Callable, Mapping
|
|
27
|
+
from datetime import datetime
|
|
28
|
+
from types import TracebackType
|
|
29
|
+
from typing import Any
|
|
30
|
+
|
|
31
|
+
from nvs_runtime.hidden_trajectory.capture_archive import CaptureArchive
|
|
32
|
+
from nvs_runtime.hidden_trajectory.capture_chain import ChainChangedExternally
|
|
33
|
+
from nvs_runtime.hidden_trajectory.formal_save import SaveResult, _CaptureSaver
|
|
34
|
+
from nvs_runtime.hidden_trajectory.k_measure import KMeasurer
|
|
35
|
+
from nvs_runtime.hidden_trajectory.run import _now
|
|
36
|
+
from nvs_runtime.integrations import hekb_formal
|
|
37
|
+
|
|
38
|
+
CHANGED_EXTERNALLY = "store_changed_externally"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class WriterError(RuntimeError):
|
|
42
|
+
"""``code``: writer_already_open, hekb_checkout_conflict, writer_closed, saver_not_configured,
|
|
43
|
+
store_changed_externally, wrong_payload, parent_not_stored, gate_not_configured."""
|
|
44
|
+
|
|
45
|
+
def __init__(self, code: str, detail: str = "") -> None:
|
|
46
|
+
super().__init__(f"{code}: {detail}" if detail else code)
|
|
47
|
+
self.code, self.detail = code, detail
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
_registry_lock = threading.Lock()
|
|
51
|
+
_registry: dict[str, FormalWriter] = {}
|
|
52
|
+
|
|
53
|
+
_TOKEN_TEMPORAL = ("nvs.token-temporal", "0.1.0")
|
|
54
|
+
_TRAJECTORY_WINDOW = ("msr.trajectory-window", "0.10.0")
|
|
55
|
+
_MEANING_FRAME = ("nvs.meaning-frame", "0.1.0")
|
|
56
|
+
_MEANING_MEASUREMENT = ("nvs.meaning-measurement", "0.1.0")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _schema_pair(envelope: Mapping[str, Any]) -> tuple[str, str]:
|
|
60
|
+
schema = envelope.get("payload_schema") if isinstance(envelope, Mapping) else None
|
|
61
|
+
if not isinstance(schema, Mapping):
|
|
62
|
+
return ("", "")
|
|
63
|
+
ident = schema.get("id")
|
|
64
|
+
version = schema.get("version")
|
|
65
|
+
return (
|
|
66
|
+
ident if isinstance(ident, str) else "",
|
|
67
|
+
version if isinstance(version, str) else "",
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _parent_ids(envelope: Mapping[str, Any], role: str | None = None) -> list[str]:
|
|
72
|
+
parents = envelope.get("parents")
|
|
73
|
+
if not isinstance(parents, list):
|
|
74
|
+
return []
|
|
75
|
+
found: list[str] = []
|
|
76
|
+
for entry in parents:
|
|
77
|
+
if not isinstance(entry, Mapping):
|
|
78
|
+
continue
|
|
79
|
+
if role is not None and entry.get("role") != role:
|
|
80
|
+
continue
|
|
81
|
+
ids = entry.get("artifact_ids")
|
|
82
|
+
if isinstance(ids, list):
|
|
83
|
+
found.extend(item for item in ids if isinstance(item, str) and item)
|
|
84
|
+
return found
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _lookup_entry(envelope: Mapping[str, Any]) -> dict[str, Any]:
|
|
88
|
+
return {
|
|
89
|
+
"content_id": envelope["content_id"],
|
|
90
|
+
"seq": envelope["seq"],
|
|
91
|
+
"observation_id": envelope["observation_id"],
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _open_store(hekb_vnext_root: str, data_dir: str) -> Any: # a seam for the tests without hekb
|
|
96
|
+
return hekb_formal._open_formal_store(hekb_vnext_root, data_dir)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _create_store(hekb_vnext_root: str, data_dir: str, declaration: Mapping[str, Any]) -> Any:
|
|
100
|
+
return hekb_formal._create_formal_store(hekb_vnext_root, data_dir, declaration)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class FormalWriter:
|
|
104
|
+
"""Make one with ``FormalWriter.create(...)`` (a new Formal Store) or ``FormalWriter.open(...)``
|
|
105
|
+
(an existing one); use it as a context manager or call ``close()``."""
|
|
106
|
+
|
|
107
|
+
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
|
108
|
+
raise TypeError("use FormalWriter.create(...) or FormalWriter.open(...)")
|
|
109
|
+
|
|
110
|
+
# ---- making one ----------------------------------------------------------------------------
|
|
111
|
+
@classmethod
|
|
112
|
+
def create(
|
|
113
|
+
cls,
|
|
114
|
+
data_dir: str | os.PathLike[str],
|
|
115
|
+
declaration: Mapping[str, Any],
|
|
116
|
+
*,
|
|
117
|
+
hekb_vnext_root: str | os.PathLike[str],
|
|
118
|
+
gate: Callable[..., Mapping[str, Any]] | None = None,
|
|
119
|
+
space_id_of: Callable[[Mapping[str, Any]], str] | None = None,
|
|
120
|
+
seal: Callable[[dict[str, Any], Mapping[str, Any]], dict[str, Any]] | None = None,
|
|
121
|
+
checker_bundle: bytes | Callable[[], bytes] | None = None,
|
|
122
|
+
clock: Callable[[], datetime] = _now,
|
|
123
|
+
k_path: bool = False,
|
|
124
|
+
key_source: Callable[[], bytes] | None = None,
|
|
125
|
+
k_measurer: KMeasurer | None = None,
|
|
126
|
+
) -> FormalWriter:
|
|
127
|
+
"""A new Formal Store (``create_formal``) in an empty folder, and the writer of it."""
|
|
128
|
+
return cls._make(
|
|
129
|
+
data_dir,
|
|
130
|
+
hekb_vnext_root,
|
|
131
|
+
declaration,
|
|
132
|
+
gate,
|
|
133
|
+
space_id_of,
|
|
134
|
+
seal,
|
|
135
|
+
checker_bundle,
|
|
136
|
+
clock,
|
|
137
|
+
(k_path, key_source, k_measurer),
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
@classmethod
|
|
141
|
+
def open(
|
|
142
|
+
cls,
|
|
143
|
+
data_dir: str | os.PathLike[str],
|
|
144
|
+
*,
|
|
145
|
+
hekb_vnext_root: str | os.PathLike[str],
|
|
146
|
+
gate: Callable[..., Mapping[str, Any]] | None = None,
|
|
147
|
+
space_id_of: Callable[[Mapping[str, Any]], str] | None = None,
|
|
148
|
+
seal: Callable[[dict[str, Any], Mapping[str, Any]], dict[str, Any]] | None = None,
|
|
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
|
+
) -> FormalWriter:
|
|
155
|
+
"""An existing Formal Store (``require_formal=True``) and its capture archive. Then
|
|
156
|
+
``unrecorded_envelopes`` says which stored envelopes have no capture record."""
|
|
157
|
+
return cls._make(
|
|
158
|
+
data_dir,
|
|
159
|
+
hekb_vnext_root,
|
|
160
|
+
None,
|
|
161
|
+
gate,
|
|
162
|
+
space_id_of,
|
|
163
|
+
seal,
|
|
164
|
+
checker_bundle,
|
|
165
|
+
clock,
|
|
166
|
+
(k_path, key_source, k_measurer),
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
@classmethod
|
|
170
|
+
def _make(
|
|
171
|
+
cls,
|
|
172
|
+
data_dir: str | os.PathLike[str],
|
|
173
|
+
hekb_vnext_root: str | os.PathLike[str],
|
|
174
|
+
declaration: Mapping[str, Any] | None,
|
|
175
|
+
gate: Any,
|
|
176
|
+
space_id_of: Any,
|
|
177
|
+
seal: Any,
|
|
178
|
+
checker_bundle: Any,
|
|
179
|
+
clock: Callable[[], datetime],
|
|
180
|
+
k: tuple[bool, Callable[[], bytes] | None, KMeasurer | None],
|
|
181
|
+
) -> FormalWriter:
|
|
182
|
+
key = os.path.realpath(os.fspath(data_dir))
|
|
183
|
+
with _registry_lock:
|
|
184
|
+
if key in _registry:
|
|
185
|
+
raise WriterError("writer_already_open", key)
|
|
186
|
+
try:
|
|
187
|
+
root = hekb_formal._claim_checkout(os.fspath(hekb_vnext_root))
|
|
188
|
+
except hekb_formal.CheckoutConflict as error:
|
|
189
|
+
raise WriterError("hekb_checkout_conflict", str(error)) from error
|
|
190
|
+
try:
|
|
191
|
+
self = object.__new__(cls)
|
|
192
|
+
self._init(
|
|
193
|
+
key, root, declaration, gate, space_id_of, seal, checker_bundle, clock, k
|
|
194
|
+
)
|
|
195
|
+
except BaseException:
|
|
196
|
+
hekb_formal._release_checkout()
|
|
197
|
+
raise
|
|
198
|
+
_registry[key] = self
|
|
199
|
+
return self
|
|
200
|
+
|
|
201
|
+
def _init(
|
|
202
|
+
self,
|
|
203
|
+
key: str,
|
|
204
|
+
root: str,
|
|
205
|
+
declaration: Mapping[str, Any] | None,
|
|
206
|
+
gate: Any,
|
|
207
|
+
space_id_of: Any,
|
|
208
|
+
seal: Any,
|
|
209
|
+
checker_bundle: bytes | Callable[[], bytes] | None,
|
|
210
|
+
clock: Callable[[], datetime],
|
|
211
|
+
k: tuple[bool, Callable[[], bytes] | None, KMeasurer | None],
|
|
212
|
+
) -> None:
|
|
213
|
+
self._key = key
|
|
214
|
+
self._lock = threading.RLock()
|
|
215
|
+
self._closed = False
|
|
216
|
+
self._dead: str | None = None
|
|
217
|
+
# the Formal Store first: a folder that is not one is left alone (no archive is made)
|
|
218
|
+
if declaration is None:
|
|
219
|
+
self._store = _open_store(root, key)
|
|
220
|
+
else:
|
|
221
|
+
self._store = _create_store(root, key, declaration)
|
|
222
|
+
self._archive = CaptureArchive(key, guarded=True)
|
|
223
|
+
self._archive.set_aside_torn_tails()
|
|
224
|
+
self._gate = gate
|
|
225
|
+
self._checker_bundle: bytes | Callable[[], bytes] | None = checker_bundle
|
|
226
|
+
self._saver: _CaptureSaver | None = None
|
|
227
|
+
if gate is not None and space_id_of is not None and seal is not None:
|
|
228
|
+
self._saver = _CaptureSaver(
|
|
229
|
+
store=self._store,
|
|
230
|
+
archive=self._archive,
|
|
231
|
+
gate=gate,
|
|
232
|
+
space_id_of=space_id_of,
|
|
233
|
+
seal=seal,
|
|
234
|
+
checker_bundle=checker_bundle,
|
|
235
|
+
clock=clock,
|
|
236
|
+
k_path=k[0],
|
|
237
|
+
key_source=k[1],
|
|
238
|
+
k_measurer=k[2],
|
|
239
|
+
)
|
|
240
|
+
self._unrecorded = tuple(self._find_unrecorded())
|
|
241
|
+
|
|
242
|
+
# ---- closing -------------------------------------------------------------------------------
|
|
243
|
+
def close(self) -> None:
|
|
244
|
+
"""Release the folder and the hekb-vnext checkout. The writer is unusable afterwards."""
|
|
245
|
+
with self._lock:
|
|
246
|
+
if self._closed:
|
|
247
|
+
return
|
|
248
|
+
self._closed = True
|
|
249
|
+
with _registry_lock:
|
|
250
|
+
if _registry.get(self._key) is self:
|
|
251
|
+
del _registry[self._key]
|
|
252
|
+
hekb_formal._release_checkout()
|
|
253
|
+
|
|
254
|
+
def __enter__(self) -> FormalWriter:
|
|
255
|
+
return self
|
|
256
|
+
|
|
257
|
+
def __exit__(
|
|
258
|
+
self,
|
|
259
|
+
exc_type: type[BaseException] | None,
|
|
260
|
+
exc: BaseException | None,
|
|
261
|
+
tb: TracebackType | None,
|
|
262
|
+
) -> None:
|
|
263
|
+
self.close()
|
|
264
|
+
|
|
265
|
+
@property
|
|
266
|
+
def closed(self) -> bool:
|
|
267
|
+
return self._closed
|
|
268
|
+
|
|
269
|
+
@property
|
|
270
|
+
def data_dir(self) -> str:
|
|
271
|
+
return self._key
|
|
272
|
+
|
|
273
|
+
@property
|
|
274
|
+
def dead(self) -> str | None:
|
|
275
|
+
"""Why this writer no longer writes (an outside write was seen), or ``None``."""
|
|
276
|
+
return self._dead
|
|
277
|
+
|
|
278
|
+
def _check_usable(self, *, writing: bool) -> None:
|
|
279
|
+
if self._closed:
|
|
280
|
+
raise WriterError("writer_closed", self._key)
|
|
281
|
+
if writing and self._dead:
|
|
282
|
+
raise WriterError(CHANGED_EXTERNALLY, self._dead)
|
|
283
|
+
|
|
284
|
+
# ---- writing -------------------------------------------------------------------------------
|
|
285
|
+
def save(self, captured: Any, **kwargs: Any) -> SaveResult:
|
|
286
|
+
"""Save one capture: contract and RAW -> Gate -> put (per envelope) -> the capture record,
|
|
287
|
+
last; see ``formal_save``. The whole order runs under the writer's lock. Another writer
|
|
288
|
+
seen on a chain (``store_changed_externally``) stops this writer for good: the record of
|
|
289
|
+
the capture in hand is written as far as it can be, and if it cannot, this raises."""
|
|
290
|
+
with self._lock:
|
|
291
|
+
self._check_usable(writing=True)
|
|
292
|
+
if self._saver is None:
|
|
293
|
+
raise WriterError("saver_not_configured", "gate, space_id_of and seal are needed")
|
|
294
|
+
try:
|
|
295
|
+
self._archive.check_unchanged() # before the first byte of this capture
|
|
296
|
+
result = self._saver.save(captured, **kwargs)
|
|
297
|
+
except ChainChangedExternally as error:
|
|
298
|
+
self._dead = str(error)
|
|
299
|
+
raise WriterError(CHANGED_EXTERNALLY, str(error)) from error
|
|
300
|
+
positions = result.record.get("positions", {})
|
|
301
|
+
seen = [
|
|
302
|
+
p["store_refusal"]["code"]
|
|
303
|
+
for p in positions.values()
|
|
304
|
+
if isinstance(p, dict) and p.get("store_refusal")
|
|
305
|
+
]
|
|
306
|
+
if CHANGED_EXTERNALLY in seen:
|
|
307
|
+
self._dead = "the Formal Store chain was written by somebody else"
|
|
308
|
+
elif self._archive.dead:
|
|
309
|
+
self._dead = self._archive.dead
|
|
310
|
+
return result
|
|
311
|
+
|
|
312
|
+
# ---- token temporal, window, frame, measurement (the capture save above is unchanged) --------
|
|
313
|
+
def save_token_or_window(
|
|
314
|
+
self, envelope: Mapping[str, Any], blobs: Mapping[str, bytes]
|
|
315
|
+
) -> dict[str, Any]:
|
|
316
|
+
"""Put a sealed ``nvs.token-temporal`` or ``msr.trajectory-window`` envelope.
|
|
317
|
+
|
|
318
|
+
The parent observation must already be in the store. Another payload is refused
|
|
319
|
+
before the Gate runs.
|
|
320
|
+
"""
|
|
321
|
+
with self._lock:
|
|
322
|
+
self._check_usable(writing=True)
|
|
323
|
+
self._refuse_other(envelope, (_TOKEN_TEMPORAL, _TRAJECTORY_WINDOW))
|
|
324
|
+
parents = _parent_ids(envelope)
|
|
325
|
+
if not parents:
|
|
326
|
+
raise WriterError("parent_not_stored", "the envelope has no parent")
|
|
327
|
+
stored, lookup = self._parents_from_store(parents)
|
|
328
|
+
return self._gate_and_put(
|
|
329
|
+
envelope, blobs, lookup=lookup, stored=stored, gate_blobs=dict(blobs)
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
def save_meaning_frame(
|
|
333
|
+
self, envelope: Mapping[str, Any], blobs: Mapping[str, bytes]
|
|
334
|
+
) -> dict[str, Any]:
|
|
335
|
+
"""Put a sealed ``nvs.meaning-frame`` envelope. A frame has no parents.
|
|
336
|
+
|
|
337
|
+
Whether an observation of ``source_space`` is in the store is not checked.
|
|
338
|
+
"""
|
|
339
|
+
with self._lock:
|
|
340
|
+
self._check_usable(writing=True)
|
|
341
|
+
self._refuse_other(envelope, (_MEANING_FRAME,))
|
|
342
|
+
return self._gate_and_put(
|
|
343
|
+
envelope, blobs, lookup={}, stored={}, gate_blobs=dict(blobs)
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
def save_meaning_measurement(
|
|
347
|
+
self,
|
|
348
|
+
envelope: Mapping[str, Any],
|
|
349
|
+
blobs: Mapping[str, bytes],
|
|
350
|
+
*,
|
|
351
|
+
include_frame_blobs: bool = True,
|
|
352
|
+
) -> dict[str, Any]:
|
|
353
|
+
"""Put a sealed ``nvs.meaning-measurement`` envelope.
|
|
354
|
+
|
|
355
|
+
The parent window, and the token-temporal parent when ``token_axis`` is present,
|
|
356
|
+
must already be in the store. The Gate is given those envelopes, the observation
|
|
357
|
+
the window names when it is stored, and any stored frame with the same
|
|
358
|
+
``frame_id``. ``include_frame_blobs`` false gives the Gate the frame envelope
|
|
359
|
+
and not its bytes.
|
|
360
|
+
"""
|
|
361
|
+
with self._lock:
|
|
362
|
+
self._check_usable(writing=True)
|
|
363
|
+
self._refuse_other(envelope, (_MEANING_MEASUREMENT,))
|
|
364
|
+
windows = _parent_ids(envelope, "source_window")
|
|
365
|
+
if len(windows) != 1:
|
|
366
|
+
raise WriterError("wrong_payload", "source_window")
|
|
367
|
+
parent_ids = [windows[0], *_parent_ids(envelope, "token_axis")]
|
|
368
|
+
stored, lookup = self._parents_from_store(parent_ids)
|
|
369
|
+
window = stored[windows[0]]["envelope"]
|
|
370
|
+
for artifact_id in _parent_ids(window):
|
|
371
|
+
held = self._store.get(artifact_id)
|
|
372
|
+
if held is not None:
|
|
373
|
+
stored[artifact_id] = {"envelope": held["envelope"]}
|
|
374
|
+
gate_blobs = dict(blobs)
|
|
375
|
+
payload = envelope.get("payload")
|
|
376
|
+
frame_id = payload.get("frame_id") if isinstance(payload, Mapping) else None
|
|
377
|
+
if isinstance(frame_id, str) and frame_id:
|
|
378
|
+
self._add_frames(stored, gate_blobs, frame_id, include_frame_blobs)
|
|
379
|
+
return self._gate_and_put(
|
|
380
|
+
envelope, blobs, lookup=lookup, stored=stored, gate_blobs=gate_blobs
|
|
381
|
+
)
|
|
382
|
+
|
|
383
|
+
def _refuse_other(
|
|
384
|
+
self, envelope: Mapping[str, Any], allowed: tuple[tuple[str, str], ...]
|
|
385
|
+
) -> None:
|
|
386
|
+
pair = _schema_pair(envelope)
|
|
387
|
+
if pair not in allowed:
|
|
388
|
+
raise WriterError("wrong_payload", f"{pair[0]} {pair[1]}".strip())
|
|
389
|
+
|
|
390
|
+
def _parents_from_store(
|
|
391
|
+
self, artifact_ids: list[str]
|
|
392
|
+
) -> tuple[dict[str, Any], dict[str, Any]]:
|
|
393
|
+
stored: dict[str, Any] = {}
|
|
394
|
+
lookup: dict[str, Any] = {}
|
|
395
|
+
for artifact_id in artifact_ids:
|
|
396
|
+
held = self._store.get(artifact_id)
|
|
397
|
+
if held is None:
|
|
398
|
+
raise WriterError("parent_not_stored", artifact_id)
|
|
399
|
+
stored[artifact_id] = {"envelope": held["envelope"]}
|
|
400
|
+
lookup[artifact_id] = _lookup_entry(held["envelope"])
|
|
401
|
+
return stored, lookup
|
|
402
|
+
|
|
403
|
+
def _add_frames(
|
|
404
|
+
self,
|
|
405
|
+
stored: dict[str, Any],
|
|
406
|
+
gate_blobs: dict[str, bytes],
|
|
407
|
+
frame_id: str,
|
|
408
|
+
include_frame_blobs: bool,
|
|
409
|
+
) -> None:
|
|
410
|
+
for artifact_id in self._stored_ids():
|
|
411
|
+
held = self._store.get(artifact_id)
|
|
412
|
+
if held is None:
|
|
413
|
+
continue
|
|
414
|
+
env = held["envelope"]
|
|
415
|
+
if _schema_pair(env) != _MEANING_FRAME:
|
|
416
|
+
continue
|
|
417
|
+
payload = env.get("payload") if isinstance(env, Mapping) else None
|
|
418
|
+
if not isinstance(payload, Mapping) or payload.get("frame_id") != frame_id:
|
|
419
|
+
continue
|
|
420
|
+
stored[artifact_id] = {"envelope": env}
|
|
421
|
+
if include_frame_blobs:
|
|
422
|
+
blobs = held.get("blobs")
|
|
423
|
+
if isinstance(blobs, Mapping):
|
|
424
|
+
gate_blobs.update(blobs)
|
|
425
|
+
|
|
426
|
+
def _bundle_bytes(self) -> bytes | None:
|
|
427
|
+
bundle = self._checker_bundle
|
|
428
|
+
if callable(bundle):
|
|
429
|
+
bundle = bundle()
|
|
430
|
+
self._checker_bundle = bundle
|
|
431
|
+
return bundle
|
|
432
|
+
|
|
433
|
+
def _gate_and_put(
|
|
434
|
+
self,
|
|
435
|
+
envelope: Mapping[str, Any],
|
|
436
|
+
blobs: Mapping[str, bytes],
|
|
437
|
+
*,
|
|
438
|
+
lookup: Mapping[str, Any],
|
|
439
|
+
stored: Mapping[str, Any],
|
|
440
|
+
gate_blobs: Mapping[str, bytes],
|
|
441
|
+
) -> dict[str, Any]:
|
|
442
|
+
"""Make the verdict, then ``IC04Store.put``. The caller holds the writer lock.
|
|
443
|
+
|
|
444
|
+
A refusal of the store (``IC04Error``) propagates with its code.
|
|
445
|
+
"""
|
|
446
|
+
if self._gate is None:
|
|
447
|
+
raise WriterError("gate_not_configured", "a gate is needed")
|
|
448
|
+
verdict = self._gate(
|
|
449
|
+
envelope, lookup=dict(lookup), stored=dict(stored), blobs=dict(gate_blobs)
|
|
450
|
+
)
|
|
451
|
+
receipt: dict[str, Any] = self._store.put(
|
|
452
|
+
dict(envelope),
|
|
453
|
+
dict(blobs),
|
|
454
|
+
gate_verdict=verdict,
|
|
455
|
+
checker_bundle=self._bundle_bytes(),
|
|
456
|
+
)
|
|
457
|
+
return receipt
|
|
458
|
+
|
|
459
|
+
# ---- reading (through the writer, W-4) -------------------------------------------------------
|
|
460
|
+
def get(self, artifact_id: str) -> dict[str, Any] | None:
|
|
461
|
+
with self._lock:
|
|
462
|
+
self._check_usable(writing=False)
|
|
463
|
+
held: dict[str, Any] | None = self._store.get(artifact_id)
|
|
464
|
+
return held
|
|
465
|
+
|
|
466
|
+
def gate_status(self, artifact_id: str) -> dict[str, Any] | None:
|
|
467
|
+
with self._lock:
|
|
468
|
+
self._check_usable(writing=False)
|
|
469
|
+
status: dict[str, Any] | None = self._store.gate_status(artifact_id)
|
|
470
|
+
return status
|
|
471
|
+
|
|
472
|
+
def records(self) -> list[dict[str, Any]]:
|
|
473
|
+
"""The capture records, in order (the chain is verified as it is read)."""
|
|
474
|
+
with self._lock:
|
|
475
|
+
self._check_usable(writing=False)
|
|
476
|
+
return list(self._archive.records())
|
|
477
|
+
|
|
478
|
+
def stored_artifact_ids(self) -> list[str]:
|
|
479
|
+
with self._lock:
|
|
480
|
+
self._check_usable(writing=False)
|
|
481
|
+
return self._stored_ids()
|
|
482
|
+
|
|
483
|
+
def torn_tails(self) -> list[dict[str, Any]]:
|
|
484
|
+
"""Every last line set aside: of the archive chains, then of the Formal Store chain."""
|
|
485
|
+
with self._lock:
|
|
486
|
+
self._check_usable(writing=False)
|
|
487
|
+
tails = self._archive.torn_tails()
|
|
488
|
+
of_store = getattr(self._store, "torn_tails", None)
|
|
489
|
+
return [*tails, *(of_store() if callable(of_store) else [])]
|
|
490
|
+
|
|
491
|
+
def observation(self, observation_id: str) -> dict[str, Any]:
|
|
492
|
+
"""Everything kept for one observation, read back (U6-6 design 4; a reading, not a recall):
|
|
493
|
+
the capture record, the contract, the id lists, and for each position the envelope and
|
|
494
|
+
GateVerdict of route R, the RAW file, and the K files of route K. Whatever is missing is
|
|
495
|
+
named in ``missing`` (nothing is left out silently). ``record`` is the latest capture record
|
|
496
|
+
of the observation."""
|
|
497
|
+
with self._lock:
|
|
498
|
+
self._check_usable(writing=False)
|
|
499
|
+
found = [
|
|
500
|
+
r for r in self._archive.records() if r.get("observation_id") == observation_id
|
|
501
|
+
]
|
|
502
|
+
if not found:
|
|
503
|
+
return {"observation_id": observation_id, "record": None, "missing": ["record"]}
|
|
504
|
+
record = found[-1]
|
|
505
|
+
missing: list[str] = []
|
|
506
|
+
contract_sha = record["contract"]["contract_sha256"]
|
|
507
|
+
contract = self._archive.read_contract(contract_sha) if contract_sha else None
|
|
508
|
+
if contract is None:
|
|
509
|
+
missing.append("contract")
|
|
510
|
+
id_lists: dict[str, bytes | None] = {}
|
|
511
|
+
if contract is not None:
|
|
512
|
+
for name, key in (
|
|
513
|
+
("input", "prompt_ids_sha256"),
|
|
514
|
+
("generated", "gen_token_ids_sha256"),
|
|
515
|
+
):
|
|
516
|
+
digest = contract["binding"].get(key)
|
|
517
|
+
id_lists[name] = self._archive.read_ids(digest) if digest else None
|
|
518
|
+
if id_lists[name] is None:
|
|
519
|
+
missing.append(f"ids.{name}")
|
|
520
|
+
trajectory = (
|
|
521
|
+
{p["point"]: p["trajectory_id"] for p in contract["positions"]} if contract else {}
|
|
522
|
+
)
|
|
523
|
+
positions: dict[str, Any] = {}
|
|
524
|
+
for point, entry in record["positions"].items():
|
|
525
|
+
item: dict[str, Any] = {
|
|
526
|
+
"trajectory_id": trajectory.get(point),
|
|
527
|
+
"envelope": None,
|
|
528
|
+
"gate_verdict": None,
|
|
529
|
+
"raw": None,
|
|
530
|
+
"k": None,
|
|
531
|
+
"k_path": entry.get("k_path"),
|
|
532
|
+
}
|
|
533
|
+
held = None
|
|
534
|
+
if entry.get("artifact_id"):
|
|
535
|
+
held = self._store.get(entry["artifact_id"])
|
|
536
|
+
if entry.get("stored") is not None:
|
|
537
|
+
if held is None:
|
|
538
|
+
missing.append(f"{point}.envelope")
|
|
539
|
+
else:
|
|
540
|
+
item["envelope"] = held["envelope"]
|
|
541
|
+
item["gate_verdict"] = held.get("gate_verdict")
|
|
542
|
+
tid = item["trajectory_id"]
|
|
543
|
+
if tid is not None:
|
|
544
|
+
item["raw"] = self._archive.raw_for_trajectory(tid)
|
|
545
|
+
if item["raw"] is None:
|
|
546
|
+
missing.append(f"{point}.raw")
|
|
547
|
+
k_entry = entry.get("k_path")
|
|
548
|
+
if k_entry is not None and k_entry["status"] == "measured":
|
|
549
|
+
board = self._archive.read_k(k_entry["board_records_sha256"])
|
|
550
|
+
causal = self._archive.read_k(k_entry["causal_log_sha256"])
|
|
551
|
+
item["k"] = {"board_records": board, "causal_log": causal}
|
|
552
|
+
if board is None:
|
|
553
|
+
missing.append(f"{point}.k.board_records")
|
|
554
|
+
if causal is None:
|
|
555
|
+
missing.append(f"{point}.k.causal_log")
|
|
556
|
+
positions[point] = item
|
|
557
|
+
return {
|
|
558
|
+
"observation_id": observation_id,
|
|
559
|
+
"record": record,
|
|
560
|
+
"contract": contract,
|
|
561
|
+
"ids": id_lists,
|
|
562
|
+
"positions": positions,
|
|
563
|
+
"missing": missing,
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
@property
|
|
567
|
+
def unrecorded_envelopes(self) -> tuple[str, ...]:
|
|
568
|
+
"""The ``artifact_id`` of every envelope that was in the Formal Store at open and in no
|
|
569
|
+
capture record's ``stored`` (the save stopped before its record). Nothing is written for
|
|
570
|
+
them."""
|
|
571
|
+
return self._unrecorded
|
|
572
|
+
|
|
573
|
+
def find_unrecorded(self) -> list[str]:
|
|
574
|
+
"""The same list, from the files as they are now."""
|
|
575
|
+
with self._lock:
|
|
576
|
+
self._check_usable(writing=False)
|
|
577
|
+
return self._find_unrecorded()
|
|
578
|
+
|
|
579
|
+
def _stored_ids(self) -> list[str]:
|
|
580
|
+
ids, _more = self._store.select({}, 10**9)
|
|
581
|
+
return list(ids)
|
|
582
|
+
|
|
583
|
+
def _find_unrecorded(self) -> list[str]:
|
|
584
|
+
recorded: set[str] = set()
|
|
585
|
+
for record in self._archive.records():
|
|
586
|
+
for position in record.get("positions", {}).values():
|
|
587
|
+
stored = position.get("stored") if isinstance(position, dict) else None
|
|
588
|
+
if isinstance(stored, dict) and isinstance(stored.get("artifact_id"), str):
|
|
589
|
+
recorded.add(stored["artifact_id"])
|
|
590
|
+
return [a for a in self._stored_ids() if a not in recorded]
|