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,397 @@
|
|
|
1
|
+
"""Transactional batch execution and concurrency control (concept C-007).
|
|
2
|
+
|
|
3
|
+
Scope: this module owns :class:`TransactionBatch` (the request shape),
|
|
4
|
+
:class:`TransactionCoordinator` (validates, runs, commits or rolls back a
|
|
5
|
+
batch), and :class:`IsolatedTransactionState` (the private overlay one
|
|
6
|
+
touched document gets for one batch). It composes the already-merged
|
|
7
|
+
single-mutation operations -- never reimplementing what they already do --
|
|
8
|
+
and the already-merged :class:`~tree_engine.core.locking.DocumentLockCoordinator`
|
|
9
|
+
for per-document serialization and deterministic multi-document ordering.
|
|
10
|
+
|
|
11
|
+
Per {p012}/{rgi6}: a batch first checks request shape, ``expected_version``,
|
|
12
|
+
and static constraints -- once, not per operation -- then runs its
|
|
13
|
+
operations in order against an isolated transactional working state, where
|
|
14
|
+
operation N+1 sees the results of operations 1..N of the same batch. The
|
|
15
|
+
batch either publishes completely, as one public ``document_version``
|
|
16
|
+
increment, or rolls back completely; external readers never observe
|
|
17
|
+
anything in between. Per {p035}, a transaction spanning several documents
|
|
18
|
+
acquires all of their locks in ascending UUID4 order, releasing them only
|
|
19
|
+
after commit or rollback -- automatic merging is forbidden, and a stale
|
|
20
|
+
``expected_version`` is refused, never merged. Per {p016}, this module runs
|
|
21
|
+
at most one full-document control check per touched document, after the
|
|
22
|
+
whole batch -- never a check per element.
|
|
23
|
+
|
|
24
|
+
Isolation design (this file's own choice; {p012}/{rgi6} require "isolated
|
|
25
|
+
transactional working state" without dictating its mechanism): each touched
|
|
26
|
+
document gets a private, deep-copied overlay -- its own ``nodes_by_id``,
|
|
27
|
+
``short_id_index``, and ``root`` -- built once when the batch starts. Every
|
|
28
|
+
operation runs against that overlay only, via the same, already-merged
|
|
29
|
+
``insert``/``delete``/``replace_range`` (``operations.py``) and
|
|
30
|
+
``set_body``/``replace_node_id`` (``updates.py``) functions used everywhere
|
|
31
|
+
else in this concept -- this file adds no mutation logic, only the
|
|
32
|
+
overlay/publish/discard plumbing around them. The live document is never
|
|
33
|
+
written to until every operation and the closing full-document check
|
|
34
|
+
succeed; committing then just swaps the three overlay attributes onto it
|
|
35
|
+
and advances ``document_version`` by exactly one. Rolling back is declining
|
|
36
|
+
to publish: the live document was never touched, so every UUID4/short_id a
|
|
37
|
+
rolled-back operation minted lived only in the discarded overlay -- never
|
|
38
|
+
resolvable through the live document. Exactly one overlay per touched
|
|
39
|
+
document is ever live, and it never outlives its batch: not multi-version
|
|
40
|
+
storage, only a private, ephemeral working copy.
|
|
41
|
+
|
|
42
|
+
Duck-typed ``document``: ``nodes_by_id`` (mutable ``node_id -> node``),
|
|
43
|
+
optional ``short_id_index``/``document_id``/``root``, and
|
|
44
|
+
``document_version`` (an ``int`` counter read for ``expected_version`` and
|
|
45
|
+
written to publish the next one; ``version`` is an accepted read fallback,
|
|
46
|
+
mirroring ``subtree_copy.py``). Imports: ``insert``/``delete``/
|
|
47
|
+
``replace_range`` (``operations.py``) and ``set_body``/``replace_node_id``
|
|
48
|
+
(``updates.py``, where this worktree actually defines them) are the single
|
|
49
|
+
mutation operations a batch composes. ``DocumentLockCoordinator``
|
|
50
|
+
(``locking.py``) and ``validate_mutation`` (``validation.py``, both
|
|
51
|
+
indirectly via every operation above, and directly, once per touched
|
|
52
|
+
document, for the closing {p016} check) are reused unmodified. ``Document``
|
|
53
|
+
(``nodes.py``) types the documents a caller passes in.
|
|
54
|
+
|
|
55
|
+
Non-goals: no per-element full parses/checks, no automatic conflict
|
|
56
|
+
resolution/merging, no multi-version storage. Source-of-truth labels
|
|
57
|
+
honored here: {p012}, {p016}, {p035}, {rgi6}.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
from __future__ import annotations
|
|
61
|
+
|
|
62
|
+
import copy
|
|
63
|
+
from dataclasses import dataclass, field
|
|
64
|
+
from typing import Any, Dict, List, Mapping, Optional, Sequence, Set, Tuple
|
|
65
|
+
from uuid import UUID
|
|
66
|
+
|
|
67
|
+
from tree_engine.core.locking import DocumentLockCoordinator
|
|
68
|
+
from tree_engine.core.nodes import Document
|
|
69
|
+
from tree_engine.core.operations import delete, insert, replace_range
|
|
70
|
+
from tree_engine.core.updates import replace_node_id as _update_replace_node_id
|
|
71
|
+
from tree_engine.core.updates import set_body as _update_set_body
|
|
72
|
+
from tree_engine.core.validation import ValidationError, validate_mutation
|
|
73
|
+
from tree_engine.errors import ErrorCode
|
|
74
|
+
|
|
75
|
+
__all__ = [
|
|
76
|
+
"TransactionError",
|
|
77
|
+
"Operation",
|
|
78
|
+
"TransactionBatch",
|
|
79
|
+
"CommitResult",
|
|
80
|
+
"IsolatedTransactionState",
|
|
81
|
+
"TransactionCoordinator",
|
|
82
|
+
]
|
|
83
|
+
|
|
84
|
+
_OPERATION_KINDS = ("insert", "delete", "replace_range", "set_body", "replace_node_id")
|
|
85
|
+
_ABSENT = object()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class TransactionError(Exception):
|
|
89
|
+
"""Raised when a batch is refused outright or must be rolled back.
|
|
90
|
+
|
|
91
|
+
``code`` is the originating :class:`~tree_engine.errors.ErrorCode`
|
|
92
|
+
(``DOCUMENT_VERSION_CONFLICT`` for a stale ``expected_version``,
|
|
93
|
+
``CONCURRENT_TREE_MODIFICATION`` for a post-batch integrity failure or
|
|
94
|
+
an out-of-band change under the lock, or a shape-check code). ``errors``
|
|
95
|
+
optionally carries the underlying
|
|
96
|
+
:class:`~tree_engine.core.validation.ValidationError` list. Raising this
|
|
97
|
+
always means no document touched by the batch was mutated.
|
|
98
|
+
"""
|
|
99
|
+
|
|
100
|
+
def __init__(self, code: ErrorCode, message: str, errors: Sequence[ValidationError] = ()) -> None:
|
|
101
|
+
self.code = code
|
|
102
|
+
self.errors: List[ValidationError] = list(errors)
|
|
103
|
+
super().__init__(f"[{code.value}] {message}")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@dataclass(frozen=True)
|
|
107
|
+
class Operation:
|
|
108
|
+
"""One entry of a :class:`TransactionBatch`: ``kind`` is one of
|
|
109
|
+
``_OPERATION_KINDS``; ``document_id`` is ``None`` for the batch's own
|
|
110
|
+
document (the ordinary, single-document case); ``args``/``kwargs`` are
|
|
111
|
+
forwarded verbatim to the matching operation function, against that
|
|
112
|
+
document's overlay."""
|
|
113
|
+
|
|
114
|
+
kind: str
|
|
115
|
+
document_id: Optional[UUID] = None
|
|
116
|
+
args: Tuple[Any, ...] = ()
|
|
117
|
+
kwargs: Mapping[str, Any] = field(default_factory=dict)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@dataclass
|
|
121
|
+
class TransactionBatch:
|
|
122
|
+
"""One request: an ordered list of operations to run as a single unit.
|
|
123
|
+
|
|
124
|
+
``document_id`` is the batch's primary (and usually only) document.
|
|
125
|
+
``expected_versions`` maps each touched document_id to the
|
|
126
|
+
``document_version`` last observed by the caller; an absent id is not
|
|
127
|
+
version-checked. Per {p012}, ``expected_version`` is checked once, at
|
|
128
|
+
batch start -- never per operation. The builder methods each append one
|
|
129
|
+
:class:`Operation` and return ``self`` for fluent assembly.
|
|
130
|
+
"""
|
|
131
|
+
|
|
132
|
+
document_id: UUID
|
|
133
|
+
expected_versions: Dict[UUID, Any] = field(default_factory=dict)
|
|
134
|
+
operations: List[Operation] = field(default_factory=list)
|
|
135
|
+
|
|
136
|
+
def _add(self, kind: str, *args: Any, document_id: Optional[UUID] = None, **kwargs: Any) -> "TransactionBatch":
|
|
137
|
+
self.operations.append(Operation(kind=kind, document_id=document_id, args=args, kwargs=kwargs))
|
|
138
|
+
return self
|
|
139
|
+
|
|
140
|
+
def insert(self, incoming: Any, *, position: str, document_id: Optional[UUID] = None, **kwargs: Any) -> "TransactionBatch":
|
|
141
|
+
return self._add("insert", incoming, position=position, document_id=document_id, **kwargs)
|
|
142
|
+
|
|
143
|
+
def delete(self, targets: Any, *, document_id: Optional[UUID] = None) -> "TransactionBatch":
|
|
144
|
+
return self._add("delete", targets, document_id=document_id)
|
|
145
|
+
|
|
146
|
+
def replace_range(self, targets: Any, incoming: Any, *, document_id: Optional[UUID] = None, **kwargs: Any) -> "TransactionBatch":
|
|
147
|
+
return self._add("replace_range", targets, incoming, document_id=document_id, **kwargs)
|
|
148
|
+
|
|
149
|
+
def set_body(self, node: Any, body: Any, *, document_id: Optional[UUID] = None, **kwargs: Any) -> "TransactionBatch":
|
|
150
|
+
return self._add("set_body", node, body, document_id=document_id, **kwargs)
|
|
151
|
+
|
|
152
|
+
def replace_node_id(self, old_node_id: UUID, new_node_id: UUID, *, document_id: Optional[UUID] = None, **kwargs: Any) -> "TransactionBatch":
|
|
153
|
+
return self._add("replace_node_id", old_node_id, new_node_id, document_id=document_id, **kwargs)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
@dataclass(frozen=True)
|
|
157
|
+
class CommitResult:
|
|
158
|
+
"""Outcome of one successful :meth:`TransactionCoordinator.execute`
|
|
159
|
+
call. ``document_versions`` maps each touched document_id to its
|
|
160
|
+
``(old_version, new_version)`` pair -- ``new_version`` is always exactly
|
|
161
|
+
one past ``old_version``, regardless of how many operations touched
|
|
162
|
+
that document. ``results`` is the ordered, per-operation return value,
|
|
163
|
+
in batch order."""
|
|
164
|
+
|
|
165
|
+
document_versions: Mapping[UUID, Tuple[Any, Any]]
|
|
166
|
+
results: Tuple[Any, ...]
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
@dataclass
|
|
170
|
+
class IsolatedTransactionState:
|
|
171
|
+
"""The private, in-memory overlay one document gets for one batch.
|
|
172
|
+
Every operation runs against ``proxy`` -- never ``document`` itself --
|
|
173
|
+
so operation N+1 sees every mutation operations 1..N already made (same
|
|
174
|
+
overlay objects, mutated in place), while ``document`` stays
|
|
175
|
+
byte-identical to its pre-batch state until
|
|
176
|
+
:meth:`TransactionCoordinator.commit` publishes it."""
|
|
177
|
+
|
|
178
|
+
document_id: Optional[UUID]
|
|
179
|
+
document: Any
|
|
180
|
+
proxy: Any
|
|
181
|
+
starting_version: Any
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
class _OverlayDocument:
|
|
185
|
+
"""Minimal duck-typed document proxy the mutation operations run
|
|
186
|
+
against: only the attributes those functions actually read or write."""
|
|
187
|
+
|
|
188
|
+
__slots__ = ("document_id", "nodes_by_id", "short_id_index", "root")
|
|
189
|
+
|
|
190
|
+
def __init__(self, *, document_id: Any, nodes_by_id: Any, short_id_index: Any, root: Any) -> None:
|
|
191
|
+
self.document_id = document_id
|
|
192
|
+
self.nodes_by_id = nodes_by_id
|
|
193
|
+
self.short_id_index = short_id_index
|
|
194
|
+
self.root = root
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _read_version(document: Any) -> Any:
|
|
198
|
+
current = getattr(document, "document_version", _ABSENT)
|
|
199
|
+
if current is _ABSENT:
|
|
200
|
+
current = getattr(document, "version", None)
|
|
201
|
+
return current
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _bump_version(document: Any, current: Any) -> Any:
|
|
205
|
+
new_version = (current + 1) if isinstance(current, int) else 1
|
|
206
|
+
document.document_version = new_version
|
|
207
|
+
return new_version
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _clone_state(document: Any) -> IsolatedTransactionState:
|
|
211
|
+
"""Build the private overlay for one document ({rgi6}): one shared memo
|
|
212
|
+
across ``nodes_by_id``/``short_id_index``/``root`` so the cloned object
|
|
213
|
+
graph keeps the same internal identity relationships (a cloned child's
|
|
214
|
+
cloned ``parent`` is the same object as the cloned parent's entry in
|
|
215
|
+
the cloned ``nodes_by_id``) that the original graph had."""
|
|
216
|
+
|
|
217
|
+
memo: Dict[int, Any] = {}
|
|
218
|
+
nodes_by_id = getattr(document, "nodes_by_id", None) or {}
|
|
219
|
+
short_id_index = getattr(document, "short_id_index", None)
|
|
220
|
+
root = getattr(document, "root", None)
|
|
221
|
+
cloned_nodes = copy.deepcopy(nodes_by_id, memo)
|
|
222
|
+
cloned_short_index = copy.deepcopy(short_id_index, memo) if isinstance(short_id_index, dict) else short_id_index
|
|
223
|
+
cloned_root = copy.deepcopy(root, memo) if root is not None else None
|
|
224
|
+
proxy = _OverlayDocument(
|
|
225
|
+
document_id=getattr(document, "document_id", None),
|
|
226
|
+
nodes_by_id=cloned_nodes,
|
|
227
|
+
short_id_index=cloned_short_index,
|
|
228
|
+
root=cloned_root,
|
|
229
|
+
)
|
|
230
|
+
return IsolatedTransactionState(
|
|
231
|
+
document_id=getattr(document, "document_id", None),
|
|
232
|
+
document=document,
|
|
233
|
+
proxy=proxy,
|
|
234
|
+
starting_version=_read_version(document),
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _check_expected_version(document: Any, expected_version: Any) -> None:
|
|
239
|
+
if expected_version is None:
|
|
240
|
+
return
|
|
241
|
+
current = _read_version(document)
|
|
242
|
+
if current != expected_version:
|
|
243
|
+
raise TransactionError(
|
|
244
|
+
ErrorCode.DOCUMENT_VERSION_CONFLICT,
|
|
245
|
+
f"expected_version {expected_version!r} does not match current "
|
|
246
|
+
f"document_version {current!r}; automatic merging is forbidden, "
|
|
247
|
+
"so this batch is refused rather than merged",
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _full_document_check(proxy: Any) -> None:
|
|
252
|
+
"""The single, closing {p016} control check for a completed batch: one
|
|
253
|
+
``validate_mutation`` call over the whole final overlay tree, never one
|
|
254
|
+
per element. The overlay's own root is checked against a throwaway,
|
|
255
|
+
empty-map stand-in document, so this call is purely diagnostic -- it
|
|
256
|
+
validates every node id in the overlay -- and never reports a false
|
|
257
|
+
conflict against the overlay's own already-registered content."""
|
|
258
|
+
|
|
259
|
+
if proxy.root is None:
|
|
260
|
+
return
|
|
261
|
+
stand_in = _OverlayDocument(document_id=proxy.document_id, nodes_by_id={}, short_id_index=None, root=None)
|
|
262
|
+
result = validate_mutation(stand_in, proxy.root, parent=None, position=None)
|
|
263
|
+
if not result.success:
|
|
264
|
+
raise TransactionError(
|
|
265
|
+
ErrorCode.CONCURRENT_TREE_MODIFICATION,
|
|
266
|
+
"post-batch full-document control check failed",
|
|
267
|
+
errors=result.errors,
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _validate_shape(batch: TransactionBatch) -> None:
|
|
272
|
+
if not isinstance(batch, TransactionBatch):
|
|
273
|
+
raise TransactionError(ErrorCode.INVALID_SELECTOR, "batch must be a TransactionBatch instance")
|
|
274
|
+
if batch.document_id is None:
|
|
275
|
+
raise TransactionError(ErrorCode.INVALID_SELECTOR, "batch.document_id is required")
|
|
276
|
+
if not batch.operations:
|
|
277
|
+
raise TransactionError(ErrorCode.INVALID_SELECTOR, "a batch must contain at least one operation")
|
|
278
|
+
for op in batch.operations:
|
|
279
|
+
if op.kind not in _OPERATION_KINDS:
|
|
280
|
+
raise TransactionError(ErrorCode.INVALID_SELECTOR, f"unrecognized operation kind: {op.kind!r}")
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _touched_document_ids(batch: TransactionBatch) -> Set[UUID]:
|
|
284
|
+
touched = {batch.document_id}
|
|
285
|
+
touched.update(batch.expected_versions.keys())
|
|
286
|
+
for op in batch.operations:
|
|
287
|
+
touched.add(op.document_id or batch.document_id)
|
|
288
|
+
return touched
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _execute_operation(op: Operation, proxy: Any, loaded_documents: Mapping[UUID, Any]) -> Any:
|
|
292
|
+
if op.kind == "delete":
|
|
293
|
+
return delete(proxy, *op.args)
|
|
294
|
+
kwargs = dict(op.kwargs)
|
|
295
|
+
kwargs.setdefault("loaded_documents", loaded_documents)
|
|
296
|
+
if op.kind == "insert":
|
|
297
|
+
return insert(proxy, *op.args, **kwargs)
|
|
298
|
+
if op.kind == "replace_range":
|
|
299
|
+
return replace_range(proxy, *op.args, **kwargs)
|
|
300
|
+
if op.kind == "set_body":
|
|
301
|
+
return _update_set_body(proxy, *op.args, **kwargs)
|
|
302
|
+
return _update_replace_node_id(proxy, *op.args, **kwargs)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
class TransactionCoordinator:
|
|
306
|
+
"""Validates, runs, and commits/rolls back one :class:`TransactionBatch`
|
|
307
|
+
at a time, serialized per document via a shared
|
|
308
|
+
:class:`~tree_engine.core.locking.DocumentLockCoordinator` ({p035})."""
|
|
309
|
+
|
|
310
|
+
def __init__(self, lock_coordinator: Optional[DocumentLockCoordinator] = None) -> None:
|
|
311
|
+
self._locks = lock_coordinator or DocumentLockCoordinator()
|
|
312
|
+
|
|
313
|
+
@property
|
|
314
|
+
def lock_coordinator(self) -> DocumentLockCoordinator:
|
|
315
|
+
return self._locks
|
|
316
|
+
|
|
317
|
+
def execute(self, documents: Mapping[UUID, Document], batch: TransactionBatch) -> CommitResult:
|
|
318
|
+
"""Run ``batch`` against ``documents`` (``document_id -> document``,
|
|
319
|
+
covering at least every id the batch touches). Order: static shape
|
|
320
|
+
check -> acquire every touched lock in ascending UUID4 order ->
|
|
321
|
+
check ``expected_version`` per document, once -> clone one overlay
|
|
322
|
+
per document -> run every operation against its target overlay,
|
|
323
|
+
each seeing prior operations' overlay writes -> one closing
|
|
324
|
+
full-document check per touched document -> commit or roll back,
|
|
325
|
+
all under the same held locks, with no partial publication.
|
|
326
|
+
"""
|
|
327
|
+
|
|
328
|
+
_validate_shape(batch)
|
|
329
|
+
touched_ids = _touched_document_ids(batch)
|
|
330
|
+
missing = touched_ids - set(documents.keys())
|
|
331
|
+
if missing:
|
|
332
|
+
raise TransactionError(
|
|
333
|
+
ErrorCode.NODE_NOT_FOUND,
|
|
334
|
+
f"documents not supplied for touched ids: {sorted(missing, key=str)}",
|
|
335
|
+
)
|
|
336
|
+
|
|
337
|
+
with self._locks.acquire_locks(touched_ids) as locked_ids:
|
|
338
|
+
for document_id in locked_ids:
|
|
339
|
+
_check_expected_version(documents[document_id], batch.expected_versions.get(document_id))
|
|
340
|
+
states = {document_id: _clone_state(documents[document_id]) for document_id in locked_ids}
|
|
341
|
+
try:
|
|
342
|
+
results = self._run_operations(batch, states)
|
|
343
|
+
for state in states.values():
|
|
344
|
+
_full_document_check(state.proxy)
|
|
345
|
+
versions = self.commit(states)
|
|
346
|
+
except Exception:
|
|
347
|
+
self.rollback(states)
|
|
348
|
+
raise
|
|
349
|
+
return CommitResult(document_versions=versions, results=tuple(results))
|
|
350
|
+
|
|
351
|
+
def execute_single(self, document: Document, batch: TransactionBatch) -> CommitResult:
|
|
352
|
+
"""Convenience wrapper for the common single-document batch."""
|
|
353
|
+
return self.execute({batch.document_id: document}, batch)
|
|
354
|
+
|
|
355
|
+
def _run_operations(self, batch: TransactionBatch, states: Mapping[UUID, IsolatedTransactionState]) -> List[Any]:
|
|
356
|
+
overlays = {document_id: state.proxy for document_id, state in states.items()}
|
|
357
|
+
results: List[Any] = []
|
|
358
|
+
for op in batch.operations:
|
|
359
|
+
target_id = op.document_id or batch.document_id
|
|
360
|
+
results.append(_execute_operation(op, states[target_id].proxy, overlays))
|
|
361
|
+
return results
|
|
362
|
+
|
|
363
|
+
def commit(self, states: Mapping[UUID, IsolatedTransactionState]) -> Dict[UUID, Tuple[Any, Any]]:
|
|
364
|
+
"""Publish every touched document's overlay and advance its public
|
|
365
|
+
``document_version`` by exactly one ({rgi6}). Two passes, so no
|
|
366
|
+
document is ever partially published: first every state is
|
|
367
|
+
re-checked against its own ``starting_version`` (defensive -- the
|
|
368
|
+
held lock already rules out another transaction changing it, so
|
|
369
|
+
this only fires if something bypassed the coordinator); only once
|
|
370
|
+
every state clears that check does the second pass swap in the
|
|
371
|
+
overlays and bump versions.
|
|
372
|
+
"""
|
|
373
|
+
|
|
374
|
+
for document_id, state in states.items():
|
|
375
|
+
if _read_version(state.document) != state.starting_version:
|
|
376
|
+
raise TransactionError(
|
|
377
|
+
ErrorCode.CONCURRENT_TREE_MODIFICATION,
|
|
378
|
+
f"document {document_id} changed underneath an active transaction",
|
|
379
|
+
)
|
|
380
|
+
versions: Dict[UUID, Tuple[Any, Any]] = {}
|
|
381
|
+
for document_id, state in states.items():
|
|
382
|
+
document = state.document
|
|
383
|
+
document.nodes_by_id = state.proxy.nodes_by_id
|
|
384
|
+
document.short_id_index = state.proxy.short_id_index
|
|
385
|
+
document.root = state.proxy.root
|
|
386
|
+
versions[document_id] = (state.starting_version, _bump_version(document, state.starting_version))
|
|
387
|
+
return versions
|
|
388
|
+
|
|
389
|
+
def rollback(self, states: Mapping[UUID, IsolatedTransactionState]) -> None:
|
|
390
|
+
"""Discard every touched document's overlay ({rgi6}). Every
|
|
391
|
+
operation this batch ran only ever mutated ``state.proxy`` -- a
|
|
392
|
+
private, unpublished clone -- so rolling back is simply declining
|
|
393
|
+
to publish it: ``state.document`` was never written to on any path
|
|
394
|
+
reaching this method, so it stays byte-identical to its pre-batch
|
|
395
|
+
snapshot, and no UUID4/short_id an operation's overlay-only writes
|
|
396
|
+
introduced is ever reachable from ``state.document``."""
|
|
397
|
+
dict(states).clear()
|