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.
Files changed (121) hide show
  1. ai_editor_tree_engine_dev-1.0.176.dist-info/METADATA +35 -0
  2. ai_editor_tree_engine_dev-1.0.176.dist-info/RECORD +121 -0
  3. ai_editor_tree_engine_dev-1.0.176.dist-info/WHEEL +5 -0
  4. ai_editor_tree_engine_dev-1.0.176.dist-info/licenses/LICENSE +21 -0
  5. ai_editor_tree_engine_dev-1.0.176.dist-info/top_level.txt +1 -0
  6. tree_engine/PUBLIC_API.md +161 -0
  7. tree_engine/__init__.py +327 -0
  8. tree_engine/checks/__init__.py +60 -0
  9. tree_engine/checks/builtin/__init__.py +5 -0
  10. tree_engine/checks/builtin/compile_check.py +53 -0
  11. tree_engine/checks/builtin/csv_syntax.py +51 -0
  12. tree_engine/checks/builtin/docstrings.py +211 -0
  13. tree_engine/checks/builtin/encoding.py +55 -0
  14. tree_engine/checks/builtin/fleet_rules.py +227 -0
  15. tree_engine/checks/builtin/format_syntax.py +82 -0
  16. tree_engine/checks/builtin/jsonl_syntax.py +49 -0
  17. tree_engine/checks/builtin/shipped.py +52 -0
  18. tree_engine/checks/builtin/syntax.py +118 -0
  19. tree_engine/checks/builtin/xml_wellformed.py +51 -0
  20. tree_engine/checks/chain.py +332 -0
  21. tree_engine/checks/external/__init__.py +5 -0
  22. tree_engine/checks/external/_base.py +61 -0
  23. tree_engine/checks/external/bandit.py +53 -0
  24. tree_engine/checks/external/black.py +48 -0
  25. tree_engine/checks/external/flake8.py +38 -0
  26. tree_engine/checks/external/isort.py +38 -0
  27. tree_engine/checks/external/mypy.py +45 -0
  28. tree_engine/checks/external/ruff.py +45 -0
  29. tree_engine/checks/external/runner.py +197 -0
  30. tree_engine/checks/model.py +110 -0
  31. tree_engine/checks/options.py +73 -0
  32. tree_engine/checks/plugin.py +171 -0
  33. tree_engine/checks/registry.py +349 -0
  34. tree_engine/core/address.py +376 -0
  35. tree_engine/core/identifier_map.py +266 -0
  36. tree_engine/core/identity.py +226 -0
  37. tree_engine/core/instrumentation.py +399 -0
  38. tree_engine/core/integrity.py +341 -0
  39. tree_engine/core/integrity_full.py +382 -0
  40. tree_engine/core/journal.py +260 -0
  41. tree_engine/core/journal_compose.py +571 -0
  42. tree_engine/core/live_tree.py +785 -0
  43. tree_engine/core/locking.py +188 -0
  44. tree_engine/core/move.py +585 -0
  45. tree_engine/core/move_references.py +323 -0
  46. tree_engine/core/node_types.py +408 -0
  47. tree_engine/core/nodes.py +348 -0
  48. tree_engine/core/offsets.py +24 -0
  49. tree_engine/core/operations.py +825 -0
  50. tree_engine/core/plugin_boundary.py +160 -0
  51. tree_engine/core/position_map.py +263 -0
  52. tree_engine/core/position_transfer.py +512 -0
  53. tree_engine/core/range_refresh.py +366 -0
  54. tree_engine/core/reference_cache.py +360 -0
  55. tree_engine/core/references.py +223 -0
  56. tree_engine/core/reparse.py +378 -0
  57. tree_engine/core/short_id.py +296 -0
  58. tree_engine/core/subtree_apply.py +397 -0
  59. tree_engine/core/subtree_copy.py +399 -0
  60. tree_engine/core/transactions.py +397 -0
  61. tree_engine/core/trivia.py +396 -0
  62. tree_engine/core/updates.py +398 -0
  63. tree_engine/core/validation.py +377 -0
  64. tree_engine/errors.py +104 -0
  65. tree_engine/exceptions.py +376 -0
  66. tree_engine/facade.py +4524 -0
  67. tree_engine/plugins/_statements.py +369 -0
  68. tree_engine/plugins/bsl/block_edit.py +449 -0
  69. tree_engine/plugins/bsl/blocks.py +127 -0
  70. tree_engine/plugins/bsl/checker.py +297 -0
  71. tree_engine/plugins/bsl/dialects.py +303 -0
  72. tree_engine/plugins/bsl/generator.py +481 -0
  73. tree_engine/plugins/bsl/import_map.py +995 -0
  74. tree_engine/plugins/bsl/plugin.py +452 -0
  75. tree_engine/plugins/contract.py +355 -0
  76. tree_engine/plugins/cpp/import_map.py +505 -0
  77. tree_engine/plugins/cpp/languages.py +99 -0
  78. tree_engine/plugins/cpp/plugin.py +501 -0
  79. tree_engine/plugins/csv_format.py +676 -0
  80. tree_engine/plugins/detachable.py +156 -0
  81. tree_engine/plugins/fallback.py +421 -0
  82. tree_engine/plugins/ini_format.py +330 -0
  83. tree_engine/plugins/json_format.py +813 -0
  84. tree_engine/plugins/json_pointer.py +203 -0
  85. tree_engine/plugins/jsonl_format.py +392 -0
  86. tree_engine/plugins/markdown_format.py +748 -0
  87. tree_engine/plugins/onec_query_format.py +61 -0
  88. tree_engine/plugins/parse_position.py +54 -0
  89. tree_engine/plugins/plain_text.py +1543 -0
  90. tree_engine/plugins/python/export_map.py +306 -0
  91. tree_engine/plugins/python/import_map.py +429 -0
  92. tree_engine/plugins/python/plugin.py +1710 -0
  93. tree_engine/plugins/registry.py +497 -0
  94. tree_engine/plugins/scan.py +87 -0
  95. tree_engine/plugins/selection.py +228 -0
  96. tree_engine/plugins/sql_format.py +61 -0
  97. tree_engine/plugins/toml_format.py +1072 -0
  98. tree_engine/plugins/xml_format.py +911 -0
  99. tree_engine/plugins/yaml/builder.py +49 -0
  100. tree_engine/plugins/yaml/emitter.py +225 -0
  101. tree_engine/plugins/yaml/flow.py +227 -0
  102. tree_engine/plugins/yaml/plugin.py +458 -0
  103. tree_engine/plugins/yaml/ranges.py +52 -0
  104. tree_engine/plugins/yaml/reader.py +359 -0
  105. tree_engine/plugins/yaml/scanner.py +298 -0
  106. tree_engine/query/adapter.py +283 -0
  107. tree_engine/query/engine.py +853 -0
  108. tree_engine/query/inspection.py +498 -0
  109. tree_engine/query/outline.py +288 -0
  110. tree_engine/query/predicates.py +263 -0
  111. tree_engine/query/rendered_lines.py +46 -0
  112. tree_engine/query/results.py +206 -0
  113. tree_engine/query/selector.py +400 -0
  114. tree_engine/query/xml_query.py +747 -0
  115. tree_engine/storage/codec.py +400 -0
  116. tree_engine/storage/document_bridge.py +579 -0
  117. tree_engine/storage/file_txn.py +459 -0
  118. tree_engine/storage/history.py +106 -0
  119. tree_engine/storage/lifecycle.py +622 -0
  120. tree_engine/storage/schema.py +403 -0
  121. tree_engine/storage/session_guard.py +398 -0
