itself 0.2.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.
itself/ledger.py ADDED
@@ -0,0 +1,373 @@
1
+ # SPDX-License-Identifier: MPL-2.0
2
+ # Copyright (C) 2026 Greater Expanse LLC
3
+
4
+ """Append-only in-memory and JSON Lines storage for protocol records."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import io
9
+ import json
10
+ import os
11
+ import stat
12
+ import tempfile
13
+ from collections.abc import Collection, Iterable, Iterator, Sequence
14
+ from copy import deepcopy
15
+ from pathlib import Path
16
+ from typing import BinaryIO
17
+
18
+ import rfc8785
19
+
20
+ from ._json import strict_json_loads
21
+ from .bundle import BundleSnapshot, BundleValidator
22
+ from .types import JsonObject, StrPath
23
+
24
+
25
+ def _clone(record: JsonObject) -> JsonObject:
26
+ return deepcopy(record)
27
+
28
+
29
+ class LedgerFormatError(ValueError):
30
+ """Raised when a JSON Lines ledger cannot be decoded into object records."""
31
+
32
+ def __init__(self, path: Path, line_number: int, detail: str) -> None:
33
+ self.path: Path = path
34
+ self.line_number: int = line_number
35
+ self.detail: str = detail
36
+ super().__init__(f"{path}:{line_number}: {detail}")
37
+
38
+
39
+ def _decode_record_stream(
40
+ handle: BinaryIO,
41
+ *,
42
+ path: Path,
43
+ max_records: int | None,
44
+ max_bytes: int | None,
45
+ ) -> tuple[list[JsonObject], int]:
46
+ """Decode JSON Lines records, returning them with the number of bytes read."""
47
+
48
+ records: list[JsonObject] = []
49
+ observed_bytes = 0
50
+ line_number = 0
51
+ while True:
52
+ read_size = -1 if max_bytes is None else max_bytes - observed_bytes + 1
53
+ raw_line = handle.readline(read_size)
54
+ if not raw_line:
55
+ break
56
+ line_number += 1
57
+ observed_bytes += len(raw_line)
58
+ if max_bytes is not None and observed_bytes > max_bytes:
59
+ raise LedgerFormatError(
60
+ path,
61
+ line_number,
62
+ f"ledger size exceeds limit {max_bytes} bytes",
63
+ )
64
+ if max_records is not None and line_number > max_records:
65
+ raise LedgerFormatError(
66
+ path,
67
+ line_number,
68
+ f"ledger record count exceeds limit {max_records}",
69
+ )
70
+ try:
71
+ line = raw_line.decode("utf-8")
72
+ except UnicodeDecodeError as error:
73
+ raise LedgerFormatError(
74
+ path,
75
+ line_number,
76
+ f"ledger line is not valid UTF-8: {error}",
77
+ ) from error
78
+ if not line.strip():
79
+ raise LedgerFormatError(
80
+ path,
81
+ line_number,
82
+ "blank lines are not valid ledger records",
83
+ )
84
+ try:
85
+ value = strict_json_loads(line)
86
+ except (json.JSONDecodeError, ValueError) as error:
87
+ raise LedgerFormatError(
88
+ path,
89
+ line_number,
90
+ f"invalid JSON: {error}",
91
+ ) from error
92
+ if not isinstance(value, dict):
93
+ raise LedgerFormatError(
94
+ path,
95
+ line_number,
96
+ "each line must contain one JSON object",
97
+ )
98
+ records.append(value)
99
+ return records, observed_bytes
100
+
101
+
102
+ def decode_jsonl_records(
103
+ content: bytes,
104
+ *,
105
+ path: StrPath,
106
+ max_records: int | None = None,
107
+ max_bytes: int | None = None,
108
+ ) -> list[JsonObject]:
109
+ """Decode complete ledger bytes with the file loader's limits and messages.
110
+
111
+ ``path`` names the source in diagnostics only; nothing is read from it.
112
+ """
113
+
114
+ if max_records is not None and max_records < 0:
115
+ raise ValueError("max_records must not be negative")
116
+ if max_bytes is not None and max_bytes < 0:
117
+ raise ValueError("max_bytes must not be negative")
118
+ source = Path(path)
119
+ if max_bytes is not None and len(content) > max_bytes:
120
+ raise LedgerFormatError(
121
+ source,
122
+ 1,
123
+ f"ledger size exceeds limit {max_bytes} bytes",
124
+ )
125
+ records, _ = _decode_record_stream(
126
+ io.BytesIO(content),
127
+ path=source,
128
+ max_records=max_records,
129
+ max_bytes=max_bytes,
130
+ )
131
+ return records
132
+
133
+
134
+ class Ledger:
135
+ """An ordered, append-only collection with atomic in-memory mutation."""
136
+
137
+ def __init__(
138
+ self,
139
+ records: Iterable[JsonObject] = (),
140
+ *,
141
+ external_refs: Collection[str] = (),
142
+ validator: BundleValidator | None = None,
143
+ ) -> None:
144
+ self._validator = validator or BundleValidator()
145
+ self._external_refs = frozenset(external_refs)
146
+ candidate = tuple(_clone(record) for record in records)
147
+ self._snapshot = self._validator.validate(
148
+ candidate,
149
+ external_refs=self._external_refs,
150
+ )
151
+ self._records = candidate
152
+
153
+ @property
154
+ def records(self) -> tuple[JsonObject, ...]:
155
+ """Return defensive copies of records in authoritative replay order."""
156
+
157
+ return tuple(_clone(record) for record in self._records)
158
+
159
+ @property
160
+ def snapshot(self) -> BundleSnapshot:
161
+ """Return the current deterministic replay snapshot."""
162
+
163
+ return self._snapshot
164
+
165
+ def __len__(self) -> int:
166
+ return len(self._records)
167
+
168
+ def __iter__(self) -> Iterator[JsonObject]:
169
+ return iter(self.records)
170
+
171
+ def append(self, record: JsonObject) -> BundleSnapshot:
172
+ """Validate and append one record without partial mutation on failure."""
173
+
174
+ return self.extend((record,))
175
+
176
+ def extend(self, records: Iterable[JsonObject]) -> BundleSnapshot:
177
+ """Validate and append a batch as one all-or-nothing operation.
178
+
179
+ References resolve against the complete candidate history, so records
180
+ that reference each other, such as a completed test and its evidence,
181
+ must arrive in the same batch.
182
+ """
183
+
184
+ additions = tuple(_clone(record) for record in records)
185
+ if not additions:
186
+ return self._snapshot
187
+
188
+ # The history is read once, so the prefix that skips the schema check
189
+ # is exactly the history the candidate was built from.
190
+ existing = self._records
191
+ candidate = existing + additions
192
+ snapshot = self._validated(candidate, schema_checked=len(existing))
193
+ self._records = candidate
194
+ self._snapshot = snapshot
195
+ return snapshot
196
+
197
+ def _validated(
198
+ self,
199
+ candidate: tuple[JsonObject, ...],
200
+ *,
201
+ schema_checked: int,
202
+ ) -> BundleSnapshot:
203
+ validator = self._validator
204
+ # Held records are private copies this validator already accepted, so
205
+ # only the additions need the per-record schema check. That shortcut
206
+ # is internal to the package, and a validator that overrides validate
207
+ # receives the whole candidate through its own method instead.
208
+ if type(validator).validate is BundleValidator.validate:
209
+ return validator._validated( # pyright: ignore[reportPrivateUsage]
210
+ candidate,
211
+ self._external_refs,
212
+ schema_checked,
213
+ )
214
+ return validator.validate(candidate, external_refs=self._external_refs)
215
+
216
+
217
+ class JsonlLedgerStore:
218
+ """Persist a logical append-only ledger as deterministic JSON Lines."""
219
+
220
+ def __init__(self, path: StrPath, validator: BundleValidator | None = None) -> None:
221
+ self.path: Path = Path(path)
222
+ self._validator = validator or BundleValidator()
223
+
224
+ def load(
225
+ self,
226
+ *,
227
+ external_refs: Collection[str] = (),
228
+ max_records: int | None = None,
229
+ max_bytes: int | None = None,
230
+ ) -> Ledger:
231
+ """Load and validate the complete ledger, or return an empty ledger."""
232
+
233
+ if max_records is not None and max_records < 0:
234
+ raise ValueError("max_records must not be negative")
235
+ if max_bytes is not None and max_bytes < 0:
236
+ raise ValueError("max_bytes must not be negative")
237
+ records = self._read_records(
238
+ max_records=max_records,
239
+ max_bytes=max_bytes,
240
+ )
241
+ return Ledger(
242
+ records,
243
+ external_refs=external_refs,
244
+ validator=self._validator,
245
+ )
246
+
247
+ def append(
248
+ self,
249
+ record: JsonObject,
250
+ *,
251
+ external_refs: Collection[str] = (),
252
+ ) -> BundleSnapshot:
253
+ """Validate and atomically persist one logical append."""
254
+
255
+ return self.extend((record,), external_refs=external_refs)
256
+
257
+ def extend(
258
+ self,
259
+ records: Iterable[JsonObject],
260
+ *,
261
+ external_refs: Collection[str] = (),
262
+ ) -> BundleSnapshot:
263
+ """Validate and atomically persist a batch of logical appends.
264
+
265
+ As with ``Ledger.extend``, records that reference each other must
266
+ arrive in the same batch.
267
+ """
268
+
269
+ additions = tuple(records)
270
+ ledger = self.load(external_refs=external_refs)
271
+ if not additions:
272
+ return ledger.snapshot
273
+
274
+ snapshot = ledger.extend(additions)
275
+ self._atomic_replace(ledger.records)
276
+ return snapshot
277
+
278
+ def _read_records(
279
+ self,
280
+ *,
281
+ max_records: int | None = None,
282
+ max_bytes: int | None = None,
283
+ ) -> list[JsonObject]:
284
+ try:
285
+ metadata = self.path.lstat()
286
+ except FileNotFoundError:
287
+ return []
288
+ if stat.S_ISLNK(metadata.st_mode):
289
+ raise OSError(f"ledger path must not be a symbolic link: {self.path}")
290
+ if not stat.S_ISREG(metadata.st_mode):
291
+ raise OSError(f"ledger path must be a regular file: {self.path}")
292
+
293
+ flags = os.O_RDONLY | getattr(os, "O_BINARY", 0)
294
+ flags |= getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)
295
+ descriptor = os.open(self.path, flags)
296
+ try:
297
+ opened_metadata = os.fstat(descriptor)
298
+ if not stat.S_ISREG(opened_metadata.st_mode) or (
299
+ opened_metadata.st_dev,
300
+ opened_metadata.st_ino,
301
+ ) != (metadata.st_dev, metadata.st_ino):
302
+ raise OSError(f"ledger path changed while opening: {self.path}")
303
+ if max_bytes is not None and opened_metadata.st_size > max_bytes:
304
+ raise LedgerFormatError(
305
+ self.path,
306
+ 1,
307
+ f"ledger size exceeds limit {max_bytes} bytes",
308
+ )
309
+ except BaseException:
310
+ os.close(descriptor)
311
+ raise
312
+
313
+ with os.fdopen(descriptor, "rb") as handle:
314
+ records, observed_bytes = _decode_record_stream(
315
+ handle,
316
+ path=self.path,
317
+ max_records=max_records,
318
+ max_bytes=max_bytes,
319
+ )
320
+ if (
321
+ observed_bytes != opened_metadata.st_size
322
+ or os.fstat(handle.fileno()).st_size != opened_metadata.st_size
323
+ ):
324
+ raise OSError(f"ledger path changed while reading: {self.path}")
325
+ return records
326
+
327
+ def _atomic_replace(self, records: Sequence[JsonObject]) -> None:
328
+ parent = self.path.parent
329
+ parent.mkdir(parents=True, exist_ok=True)
330
+ try:
331
+ original_metadata = self.path.lstat()
332
+ except FileNotFoundError:
333
+ original_metadata = None
334
+ if original_metadata is not None:
335
+ if stat.S_ISLNK(original_metadata.st_mode):
336
+ raise OSError(f"ledger path must not be a symbolic link: {self.path}")
337
+ if not stat.S_ISREG(original_metadata.st_mode):
338
+ raise OSError(f"ledger path must be a regular file: {self.path}")
339
+
340
+ descriptor, temporary_name = tempfile.mkstemp(
341
+ dir=parent,
342
+ prefix=f".{self.path.name}.",
343
+ suffix=".tmp",
344
+ )
345
+ temporary_path = Path(temporary_name)
346
+ try:
347
+ with os.fdopen(descriptor, "wb") as handle:
348
+ for record in records:
349
+ handle.write(rfc8785.dumps(record))
350
+ handle.write(b"\n")
351
+ handle.flush()
352
+ os.fsync(handle.fileno())
353
+
354
+ try:
355
+ current_metadata = self.path.lstat()
356
+ except FileNotFoundError:
357
+ current_metadata = None
358
+ if original_metadata is None:
359
+ if current_metadata is not None:
360
+ raise OSError(f"ledger path appeared while writing: {self.path}")
361
+ elif current_metadata is None or (
362
+ current_metadata.st_dev,
363
+ current_metadata.st_ino,
364
+ ) != (
365
+ original_metadata.st_dev,
366
+ original_metadata.st_ino,
367
+ ):
368
+ raise OSError(f"ledger path changed while writing: {self.path}")
369
+ else:
370
+ temporary_path.chmod(stat.S_IMODE(original_metadata.st_mode))
371
+ os.replace(temporary_path, self.path)
372
+ finally:
373
+ temporary_path.unlink(missing_ok=True)
itself/py.typed ADDED
File without changes