ai-editor-tree-engine-dev 1.0.176__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.
- ai_editor_tree_engine_dev-1.0.176.dist-info/METADATA +35 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/RECORD +121 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/WHEEL +5 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/licenses/LICENSE +21 -0
- ai_editor_tree_engine_dev-1.0.176.dist-info/top_level.txt +1 -0
- tree_engine/PUBLIC_API.md +161 -0
- tree_engine/__init__.py +327 -0
- tree_engine/checks/__init__.py +60 -0
- tree_engine/checks/builtin/__init__.py +5 -0
- tree_engine/checks/builtin/compile_check.py +53 -0
- tree_engine/checks/builtin/csv_syntax.py +51 -0
- tree_engine/checks/builtin/docstrings.py +211 -0
- tree_engine/checks/builtin/encoding.py +55 -0
- tree_engine/checks/builtin/fleet_rules.py +227 -0
- tree_engine/checks/builtin/format_syntax.py +82 -0
- tree_engine/checks/builtin/jsonl_syntax.py +49 -0
- tree_engine/checks/builtin/shipped.py +52 -0
- tree_engine/checks/builtin/syntax.py +118 -0
- tree_engine/checks/builtin/xml_wellformed.py +51 -0
- tree_engine/checks/chain.py +332 -0
- tree_engine/checks/external/__init__.py +5 -0
- tree_engine/checks/external/_base.py +61 -0
- tree_engine/checks/external/bandit.py +53 -0
- tree_engine/checks/external/black.py +48 -0
- tree_engine/checks/external/flake8.py +38 -0
- tree_engine/checks/external/isort.py +38 -0
- tree_engine/checks/external/mypy.py +45 -0
- tree_engine/checks/external/ruff.py +45 -0
- tree_engine/checks/external/runner.py +197 -0
- tree_engine/checks/model.py +110 -0
- tree_engine/checks/options.py +73 -0
- tree_engine/checks/plugin.py +171 -0
- tree_engine/checks/registry.py +349 -0
- tree_engine/core/address.py +376 -0
- tree_engine/core/identifier_map.py +266 -0
- tree_engine/core/identity.py +226 -0
- tree_engine/core/instrumentation.py +399 -0
- tree_engine/core/integrity.py +341 -0
- tree_engine/core/integrity_full.py +382 -0
- tree_engine/core/journal.py +260 -0
- tree_engine/core/journal_compose.py +571 -0
- tree_engine/core/live_tree.py +785 -0
- tree_engine/core/locking.py +188 -0
- tree_engine/core/move.py +585 -0
- tree_engine/core/move_references.py +323 -0
- tree_engine/core/node_types.py +408 -0
- tree_engine/core/nodes.py +348 -0
- tree_engine/core/offsets.py +24 -0
- tree_engine/core/operations.py +825 -0
- tree_engine/core/plugin_boundary.py +160 -0
- tree_engine/core/position_map.py +263 -0
- tree_engine/core/position_transfer.py +512 -0
- tree_engine/core/range_refresh.py +366 -0
- tree_engine/core/reference_cache.py +360 -0
- tree_engine/core/references.py +223 -0
- tree_engine/core/reparse.py +378 -0
- tree_engine/core/short_id.py +296 -0
- tree_engine/core/subtree_apply.py +397 -0
- tree_engine/core/subtree_copy.py +399 -0
- tree_engine/core/transactions.py +397 -0
- tree_engine/core/trivia.py +396 -0
- tree_engine/core/updates.py +398 -0
- tree_engine/core/validation.py +377 -0
- tree_engine/errors.py +104 -0
- tree_engine/exceptions.py +376 -0
- tree_engine/facade.py +4524 -0
- tree_engine/plugins/_statements.py +369 -0
- tree_engine/plugins/bsl/block_edit.py +449 -0
- tree_engine/plugins/bsl/blocks.py +127 -0
- tree_engine/plugins/bsl/checker.py +297 -0
- tree_engine/plugins/bsl/dialects.py +303 -0
- tree_engine/plugins/bsl/generator.py +481 -0
- tree_engine/plugins/bsl/import_map.py +995 -0
- tree_engine/plugins/bsl/plugin.py +452 -0
- tree_engine/plugins/contract.py +355 -0
- tree_engine/plugins/cpp/import_map.py +505 -0
- tree_engine/plugins/cpp/languages.py +99 -0
- tree_engine/plugins/cpp/plugin.py +501 -0
- tree_engine/plugins/csv_format.py +676 -0
- tree_engine/plugins/detachable.py +156 -0
- tree_engine/plugins/fallback.py +421 -0
- tree_engine/plugins/ini_format.py +330 -0
- tree_engine/plugins/json_format.py +813 -0
- tree_engine/plugins/json_pointer.py +203 -0
- tree_engine/plugins/jsonl_format.py +392 -0
- tree_engine/plugins/markdown_format.py +748 -0
- tree_engine/plugins/onec_query_format.py +61 -0
- tree_engine/plugins/parse_position.py +54 -0
- tree_engine/plugins/plain_text.py +1543 -0
- tree_engine/plugins/python/export_map.py +306 -0
- tree_engine/plugins/python/import_map.py +429 -0
- tree_engine/plugins/python/plugin.py +1710 -0
- tree_engine/plugins/registry.py +497 -0
- tree_engine/plugins/scan.py +87 -0
- tree_engine/plugins/selection.py +228 -0
- tree_engine/plugins/sql_format.py +61 -0
- tree_engine/plugins/toml_format.py +1072 -0
- tree_engine/plugins/xml_format.py +911 -0
- tree_engine/plugins/yaml/builder.py +49 -0
- tree_engine/plugins/yaml/emitter.py +225 -0
- tree_engine/plugins/yaml/flow.py +227 -0
- tree_engine/plugins/yaml/plugin.py +458 -0
- tree_engine/plugins/yaml/ranges.py +52 -0
- tree_engine/plugins/yaml/reader.py +359 -0
- tree_engine/plugins/yaml/scanner.py +298 -0
- tree_engine/query/adapter.py +283 -0
- tree_engine/query/engine.py +853 -0
- tree_engine/query/inspection.py +498 -0
- tree_engine/query/outline.py +288 -0
- tree_engine/query/predicates.py +263 -0
- tree_engine/query/rendered_lines.py +46 -0
- tree_engine/query/results.py +206 -0
- tree_engine/query/selector.py +400 -0
- tree_engine/query/xml_query.py +747 -0
- tree_engine/storage/codec.py +400 -0
- tree_engine/storage/document_bridge.py +579 -0
- tree_engine/storage/file_txn.py +459 -0
- tree_engine/storage/history.py +106 -0
- tree_engine/storage/lifecycle.py +622 -0
- tree_engine/storage/schema.py +403 -0
- tree_engine/storage/session_guard.py +398 -0
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
"""Edit-session conflict guard with dual-SHA verification (C-012).
|
|
2
|
+
|
|
3
|
+
Author: Vasiliy Zdanovskiy
|
|
4
|
+
email: vasilyvz@gmail.com
|
|
5
|
+
|
|
6
|
+
Scope (C-012, narrowed to this atomic step's target file), per {p086} and
|
|
7
|
+
{p089}: two coordinated things and nothing else.
|
|
8
|
+
|
|
9
|
+
1. Pure dual-SHA helpers. :func:`source_sha256` hashes the exact source
|
|
10
|
+
bytes with no normalization at all -- no newline folding, no encoding
|
|
11
|
+
round-trip, no trimming -- so the digest tracks the file byte-for-byte.
|
|
12
|
+
:func:`tree_payload_sha256` hashes the codec layer's canonical tree
|
|
13
|
+
payload with the CHECKSUMS section excluded, since that section holds
|
|
14
|
+
the digest itself. Both are stateless module-level functions holding no
|
|
15
|
+
reference to any tree object, reusable for acceptance gating at open and
|
|
16
|
+
for post-publication verification alike.
|
|
17
|
+
|
|
18
|
+
2. :class:`EditSession`. At open it records ``base_source_sha256`` and
|
|
19
|
+
``base_tree_payload_sha256``; before any write it re-reads *both* files
|
|
20
|
+
and recomputes both digests. A changed source raises
|
|
21
|
+
``ConcurrentSourceModification``, a changed tree file
|
|
22
|
+
``ConcurrentTreeModification``; :meth:`EditSession.accept_publication`
|
|
23
|
+
advances the base digests once a publish is verified ({p091}).
|
|
24
|
+
|
|
25
|
+
Content, not metadata: per {p093} mtime and size are an auxiliary
|
|
26
|
+
optimization for this layer only, never a decision input. They ride on
|
|
27
|
+
:class:`FileEvidence` purely as diagnostics; every verdict comes from the
|
|
28
|
+
SHA-256 of the bytes, because a same-second edit that leaves the file the
|
|
29
|
+
same size is a real modification and must still be caught. A detected
|
|
30
|
+
conflict may be overwritten only by naming a
|
|
31
|
+
:class:`ConflictResolutionPolicy` member -- no boolean ``force`` flag
|
|
32
|
+
exists, and the default is ``REFUSE``.
|
|
33
|
+
|
|
34
|
+
Boundaries. All state here lives on the session, never on the tree object
|
|
35
|
+
({p025}, {p089}). In-process serialization belongs to
|
|
36
|
+
:class:`tree_engine.core.locking.DocumentLockCoordinator`; publication
|
|
37
|
+
belongs to :mod:`tree_engine.storage.file_txn`, which deliberately carries
|
|
38
|
+
no external-modification detection -- that duty is this module's. Two
|
|
39
|
+
concurrent sessions keep independent baselines and nothing is arbitrated
|
|
40
|
+
here: whichever publishes first and accepts stays consistent, while a
|
|
41
|
+
session still on the older baseline is refused at its next check -- first
|
|
42
|
+
publisher wins, later ones are refused, never merged ({p035}).
|
|
43
|
+
|
|
44
|
+
Source-of-truth labels honored here: {p086}, {p089}, {p091}, {p093}.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
from __future__ import annotations
|
|
48
|
+
|
|
49
|
+
import hashlib
|
|
50
|
+
import json
|
|
51
|
+
import os
|
|
52
|
+
import threading
|
|
53
|
+
from dataclasses import dataclass
|
|
54
|
+
from enum import Enum
|
|
55
|
+
from pathlib import Path
|
|
56
|
+
from typing import Any, Callable, Dict, Mapping, Optional, Union
|
|
57
|
+
|
|
58
|
+
from tree_engine.errors import ErrorCode
|
|
59
|
+
from tree_engine.exceptions import (
|
|
60
|
+
ChecksumMismatch,
|
|
61
|
+
ConcurrentSourceModification,
|
|
62
|
+
ConcurrentTreeModification,
|
|
63
|
+
StorageIOError,
|
|
64
|
+
TreePayloadInvalid,
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
__all__ = [
|
|
68
|
+
"CHECKSUMS_SECTION_KEYS", "ConflictResolutionPolicy", "FileEvidence",
|
|
69
|
+
"ConflictReport", "EditSession", "TreeCanonicalizer", "source_sha256",
|
|
70
|
+
"tree_payload_sha256", "strip_checksums_section", "canonical_payload_bytes",
|
|
71
|
+
"default_tree_canonicalizer",
|
|
72
|
+
]
|
|
73
|
+
|
|
74
|
+
PathLike = Union[str, Path]
|
|
75
|
+
|
|
76
|
+
#: Names the CHECKSUMS service section may appear under: the lowercase key
|
|
77
|
+
#: of :class:`tree_engine.storage.schema.TreeFile` and the upper-case
|
|
78
|
+
#: spelling of {p085}. Both are stripped, so either convention hashes alike.
|
|
79
|
+
CHECKSUMS_SECTION_KEYS = ("checksums", "CHECKSUMS")
|
|
80
|
+
|
|
81
|
+
#: Maps raw tree-file bytes to the canonical payload bytes that
|
|
82
|
+
#: :func:`tree_payload_sha256` consumes. Injectable so the codec layer can
|
|
83
|
+
#: supply its own version-pinned canonicalization ({p100}).
|
|
84
|
+
TreeCanonicalizer = Callable[[bytes], bytes]
|
|
85
|
+
|
|
86
|
+
# ---- Pure dual-SHA helpers ------------------------------------------------
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def source_sha256(source_bytes: bytes) -> str:
|
|
90
|
+
"""SHA-256 hex digest of the exact source bytes, unnormalized ({p086}).
|
|
91
|
+
|
|
92
|
+
Hashed verbatim, so the digest changes for a single flipped byte even
|
|
93
|
+
when the file's size and mtime are unchanged.
|
|
94
|
+
"""
|
|
95
|
+
return hashlib.sha256(source_bytes).hexdigest()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def tree_payload_sha256(canonical_payload: bytes) -> str:
|
|
99
|
+
"""SHA-256 hex digest of the canonical tree payload ({p086}).
|
|
100
|
+
|
|
101
|
+
``canonical_payload`` is the codec layer's deterministic serialization
|
|
102
|
+
with CHECKSUMS already excluded; see :func:`canonical_payload_bytes`.
|
|
103
|
+
"""
|
|
104
|
+
return hashlib.sha256(canonical_payload).hexdigest()
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def strip_checksums_section(document: Mapping[str, Any]) -> Dict[str, Any]:
|
|
108
|
+
"""Copy a decoded tree-file mapping without CHECKSUMS ({p086}); input unmutated."""
|
|
109
|
+
if not isinstance(document, Mapping):
|
|
110
|
+
raise TypeError(f"strip_checksums_section expects a mapping, got {type(document).__name__}")
|
|
111
|
+
return {key: value for key, value in document.items() if key not in CHECKSUMS_SECTION_KEYS}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def canonical_payload_bytes(document: Mapping[str, Any]) -> bytes:
|
|
115
|
+
"""Canonicalize a decoded tree-file mapping to deterministic bytes.
|
|
116
|
+
|
|
117
|
+
The default when the codec injects no version-pinned form ({p100}):
|
|
118
|
+
CHECKSUMS dropped, keys sorted at every depth, minimal separators,
|
|
119
|
+
UTF-8 -- so key order and file whitespace never move the digest.
|
|
120
|
+
"""
|
|
121
|
+
stripped = strip_checksums_section(document)
|
|
122
|
+
try:
|
|
123
|
+
text = json.dumps(stripped, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
|
124
|
+
except (TypeError, ValueError) as exc:
|
|
125
|
+
raise TreePayloadInvalid(
|
|
126
|
+
f"tree payload is not canonically serializable: {exc}", reason="not_serializable") from exc
|
|
127
|
+
return text.encode("utf-8")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def default_tree_canonicalizer(raw_tree_file_bytes: bytes) -> bytes:
|
|
131
|
+
"""Map raw tree-file bytes to canonical payload bytes without CHECKSUMS.
|
|
132
|
+
|
|
133
|
+
Safe and declarative per {p100}: a plain JSON decode, a section drop, a
|
|
134
|
+
deterministic re-encode -- no ``eval``, ``exec``, ``pickle``, dynamic
|
|
135
|
+
import. Raises ``TreePayloadInvalid`` on undecodable bytes.
|
|
136
|
+
"""
|
|
137
|
+
try:
|
|
138
|
+
document = json.loads(raw_tree_file_bytes.decode("utf-8"))
|
|
139
|
+
except (UnicodeDecodeError, ValueError) as exc:
|
|
140
|
+
raise TreePayloadInvalid(
|
|
141
|
+
f"tree file is not decodable as a tree-file mapping: {exc}", reason="undecodable") from exc
|
|
142
|
+
if not isinstance(document, Mapping):
|
|
143
|
+
raise TreePayloadInvalid(
|
|
144
|
+
f"tree file must decode to a mapping, got {type(document).__name__}", reason="not_a_mapping")
|
|
145
|
+
return canonical_payload_bytes(document)
|
|
146
|
+
|
|
147
|
+
# ---- Evidence and verdict -------------------------------------------------
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class ConflictResolutionPolicy(Enum):
|
|
151
|
+
"""Named policies under which a detected conflict may be overwritten.
|
|
152
|
+
``REFUSE`` is the default everywhere here; any other member must be
|
|
153
|
+
named explicitly at the call site, so no boolean flag can relax the
|
|
154
|
+
guard by accident ({p089})."""
|
|
155
|
+
|
|
156
|
+
REFUSE = "refuse"
|
|
157
|
+
OVERWRITE_SOURCE = "overwrite_source"
|
|
158
|
+
OVERWRITE_TREE = "overwrite_tree"
|
|
159
|
+
OVERWRITE_BOTH = "overwrite_both"
|
|
160
|
+
|
|
161
|
+
def allows_source_overwrite(self) -> bool:
|
|
162
|
+
"""True only for the members that name a source overwrite."""
|
|
163
|
+
return self in (ConflictResolutionPolicy.OVERWRITE_SOURCE, ConflictResolutionPolicy.OVERWRITE_BOTH)
|
|
164
|
+
|
|
165
|
+
def allows_tree_overwrite(self) -> bool:
|
|
166
|
+
"""True only for the members that name a tree-file overwrite."""
|
|
167
|
+
return self in (ConflictResolutionPolicy.OVERWRITE_TREE, ConflictResolutionPolicy.OVERWRITE_BOTH)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
@dataclass(frozen=True)
|
|
171
|
+
class FileEvidence:
|
|
172
|
+
"""One file's on-disk facts at a single instant. ``sha256`` is the only
|
|
173
|
+
field a verdict is derived from; ``size`` and ``mtime_ns`` are
|
|
174
|
+
diagnostics, never a decision input ({p093}). ``sha256`` is None exactly
|
|
175
|
+
when the file is missing or unreadable, and ``unreadable_reason`` says
|
|
176
|
+
which."""
|
|
177
|
+
|
|
178
|
+
path: Path
|
|
179
|
+
exists: bool
|
|
180
|
+
sha256: Optional[str] = None
|
|
181
|
+
size: Optional[int] = None
|
|
182
|
+
mtime_ns: Optional[int] = None
|
|
183
|
+
unreadable_reason: Optional[str] = None
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
@dataclass(frozen=True)
|
|
187
|
+
class ConflictReport:
|
|
188
|
+
"""The outcome of one pre-write verification ({p089})."""
|
|
189
|
+
|
|
190
|
+
source: FileEvidence
|
|
191
|
+
tree: FileEvidence
|
|
192
|
+
base_source_sha256: str
|
|
193
|
+
base_tree_payload_sha256: str
|
|
194
|
+
source_changed: bool
|
|
195
|
+
tree_changed: bool
|
|
196
|
+
|
|
197
|
+
@property
|
|
198
|
+
def has_conflict(self) -> bool:
|
|
199
|
+
"""True when either file no longer matches its base digest."""
|
|
200
|
+
return self.source_changed or self.tree_changed
|
|
201
|
+
|
|
202
|
+
@property
|
|
203
|
+
def error_code(self) -> Optional[ErrorCode]:
|
|
204
|
+
"""The code a refusing write signals; the source is reported first."""
|
|
205
|
+
if self.source_changed:
|
|
206
|
+
return ErrorCode.CONCURRENT_SOURCE_MODIFICATION
|
|
207
|
+
if self.tree_changed:
|
|
208
|
+
return ErrorCode.CONCURRENT_TREE_MODIFICATION
|
|
209
|
+
return None
|
|
210
|
+
|
|
211
|
+
# ---- Session guard --------------------------------------------------------
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
class EditSession:
|
|
215
|
+
"""Session-scoped external-modification guard for one source/tree pair.
|
|
216
|
+
|
|
217
|
+
Holds the base digests recorded when the external edit session opened
|
|
218
|
+
and re-verifies them against real disk state before every write. That
|
|
219
|
+
state lives here and never on the tree object ({p025}). Safe to share
|
|
220
|
+
across threads: the mutable base digests are guarded by a private lock
|
|
221
|
+
held only for the instant needed to read or advance them.
|
|
222
|
+
"""
|
|
223
|
+
|
|
224
|
+
def __init__(
|
|
225
|
+
self,
|
|
226
|
+
source_path: PathLike,
|
|
227
|
+
tree_path: PathLike,
|
|
228
|
+
*,
|
|
229
|
+
base_source_sha256: Optional[str] = None,
|
|
230
|
+
base_tree_payload_sha256: Optional[str] = None,
|
|
231
|
+
tree_canonicalizer: TreeCanonicalizer = default_tree_canonicalizer,
|
|
232
|
+
) -> None:
|
|
233
|
+
"""Open a session over ``source_path`` and ``tree_path``. Base
|
|
234
|
+
digests default to the files' real digests now; a caller that
|
|
235
|
+
already computed them while validating the pair may pass them
|
|
236
|
+
instead of paying for a second read. A digest that cannot be
|
|
237
|
+
established (absent or undecodable file) raises ``StorageIOError``."""
|
|
238
|
+
self._source_path = Path(source_path)
|
|
239
|
+
self._tree_path = Path(tree_path)
|
|
240
|
+
self._canonicalize = tree_canonicalizer
|
|
241
|
+
self._lock = threading.Lock()
|
|
242
|
+
if base_source_sha256 is None:
|
|
243
|
+
base_source_sha256 = self._require_digest(self._source_evidence())
|
|
244
|
+
if base_tree_payload_sha256 is None:
|
|
245
|
+
base_tree_payload_sha256 = self._require_digest(self._tree_evidence())
|
|
246
|
+
self._base_source_sha256 = base_source_sha256
|
|
247
|
+
self._base_tree_payload_sha256 = base_tree_payload_sha256
|
|
248
|
+
|
|
249
|
+
@property
|
|
250
|
+
def source_path(self) -> Path:
|
|
251
|
+
"""The source file this session guards."""
|
|
252
|
+
return self._source_path
|
|
253
|
+
|
|
254
|
+
@property
|
|
255
|
+
def tree_path(self) -> Path:
|
|
256
|
+
"""The serialized tree file paired with that source."""
|
|
257
|
+
return self._tree_path
|
|
258
|
+
|
|
259
|
+
@property
|
|
260
|
+
def base_source_sha256(self) -> str:
|
|
261
|
+
"""Digest of the source bytes this session was opened over."""
|
|
262
|
+
with self._lock:
|
|
263
|
+
return self._base_source_sha256
|
|
264
|
+
|
|
265
|
+
@property
|
|
266
|
+
def base_tree_payload_sha256(self) -> str:
|
|
267
|
+
"""Digest of the tree payload this session was opened over."""
|
|
268
|
+
with self._lock:
|
|
269
|
+
return self._base_tree_payload_sha256
|
|
270
|
+
|
|
271
|
+
# -- disk evidence ------------------------------------------------------
|
|
272
|
+
|
|
273
|
+
def _read_bytes(self, path: Path) -> Optional[bytes]:
|
|
274
|
+
"""Return the file's bytes, or None if it no longer exists. Only
|
|
275
|
+
absence is reported as None, so a deletion is classified as an
|
|
276
|
+
external modification; every other OS failure is a genuine I/O
|
|
277
|
+
fault and raises ``StorageIOError``."""
|
|
278
|
+
try:
|
|
279
|
+
return path.read_bytes()
|
|
280
|
+
except FileNotFoundError:
|
|
281
|
+
return None
|
|
282
|
+
except OSError as exc:
|
|
283
|
+
raise StorageIOError(f"cannot read {path}: {exc}", path=str(path), phase="verify_read") from exc
|
|
284
|
+
|
|
285
|
+
def _evidence(self, path: Path, digest_of: Callable[[bytes], str]) -> FileEvidence:
|
|
286
|
+
"""On-disk facts for one file; the digest is None when it is missing
|
|
287
|
+
or no longer readable as a payload. ``size``/``mtime_ns`` are read
|
|
288
|
+
here as diagnostics only, never as a decision input ({p093})."""
|
|
289
|
+
data = self._read_bytes(path)
|
|
290
|
+
try:
|
|
291
|
+
info = os.stat(path)
|
|
292
|
+
size: Optional[int] = info.st_size
|
|
293
|
+
mtime_ns: Optional[int] = info.st_mtime_ns
|
|
294
|
+
except OSError:
|
|
295
|
+
size, mtime_ns = None, None
|
|
296
|
+
if data is None:
|
|
297
|
+
return FileEvidence(path, False, None, size, mtime_ns, "missing")
|
|
298
|
+
try:
|
|
299
|
+
return FileEvidence(path, True, digest_of(data), size, mtime_ns)
|
|
300
|
+
except TreePayloadInvalid as exc:
|
|
301
|
+
return FileEvidence(path, True, None, size, mtime_ns, str(exc))
|
|
302
|
+
|
|
303
|
+
def _source_evidence(self) -> FileEvidence:
|
|
304
|
+
"""Current on-disk facts about the source file."""
|
|
305
|
+
return self._evidence(self._source_path, source_sha256)
|
|
306
|
+
|
|
307
|
+
def _tree_evidence(self) -> FileEvidence:
|
|
308
|
+
"""Current on-disk facts about the tree file. A file that no longer
|
|
309
|
+
canonicalizes yields no digest rather than a payload fault, so the
|
|
310
|
+
caller sees CONCURRENT_TREE_MODIFICATION: external corruption is an
|
|
311
|
+
external modification."""
|
|
312
|
+
return self._evidence(self._tree_path, lambda raw: tree_payload_sha256(self._canonicalize(raw)))
|
|
313
|
+
|
|
314
|
+
def _require_digest(self, evidence: FileEvidence) -> str:
|
|
315
|
+
"""Return the evidence digest, refusing to open a session without one."""
|
|
316
|
+
if evidence.sha256 is None:
|
|
317
|
+
raise StorageIOError(
|
|
318
|
+
f"cannot open a session over {evidence.path}: {evidence.unreadable_reason}",
|
|
319
|
+
path=str(evidence.path), phase="open_baseline")
|
|
320
|
+
return evidence.sha256
|
|
321
|
+
|
|
322
|
+
# -- verification -------------------------------------------------------
|
|
323
|
+
|
|
324
|
+
def inspect(self) -> ConflictReport:
|
|
325
|
+
"""Recompute both digests from disk and report, without raising. A
|
|
326
|
+
file that vanished or became undecodable has no current digest and
|
|
327
|
+
counts as changed: the bytes this session was opened over are no
|
|
328
|
+
longer the bytes on disk."""
|
|
329
|
+
source = self._source_evidence()
|
|
330
|
+
tree = self._tree_evidence()
|
|
331
|
+
with self._lock:
|
|
332
|
+
base_source = self._base_source_sha256
|
|
333
|
+
base_tree = self._base_tree_payload_sha256
|
|
334
|
+
return ConflictReport(
|
|
335
|
+
source=source, tree=tree,
|
|
336
|
+
base_source_sha256=base_source, base_tree_payload_sha256=base_tree,
|
|
337
|
+
source_changed=source.sha256 != base_source,
|
|
338
|
+
tree_changed=tree.sha256 != base_tree)
|
|
339
|
+
|
|
340
|
+
def check_before_write(
|
|
341
|
+
self, policy: ConflictResolutionPolicy = ConflictResolutionPolicy.REFUSE
|
|
342
|
+
) -> ConflictReport:
|
|
343
|
+
"""Verify the pair before a write and refuse on a conflict ({p089}).
|
|
344
|
+
Returns the report when both files still match their base digests,
|
|
345
|
+
or when ``policy`` names the overwrite covering each detected
|
|
346
|
+
conflict. Otherwise raises ``ConcurrentSourceModification`` for a
|
|
347
|
+
changed source and ``ConcurrentTreeModification`` for a changed tree
|
|
348
|
+
file; the source is checked first."""
|
|
349
|
+
if not isinstance(policy, ConflictResolutionPolicy):
|
|
350
|
+
raise TypeError(
|
|
351
|
+
f"policy must be a named ConflictResolutionPolicy member, got {type(policy).__name__}")
|
|
352
|
+
report = self.inspect()
|
|
353
|
+
if report.source_changed and not policy.allows_source_overwrite():
|
|
354
|
+
raise ConcurrentSourceModification(
|
|
355
|
+
f"source file {self._source_path} changed outside this edit session",
|
|
356
|
+
path=str(self._source_path),
|
|
357
|
+
base_source_sha256=report.base_source_sha256,
|
|
358
|
+
current_source_sha256=report.source.sha256,
|
|
359
|
+
exists=report.source.exists, reason=report.source.unreadable_reason)
|
|
360
|
+
if report.tree_changed and not policy.allows_tree_overwrite():
|
|
361
|
+
raise ConcurrentTreeModification(
|
|
362
|
+
f"tree file {self._tree_path} changed outside this edit session",
|
|
363
|
+
path=str(self._tree_path),
|
|
364
|
+
base_tree_payload_sha256=report.base_tree_payload_sha256,
|
|
365
|
+
current_tree_payload_sha256=report.tree.sha256,
|
|
366
|
+
exists=report.tree.exists, reason=report.tree.unreadable_reason)
|
|
367
|
+
return report
|
|
368
|
+
|
|
369
|
+
def accept_publication(
|
|
370
|
+
self, expected_source_sha256: str, expected_tree_payload_sha256: str
|
|
371
|
+
) -> ConflictReport:
|
|
372
|
+
"""Advance the base digests after a publish, once verified ({p091}).
|
|
373
|
+
Re-reads both published files, recomputes both digests, and adopts
|
|
374
|
+
them as the new baseline only when they equal what the publication
|
|
375
|
+
claims to have written. A mismatch leaves the baseline untouched and
|
|
376
|
+
raises ``ChecksumMismatch`` -- the caller's signal to run storage
|
|
377
|
+
recovery rather than to mark the session clean."""
|
|
378
|
+
source = self._source_evidence()
|
|
379
|
+
tree = self._tree_evidence()
|
|
380
|
+
if source.sha256 != expected_source_sha256:
|
|
381
|
+
raise ChecksumMismatch(
|
|
382
|
+
f"published source {self._source_path} does not match its expected digest",
|
|
383
|
+
path=str(self._source_path), expected_source_sha256=expected_source_sha256,
|
|
384
|
+
actual_source_sha256=source.sha256)
|
|
385
|
+
if tree.sha256 != expected_tree_payload_sha256:
|
|
386
|
+
raise ChecksumMismatch(
|
|
387
|
+
f"published tree file {self._tree_path} does not match its expected digest",
|
|
388
|
+
path=str(self._tree_path),
|
|
389
|
+
expected_tree_payload_sha256=expected_tree_payload_sha256,
|
|
390
|
+
actual_tree_payload_sha256=tree.sha256)
|
|
391
|
+
with self._lock:
|
|
392
|
+
self._base_source_sha256 = expected_source_sha256
|
|
393
|
+
self._base_tree_payload_sha256 = expected_tree_payload_sha256
|
|
394
|
+
return ConflictReport(
|
|
395
|
+
source=source, tree=tree,
|
|
396
|
+
base_source_sha256=expected_source_sha256,
|
|
397
|
+
base_tree_payload_sha256=expected_tree_payload_sha256,
|
|
398
|
+
source_changed=False, tree_changed=False)
|