@@ -0,0 +1,459 @@
1
+ """Recoverable file-transaction primitive for the source/tree file pair (C-012).
2
+
3
+ Scope (concept C-012, narrowed to exactly the atomic-publication mechanism):
4
+ this module owns the low-level machinery that publishes a small, fixed set
5
+ of files (in practice, one document's source file and its serialized tree
6
+ file) so that a crash at any point leaves the pair recoverable, and a
7
+ reader never observes a torn write. It knows nothing about tree schemas,
8
+ checksums, edit sessions, or conflict policy -- those belong to the
9
+ sibling storage-lifecycle module built on top of this one. Payload bytes
10
+ already fully serialized are handed in by the caller; this module never
11
+ parses, validates, or serializes tree content of any kind.
12
+
13
+ Per {p090}: "Storage/integration-slой sohranyaet svyazannuyu paru kak
14
+ vosstanavlivaemuyu faylovuyu tranzaktsiyu... Chastichno opublikovannaya
15
+ para obnaruzhivaetsya i vosstanavlivaetsya storage-sloyem pri sleduyushchem
16
+ otkrytii." In English: the linked pair is published as a recoverable file
17
+ transaction, and a partially published pair is detected and recovered by
18
+ the storage layer at the next open.
19
+
20
+ Protocol (per file entry, target path T, deterministic siblings T+".tmp"
21
+ and T+".bak"):
22
+
23
+ 1. Stage: write the new bytes to T+".tmp" and fsync that file's data.
24
+ 2. Journal: write a manifest (JSON) listing every entry -- target, temp,
25
+ backup paths and whether T pre-existed -- to a caller-supplied journal
26
+ path, via the same stage-then-rename durability pattern. The journal
27
+ is the single fact that says "a transaction is in flight"; its
28
+ removal is always the last act of any outcome (success, roll-forward,
29
+ or roll-back).
30
+ 3. Backup (only for entries where T pre-existed): create T+".bak" as a
31
+ *hard link* to the still-untouched T, so the original bytes remain
32
+ reachable under two names without ever removing T. No copy is needed.
33
+ 4. Publish: `os.rename(T+".tmp", T)`, one atomic filesystem operation
34
+ per entry that swaps T's directory entry onto the staged bytes. T is
35
+ never briefly absent, so a reader opening T at any instant sees
36
+ either the fully old bytes or the fully new bytes, never neither.
37
+ 5. Finalize: once every entry's publish rename has happened, drop the
38
+ now-unneeded backups and the journal.
39
+
40
+ Because step 4 is the only step that consumes (removes) the ".tmp" name,
41
+ "is T+'.tmp' gone?" is exactly the fact "did this entry finish publishing"
42
+ -- the recovery logic below needs no other bookkeeping to tell rolled-
43
+ forward entries from not-yet-published ones.
44
+
45
+ Recovery, run by the caller at the next open (never automatically inside
46
+ `publish`, so the two concerns -- doing a transaction, and discovering one
47
+ left mid-flight -- stay separable and both idempotent):
48
+
49
+ * No journal on disk: no transaction was in flight (or one already fully
50
+ finalized). Only stray ".tmp" files beside the given targets, left by
51
+ an attempt that crashed before the journal was even written, are
52
+ cleaned up.
53
+ * Journal present, every entry's ".tmp" already consumed: the
54
+ transaction reached step 4 for everything but crashed before step 5.
55
+ Roll forward: drop leftover backups and the journal.
56
+ * Journal present, at least one entry not yet published: roll back --
57
+ for any entry that *did* finish (rename its backup back onto the
58
+ target, or delete the target if the entry created a brand-new file
59
+ with no backup), then drop stray ".tmp"/".bak" files and the journal.
60
+ Every target ends up back at its pre-transaction state.
61
+
62
+ Filesystem failures at any step raise :class:`StorageIOError`, carrying
63
+ :attr:`~tree_engine.errors.ErrorCode.STORAGE_IO_ERROR`, the offending path,
64
+ and a `phase` tag. This module performs no checksum computation, no
65
+ session/conflict bookkeeping, and no tree-schema parsing -- see the
66
+ sibling storage-lifecycle step for all of that.
67
+
68
+ Source-of-truth requirement labels honored here: {p090}.
69
+ """
70
+
71
+ from __future__ import annotations
72
+
73
+ import contextlib
74
+ import fcntl
75
+ import hashlib
76
+ import json
77
+ import os
78
+ import stat
79
+ import tempfile
80
+ from dataclasses import dataclass, field
81
+ from pathlib import Path
82
+ from typing import Callable, Iterator, List, Optional, Sequence, Tuple, Union
83
+
84
+ from tree_engine.errors import ErrorCode
85
+
86
+ __all__ = [
87
+ "StorageIOError",
88
+ "FileWrite",
89
+ "RecoveryReport",
90
+ "PublishHook",
91
+ "PairLockBusy",
92
+ "inherit_ownership",
93
+ "pair_lock",
94
+ "publish",
95
+ "recover",
96
+ ]
97
+
98
+ #: ``hook(staged_path, reference_path)`` -- called for each staged file after its bytes are
99
+ #: complete and before the rename that publishes it.
100
+ PublishHook = Callable[[Path, Path], None]
101
+
102
+ PathLike = Union[str, Path]
103
+
104
+
105
+ class StorageIOError(Exception):
106
+ """A filesystem failure encountered while publishing or recovering a
107
+ file-transaction. ``code`` is always
108
+ :attr:`~tree_engine.errors.ErrorCode.STORAGE_IO_ERROR`; ``phase``
109
+ names the step that failed (e.g. ``"stage_temp"``, ``"fsync_temp"``,
110
+ ``"backup_link"``, ``"publish_rename"``, ``"rollback_restore"``,
111
+ ``"read_journal"``); ``path`` is the file the failing operation acted
112
+ on."""
113
+
114
+ def __init__(self, phase: str, path: Path, message: str) -> None:
115
+ self.code = ErrorCode.STORAGE_IO_ERROR
116
+ self.phase = phase
117
+ self.path = path
118
+ super().__init__(f"[{ErrorCode.STORAGE_IO_ERROR.value}] {phase} failed for {path}: {message}")
119
+
120
+
121
+ @dataclass(frozen=True)
122
+ class FileWrite:
123
+ """One entry to publish: the exact bytes that should become the
124
+ contents of ``target_path`` once the transaction commits."""
125
+
126
+ target_path: Path
127
+ content: bytes
128
+
129
+
130
+ @dataclass(frozen=True)
131
+ class RecoveryReport:
132
+ """Outcome of one :func:`recover` call. ``action`` is ``"none"`` (no
133
+ journal found, nothing but possibly stray temp files to clean),
134
+ ``"rolled_forward"`` (a completed transaction was finalized), or
135
+ ``"rolled_back"`` (an incomplete transaction was undone). ``entries``
136
+ lists the target paths the journal covered (empty when ``action`` is
137
+ ``"none"``)."""
138
+
139
+ action: str
140
+ journal_present: bool
141
+ entries: Tuple[Path, ...] = field(default_factory=tuple)
142
+ orphan_temp_files_removed: Tuple[Path, ...] = field(default_factory=tuple)
143
+
144
+
145
+ @dataclass(frozen=True)
146
+ class _PlanEntry:
147
+ target: Path
148
+ temp: Path
149
+ backup: Path
150
+ had_target: bool
151
+
152
+
153
+ def _temp_path(target: Path) -> Path:
154
+ return target.with_name(target.name + ".tmp")
155
+
156
+
157
+ def _backup_path(target: Path) -> Path:
158
+ return target.with_name(target.name + ".bak")
159
+
160
+
161
+ def _stage_temp(temp_path: Path, content: bytes) -> None:
162
+ """Write ``content`` to ``temp_path`` and durably sync its data.
163
+ Creation/write failures raise phase ``"stage_temp"``; a failure of the
164
+ sync itself raises phase ``"fsync_temp"``, kept distinct so callers
165
+ (and the contract tests) can tell the two apart."""
166
+
167
+ try:
168
+ fd = os.open(str(temp_path), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o644)
169
+ except OSError as exc:
170
+ raise StorageIOError("stage_temp", temp_path, str(exc)) from exc
171
+ try:
172
+ try:
173
+ os.write(fd, content)
174
+ except OSError as exc:
175
+ raise StorageIOError("stage_temp", temp_path, str(exc)) from exc
176
+ try:
177
+ os.fsync(fd)
178
+ except OSError as exc:
179
+ raise StorageIOError("fsync_temp", temp_path, str(exc)) from exc
180
+ finally:
181
+ os.close(fd)
182
+
183
+
184
+ def _rename(src: Path, dst: Path, *, phase: str) -> None:
185
+ try:
186
+ os.rename(str(src), str(dst))
187
+ except OSError as exc:
188
+ raise StorageIOError(phase, dst, str(exc)) from exc
189
+
190
+
191
+ def _link(src: Path, dst: Path, *, phase: str) -> None:
192
+ try:
193
+ os.link(str(src), str(dst))
194
+ except OSError as exc:
195
+ raise StorageIOError(phase, dst, str(exc)) from exc
196
+
197
+
198
+ def _unlink(path: Path, *, phase: str) -> None:
199
+ try:
200
+ path.unlink()
201
+ except FileNotFoundError:
202
+ return
203
+ except OSError as exc:
204
+ raise StorageIOError(phase, path, str(exc)) from exc
205
+
206
+
207
+ def _build_plan(files: Sequence[FileWrite]) -> List[_PlanEntry]:
208
+ plan: List[_PlanEntry] = []
209
+ for fw in files:
210
+ target = Path(fw.target_path)
211
+ plan.append(
212
+ _PlanEntry(
213
+ target=target,
214
+ temp=_temp_path(target),
215
+ backup=_backup_path(target),
216
+ had_target=target.exists(),
217
+ )
218
+ )
219
+ return plan
220
+
221
+
222
+ def _write_journal(journal_path: Path, plan: Sequence[_PlanEntry]) -> None:
223
+ payload = {
224
+ "version": 1,
225
+ "entries": [
226
+ {
227
+ "target": str(e.target),
228
+ "temp": str(e.temp),
229
+ "backup": str(e.backup),
230
+ "had_target": e.had_target,
231
+ }
232
+ for e in plan
233
+ ],
234
+ }
235
+ data = json.dumps(payload, sort_keys=True).encode("utf-8")
236
+ journal_tmp = journal_path.with_name(journal_path.name + ".tmp")
237
+ _stage_temp(journal_tmp, data)
238
+ _rename(journal_tmp, journal_path, phase="write_journal")
239
+
240
+
241
+ def _read_journal(journal_path: Path) -> List[_PlanEntry]:
242
+ try:
243
+ raw = journal_path.read_bytes()
244
+ except OSError as exc:
245
+ raise StorageIOError("read_journal", journal_path, str(exc)) from exc
246
+ try:
247
+ payload = json.loads(raw.decode("utf-8"))
248
+ return [
249
+ _PlanEntry(
250
+ target=Path(e["target"]),
251
+ temp=Path(e["temp"]),
252
+ backup=Path(e["backup"]),
253
+ had_target=bool(e["had_target"]),
254
+ )
255
+ for e in payload["entries"]
256
+ ]
257
+ except (ValueError, KeyError, TypeError) as exc:
258
+ raise StorageIOError("read_journal", journal_path, f"corrupt journal: {exc}") from exc
259
+
260
+
261
+ def _finalize(plan: Sequence[_PlanEntry], journal_path: Path) -> None:
262
+ """Both renames are already confirmed done for every entry: drop the
263
+ now-unneeded backups, then the journal itself last."""
264
+
265
+ for entry in plan:
266
+ if entry.had_target:
267
+ _unlink(entry.backup, phase="finalize_backup")
268
+ _unlink(journal_path, phase="finalize_journal")
269
+
270
+
271
+ def _rollback(plan: Sequence[_PlanEntry], journal_path: Path) -> List[Path]:
272
+ """Undo every entry back to its pre-transaction state and drop stray
273
+ temp files. Returns the temp paths that were found and removed."""
274
+
275
+ orphans: List[Path] = []
276
+ for entry in plan:
277
+ published = not entry.temp.exists()
278
+ if published:
279
+ if entry.had_target:
280
+ _rename(entry.backup, entry.target, phase="rollback_restore")
281
+ elif entry.target.exists():
282
+ _unlink(entry.target, phase="rollback_delete_created")
283
+ else:
284
+ if entry.had_target and entry.backup.exists() and not entry.target.exists():
285
+ _rename(entry.backup, entry.target, phase="rollback_restore")
286
+ elif entry.had_target:
287
+ _unlink(entry.backup, phase="rollback_backup")
288
+ if entry.temp.exists():
289
+ _unlink(entry.temp, phase="rollback_temp")
290
+ orphans.append(entry.temp)
291
+ _unlink(journal_path, phase="finalize_journal")
292
+ return orphans
293
+
294
+
295
+ class PairLockBusy(Exception):
296
+ """Another process holds the publication lock of this source/tree pair."""
297
+
298
+
299
+ def inherit_ownership(staged_path: PathLike, reference_path: PathLike) -> None:
300
+ """Give ``staged_path`` the owner, group and permission bits of ``reference_path``.
301
+
302
+ A plain callable usable as a publish hook. uid/gid are copied (a ``PermissionError`` from the
303
+ OS propagates unmasked when the ids differ and the process may not chown); for a regular
304
+ reference file the mode becomes ``reference mode & 0o666``, for a directory it is unchanged.
305
+ A missing ``staged_path`` raises ``FileNotFoundError`` naming it."""
306
+
307
+ staged, reference = Path(staged_path), Path(reference_path)
308
+ try:
309
+ staged_stat = os.stat(staged)
310
+ except FileNotFoundError:
311
+ raise FileNotFoundError(f"staged file does not exist: {staged}") from None
312
+ ref_stat = os.stat(reference)
313
+ if (staged_stat.st_uid, staged_stat.st_gid) != (ref_stat.st_uid, ref_stat.st_gid):
314
+ os.chown(staged, ref_stat.st_uid, ref_stat.st_gid)
315
+ if stat.S_ISREG(ref_stat.st_mode):
316
+ os.chmod(staged, ref_stat.st_mode & 0o666)
317
+
318
+
319
+ def _open_lock_fd(key: Path) -> Tuple[int, Optional[Path]]:
320
+ """Open the lock descriptor for the pair keyed by ``key`` (outside the pair's directory, so
321
+ nothing survives there). Returns ``(fd, lock_file_path_or_None)``."""
322
+
323
+ digest = hashlib.sha256(str(key).encode("utf-8", "surrogateescape")).hexdigest()
324
+ try:
325
+ lock_dir = Path(tempfile.gettempdir()) / "tree_engine_pair_locks"
326
+ lock_dir.mkdir(mode=0o1777, exist_ok=True)
327
+ path = lock_dir / (digest + ".lock")
328
+ fd = os.open(str(path), os.O_RDWR | os.O_CREAT, 0o666)
329
+ try:
330
+ os.chmod(path, 0o666)
331
+ except OSError:
332
+ pass
333
+ return fd, path
334
+ except OSError:
335
+ # No usable lock directory: fall back to the pair's own directory (coarser, no residue).
336
+ return os.open(str(key.parent), os.O_RDONLY), None
337
+
338
+
339
+ @contextlib.contextmanager
340
+ def pair_lock(source_path: PathLike) -> Iterator[None]:
341
+ """Hold an advisory exclusive OS-level lock keyed by the pair of ``source_path``.
342
+
343
+ Non-blocking: when another process (or descriptor) holds it, :class:`PairLockBusy` is raised at
344
+ once. The kernel drops the lock when its holder dies, so a crashed holder never blocks later
345
+ callers. The lock file lives in the temp directory, never beside the pair, and is removed on
346
+ release; the inode re-check closes the unlink race between concurrent acquirers."""
347
+
348
+ key = Path(os.path.realpath(str(source_path)))
349
+ while True:
350
+ fd, lock_path = _open_lock_fd(key)
351
+ try:
352
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
353
+ except OSError as exc:
354
+ os.close(fd)
355
+ raise PairLockBusy(f"publication lock of {key} is held by another process") from exc
356
+ if lock_path is None:
357
+ break
358
+ try:
359
+ if os.fstat(fd).st_ino == os.stat(lock_path).st_ino:
360
+ break
361
+ except FileNotFoundError:
362
+ pass
363
+ os.close(fd) # the previous holder unlinked the file we opened: retry on the new one
364
+ try:
365
+ yield
366
+ finally:
367
+ try:
368
+ if lock_path is not None:
369
+ with contextlib.suppress(OSError):
370
+ os.unlink(lock_path)
371
+ finally:
372
+ os.close(fd)
373
+
374
+
375
+ def publish(files: Sequence[FileWrite], journal_path: PathLike, *,
376
+ before_publish: Optional[PublishHook] = None,
377
+ reference_path: Optional[PathLike] = None) -> None:
378
+ """Publish every entry in ``files`` as one recoverable transaction.
379
+
380
+ On success every ``target_path`` holds its new ``content``, and no
381
+ journal, backup, or temp file is left behind. On a filesystem failure
382
+ at any step, :class:`StorageIOError` propagates and the on-disk state
383
+ is left exactly where the failed step left it -- always safe to hand
384
+ to :func:`recover`, which is the only step responsible for cleanup.
385
+ ``publish`` never attempts recovery itself, so the two concerns stay
386
+ separable and both idempotent.
387
+ """
388
+
389
+ if not files:
390
+ raise ValueError("publish() requires at least one FileWrite")
391
+ journal = Path(journal_path)
392
+ plan = _build_plan(files)
393
+ if len({e.target for e in plan}) != len(plan):
394
+ raise ValueError("publish() targets must be distinct paths")
395
+
396
+ for entry, fw in zip(plan, files):
397
+ _stage_temp(entry.temp, fw.content)
398
+
399
+ if before_publish is not None:
400
+ reference = Path(reference_path) if reference_path is not None else journal.parent
401
+ for entry in plan:
402
+ try:
403
+ before_publish(entry.temp, reference)
404
+ except BaseException as exc:
405
+ for staged in plan:
406
+ with contextlib.suppress(OSError):
407
+ staged.temp.unlink()
408
+ if isinstance(exc, Exception):
409
+ raise StorageIOError("publish_hook", entry.target, f"{type(exc).__name__}: {exc}") from exc
410
+ raise
411
+
412
+ _write_journal(journal, plan)
413
+
414
+ for entry in plan:
415
+ if entry.had_target:
416
+ _unlink(entry.backup, phase="backup_link") # clear any stale leftover first
417
+ _link(entry.target, entry.backup, phase="backup_link")
418
+
419
+ for entry in plan:
420
+ _rename(entry.temp, entry.target, phase="publish_rename")
421
+
422
+ _finalize(plan, journal)
423
+
424
+
425
+ def recover(target_paths: Sequence[PathLike], journal_path: PathLike) -> RecoveryReport:
426
+ """Inspect ``journal_path`` and the deterministic temp/backup siblings
427
+ of ``target_paths`` at open time, and restore a fully consistent
428
+ state: forward if every entry's publish rename already happened,
429
+ backward otherwise. Safe and idempotent to call whether or not a
430
+ transaction was actually in flight.
431
+ """
432
+
433
+ targets = [Path(p) for p in target_paths]
434
+ journal = Path(journal_path)
435
+
436
+ if not journal.exists():
437
+ removed: List[Path] = []
438
+ for target in targets:
439
+ temp = _temp_path(target)
440
+ if temp.exists():
441
+ _unlink(temp, phase="cleanup_temp")
442
+ removed.append(temp)
443
+ return RecoveryReport(action="none", journal_present=False, orphan_temp_files_removed=tuple(removed))
444
+
445
+ plan = _read_journal(journal)
446
+ entry_targets = tuple(e.target for e in plan)
447
+ all_published = all(not e.temp.exists() for e in plan)
448
+
449
+ if all_published:
450
+ _finalize(plan, journal)
451
+ return RecoveryReport(action="rolled_forward", journal_present=True, entries=entry_targets)
452
+
453
+ orphans = _rollback(plan, journal)
454
+ return RecoveryReport(
455
+ action="rolled_back",
456
+ journal_present=True,
457
+ entries=entry_targets,
458
+ orphan_temp_files_removed=tuple(orphans),
459
+ )
@@ -0,0 +1,106 @@
1
+ """The engine's history port: checkpoints the engine records, in a store it does not own.
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+
6
+ Scope: the interface, and nothing else. Recording the editing history of a document is part of the
7
+ ENGINE's lifecycle -- a checkpoint when a document is opened, and a checkpoint after every write --
8
+ because history that exists only as a side effect in one consumer's code is history no other
9
+ consumer has. But the engine must not own a history STORE: the shipped consumer already keeps an
10
+ ephemeral per-session repository with its own initialisation, revision log and rollback, and a
11
+ second implementation inside the engine would be a competing source of truth for the same fact.
12
+
13
+ So the engine declares :class:`HistoryPort`, calls it at exactly those two moments, and knows
14
+ nothing else. Its vocabulary is "checkpoint": this module names no version-control system, imports
15
+ nothing outside the standard library, and never creates, locates or reasons about a repository. An
16
+ implementation is free to be a git repository, an append-only log, or a database; the engine cannot
17
+ tell and must not care.
18
+
19
+ There is deliberately no default implementation here. A no-op recorder would be a stub in
20
+ production code, and worse, it would let a consumer believe history was being kept when nothing
21
+ was. A consumer that keeps no history -- a read-only preview is exactly one -- supplies no port at
22
+ all, and then the engine records nothing, which is the same rule as read-only writing nothing.
23
+
24
+ Two checkpoint shapes, and the difference is load-bearing. A FULL checkpoint carries both artefacts,
25
+ the rendered source and the serialized tree that holds node identity; a DEGRADED one carries the
26
+ source alone, because for this document there is no tree file -- the tree was rebuilt in memory and
27
+ not published, or the format's plugin cannot be serialized into one at all. An implementation that
28
+ records both alike would silently lose the ability to restore identity from a revision, so
29
+ :attr:`Checkpoint.full` states the difference rather than leaving it to be inferred.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ from dataclasses import dataclass
35
+ from enum import Enum
36
+ from pathlib import Path
37
+ from typing import Optional, Protocol, Tuple, runtime_checkable
38
+ from uuid import UUID
39
+
40
+ __all__ = ["Checkpoint", "CheckpointKind", "HistoryPort"]
41
+
42
+
43
+ class CheckpointKind(str, Enum):
44
+ """The two moments the engine records. ``OPEN`` is the baseline taken when a document is
45
+ initialised, before any mutation, so a history has something to roll back TO; ``WRITE`` is
46
+ taken after a publication has been verified on disk, never before it."""
47
+
48
+ OPEN = "open"
49
+ WRITE = "write"
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class Checkpoint:
54
+ """One recordable state of a document, with the artefacts themselves.
55
+
56
+ The bytes are carried, not just the paths, because an ``OPEN`` checkpoint describes state the
57
+ engine did NOT write -- it read it, or it built the tree in memory -- and an implementation
58
+ that re-read the paths would be recording whatever the filesystem happens to hold at that
59
+ later instant instead of what the engine actually opened.
60
+
61
+ ``written_paths`` is empty for every ``OPEN`` checkpoint, which is precisely the statement that
62
+ opening a document changes no file. For a ``WRITE`` it is the exact set the engine published,
63
+ in publication order, so an implementation that stages artefacts stages those and nothing else.
64
+ ``branch`` is the open decision's own name for how the document was obtained, carried as a
65
+ plain string so this module stays free of every other module in the package.
66
+ """
67
+
68
+ kind: CheckpointKind
69
+ document_id: UUID
70
+ document_version: int
71
+ source_path: Optional[Path]
72
+ source_bytes: bytes
73
+ source_sha256: str
74
+ tree_path: Optional[Path] = None
75
+ tree_bytes: Optional[bytes] = None
76
+ tree_payload_sha256: Optional[str] = None
77
+ written_paths: Tuple[Path, ...] = ()
78
+ branch: Optional[str] = None
79
+ format_id: Optional[str] = None
80
+ source_format_id: Optional[str] = None
81
+
82
+ @property
83
+ def full(self) -> bool:
84
+ """True when this checkpoint carries the tree as well as the source, and can therefore
85
+ restore node identity; False when it carries the source alone and cannot."""
86
+ return self.tree_bytes is not None
87
+
88
+
89
+ @runtime_checkable
90
+ class HistoryPort(Protocol):
91
+ """What a consumer supplies so the engine can record a document's history.
92
+
93
+ One method, called by the engine and never by the consumer: at open, and after each verified
94
+ write. An implementation maps the two :class:`Checkpoint` shapes onto its own store -- the
95
+ shipped editor routes a full checkpoint to its tree-and-source commit and a degraded one to its
96
+ source-only commit -- and returns the revision it created, or None if it names none. The
97
+ engine only passes that value back to its caller; it never interprets it.
98
+
99
+ An implementation must not raise for ordinary conditions: it is invoked inside an operation
100
+ that has already succeeded, and a checkpoint failure must not be reported as a failure of the
101
+ open or the write that had in fact completed.
102
+ """
103
+
104
+ def record_checkpoint(self, checkpoint: Checkpoint) -> Optional[str]:
105
+ """Record ``checkpoint``, returning the revision identifier it created, if any."""
106
+ ...