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,62 @@
|
|
|
1
|
+
"""The ``nvs.hidden-trajectory`` path of nvs-runtime: from a RawObservationContract v2 to the Gate.
|
|
2
|
+
|
|
3
|
+
This package calls the owners of the rules and reimplements none of them: the contract's
|
|
4
|
+
structure and hash are checked by ``nvs_observation.contract_check``; the space id, the artifact
|
|
5
|
+
ids and the checks are sensos's (the contracts Gate).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from nvs_runtime.hidden_trajectory.envelope import (
|
|
11
|
+
BuildResult,
|
|
12
|
+
EnvelopeIds,
|
|
13
|
+
ParentRef,
|
|
14
|
+
build_envelope,
|
|
15
|
+
build_envelopes,
|
|
16
|
+
contract_ref_of,
|
|
17
|
+
session_refusals,
|
|
18
|
+
)
|
|
19
|
+
from nvs_runtime.hidden_trajectory.payload import (
|
|
20
|
+
PAYLOAD_SCHEMA_ID,
|
|
21
|
+
PAYLOAD_SCHEMA_VERSION,
|
|
22
|
+
POLICY_ALL_ROWS,
|
|
23
|
+
PayloadNotBuilt,
|
|
24
|
+
blob_uri,
|
|
25
|
+
build_payload,
|
|
26
|
+
kind_of,
|
|
27
|
+
legacy_position,
|
|
28
|
+
position_obstacles,
|
|
29
|
+
session_obstacles,
|
|
30
|
+
token_index_bytes,
|
|
31
|
+
)
|
|
32
|
+
from nvs_runtime.hidden_trajectory.record import (
|
|
33
|
+
RECORD_VERSION,
|
|
34
|
+
capture_block,
|
|
35
|
+
empty_generation_record,
|
|
36
|
+
with_gate_result,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
__all__ = [
|
|
40
|
+
"PAYLOAD_SCHEMA_ID",
|
|
41
|
+
"PAYLOAD_SCHEMA_VERSION",
|
|
42
|
+
"POLICY_ALL_ROWS",
|
|
43
|
+
"RECORD_VERSION",
|
|
44
|
+
"BuildResult",
|
|
45
|
+
"EnvelopeIds",
|
|
46
|
+
"ParentRef",
|
|
47
|
+
"PayloadNotBuilt",
|
|
48
|
+
"blob_uri",
|
|
49
|
+
"build_envelope",
|
|
50
|
+
"build_envelopes",
|
|
51
|
+
"build_payload",
|
|
52
|
+
"capture_block",
|
|
53
|
+
"contract_ref_of",
|
|
54
|
+
"empty_generation_record",
|
|
55
|
+
"kind_of",
|
|
56
|
+
"legacy_position",
|
|
57
|
+
"position_obstacles",
|
|
58
|
+
"session_obstacles",
|
|
59
|
+
"session_refusals",
|
|
60
|
+
"token_index_bytes",
|
|
61
|
+
"with_gate_result",
|
|
62
|
+
]
|
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
"""The child process of the Gate (design U6T-1 v0.1 4): the sensos contracts behind a JSON door.
|
|
2
|
+
|
|
3
|
+
**Never imported by nvs-runtime's own process** (by design, no cross-imports). It is a
|
|
4
|
+
script, run by ``GateClient`` in ``GATE_PY`` (an interpreter with ``jsonschema``), and it imports
|
|
5
|
+
the sensos checkout named by ``SENSOS_TOOLS`` (its ``tools/`` directory). It is a file of the
|
|
6
|
+
package so that it travels with it and enters the checker bundle (``gate-checker-bundle/1``);
|
|
7
|
+
nothing in it imports ``nvs_runtime``. Standard library and sensos only.
|
|
8
|
+
|
|
9
|
+
stdin: one JSON object with an ``op``; stdout: one JSON object.
|
|
10
|
+
|
|
11
|
+
* ``hid_space_id`` ``{materials}`` -> ``{space_id}`` (contracts.hid_space)
|
|
12
|
+
* ``seal`` ``{envelope, lookup}`` -> ``{envelope}`` with its two ids (contracts.ids)
|
|
13
|
+
* ``session_id`` / ``observation_id`` -> ``{id}`` (contracts.ids)
|
|
14
|
+
* ``check`` ``{envelope, lookup, stored, blobs (base64), contract_facts}`` ->
|
|
15
|
+
``{l1_codes, l1_messages, payload, window}`` (the form of the U6-4 door, unchanged)
|
|
16
|
+
* ``gate``: the same request; ``{l1: [{code, message}], payload, window, envelope_sha256,
|
|
17
|
+
lookup_sha256, contract_facts_sha256}``. The three hashes are SHA-256 of the JCS
|
|
18
|
+
(``contracts.jcs``, RFC 8785) of the envelope, of the lookup and of the contract facts (``null``
|
|
19
|
+
for none): sensos's JCS is the only one, nothing is copied (design N-2).
|
|
20
|
+
* ``catalog`` -> ``{rows: [[payload_schema, check, reason], ...], sha256}``: the UNVERIFIABLE
|
|
21
|
+
catalogue (``contracts.hidden_trajectory.UNVERIFIABLE_CATALOG``, DC-7), rows in the order of
|
|
22
|
+
the code points; ``sha256`` is that of the JCS of the rows as ``{payload_schema, check, reason}``.
|
|
23
|
+
* ``jcs_sha256`` ``{value}`` -> ``{sha256}``.
|
|
24
|
+
* ``checker_files`` ``{extra_files: [{repo, path, b64}]}``: makes the checker bundle. It first runs
|
|
25
|
+
a fixed warm-up that loads, through the public functions of the checker, every file it can
|
|
26
|
+
read (the schemas of ``common/``, ``IC-00/1.1.0/``, ``msr/``, ``nvs/``, the row rules); the
|
|
27
|
+
bundle holds the ``.py`` files of the modules loaded from ``SENSOS_TOOLS`` and the other files
|
|
28
|
+
the process opened below the sensos root, plus ``extra_files`` (nvs-runtime's own). The answer:
|
|
29
|
+
``{bundle_b64, bundle_sha256, files: [{repo, path, sha256}], runtime}``.
|
|
30
|
+
|
|
31
|
+
``check`` and ``gate`` run the envelope rule first (IC-00 by ``contract.version``). Only if it
|
|
32
|
+
reports nothing is the payload checked, by ``gate_nvs.check_nvs_payload``: ``payload`` is then
|
|
33
|
+
``{kind, status, violations, unverifiable}``, else the string ``"not_run"``. For
|
|
34
|
+
``msr.trajectory-window`` 0.10.0 the space of the window is checked as well and reported under
|
|
35
|
+
``window``. Any request may carry ``"trace": true``; the answer then has ``_trace`` (the files
|
|
36
|
+
below the sensos root that the process opened or imported), for the test of the bundle.
|
|
37
|
+
|
|
38
|
+
A ``contract_facts`` of the wrong shape is an error of the caller, not a violation of the
|
|
39
|
+
envelope: the exit status is 2 and stdout is ``{"error": "gate_internal_error", "message": ...}``.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
from __future__ import annotations
|
|
43
|
+
|
|
44
|
+
import base64
|
|
45
|
+
import builtins
|
|
46
|
+
import hashlib
|
|
47
|
+
import importlib
|
|
48
|
+
import importlib.metadata
|
|
49
|
+
import io
|
|
50
|
+
import json
|
|
51
|
+
import os
|
|
52
|
+
import platform
|
|
53
|
+
import sys
|
|
54
|
+
from typing import Any, Final
|
|
55
|
+
|
|
56
|
+
_TOOLS = os.environ.get("SENSOS_TOOLS") or sys.exit(
|
|
57
|
+
"SENSOS_TOOLS is not set (tools/ of a sensos checkout with contracts/gate_nvs.py)"
|
|
58
|
+
)
|
|
59
|
+
sys.path.insert(0, _TOOLS)
|
|
60
|
+
|
|
61
|
+
_OPENED: list[str] = []
|
|
62
|
+
_real_open = io.open
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _recording_open(file: Any, *args: Any, **kwargs: Any) -> Any:
|
|
66
|
+
if isinstance(file, str | os.PathLike):
|
|
67
|
+
_OPENED.append(os.path.realpath(file))
|
|
68
|
+
return _real_open(file, *args, **kwargs)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
io.open = _recording_open
|
|
72
|
+
builtins.open = _recording_open
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
#: The only modules this script ever imports from sensos: the names are fixed here, in the file.
|
|
76
|
+
#: Nothing of the request (``op`` or anything else) is used to make a name for ``import_module``.
|
|
77
|
+
_ALLOWED_MODULES: Final = (
|
|
78
|
+
"contracts.contract_facts",
|
|
79
|
+
"contracts.gate",
|
|
80
|
+
"contracts.gate_nvs",
|
|
81
|
+
"contracts.hid_space",
|
|
82
|
+
"contracts.hidden_trajectory",
|
|
83
|
+
"contracts.hidden_trajectory_window",
|
|
84
|
+
"contracts.ic00_versions",
|
|
85
|
+
"contracts.ids",
|
|
86
|
+
"contracts.jcs",
|
|
87
|
+
"contracts.schemas",
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _sensos(name: str) -> Any:
|
|
92
|
+
"""A module of the sensos contracts, by its short name; only a name of ``_ALLOWED_MODULES``.
|
|
93
|
+
|
|
94
|
+
Loaded by name, not by an ``import`` statement: this file is a script of the package that runs
|
|
95
|
+
in another interpreter, and the static test of the package (``test_e09``) keeps every
|
|
96
|
+
``import`` of its modules free of sensos names. The argument of ``import_module`` is always an
|
|
97
|
+
element of the constant tuple above, never a string built from ``name``."""
|
|
98
|
+
for allowed in _ALLOWED_MODULES:
|
|
99
|
+
if allowed == f"contracts.{name}":
|
|
100
|
+
return importlib.import_module(allowed)
|
|
101
|
+
raise SystemExit(f"module not allowed: {name!r}")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
gate = _sensos("gate")
|
|
105
|
+
gate_nvs = _sensos("gate_nvs")
|
|
106
|
+
ids = _sensos("ids")
|
|
107
|
+
schemas = _sensos("schemas")
|
|
108
|
+
ContractFactsError = _sensos("contract_facts").ContractFactsError
|
|
109
|
+
hid_space_id = _sensos("hid_space").hid_space_id
|
|
110
|
+
UNVERIFIABLE_CATALOG = _sensos("hidden_trajectory").UNVERIFIABLE_CATALOG
|
|
111
|
+
HiddenTrajectoryResult = _sensos("hidden_trajectory").HiddenTrajectoryResult
|
|
112
|
+
row_rule_registry = _sensos("hidden_trajectory").row_rule_registry
|
|
113
|
+
check_window_space = _sensos("hidden_trajectory_window").check_window_space
|
|
114
|
+
RULES = _sensos("ic00_versions").RULES
|
|
115
|
+
check_envelope_versioned = _sensos("ic00_versions").check_envelope_versioned
|
|
116
|
+
jcs = _sensos("jcs").jcs
|
|
117
|
+
|
|
118
|
+
WINDOW_SCHEMA = ("msr.trajectory-window", "0.10.0")
|
|
119
|
+
BUNDLE_VERSION = "gate-checker-bundle/1"
|
|
120
|
+
SENSOS = "sensos"
|
|
121
|
+
_ROOT = os.path.dirname(os.path.realpath(_TOOLS))
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _sha(value: Any) -> str:
|
|
125
|
+
return hashlib.sha256(jcs(value)).hexdigest()
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _violations(found: Any) -> list[dict[str, str]]:
|
|
129
|
+
return [{"code": v.code, "message": v.message} for v in found]
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _result(kind: str, result: Any) -> dict[str, Any]:
|
|
133
|
+
return {
|
|
134
|
+
"kind": kind,
|
|
135
|
+
"status": result.status,
|
|
136
|
+
"violations": _violations(result.violations),
|
|
137
|
+
"unverifiable": [{"check": u.check, "reason": u.reason} for u in result.unverifiable],
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
# A HiddenTrajectoryResult is not one kind. The id of the payload schema names it. An id
|
|
142
|
+
# that is not here must not be reported as hidden_trajectory.
|
|
143
|
+
_RESULT_KIND = {
|
|
144
|
+
"nvs.hidden-trajectory": "hidden_trajectory",
|
|
145
|
+
"nvs.meaning-measurement": "meaning_measurement",
|
|
146
|
+
"nvs.meaning-frame": "meaning_frame",
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _payload_part(schema_id: str, found: Any) -> dict[str, Any]:
|
|
151
|
+
"""The payload layer. A list (``nvs.token-temporal`` and the other ic02 checkers) stays
|
|
152
|
+
``ic02``. A ``HiddenTrajectoryResult`` takes its kind from the schema id, and keeps the
|
|
153
|
+
status the checker returned (``PASS``, ``PASS_UNVERIFIED`` or ``FAIL``)."""
|
|
154
|
+
if isinstance(found, HiddenTrajectoryResult):
|
|
155
|
+
kind = _RESULT_KIND.get(schema_id)
|
|
156
|
+
if kind is None:
|
|
157
|
+
raise RuntimeError(
|
|
158
|
+
f"no kind for HiddenTrajectoryResult of payload_schema {schema_id!r}"
|
|
159
|
+
)
|
|
160
|
+
return _result(kind, found)
|
|
161
|
+
return {
|
|
162
|
+
"kind": "ic02",
|
|
163
|
+
"status": "FAIL" if found else "PASS",
|
|
164
|
+
"violations": _violations(found),
|
|
165
|
+
"unverifiable": [],
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _parts(request: dict[str, Any]) -> dict[str, Any]:
|
|
170
|
+
"""``{l1: [violations], payload, window}``: the three layers, L1 first (a failed L1 stops the
|
|
171
|
+
rest)."""
|
|
172
|
+
envelope, lookup = request["envelope"], request.get("lookup") or {}
|
|
173
|
+
stored = request.get("stored") or {}
|
|
174
|
+
blobs = {uri: base64.b64decode(data) for uri, data in (request.get("blobs") or {}).items()}
|
|
175
|
+
l1 = _violations(check_envelope_versioned(envelope, lookup))
|
|
176
|
+
out: dict[str, Any] = {"l1": l1, "payload": "not_run", "window": None}
|
|
177
|
+
if l1:
|
|
178
|
+
return out
|
|
179
|
+
schema = envelope["payload_schema"]
|
|
180
|
+
# the parent contents of a calibration, as examples/pb_path/gate_ic02_cli.py passes them
|
|
181
|
+
parent_contents = (
|
|
182
|
+
{a: e["content_id"] for a, e in lookup.items()}
|
|
183
|
+
if schema["id"] == "msr.calibration"
|
|
184
|
+
else None
|
|
185
|
+
)
|
|
186
|
+
found = gate_nvs.check_nvs_payload(
|
|
187
|
+
envelope, stored, blobs, parent_contents, contract_facts=request.get("contract_facts")
|
|
188
|
+
)
|
|
189
|
+
out["payload"] = _payload_part(schema["id"], found)
|
|
190
|
+
if (schema["id"], schema["version"]) == WINDOW_SCHEMA:
|
|
191
|
+
out["window"] = _result("window_space", check_window_space(envelope, stored))
|
|
192
|
+
return out
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def check(request: dict[str, Any]) -> dict[str, Any]:
|
|
196
|
+
parts = _parts(request)
|
|
197
|
+
return {
|
|
198
|
+
"l1_codes": sorted({v["code"] for v in parts["l1"]}),
|
|
199
|
+
"l1_messages": [v["message"] for v in parts["l1"]],
|
|
200
|
+
"payload": parts["payload"],
|
|
201
|
+
"window": parts["window"],
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def gate_op(request: dict[str, Any]) -> dict[str, Any]:
|
|
206
|
+
parts = _parts(request)
|
|
207
|
+
facts = request.get("contract_facts")
|
|
208
|
+
return {
|
|
209
|
+
**parts,
|
|
210
|
+
"envelope_sha256": _sha(request["envelope"]),
|
|
211
|
+
"lookup_sha256": _sha(request.get("lookup") or {}),
|
|
212
|
+
"contract_facts_sha256": None if facts is None else _sha(facts),
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def catalog(_request: dict[str, Any]) -> dict[str, Any]:
|
|
217
|
+
rows = sorted([list(row) for row in UNVERIFIABLE_CATALOG])
|
|
218
|
+
as_objects = [{"payload_schema": s, "check": c, "reason": r} for s, c, r in rows]
|
|
219
|
+
return {"rows": rows, "sha256": _sha(as_objects)}
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _warm_up() -> None:
|
|
223
|
+
"""Load, through public functions, every file of the checker that a check can read. The same
|
|
224
|
+
calls every time, so the set of files is the same every time."""
|
|
225
|
+
schemas.registry() # common/, msr/ (with the archives)
|
|
226
|
+
for path in gate.PAYLOAD_SCHEMAS.values():
|
|
227
|
+
schemas.validator(path)
|
|
228
|
+
for version in sorted(RULES): # the envelope schema of each IC-00 version
|
|
229
|
+
check_envelope_versioned({"contract": {"version": version}}, {})
|
|
230
|
+
row_rule_registry() # tools/contracts/hid_row_rules.json
|
|
231
|
+
try: # loads nvs/hidden-trajectory.schema.json; the answer is of no interest
|
|
232
|
+
gate_nvs.check_nvs_payload(
|
|
233
|
+
{"payload_schema": {"id": "nvs.hidden-trajectory", "version": "0.1.0"}, "payload": {}},
|
|
234
|
+
{},
|
|
235
|
+
{},
|
|
236
|
+
None,
|
|
237
|
+
contract_facts=None,
|
|
238
|
+
)
|
|
239
|
+
except Exception: # noqa: BLE001, S110 -- reading the files is what counts here
|
|
240
|
+
pass
|
|
241
|
+
try: # loads nvs/meaning-frame.schema.json; the answer is of no interest
|
|
242
|
+
gate_nvs.check_nvs_payload(
|
|
243
|
+
{"payload_schema": {"id": "nvs.meaning-frame", "version": "0.1.0"}, "payload": {}},
|
|
244
|
+
{},
|
|
245
|
+
{},
|
|
246
|
+
None,
|
|
247
|
+
contract_facts=None,
|
|
248
|
+
)
|
|
249
|
+
except Exception: # noqa: BLE001, S110 -- reading the files is what counts here
|
|
250
|
+
pass
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _below_root(path: str) -> str | None:
|
|
254
|
+
real = os.path.realpath(path)
|
|
255
|
+
if real != _ROOT and not real.startswith(_ROOT + os.sep):
|
|
256
|
+
return None
|
|
257
|
+
return os.path.relpath(real, _ROOT).replace(os.sep, "/")
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _loaded_py() -> list[str]:
|
|
261
|
+
found = set()
|
|
262
|
+
for module in list(sys.modules.values()):
|
|
263
|
+
name = getattr(module, "__file__", None)
|
|
264
|
+
if isinstance(name, str) and name.endswith(".py"):
|
|
265
|
+
rel = _below_root(name)
|
|
266
|
+
if rel is not None and rel.startswith("tools/"):
|
|
267
|
+
found.add(rel)
|
|
268
|
+
return sorted(found)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _opened_other() -> list[str]:
|
|
272
|
+
found = set()
|
|
273
|
+
for name in _OPENED:
|
|
274
|
+
rel = _below_root(name)
|
|
275
|
+
if rel is None or "/__pycache__/" in f"/{rel}" or rel.endswith((".py", ".pyc")):
|
|
276
|
+
continue
|
|
277
|
+
if os.path.isfile(name):
|
|
278
|
+
found.add(rel)
|
|
279
|
+
return sorted(found)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def checker_files(request: dict[str, Any]) -> dict[str, Any]:
|
|
283
|
+
_warm_up()
|
|
284
|
+
files: list[dict[str, str]] = []
|
|
285
|
+
for rel in sorted({*_loaded_py(), *_opened_other()}):
|
|
286
|
+
data = _real_open(os.path.join(_ROOT, rel), "rb").read()
|
|
287
|
+
files.append({"repo": SENSOS, "path": rel, "b64": base64.b64encode(data).decode("ascii")})
|
|
288
|
+
for extra in request.get("extra_files") or []:
|
|
289
|
+
files.append({"repo": extra["repo"], "path": extra["path"], "b64": extra["b64"]})
|
|
290
|
+
files.sort(key=lambda f: (f["repo"], f["path"]))
|
|
291
|
+
bundle = jcs(
|
|
292
|
+
{
|
|
293
|
+
"version": BUNDLE_VERSION,
|
|
294
|
+
"files": [
|
|
295
|
+
{
|
|
296
|
+
"repo": f["repo"],
|
|
297
|
+
"path": f["path"],
|
|
298
|
+
"sha256": _bytes_sha(f["b64"]),
|
|
299
|
+
"bytes_b64": f["b64"],
|
|
300
|
+
}
|
|
301
|
+
for f in files
|
|
302
|
+
],
|
|
303
|
+
}
|
|
304
|
+
)
|
|
305
|
+
return {
|
|
306
|
+
"bundle_b64": base64.b64encode(bundle).decode("ascii"),
|
|
307
|
+
"bundle_sha256": hashlib.sha256(bundle).hexdigest(),
|
|
308
|
+
"files": [
|
|
309
|
+
{"repo": f["repo"], "path": f["path"], "sha256": _bytes_sha(f["b64"])} for f in files
|
|
310
|
+
],
|
|
311
|
+
"runtime": {
|
|
312
|
+
"python": platform.python_version(),
|
|
313
|
+
"implementation": platform.python_implementation(),
|
|
314
|
+
"packages": {
|
|
315
|
+
"jsonschema": importlib.metadata.version("jsonschema"),
|
|
316
|
+
"referencing": importlib.metadata.version("referencing"),
|
|
317
|
+
},
|
|
318
|
+
"platform": {"system": platform.system(), "machine": platform.machine()},
|
|
319
|
+
},
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _bytes_sha(b64: str) -> str:
|
|
324
|
+
return hashlib.sha256(base64.b64decode(b64)).hexdigest()
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def run(request: dict[str, Any]) -> dict[str, Any]:
|
|
328
|
+
op = request.get("op") if isinstance(request, dict) else None
|
|
329
|
+
if op == "check":
|
|
330
|
+
return check(request)
|
|
331
|
+
if op == "gate":
|
|
332
|
+
return gate_op(request)
|
|
333
|
+
if op == "catalog":
|
|
334
|
+
return catalog(request)
|
|
335
|
+
if op == "checker_files":
|
|
336
|
+
return checker_files(request)
|
|
337
|
+
if op == "jcs_sha256":
|
|
338
|
+
return {"sha256": _sha(request["value"])}
|
|
339
|
+
if op == "hid_space_id":
|
|
340
|
+
return {"space_id": hid_space_id(request["materials"])}
|
|
341
|
+
if op == "seal":
|
|
342
|
+
envelope, lookup = request["envelope"], request.get("lookup") or {}
|
|
343
|
+
envelope["content_id"] = ids.content_id(envelope, lookup)
|
|
344
|
+
envelope["artifact_id"] = ids.artifact_id(envelope, lookup)
|
|
345
|
+
return {"envelope": envelope}
|
|
346
|
+
if op == "session_id":
|
|
347
|
+
return {
|
|
348
|
+
"id": ids.session_id_experiment(
|
|
349
|
+
request["spec"],
|
|
350
|
+
request["item_id"],
|
|
351
|
+
request["condition"],
|
|
352
|
+
request["replicate"],
|
|
353
|
+
request["rng_seed"],
|
|
354
|
+
)
|
|
355
|
+
}
|
|
356
|
+
if op == "observation_id":
|
|
357
|
+
return {"id": ids.observation_id(request["session_id"], request["ordinal"])}
|
|
358
|
+
raise SystemExit(f"unknown op: {op!r}") # an op is only ever compared, never imported
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def main() -> int:
|
|
362
|
+
request = json.load(sys.stdin)
|
|
363
|
+
try:
|
|
364
|
+
answer = run(request)
|
|
365
|
+
except ContractFactsError as exc:
|
|
366
|
+
print(json.dumps({"error": exc.code, "message": exc.message}))
|
|
367
|
+
return 2
|
|
368
|
+
if request.get("trace"):
|
|
369
|
+
answer["_trace"] = {"modules": _loaded_py(), "opened": _opened_other()}
|
|
370
|
+
print(json.dumps(answer))
|
|
371
|
+
return 0
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
if __name__ == "__main__":
|
|
375
|
+
sys.exit(main())
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Load an observation Adapter by module and class name (src never imports ``sensos_inference``).
|
|
2
|
+
|
|
3
|
+
The catalog gives the strings. Construction follows the real-machine tests' ``_load``: a capture
|
|
4
|
+
provider from the snapshot directory, then the Adapter. ``importlib`` is the only way the Adapter
|
|
5
|
+
package is reached; a missing ``sensos_inference`` is a clear error, not a traceback.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import importlib
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
from collections.abc import Callable, Mapping
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
_MISSING_MESSAGE = (
|
|
18
|
+
"sensos-inference が導入されていません。"
|
|
19
|
+
"PYTHONPATH に sensos-inference の src を足すか、"
|
|
20
|
+
"パッケージ sensos-inference を導入してください。"
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class AdapterLoadError(RuntimeError):
|
|
25
|
+
"""The Adapter package could not be imported, or the snapshot could not be turned into one."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _import(name: str, import_module: Callable[[str], Any]) -> Any:
|
|
29
|
+
try:
|
|
30
|
+
return import_module(name)
|
|
31
|
+
except ModuleNotFoundError as error:
|
|
32
|
+
missing = getattr(error, "name", None) or str(error)
|
|
33
|
+
if "sensos_inference" in str(missing) or name.startswith("sensos_inference"):
|
|
34
|
+
raise AdapterLoadError(_MISSING_MESSAGE) from error
|
|
35
|
+
raise AdapterLoadError(f"could not import {name}: {error}") from error
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def load_adapter(
|
|
39
|
+
spec: Mapping[str, Any],
|
|
40
|
+
snapshot: Path,
|
|
41
|
+
*,
|
|
42
|
+
hash_cache_dir: Path | None = None,
|
|
43
|
+
import_module: Callable[[str], Any] = importlib.import_module,
|
|
44
|
+
) -> Any:
|
|
45
|
+
"""Build the Adapter named by ``spec`` from ``snapshot``.
|
|
46
|
+
|
|
47
|
+
``import_module`` is a seam for the tests: they pass a fake name or a function that raises
|
|
48
|
+
``ModuleNotFoundError``.
|
|
49
|
+
"""
|
|
50
|
+
adapter_mod = _import(str(spec["adapter_module"]), import_module)
|
|
51
|
+
provider_mod = _import(str(spec["provider_module"]), import_module)
|
|
52
|
+
provider_cls = getattr(provider_mod, str(spec["provider_class"]))
|
|
53
|
+
adapter_cls = getattr(adapter_mod, str(spec["adapter_class"]))
|
|
54
|
+
cache = hash_cache_dir
|
|
55
|
+
if cache is None:
|
|
56
|
+
env = os.environ.get("U2_HASH_CACHE_DIR")
|
|
57
|
+
cache = Path(env) if env else None
|
|
58
|
+
kwargs: dict[str, Any] = {"snapshot_dir": snapshot, "hash_cache_dir": cache}
|
|
59
|
+
model_id = spec.get("provider_model_id")
|
|
60
|
+
provider = provider_cls(model_id, **kwargs) if model_id else provider_cls(**kwargs)
|
|
61
|
+
provider._ensure_loaded_from(provider._load_target())
|
|
62
|
+
if spec.get("needs_config"):
|
|
63
|
+
config = json.loads((snapshot / "config.json").read_text(encoding="utf-8"))
|
|
64
|
+
text = config.get("text_config", config)
|
|
65
|
+
return adapter_cls(
|
|
66
|
+
provider,
|
|
67
|
+
n_layers=int(text["num_hidden_layers"]),
|
|
68
|
+
dimension=int(provider.hidden_size() or 0),
|
|
69
|
+
)
|
|
70
|
+
return adapter_cls(provider)
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Functions shared by the K path and a repeated capture.
|
|
2
|
+
|
|
3
|
+
Standard library only. The Developer Tools use these names for the K files and the K checks.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
from collections.abc import Mapping, Sequence
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def canonical_bytes(value: Any) -> bytes:
|
|
14
|
+
"""The canonical JSON of a K file: sorted keys, no spaces, UTF-8."""
|
|
15
|
+
return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode(
|
|
16
|
+
"utf-8"
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def key_independent(wires: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]:
|
|
21
|
+
"""The board records without their ``hmac``: what a second run with another key must repeat."""
|
|
22
|
+
return [{k: v for k, v in dict(w).items() if k != "hmac"} for w in wires]
|