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,204 @@
|
|
|
1
|
+
"""The capture archive (U6T-2 design 6): where the contract document, the RAW files and the capture
|
|
2
|
+
record of every capture are kept.
|
|
3
|
+
|
|
4
|
+
It lives beside a Formal Store, under ``<data_dir>/capture/``, and is never mixed with the
|
|
5
|
+
store's chain, declaration or index::
|
|
6
|
+
|
|
7
|
+
capture/contracts/aa/bb/<contract_sha256> the canonical JSON bytes of the contract document
|
|
8
|
+
capture/raw/aa/bb/<sha256 of the file> a RAW file (raw_store format), as encoded
|
|
9
|
+
capture/raw_index.jsonl chain: {raw_sha256, trajectory_id}, every RAW file
|
|
10
|
+
capture/records.jsonl chain: the capture records (nvs.capture-record/1)
|
|
11
|
+
|
|
12
|
+
Content is found by its hash; the same content is never written twice; nothing is overwritten or
|
|
13
|
+
deleted. No Gate is run here: a capture record is not an IC-00 artifact (DC-U6-3 (a)), so this is
|
|
14
|
+
not "formal storage". Only the save (``formal_save.py``) writes
|
|
15
|
+
here, and it writes through one object. Standard library plus this package.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import hashlib
|
|
21
|
+
import json
|
|
22
|
+
import os
|
|
23
|
+
from collections.abc import Iterator, Mapping
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from typing import Any
|
|
26
|
+
|
|
27
|
+
from nvs_runtime.hidden_trajectory.capture_chain import ChainError, ChainFile
|
|
28
|
+
from nvs_runtime.hidden_trajectory.record_schema import validate_record
|
|
29
|
+
|
|
30
|
+
__all__ = ["ArchiveError", "CaptureArchive", "ChainError", "contract_bytes"]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ArchiveError(Exception):
|
|
34
|
+
"""An archive write or read that cannot be done as asked (a name that does not match its bytes,
|
|
35
|
+
a file that differs...)."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _reject_floats(value: Any, path: str = "$") -> None:
|
|
39
|
+
if isinstance(value, float):
|
|
40
|
+
raise ArchiveError(f"the contract has a float at {path}: it has no stable text form")
|
|
41
|
+
if isinstance(value, Mapping):
|
|
42
|
+
for key, item in value.items():
|
|
43
|
+
_reject_floats(item, f"{path}.{key}")
|
|
44
|
+
elif isinstance(value, list | tuple):
|
|
45
|
+
for i, item in enumerate(value):
|
|
46
|
+
_reject_floats(item, f"{path}[{i}]")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def contract_bytes(document: Mapping[str, Any]) -> bytes:
|
|
50
|
+
"""The canonical bytes of a contract document (sorted keys, no spaces, UTF-8), the same bytes
|
|
51
|
+
the contract hash is taken over."""
|
|
52
|
+
_reject_floats(document)
|
|
53
|
+
return json.dumps(document, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode(
|
|
54
|
+
"utf-8"
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _sha(data: bytes) -> str:
|
|
59
|
+
return hashlib.sha256(data).hexdigest()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class CaptureArchive:
|
|
63
|
+
"""``CaptureArchive(data_dir)``: opens (and verifies) both chains; ``ChainError`` if one is
|
|
64
|
+
broken."""
|
|
65
|
+
|
|
66
|
+
def __init__(self, data_dir: Path | str, *, guarded: bool = False) -> None:
|
|
67
|
+
"""``guarded`` (the ``FormalWriter`` only): both chains check the file before an append and
|
|
68
|
+
read a half-written last line as "not written" until ``set_aside_torn_tails`` moves it
|
|
69
|
+
(see ``capture_chain``)."""
|
|
70
|
+
self.root = Path(data_dir) / "capture"
|
|
71
|
+
self._index = ChainFile(self.root / "raw_index.jsonl", guarded=guarded)
|
|
72
|
+
self._records = ChainFile(self.root / "records.jsonl", guarded=guarded)
|
|
73
|
+
self._trajectory: dict[str, str] = {}
|
|
74
|
+
for entry in self._index.records():
|
|
75
|
+
self._trajectory[entry["trajectory_id"]] = entry["raw_sha256"]
|
|
76
|
+
|
|
77
|
+
# ---- the guards of the chains (guarded archive) ---------------------------------------------
|
|
78
|
+
def set_aside_torn_tails(self) -> list[dict[str, Any]]:
|
|
79
|
+
"""Set aside the half-written last line of each chain, if there is one. Returns what was
|
|
80
|
+
recorded."""
|
|
81
|
+
done = (chain.set_aside_torn_tail() for chain in (self._index, self._records))
|
|
82
|
+
return [record for record in done if record is not None]
|
|
83
|
+
|
|
84
|
+
def torn_tails(self) -> list[dict[str, Any]]:
|
|
85
|
+
"""Every last line set aside in this archive (``quarantine/torn_tails.jsonl``)."""
|
|
86
|
+
return self._records.torn_records()
|
|
87
|
+
|
|
88
|
+
def check_unchanged(self) -> None:
|
|
89
|
+
"""``ChainChangedExternally`` if either chain was written by somebody else."""
|
|
90
|
+
self._index.check_unchanged()
|
|
91
|
+
self._records.check_unchanged()
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def dead(self) -> str | None:
|
|
95
|
+
"""The reason a chain of this archive saw another writer (and will not be written), or
|
|
96
|
+
``None``."""
|
|
97
|
+
return self._index.dead or self._records.dead
|
|
98
|
+
|
|
99
|
+
# ---- files by hash -----------------------------------------------------------------------
|
|
100
|
+
def _path(self, kind: str, sha: str) -> Path:
|
|
101
|
+
return self.root / kind / sha[:2] / sha[2:4] / sha
|
|
102
|
+
|
|
103
|
+
def _put(self, kind: str, sha: str, data: bytes) -> bool:
|
|
104
|
+
"""Write ``data`` under its hash; ``False`` (nothing written) if it is already there. A file
|
|
105
|
+
with the name and other bytes is an error."""
|
|
106
|
+
if _sha(data) != sha:
|
|
107
|
+
raise ArchiveError(f"{kind} {sha}: the bytes are not those of the name")
|
|
108
|
+
path = self._path(kind, sha)
|
|
109
|
+
if path.exists():
|
|
110
|
+
if path.read_bytes() != data:
|
|
111
|
+
raise ArchiveError(f"{kind} {sha}: a file of this name has other bytes")
|
|
112
|
+
return False
|
|
113
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
114
|
+
temporary = path.with_name(f".{path.name}.tmp")
|
|
115
|
+
with temporary.open("wb") as handle:
|
|
116
|
+
handle.write(data)
|
|
117
|
+
handle.flush()
|
|
118
|
+
os.fsync(handle.fileno())
|
|
119
|
+
os.replace(temporary, path)
|
|
120
|
+
return True
|
|
121
|
+
|
|
122
|
+
def _get(self, kind: str, sha: str) -> bytes | None:
|
|
123
|
+
path = self._path(kind, sha)
|
|
124
|
+
if not path.is_file():
|
|
125
|
+
return None
|
|
126
|
+
data = path.read_bytes()
|
|
127
|
+
if _sha(data) != sha:
|
|
128
|
+
raise ArchiveError(f"{kind} {sha}: the file does not match its hash")
|
|
129
|
+
return data
|
|
130
|
+
|
|
131
|
+
def write_contract(self, document: Mapping[str, Any], contract_sha256: str) -> bool:
|
|
132
|
+
"""Keep the contract document under ``contract_sha256``. The canonical bytes must hash to it
|
|
133
|
+
(else ``ArchiveError``)."""
|
|
134
|
+
return self._put("contracts", contract_sha256, contract_bytes(document))
|
|
135
|
+
|
|
136
|
+
def read_contract(self, contract_sha256: str) -> dict[str, Any] | None:
|
|
137
|
+
data = self._get("contracts", contract_sha256)
|
|
138
|
+
if data is None:
|
|
139
|
+
return None
|
|
140
|
+
document: dict[str, Any] = json.loads(data)
|
|
141
|
+
return document
|
|
142
|
+
|
|
143
|
+
def write_raw(
|
|
144
|
+
self, raw_bytes: Mapping[str, bytes], trajectory_ids: Mapping[str, str]
|
|
145
|
+
) -> dict[str, dict[str, Any]]:
|
|
146
|
+
"""Keep every RAW file under the SHA-256 of its bytes and index its ``trajectory_id``.
|
|
147
|
+
``{point: {sha256, written}}``."""
|
|
148
|
+
out: dict[str, dict[str, Any]] = {}
|
|
149
|
+
for point, data in raw_bytes.items():
|
|
150
|
+
digest = _sha(data)
|
|
151
|
+
tid = trajectory_ids[point]
|
|
152
|
+
written = self._put("raw", digest, data)
|
|
153
|
+
known = self._trajectory.get(tid)
|
|
154
|
+
if known is None:
|
|
155
|
+
self._index.append({"raw_sha256": digest, "trajectory_id": tid})
|
|
156
|
+
self._trajectory[tid] = digest
|
|
157
|
+
elif known != digest:
|
|
158
|
+
raise ArchiveError(f"trajectory_id {tid} is indexed with another RAW file")
|
|
159
|
+
out[point] = {"sha256": digest, "written": written}
|
|
160
|
+
return out
|
|
161
|
+
|
|
162
|
+
def read_raw(self, raw_sha256: str) -> bytes | None:
|
|
163
|
+
return self._get("raw", raw_sha256)
|
|
164
|
+
|
|
165
|
+
def raw_for_trajectory(self, trajectory_id: str) -> bytes | None:
|
|
166
|
+
digest = self._trajectory.get(trajectory_id)
|
|
167
|
+
return None if digest is None else self.read_raw(digest)
|
|
168
|
+
|
|
169
|
+
# ---- the K path and the id lists (U6-6a) ----------------------------------------------------
|
|
170
|
+
def write_k(self, data: bytes) -> dict[str, Any]:
|
|
171
|
+
"""Keep a K file (the board records, or the causal log) under the SHA-256 of its bytes.
|
|
172
|
+
``{sha256, written}``."""
|
|
173
|
+
digest = _sha(data)
|
|
174
|
+
return {"sha256": digest, "written": self._put("k", digest, data)}
|
|
175
|
+
|
|
176
|
+
def read_k(self, sha256: str) -> bytes | None:
|
|
177
|
+
return self._get("k", sha256)
|
|
178
|
+
|
|
179
|
+
def write_ids(self, data: bytes, expected_sha256: str) -> bool:
|
|
180
|
+
"""Keep an id list (little-endian int64, as the contract's ``prompt_ids_sha256`` and
|
|
181
|
+
``gen_token_ids_sha256`` hash it) under ``expected_sha256``, the contract's value. Bytes
|
|
182
|
+
that
|
|
183
|
+
do not hash to it are refused and nothing is written (``ArchiveError``)."""
|
|
184
|
+
return self._put("ids", expected_sha256, data)
|
|
185
|
+
|
|
186
|
+
def read_ids(self, sha256: str) -> bytes | None:
|
|
187
|
+
return self._get("ids", sha256)
|
|
188
|
+
|
|
189
|
+
# ---- the capture records -----------------------------------------------------------------
|
|
190
|
+
def append_record(self, record: Mapping[str, Any]) -> dict[str, Any]:
|
|
191
|
+
"""Chain one capture record (it must fit ``nvs.capture-record/1``). Returns its line. Raises
|
|
192
|
+
if the record is invalid or the file cannot be written."""
|
|
193
|
+
problems = validate_record(record)
|
|
194
|
+
if problems:
|
|
195
|
+
raise ArchiveError(
|
|
196
|
+
f"the record does not fit nvs.capture-record/1: {'; '.join(problems[:3])}"
|
|
197
|
+
)
|
|
198
|
+
return self._records.append(record)
|
|
199
|
+
|
|
200
|
+
def records(self) -> Iterator[dict[str, Any]]:
|
|
201
|
+
return self._records.records()
|
|
202
|
+
|
|
203
|
+
def __len__(self) -> int:
|
|
204
|
+
return len(self._records)
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
"""An append-only hash chain of JSON lines, in the format of hekb-vnext's ``graph/chainlog.py``
|
|
2
|
+
(U6T-2b').
|
|
3
|
+
|
|
4
|
+
Each line: ``{"seq": n, "prev": <hash of the previous line>, "record": {...}, "hash": <sha256 of
|
|
5
|
+
prev + canonical(record)>}``,
|
|
6
|
+
``canonical`` being sorted keys, no spaces, ASCII escapes. Lines are only appended. The format is
|
|
7
|
+
written here and not imported
|
|
8
|
+
(nvs-runtime does not import hekb-vnext for this); a test compares the bytes with hekb-vnext's own
|
|
9
|
+
``ChainLog`` when its
|
|
10
|
+
checkout is given.
|
|
11
|
+
|
|
12
|
+
``ChainFile._write`` is the one place that touches the file: a check before the write (U6T-2b-a:
|
|
13
|
+
someone else wrote since the
|
|
14
|
+
last append) and the handling of a half-written last line belong there, and nowhere else.
|
|
15
|
+
|
|
16
|
+
A chain opened with ``guarded=True`` (the archive of the ``FormalWriter``, U6T-2b-b; the same
|
|
17
|
+
ideas as hekb-vnext's
|
|
18
|
+
``GuardedChainLog``, and the same files and records for a torn line):
|
|
19
|
+
|
|
20
|
+
1. before every append the file is compared with the memory (its size, and the ``hash`` of its last
|
|
21
|
+
line against ``head``). A
|
|
22
|
+
difference means somebody else wrote: nothing is written, the handle never writes again
|
|
23
|
+
(``dead``), reads still work.
|
|
24
|
+
This is detection, not a lock: a writer between the check and the write is not seen (U6T-8).
|
|
25
|
+
2. a last line that does not end in a newline was being written when the process stopped. It is
|
|
26
|
+
read as "not written"; the
|
|
27
|
+
bytes are saved first (``quarantine/<file>.<length>.torn``, fsync), described in
|
|
28
|
+
``quarantine/torn_tails.jsonl`` (fsync),
|
|
29
|
+
and only then is the file cut back to the start of that line (fsync). A failure before the cut
|
|
30
|
+
leaves the file as it was
|
|
31
|
+
and the chain does not open. A line that ends in a newline and cannot be read, a chain that does
|
|
32
|
+
not add up and a fork
|
|
33
|
+
are not touched: they fail as before.
|
|
34
|
+
|
|
35
|
+
A chain opened without ``guarded`` behaves as it always did.
|
|
36
|
+
|
|
37
|
+
Standard library only.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
from __future__ import annotations
|
|
41
|
+
|
|
42
|
+
import hashlib
|
|
43
|
+
import json
|
|
44
|
+
import os
|
|
45
|
+
from collections.abc import Iterator, Mapping
|
|
46
|
+
from datetime import UTC, datetime
|
|
47
|
+
from pathlib import Path
|
|
48
|
+
from typing import Any, Final
|
|
49
|
+
|
|
50
|
+
GENESIS: Final = "0" * 64
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class ChainError(RuntimeError):
|
|
54
|
+
"""The chain does not verify (a line was changed, removed, inserted or cut)."""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class ChainChangedExternally(ChainError):
|
|
58
|
+
"""The file is not what this handle last wrote (size or last line differ from memory). Nothing
|
|
59
|
+
was written."""
|
|
60
|
+
|
|
61
|
+
code = "store_changed_externally"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class TornTailError(ChainError):
|
|
65
|
+
"""The half-written last line could not be set aside safely; the file was not changed."""
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
QUARANTINE_DIR: Final = "quarantine"
|
|
69
|
+
TORN_RECORD_FILE: Final = "torn_tails.jsonl"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _fsync_dir(path: Path) -> None:
|
|
73
|
+
descriptor = os.open(str(path), os.O_RDONLY)
|
|
74
|
+
try:
|
|
75
|
+
os.fsync(descriptor)
|
|
76
|
+
finally:
|
|
77
|
+
os.close(descriptor)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _utc_now() -> str:
|
|
81
|
+
return datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def canonical(value: Any) -> str:
|
|
85
|
+
return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def line_hash(prev: str, record: Any) -> str:
|
|
89
|
+
return hashlib.sha256((prev + canonical(record)).encode("utf-8")).hexdigest()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class ChainFile:
|
|
93
|
+
"""One chain file. Opening verifies the whole file (``ChainError`` if it is broken)."""
|
|
94
|
+
|
|
95
|
+
def __init__(self, path: Path | str, *, guarded: bool = False) -> None:
|
|
96
|
+
self.path = Path(path)
|
|
97
|
+
self._seq = 0
|
|
98
|
+
self._head = GENESIS
|
|
99
|
+
self._size = 0
|
|
100
|
+
self.guarded = guarded
|
|
101
|
+
self.dead: str | None = None
|
|
102
|
+
self.torn: dict[str, Any] | None = None
|
|
103
|
+
if guarded:
|
|
104
|
+
self._open_guarded()
|
|
105
|
+
elif self.path.exists():
|
|
106
|
+
for line in self.verify():
|
|
107
|
+
self._seq = line["seq"] + 1
|
|
108
|
+
self._head = line["hash"]
|
|
109
|
+
|
|
110
|
+
def _open_guarded(self) -> None:
|
|
111
|
+
data = self.path.read_bytes() if self.path.exists() else b""
|
|
112
|
+
cut = data.rfind(b"\n") + 1
|
|
113
|
+
complete, tail = data[:cut], data[cut:]
|
|
114
|
+
for line in self._verify_bytes(complete):
|
|
115
|
+
self._seq = line["seq"] + 1
|
|
116
|
+
self._head = line["hash"]
|
|
117
|
+
self._size = cut
|
|
118
|
+
if tail:
|
|
119
|
+
self.torn = {"offset": cut, "bytes": tail, "original_length": len(data)}
|
|
120
|
+
|
|
121
|
+
def _verify_bytes(self, data: bytes) -> Iterator[dict[str, Any]]:
|
|
122
|
+
prev, seq = GENESIS, 0
|
|
123
|
+
for raw in data.split(b"\n")[:-1]:
|
|
124
|
+
try:
|
|
125
|
+
line = json.loads(raw.decode("utf-8"))
|
|
126
|
+
valid = (
|
|
127
|
+
isinstance(line, dict)
|
|
128
|
+
and line["seq"] == seq
|
|
129
|
+
and line["prev"] == prev
|
|
130
|
+
and line["hash"] == line_hash(prev, line["record"])
|
|
131
|
+
)
|
|
132
|
+
except (ValueError, KeyError, TypeError) as error:
|
|
133
|
+
raise ChainError(f"{self.path.name}: unreadable line at seq {seq}") from error
|
|
134
|
+
if not valid:
|
|
135
|
+
raise ChainError(f"{self.path.name}: chain broken at seq {seq}")
|
|
136
|
+
prev, seq = str(line["hash"]), seq + 1
|
|
137
|
+
yield line
|
|
138
|
+
|
|
139
|
+
def __len__(self) -> int:
|
|
140
|
+
return self._seq
|
|
141
|
+
|
|
142
|
+
@property
|
|
143
|
+
def head(self) -> str:
|
|
144
|
+
return self._head
|
|
145
|
+
|
|
146
|
+
def verify(self) -> Iterator[dict[str, Any]]:
|
|
147
|
+
prev, seq = GENESIS, 0
|
|
148
|
+
if not self.path.exists():
|
|
149
|
+
return
|
|
150
|
+
if self.guarded:
|
|
151
|
+
data = self.path.read_bytes()
|
|
152
|
+
if data and not data.endswith(b"\n"):
|
|
153
|
+
raise ChainError(f"{self.path.name}: the last line does not end in a newline")
|
|
154
|
+
yield from self._verify_bytes(data)
|
|
155
|
+
return
|
|
156
|
+
with self.path.open(encoding="utf-8") as handle:
|
|
157
|
+
for raw in handle:
|
|
158
|
+
try:
|
|
159
|
+
line = json.loads(raw)
|
|
160
|
+
valid = (
|
|
161
|
+
isinstance(line, dict)
|
|
162
|
+
and line["seq"] == seq
|
|
163
|
+
and line["prev"] == prev
|
|
164
|
+
and line["hash"] == line_hash(prev, line["record"])
|
|
165
|
+
)
|
|
166
|
+
except (ValueError, KeyError, TypeError) as error:
|
|
167
|
+
raise ChainError(f"{self.path.name}: unreadable line at seq {seq}") from error
|
|
168
|
+
if not valid:
|
|
169
|
+
raise ChainError(f"{self.path.name}: chain broken at seq {seq}")
|
|
170
|
+
prev, seq = str(line["hash"]), seq + 1
|
|
171
|
+
yield line
|
|
172
|
+
|
|
173
|
+
def records(self) -> Iterator[dict[str, Any]]:
|
|
174
|
+
for line in self.verify():
|
|
175
|
+
record: dict[str, Any] = line["record"]
|
|
176
|
+
yield record
|
|
177
|
+
|
|
178
|
+
def append(self, record: Mapping[str, Any]) -> dict[str, Any]:
|
|
179
|
+
"""Append one record and return its line. The file is flushed and synced before this
|
|
180
|
+
returns."""
|
|
181
|
+
if self.torn is not None:
|
|
182
|
+
raise TornTailError(f"{self.path.name}: a torn last line is not set aside yet")
|
|
183
|
+
if self.guarded:
|
|
184
|
+
self.check_unchanged()
|
|
185
|
+
body = dict(record)
|
|
186
|
+
line = {
|
|
187
|
+
"seq": self._seq,
|
|
188
|
+
"prev": self._head,
|
|
189
|
+
"record": body,
|
|
190
|
+
"hash": line_hash(self._head, body),
|
|
191
|
+
}
|
|
192
|
+
self._write(json.dumps(line, sort_keys=True, separators=(",", ":")) + "\n")
|
|
193
|
+
self._seq += 1
|
|
194
|
+
self._head = str(line["hash"])
|
|
195
|
+
return line
|
|
196
|
+
|
|
197
|
+
def _write(self, text: str) -> None:
|
|
198
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
199
|
+
with self.path.open("a", encoding="utf-8") as handle:
|
|
200
|
+
handle.write(text)
|
|
201
|
+
handle.flush()
|
|
202
|
+
os.fsync(handle.fileno())
|
|
203
|
+
self._size += len(text.encode("utf-8"))
|
|
204
|
+
|
|
205
|
+
# ---- the check before an append (guarded) ---------------------------------------------------
|
|
206
|
+
def _last_line_hash(self) -> str:
|
|
207
|
+
if not self._size:
|
|
208
|
+
return GENESIS
|
|
209
|
+
with self.path.open("rb") as handle:
|
|
210
|
+
handle.seek(max(0, self._size - 1 - 65536))
|
|
211
|
+
block = handle.read(min(self._size, 1 + 65536))
|
|
212
|
+
body = block[:-1] if block.endswith(b"\n") else block
|
|
213
|
+
last = body[body.rfind(b"\n") + 1 :]
|
|
214
|
+
try:
|
|
215
|
+
return str(json.loads(last)["hash"])
|
|
216
|
+
except (ValueError, KeyError, TypeError):
|
|
217
|
+
return ""
|
|
218
|
+
|
|
219
|
+
def check_unchanged(self) -> None:
|
|
220
|
+
"""Raise ``ChainChangedExternally`` (and kill the handle for writing) unless the file is as
|
|
221
|
+
this handle left it."""
|
|
222
|
+
if self.dead:
|
|
223
|
+
raise ChainChangedExternally(self.dead)
|
|
224
|
+
try:
|
|
225
|
+
size = self.path.stat().st_size if self.path.exists() else 0
|
|
226
|
+
same = size == self._size and (self._size == 0 or self._last_line_hash() == self._head)
|
|
227
|
+
except OSError as error:
|
|
228
|
+
self.dead = f"{self.path.name}: cannot be read before an append: {type(error).__name__}"
|
|
229
|
+
raise ChainChangedExternally(self.dead) from error
|
|
230
|
+
if not same:
|
|
231
|
+
self.dead = (
|
|
232
|
+
f"{self.path.name}: the file is not what this handle wrote "
|
|
233
|
+
f"(size {size}, expected {self._size})"
|
|
234
|
+
)
|
|
235
|
+
raise ChainChangedExternally(self.dead)
|
|
236
|
+
|
|
237
|
+
# ---- the torn last line: the evidence first, the cut last (guarded) --------------------------
|
|
238
|
+
@property
|
|
239
|
+
def quarantine_dir(self) -> Path:
|
|
240
|
+
return self.path.parent / QUARANTINE_DIR
|
|
241
|
+
|
|
242
|
+
@property
|
|
243
|
+
def record_path(self) -> Path:
|
|
244
|
+
return self.quarantine_dir / TORN_RECORD_FILE
|
|
245
|
+
|
|
246
|
+
def torn_records(self) -> list[dict[str, Any]]:
|
|
247
|
+
"""Every tail that was set aside in this folder (the quarantine record, verified)."""
|
|
248
|
+
if not self.record_path.exists():
|
|
249
|
+
return []
|
|
250
|
+
return list(ChainFile(self.record_path).records())
|
|
251
|
+
|
|
252
|
+
def _step_write_evidence(self, target: Path, tail: bytes) -> None: # step 1
|
|
253
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
254
|
+
if target.exists():
|
|
255
|
+
if target.read_bytes() != tail:
|
|
256
|
+
raise TornTailError(f"{target.name} exists with other bytes")
|
|
257
|
+
return
|
|
258
|
+
part = target.with_name(target.name + ".part")
|
|
259
|
+
with part.open("wb") as handle:
|
|
260
|
+
handle.write(tail)
|
|
261
|
+
handle.flush()
|
|
262
|
+
os.fsync(handle.fileno())
|
|
263
|
+
os.replace(part, target)
|
|
264
|
+
_fsync_dir(target.parent)
|
|
265
|
+
|
|
266
|
+
def _step_write_record(self, record: dict[str, Any]) -> None: # step 2
|
|
267
|
+
log = ChainFile(self.record_path)
|
|
268
|
+
for earlier in log.records():
|
|
269
|
+
if all(earlier.get(k) == record[k] for k in ("file", "original_length", "torn_sha256")):
|
|
270
|
+
return # an earlier try got this far
|
|
271
|
+
log.append(record) # synced by append
|
|
272
|
+
_fsync_dir(self.record_path.parent)
|
|
273
|
+
|
|
274
|
+
def _step_cut(self, offset: int) -> None: # step 3
|
|
275
|
+
with self.path.open("r+b") as handle:
|
|
276
|
+
handle.truncate(offset)
|
|
277
|
+
handle.flush()
|
|
278
|
+
os.fsync(handle.fileno())
|
|
279
|
+
|
|
280
|
+
def set_aside_torn_tail(self) -> dict[str, Any] | None:
|
|
281
|
+
"""1) the bytes to ``quarantine/<file>.<original length>.torn``, fsync; 2) their SHA-256,
|
|
282
|
+
length, offset and time to the
|
|
283
|
+
quarantine record, fsync; 3) only then cut the file back to the start of the torn line,
|
|
284
|
+
fsync. A failure in 1) or 2) leaves
|
|
285
|
+
the file exactly as it was and raises ``TornTailError``. ``None`` if there is no torn
|
|
286
|
+
tail."""
|
|
287
|
+
if self.torn is None:
|
|
288
|
+
return None
|
|
289
|
+
tail, offset = self.torn["bytes"], self.torn["offset"]
|
|
290
|
+
original = self.torn["original_length"]
|
|
291
|
+
name = f"{self.path.name}.{original}.torn"
|
|
292
|
+
record = {
|
|
293
|
+
"kind": "torn_tail",
|
|
294
|
+
"file": self.path.name,
|
|
295
|
+
"original_length": original,
|
|
296
|
+
"offset": offset,
|
|
297
|
+
"torn_length": len(tail),
|
|
298
|
+
"torn_sha256": hashlib.sha256(tail).hexdigest(),
|
|
299
|
+
"torn_file": f"{QUARANTINE_DIR}/{name}",
|
|
300
|
+
"quarantined_at": _utc_now(),
|
|
301
|
+
}
|
|
302
|
+
try:
|
|
303
|
+
self._step_write_evidence(self.quarantine_dir / name, tail)
|
|
304
|
+
self._step_write_record(record)
|
|
305
|
+
except Exception as error: # noqa: BLE001
|
|
306
|
+
raise TornTailError(
|
|
307
|
+
f"{self.path.name}: the torn last line was not set aside "
|
|
308
|
+
f"({type(error).__name__}: {error}); the file is unchanged"
|
|
309
|
+
) from error
|
|
310
|
+
try:
|
|
311
|
+
self._step_cut(offset)
|
|
312
|
+
except Exception as error: # noqa: BLE001
|
|
313
|
+
raise TornTailError(
|
|
314
|
+
f"{self.path.name}: the torn last line is kept but the file could not be cut "
|
|
315
|
+
f"({type(error).__name__}: {error})"
|
|
316
|
+
) from error
|
|
317
|
+
self.torn = None
|
|
318
|
+
self._size = offset
|
|
319
|
+
return record
|