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
tree_engine/core/move.py
ADDED
|
@@ -0,0 +1,585 @@
|
|
|
1
|
+
"""Atomic subtree move: intra-document and cross-document (concept C-020).
|
|
2
|
+
|
|
3
|
+
Scope, narrowed exactly to what this atomic step owns per {p009}/{p039}:
|
|
4
|
+
this file is the transaction orchestrator for :func:`move`. It owns locking
|
|
5
|
+
order, running the shared C-006 preflight validator against the target
|
|
6
|
+
document before any mutation, structural relocation (detach from the
|
|
7
|
+
source, reattach in the target) with full rollback on any failure, UUID4
|
|
8
|
+
identity preservation, and target-document short_id reassignment (free
|
|
9
|
+
short_ids kept, conflicting ones reassigned from the target's own
|
|
10
|
+
allocator, with the old->new remap returned to the caller). It never
|
|
11
|
+
implements reference conversion and never implements the move contract
|
|
12
|
+
tests -- both are sibling artifacts.
|
|
13
|
+
|
|
14
|
+
Two sibling facilities are not yet importable modules in this worktree, so,
|
|
15
|
+
following the precedent set by ``validation.py``'s ``next_short_id`` and
|
|
16
|
+
``address.py``'s ``resolve_short_id``, both are consumed here only as
|
|
17
|
+
caller-injected, duck-typed callables -- this file never imports either
|
|
18
|
+
sibling module and never stubs a fake replacement for it:
|
|
19
|
+
|
|
20
|
+
* ``lock_coordinator`` -- the sibling ``locking.py`` facility. Called as
|
|
21
|
+
``lock_coordinator(document_ids)`` with the participating ``document_id``
|
|
22
|
+
values already sorted here in deterministic UUID4 order (per {p035}), and
|
|
23
|
+
used as a context manager: ``with lock_coordinator(document_ids): ...``.
|
|
24
|
+
``None`` means no locking is attempted, mirroring ``validate_mutation``'s
|
|
25
|
+
own ``is_type_compatible=None`` "skip rather than guess" convention.
|
|
26
|
+
* ``reconcile_references`` -- the sibling move-references file's reference
|
|
27
|
+
reconciliation, called once as ``reconcile_references(source_document=...,
|
|
28
|
+
target_document=..., moved_roots=..., short_id_remap=...,
|
|
29
|
+
loaded_documents=...)`` after the structural relocation. It must return an
|
|
30
|
+
object exposing ``.apply(source_document, target_document,
|
|
31
|
+
loaded_documents)`` -- the duck-typed "ReferenceDelta" contract -- called
|
|
32
|
+
inside the same rollback scope as the structural change. ``None`` means no
|
|
33
|
+
reconciliation is attempted.
|
|
34
|
+
|
|
35
|
+
Duck-typed ``document``/``node`` contract, identical to ``operations.py``'s:
|
|
36
|
+
``document.nodes_by_id`` (mutable node_id -> node), an optional
|
|
37
|
+
``document.short_id_index`` (short_id -> node_id), an optional
|
|
38
|
+
``document.document_id``; a node exposes ``node_id``, an optional
|
|
39
|
+
``short_id``, a settable ``parent`` back-link, a settable ``children``
|
|
40
|
+
sequence, and an optional ``buffer_range`` ``(start, end)`` pair.
|
|
41
|
+
|
|
42
|
+
Rollback: every mutation this file performs directly (children splices,
|
|
43
|
+
index-map registration/unregistration, short_id/parent/buffer_range writes)
|
|
44
|
+
is recorded on a changelog before it happens. Validation failure mutates
|
|
45
|
+
nothing, so both documents are left byte-for-byte as given. A failure after
|
|
46
|
+
that -- including the injected ``reconcile_references``/``.apply`` call --
|
|
47
|
+
undoes every recorded change, in reverse order, before re-raising, so a
|
|
48
|
+
mid-move failure still leaves both documents exactly as they were.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
from __future__ import annotations
|
|
52
|
+
|
|
53
|
+
from contextlib import nullcontext
|
|
54
|
+
from dataclasses import dataclass
|
|
55
|
+
from types import SimpleNamespace
|
|
56
|
+
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple
|
|
57
|
+
from uuid import UUID
|
|
58
|
+
|
|
59
|
+
from tree_engine.core.identity import NodeAddress
|
|
60
|
+
from tree_engine.core.nodes import NodeSchemaError
|
|
61
|
+
from tree_engine.core.validation import (
|
|
62
|
+
ShortIdReassignment,
|
|
63
|
+
ValidationError,
|
|
64
|
+
validate_mutation,
|
|
65
|
+
)
|
|
66
|
+
from tree_engine.errors import ErrorCode
|
|
67
|
+
|
|
68
|
+
__all__ = ["MoveError", "MoveResult", "move"]
|
|
69
|
+
|
|
70
|
+
_BEFORE_AFTER = frozenset({"before", "after"})
|
|
71
|
+
_PARENT_POSITIONS = frozenset({"first_child", "last_child", "child_index"})
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class MoveError(Exception):
|
|
75
|
+
"""Raised before any mutation, or after a full rollback of one. Carries
|
|
76
|
+
the never-empty ``errors`` list from the shared preflight validator
|
|
77
|
+
(e.g. ``NODE_ID_CONFLICT``) or this file's own resolution/contiguity
|
|
78
|
+
pre-checks."""
|
|
79
|
+
|
|
80
|
+
def __init__(self, errors: Sequence[ValidationError]) -> None:
|
|
81
|
+
self.errors: List[ValidationError] = list(errors)
|
|
82
|
+
summary = "; ".join(f"{e.code.value}: {e.message}" for e in self.errors)
|
|
83
|
+
super().__init__(summary or "move rejected")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass(frozen=True)
|
|
87
|
+
class MoveResult:
|
|
88
|
+
"""Outcome of one successful :func:`move` call. ``node_id``/``short_id``
|
|
89
|
+
name the first moved root; ``position`` is its final index among the
|
|
90
|
+
target parent's children. ``remap`` is the old_short_id ->
|
|
91
|
+
new_short_id reassignment plan applied in the target document (free
|
|
92
|
+
short_ids never appear in it). ``removed``/``inserted`` are the moved
|
|
93
|
+
nodes' addresses in the source/target document -- same UUID4 ``node_id``,
|
|
94
|
+
per {p039} only ``document_id`` changes for a cross-document move.
|
|
95
|
+
``reference_delta`` is whatever the injected ``reconcile_references``
|
|
96
|
+
callable returned (``None`` when it was not supplied)."""
|
|
97
|
+
|
|
98
|
+
node_id: Optional[UUID]
|
|
99
|
+
short_id: Optional[Any]
|
|
100
|
+
position: Optional[int]
|
|
101
|
+
remap: Tuple[ShortIdReassignment, ...] = ()
|
|
102
|
+
removed: Tuple[NodeAddress, ...] = ()
|
|
103
|
+
inserted: Tuple[NodeAddress, ...] = ()
|
|
104
|
+
reference_delta: Any = None
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
# -- internal helpers (duplicated in miniature from the sibling operations.py,
|
|
108
|
+
# which is the established precedent for this -- see updates.py) -----------
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _resolve(document: Any, ref: Any) -> Optional[Any]:
|
|
112
|
+
if ref is None:
|
|
113
|
+
return None
|
|
114
|
+
nodes_by_id = getattr(document, "nodes_by_id", None) or {}
|
|
115
|
+
candidate_id = getattr(ref, "node_id", None)
|
|
116
|
+
if candidate_id is not None and nodes_by_id.get(candidate_id) is ref:
|
|
117
|
+
return ref
|
|
118
|
+
if isinstance(ref, UUID) and ref in nodes_by_id:
|
|
119
|
+
return nodes_by_id[ref]
|
|
120
|
+
short_index = getattr(document, "short_id_index", None)
|
|
121
|
+
if isinstance(short_index, dict) and ref in short_index:
|
|
122
|
+
return nodes_by_id.get(short_index[ref])
|
|
123
|
+
for node in nodes_by_id.values():
|
|
124
|
+
if getattr(node, "short_id", None) == ref:
|
|
125
|
+
return node
|
|
126
|
+
return None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _children_list(node: Any) -> List[Any]:
|
|
130
|
+
return list(getattr(node, "children", None) or ())
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _address(document: Any, node: Any) -> NodeAddress:
|
|
134
|
+
return NodeAddress(document_id=getattr(document, "document_id", None), node_id=getattr(node, "node_id", None))
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _fragment_nodes(root: Any) -> List[Any]:
|
|
138
|
+
ordered: List[Any] = []
|
|
139
|
+
stack = [root]
|
|
140
|
+
while stack:
|
|
141
|
+
node = stack.pop(0)
|
|
142
|
+
ordered.append(node)
|
|
143
|
+
stack = list(getattr(node, "children", None) or ()) + stack
|
|
144
|
+
return ordered
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _range_byte_length(nodes: Sequence[Any]) -> int:
|
|
148
|
+
ranges = [getattr(n, "buffer_range", None) for n in nodes]
|
|
149
|
+
if not ranges or any(r is None for r in ranges):
|
|
150
|
+
return 0
|
|
151
|
+
return ranges[-1][1] - ranges[0][0]
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _single_sequence_field(parent_node: Any) -> None:
|
|
155
|
+
"""Validate that ``parent_node`` can hold its children in a sequence field, BEFORE any
|
|
156
|
+
splice touches it -- duplicated in miniature from ``operations.py`` (the established
|
|
157
|
+
precedent for this file, per the module docstring) rather than imported, since this file
|
|
158
|
+
never imports its sibling. Raises the identical ``NodeSchemaError(INVALID_PARENT_TYPE, ...)``
|
|
159
|
+
``core.live_tree.sync_fields`` would otherwise only discover AFTER ``_detach``/``_attach``
|
|
160
|
+
have already spliced ``children``/``nodes_by_id`` (bug 17f05476 residue: a move's own
|
|
161
|
+
rollback log only unwinds what happens INSIDE this function's ``try`` block, never a later
|
|
162
|
+
``sync_fields`` failure raised back in ``facade._commit_mutation`` once this call has
|
|
163
|
+
already returned successfully)."""
|
|
164
|
+
if parent_node is None:
|
|
165
|
+
return
|
|
166
|
+
if not hasattr(parent_node, "fields"):
|
|
167
|
+
return
|
|
168
|
+
field_items = list(parent_node.fields.items())
|
|
169
|
+
|
|
170
|
+
def is_node_sequence(value: Any) -> bool:
|
|
171
|
+
return bool(
|
|
172
|
+
isinstance(value, tuple)
|
|
173
|
+
and value
|
|
174
|
+
and all(hasattr(item, "kind") for item in value)
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
def is_node_field(value: Any) -> bool:
|
|
178
|
+
return hasattr(value, "kind") or is_node_sequence(value)
|
|
179
|
+
|
|
180
|
+
sequences = [name for name, value in field_items if is_node_sequence(value)]
|
|
181
|
+
|
|
182
|
+
seq_name: Optional[str] = None
|
|
183
|
+
if len(sequences) == 1:
|
|
184
|
+
seq_name = sequences[0]
|
|
185
|
+
elif not sequences and isinstance(parent_node.fields.get("body"), tuple):
|
|
186
|
+
# Mirrors core.live_tree.sync_fields's own widened check EXACTLY (bug 62759f8a) --
|
|
187
|
+
# see the identical comment in operations.py's copy of this helper.
|
|
188
|
+
seq_name = "body"
|
|
189
|
+
|
|
190
|
+
if seq_name is not None:
|
|
191
|
+
return
|
|
192
|
+
|
|
193
|
+
has_node_valued_fields = any(is_node_field(value) for value in parent_node.fields.values())
|
|
194
|
+
if not has_node_valued_fields:
|
|
195
|
+
return
|
|
196
|
+
|
|
197
|
+
if not sequences:
|
|
198
|
+
raise NodeSchemaError(
|
|
199
|
+
ErrorCode.INVALID_PARENT_TYPE,
|
|
200
|
+
f"node kind {parent_node.kind!r} does not hold its children in exactly one sequence "
|
|
201
|
+
"field, so a sequence edit cannot be expressed on it; splice into the "
|
|
202
|
+
"sequence-holding descendant instead",
|
|
203
|
+
)
|
|
204
|
+
# Otherwise multiple sequences: ambiguous, left for sync_fields's own "already matching"
|
|
205
|
+
# fallback to resolve -- unchanged from operations.py's identical precedent.
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _resolve_source_range(document: Any, targets: Any) -> Tuple[List[Any], Any, int, int]:
|
|
209
|
+
"""Resolve ``targets`` (mirrors ``operations._resolve_contiguous_range``)."""
|
|
210
|
+
refs = list(targets) if isinstance(targets, (list, tuple)) else [targets]
|
|
211
|
+
if not refs:
|
|
212
|
+
raise MoveError([ValidationError(code=ErrorCode.NODE_NOT_FOUND, message="at least one target is required")])
|
|
213
|
+
resolved: List[Any] = []
|
|
214
|
+
for ref in refs:
|
|
215
|
+
node = _resolve(document, ref)
|
|
216
|
+
if node is None:
|
|
217
|
+
raise MoveError([ValidationError(code=ErrorCode.NODE_NOT_FOUND, message=f"target could not be resolved: {ref!r}")])
|
|
218
|
+
resolved.append(node)
|
|
219
|
+
parent_node = getattr(resolved[0], "parent", None)
|
|
220
|
+
if parent_node is None:
|
|
221
|
+
raise MoveError([ValidationError(code=ErrorCode.NODE_NOT_FOUND, message="target has no resolvable parent")])
|
|
222
|
+
for node in resolved[1:]:
|
|
223
|
+
if getattr(node, "parent", None) is not parent_node:
|
|
224
|
+
raise MoveError([ValidationError(code=ErrorCode.INVALID_POSITION, message="targets do not share the same parent")])
|
|
225
|
+
siblings = _children_list(parent_node)
|
|
226
|
+
try:
|
|
227
|
+
start = siblings.index(resolved[0])
|
|
228
|
+
except ValueError:
|
|
229
|
+
raise MoveError([ValidationError(code=ErrorCode.NODE_NOT_FOUND, message="target is not among its parent's children")])
|
|
230
|
+
end = start + len(resolved)
|
|
231
|
+
if siblings[start:end] != resolved:
|
|
232
|
+
raise MoveError([ValidationError(code=ErrorCode.INVALID_POSITION, message="targets are not a contiguous sibling range in the given order")])
|
|
233
|
+
return resolved, parent_node, start, end
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _resolve_target_position(target_document: Any, position: str, parent: Any, sibling: Any, index: Optional[int]) -> Tuple[Any, int]:
|
|
237
|
+
"""Resolve the target attach point (mirrors ``operations.insert``). Read-only."""
|
|
238
|
+
parent_node = _resolve(target_document, parent) if parent is not None else None
|
|
239
|
+
sibling_node = _resolve(target_document, sibling) if sibling is not None else None
|
|
240
|
+
if position in _BEFORE_AFTER:
|
|
241
|
+
if sibling_node is None:
|
|
242
|
+
raise MoveError([ValidationError(code=ErrorCode.NODE_NOT_FOUND, message=f"sibling could not be resolved: {sibling!r}")])
|
|
243
|
+
if parent_node is None:
|
|
244
|
+
parent_node = getattr(sibling_node, "parent", None)
|
|
245
|
+
if parent_node is None:
|
|
246
|
+
raise MoveError([ValidationError(code=ErrorCode.NODE_NOT_FOUND, message="sibling has no resolvable parent")])
|
|
247
|
+
siblings = _children_list(parent_node)
|
|
248
|
+
try:
|
|
249
|
+
anchor = siblings.index(sibling_node)
|
|
250
|
+
except ValueError:
|
|
251
|
+
raise MoveError([ValidationError(code=ErrorCode.INVALID_POSITION, message="sibling is not a child of its parent")])
|
|
252
|
+
return parent_node, (anchor if position == "before" else anchor + 1)
|
|
253
|
+
if position in _PARENT_POSITIONS:
|
|
254
|
+
if parent_node is None:
|
|
255
|
+
raise MoveError([ValidationError(code=ErrorCode.NODE_NOT_FOUND, message=f"parent could not be resolved: {parent!r}")])
|
|
256
|
+
siblings = _children_list(parent_node)
|
|
257
|
+
if position == "first_child":
|
|
258
|
+
return parent_node, 0
|
|
259
|
+
if position == "last_child":
|
|
260
|
+
return parent_node, len(siblings)
|
|
261
|
+
return parent_node, (0 if index is None else max(0, min(index, len(siblings))))
|
|
262
|
+
raise MoveError([ValidationError(code=ErrorCode.INVALID_POSITION, message=f"unrecognized position: {position!r}")])
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
# -- rollback changelog: zero-arg undo callables, run in reverse order ------
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _log_setattr(log: List[Callable[[], None]], obj: Any, name: str, value: Any) -> None:
|
|
269
|
+
old = getattr(obj, name, None)
|
|
270
|
+
setattr(obj, name, value)
|
|
271
|
+
log.append(lambda: setattr(obj, name, old))
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _log_dict_set(log: List[Callable[[], None]], mapping: Dict[Any, Any], key: Any, value: Any) -> None:
|
|
275
|
+
existed = key in mapping
|
|
276
|
+
old = mapping.get(key)
|
|
277
|
+
mapping[key] = value
|
|
278
|
+
log.append((lambda: mapping.__setitem__(key, old)) if existed else (lambda: mapping.pop(key, None)))
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _log_dict_pop(log: List[Callable[[], None]], mapping: Dict[Any, Any], key: Any) -> None:
|
|
282
|
+
if key in mapping:
|
|
283
|
+
old = mapping[key]
|
|
284
|
+
del mapping[key]
|
|
285
|
+
log.append(lambda: mapping.__setitem__(key, old))
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _detach(
|
|
289
|
+
document: Any,
|
|
290
|
+
resolved: Sequence[Any],
|
|
291
|
+
parent_node: Any,
|
|
292
|
+
start: int,
|
|
293
|
+
end: int,
|
|
294
|
+
log: List[Callable[[], None]],
|
|
295
|
+
removed_length: int,
|
|
296
|
+
) -> None:
|
|
297
|
+
siblings = _children_list(parent_node)
|
|
298
|
+
_log_setattr(log, parent_node, "children", tuple(siblings[:start] + siblings[end:]) if isinstance(getattr(parent_node, "children", None), tuple) else siblings[:start] + siblings[end:])
|
|
299
|
+
if removed_length:
|
|
300
|
+
for later in siblings[end:]:
|
|
301
|
+
_shift(later, -removed_length, log)
|
|
302
|
+
_propagate_ancestor_range_delta(parent_node, -removed_length, log)
|
|
303
|
+
nodes_by_id = getattr(document, "nodes_by_id", None) or {}
|
|
304
|
+
short_index = getattr(document, "short_id_index", None)
|
|
305
|
+
for root in resolved:
|
|
306
|
+
for node in _fragment_nodes(root):
|
|
307
|
+
_log_dict_pop(log, nodes_by_id, getattr(node, "node_id", None))
|
|
308
|
+
if isinstance(short_index, dict):
|
|
309
|
+
_log_dict_pop(log, short_index, getattr(node, "short_id", None))
|
|
310
|
+
_log_setattr(log, root, "parent", None)
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _shift(node: Any, delta: int, log: List[Callable[[], None]]) -> None:
|
|
314
|
+
rng = getattr(node, "buffer_range", None)
|
|
315
|
+
if rng is not None:
|
|
316
|
+
_log_setattr(log, node, "buffer_range", (rng[0] + delta, rng[1] + delta))
|
|
317
|
+
for child in _children_list(node):
|
|
318
|
+
_shift(child, delta, log)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _propagate_ancestor_range_delta(node: Any, delta: int, log: List[Callable[[], None]]) -> None:
|
|
322
|
+
"""Bug 09cc74c6: extend the touched parent's own buffer_range bookkeeping all the way to
|
|
323
|
+
the document root, instead of stopping at ``node`` (the immediate parent both ``_detach``
|
|
324
|
+
and ``_attach`` used to touch alone, per the settled-but-narrow bug baa7a7a4 scope recorded
|
|
325
|
+
in ``tests/core/test_move_buffer_range.py``'s cross-parent-move test: "neither touches a
|
|
326
|
+
grandparent's aggregate range or an untouched sibling container's absolute offsets... a
|
|
327
|
+
separate, PRE-EXISTING gap... out of scope [t]here").
|
|
328
|
+
|
|
329
|
+
Walks from ``node`` (the parent ``_detach``/``_attach`` just spliced) up through every
|
|
330
|
+
ancestor to the root. At each level: (1) that ancestor's own ``buffer_range`` END moves by
|
|
331
|
+
``delta`` -- the {p029} ancestor-CHAIN half, O(depth) and never more, exactly mirroring how
|
|
332
|
+
``SubtreeBytesAggregate`` itself only ever walks a node_path's ancestor prefixes for its own
|
|
333
|
+
aggregate; (2) every LATER sibling of the current node under ITS OWN parent -- an "uncle"
|
|
334
|
+
container the mutation site sits nested inside, from that level's point of view -- has its
|
|
335
|
+
whole subtree shifted by ``delta`` via the same ``_shift`` already applied, one level down,
|
|
336
|
+
to the touched parent's own later children. Without step (2) an uncle positioned after the
|
|
337
|
+
mutation site in the same buffer keeps the pre-move absolute offset forever, exactly the
|
|
338
|
+
"untouched sibling container" bug 09cc74c6 names.
|
|
339
|
+
|
|
340
|
+
``delta`` is negative for ``_detach`` (content removed) and positive for ``_attach``
|
|
341
|
+
(content inserted); a same-parent move nets to zero at every level once both calls have run,
|
|
342
|
+
since the fragment's own byte length is unchanged (see ``move()``'s own ``removed_length``
|
|
343
|
+
docstring note) -- correctly leaving an unmoved ancestor's overall span untouched.
|
|
344
|
+
"""
|
|
345
|
+
current = node
|
|
346
|
+
while current is not None:
|
|
347
|
+
rng = getattr(current, "buffer_range", None)
|
|
348
|
+
if rng is not None:
|
|
349
|
+
_log_setattr(log, current, "buffer_range", (rng[0], rng[1] + delta))
|
|
350
|
+
grandparent = getattr(current, "parent", None)
|
|
351
|
+
if grandparent is not None:
|
|
352
|
+
level_siblings = _children_list(grandparent)
|
|
353
|
+
try:
|
|
354
|
+
own_index = level_siblings.index(current)
|
|
355
|
+
except ValueError:
|
|
356
|
+
own_index = None
|
|
357
|
+
if own_index is not None:
|
|
358
|
+
for later in level_siblings[own_index + 1:]:
|
|
359
|
+
_shift(later, delta, log)
|
|
360
|
+
current = grandparent
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _resolve_target_offset(parent_node: Any, splice_index: int, siblings: Sequence[Any]) -> Optional[int]:
|
|
364
|
+
"""Absolute byte offset in the TARGET buffer where the splice lands.
|
|
365
|
+
|
|
366
|
+
Mirrors how ``_detach`` derives its bookkeeping from existing node ranges rather than
|
|
367
|
+
recomputing them from scratch: the sibling landing at (or immediately before)
|
|
368
|
+
``splice_index`` already carries the exact boundary in its own ``buffer_range``, so that is
|
|
369
|
+
read directly instead of re-summing preceding siblings' spans. Only an EMPTY parent (no
|
|
370
|
+
children at all, so neither an anchor-at nor an anchor-before sibling exists) falls back to
|
|
371
|
+
the parent's own range start -- the same "nothing before it moved" assumption ``_detach``
|
|
372
|
+
relies on when it leaves ``buffer_range[0]`` untouched while shrinking only the end. Returns
|
|
373
|
+
``None`` when no boundary is resolvable (any touched node lacks ``buffer_range``), which
|
|
374
|
+
tells the caller to skip offset bookkeeping entirely rather than guess. ``splice_index`` is
|
|
375
|
+
clamped into ``[0, len(siblings)]`` first: for a same-parent move it was resolved against
|
|
376
|
+
the pre-``_detach`` sibling count and can now legitimately exceed the post-detach list --
|
|
377
|
+
exactly the out-of-range index the structural splice two lines below already tolerates via
|
|
378
|
+
plain list slicing (``siblings[:splice_index]`` truncates instead of raising); this mirrors
|
|
379
|
+
that same tolerance instead of raising ``IndexError`` on ``siblings[splice_index - 1]``.
|
|
380
|
+
"""
|
|
381
|
+
clamped = max(0, min(splice_index, len(siblings)))
|
|
382
|
+
if clamped < len(siblings):
|
|
383
|
+
rng = getattr(siblings[clamped], "buffer_range", None)
|
|
384
|
+
if rng is not None:
|
|
385
|
+
return rng[0]
|
|
386
|
+
if clamped > 0:
|
|
387
|
+
rng = getattr(siblings[clamped - 1], "buffer_range", None)
|
|
388
|
+
if rng is not None:
|
|
389
|
+
return rng[1]
|
|
390
|
+
parent_rng = getattr(parent_node, "buffer_range", None)
|
|
391
|
+
return parent_rng[0] if parent_rng is not None else None
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def _attach(
|
|
395
|
+
target_document: Any,
|
|
396
|
+
parent_node: Any,
|
|
397
|
+
splice_index: int,
|
|
398
|
+
roots: Sequence[Any],
|
|
399
|
+
log: List[Callable[[], None]],
|
|
400
|
+
inserted_length: int,
|
|
401
|
+
) -> None:
|
|
402
|
+
siblings = _children_list(parent_node)
|
|
403
|
+
target_offset = _resolve_target_offset(parent_node, splice_index, siblings)
|
|
404
|
+
new_children = siblings[:splice_index] + list(roots) + siblings[splice_index:]
|
|
405
|
+
_log_setattr(log, parent_node, "children", tuple(new_children) if isinstance(getattr(parent_node, "children", None), tuple) else new_children)
|
|
406
|
+
nodes_by_id = getattr(target_document, "nodes_by_id", None)
|
|
407
|
+
if nodes_by_id is None:
|
|
408
|
+
nodes_by_id = {}
|
|
409
|
+
target_document.nodes_by_id = nodes_by_id
|
|
410
|
+
short_index = getattr(target_document, "short_id_index", None)
|
|
411
|
+
for root in roots:
|
|
412
|
+
_log_setattr(log, root, "parent", parent_node)
|
|
413
|
+
for node in _fragment_nodes(root):
|
|
414
|
+
node_id = getattr(node, "node_id", None)
|
|
415
|
+
if node_id is not None:
|
|
416
|
+
_log_dict_set(log, nodes_by_id, node_id, node)
|
|
417
|
+
if isinstance(short_index, dict):
|
|
418
|
+
short_id = getattr(node, "short_id", None)
|
|
419
|
+
if short_id is not None:
|
|
420
|
+
_log_dict_set(log, short_index, short_id, node_id)
|
|
421
|
+
if inserted_length and target_offset is not None:
|
|
422
|
+
# Relocate the moved roots (and every descendant) from their stale source-document
|
|
423
|
+
# offsets to where they now actually sit in the target buffer -- the missing half of
|
|
424
|
+
# this file's buffer_range bookkeeping (bug baa7a7a4): `_detach` already shrinks the
|
|
425
|
+
# source parent and shifts its later siblings left; nothing here mirrored that for the
|
|
426
|
+
# target side, so every downstream offset went stale after any move, corrupting anything
|
|
427
|
+
# that slices `source_text[start:end]` off `buffer_range` (e.g. the preview loader).
|
|
428
|
+
first_root_range = getattr(roots[0], "buffer_range", None)
|
|
429
|
+
if first_root_range is not None:
|
|
430
|
+
delta = target_offset - first_root_range[0]
|
|
431
|
+
if delta:
|
|
432
|
+
for root in roots:
|
|
433
|
+
_shift(root, delta, log)
|
|
434
|
+
for later in siblings[splice_index:]:
|
|
435
|
+
_shift(later, inserted_length, log)
|
|
436
|
+
_propagate_ancestor_range_delta(parent_node, inserted_length, log)
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def _apply_short_id_plan(fragment_nodes: Sequence[Any], plan: Sequence[ShortIdReassignment], log: List[Callable[[], None]]) -> None:
|
|
440
|
+
by_id = {getattr(n, "node_id", None): n for n in fragment_nodes}
|
|
441
|
+
for entry in plan:
|
|
442
|
+
node = by_id.get(entry.node_id)
|
|
443
|
+
if node is not None and hasattr(node, "short_id"):
|
|
444
|
+
_log_setattr(log, node, "short_id", entry.new_short_id)
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
# -- public entry point ------------------------------------------------
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def move(
|
|
451
|
+
source_document: Any,
|
|
452
|
+
targets: Any,
|
|
453
|
+
*,
|
|
454
|
+
position: str,
|
|
455
|
+
target_document: Any = None,
|
|
456
|
+
parent: Any = None,
|
|
457
|
+
sibling: Any = None,
|
|
458
|
+
index: Optional[int] = None,
|
|
459
|
+
is_type_compatible: Optional[Callable[[Any, Optional[str], Any], bool]] = None,
|
|
460
|
+
references: Optional[Iterable[Any]] = None,
|
|
461
|
+
loaded_documents: Optional[Dict[Any, Any]] = None,
|
|
462
|
+
used_short_ids: Optional[Sequence[Any]] = None,
|
|
463
|
+
next_short_id: Optional[Callable[[], Any]] = None,
|
|
464
|
+
lock_coordinator: Optional[Callable[[Sequence[UUID]], Any]] = None,
|
|
465
|
+
reconcile_references: Optional[Callable[..., Any]] = None,
|
|
466
|
+
) -> MoveResult:
|
|
467
|
+
"""Move a subtree (or a contiguous sibling range) within one document or
|
|
468
|
+
across two documents, as a single atomic transaction (see module
|
|
469
|
+
docstring). ``targets`` names the existing range to relocate, exactly as
|
|
470
|
+
``operations.delete`` accepts it. ``position``/``parent``/``sibling``/
|
|
471
|
+
``index`` address the attach point in ``target_document`` (defaults to
|
|
472
|
+
``source_document``), exactly as ``operations.insert`` accepts them.
|
|
473
|
+
|
|
474
|
+
Both ``document_id`` values are sorted (UUID4 order, per {p035}) before
|
|
475
|
+
``lock_coordinator`` -- if supplied -- is entered as a context manager
|
|
476
|
+
around the whole operation. The shared preflight validator then runs
|
|
477
|
+
against ``target_document`` with the moved subtree's own node_ids
|
|
478
|
+
excluded from the conflict check (they name themselves, not a new
|
|
479
|
+
collision): a genuine UUID4 collision raises :class:`MoveError` wrapping
|
|
480
|
+
``NODE_ID_CONFLICT`` before anything is mutated. Only then does the
|
|
481
|
+
structural relocation happen, followed by ``reconcile_references`` and
|
|
482
|
+
its returned delta's ``.apply`` -- both inside the same rollback scope.
|
|
483
|
+
"""
|
|
484
|
+
target_document = source_document if target_document is None else target_document
|
|
485
|
+
resolved, src_parent, start, end = _resolve_source_range(source_document, targets)
|
|
486
|
+
|
|
487
|
+
src_doc_id = getattr(source_document, "document_id", None)
|
|
488
|
+
tgt_doc_id = getattr(target_document, "document_id", None)
|
|
489
|
+
doc_ids = sorted({d for d in (src_doc_id, tgt_doc_id) if d is not None})
|
|
490
|
+
scope = lock_coordinator(doc_ids) if lock_coordinator is not None else nullcontext()
|
|
491
|
+
|
|
492
|
+
with scope:
|
|
493
|
+
parent_node, splice_index = _resolve_target_position(target_document, position, parent, sibling, index)
|
|
494
|
+
|
|
495
|
+
# Fix for bug 518eb5cd: same-parent moves ANCHORED TO A SIBLING (position 'before'/'after').
|
|
496
|
+
# _resolve_target_position computes splice_index against the pre-detach sibling list only
|
|
497
|
+
# for sibling-anchored moves (position in _BEFORE_AFTER). Explicit positions ('first_child',
|
|
498
|
+
# 'last_child', 'child_index') are passed by callers already in post-detach semantics.
|
|
499
|
+
# When the moved node's original index (start) is strictly below the resolved index,
|
|
500
|
+
# _detach will shift later siblings left by 1, making the unadjusted splice_index
|
|
501
|
+
# land one slot too far right. Decrement only for sibling-anchored same-parent moves.
|
|
502
|
+
if (source_document is target_document and src_parent is parent_node and start < splice_index
|
|
503
|
+
and position in ('before', 'after') and sibling is not None):
|
|
504
|
+
splice_index -= 1
|
|
505
|
+
|
|
506
|
+
# Read-only preflight shim: target_document's nodes_by_id with only
|
|
507
|
+
# the moved nodes' own entries excluded, by object identity (not id
|
|
508
|
+
# value), so an intra-document move is never mistaken for a
|
|
509
|
+
# conflict against itself while a genuine conflict -- a *different*
|
|
510
|
+
# object already holding that UUID4 in the target -- is still caught.
|
|
511
|
+
moved_objects = {id(n) for root in resolved for n in _fragment_nodes(root)}
|
|
512
|
+
real_map = getattr(target_document, "nodes_by_id", None) or {}
|
|
513
|
+
shim = SimpleNamespace(
|
|
514
|
+
nodes_by_id={k: v for k, v in real_map.items() if id(v) not in moved_objects},
|
|
515
|
+
document_id=tgt_doc_id,
|
|
516
|
+
)
|
|
517
|
+
|
|
518
|
+
errors: List[ValidationError] = []
|
|
519
|
+
combined_plan: List[ShortIdReassignment] = []
|
|
520
|
+
for root in resolved:
|
|
521
|
+
result = validate_mutation(
|
|
522
|
+
shim, root, parent=parent_node, position=position, index=splice_index,
|
|
523
|
+
is_type_compatible=is_type_compatible, references=references,
|
|
524
|
+
loaded_documents=loaded_documents, used_short_ids=used_short_ids, next_short_id=next_short_id,
|
|
525
|
+
)
|
|
526
|
+
if not result.success:
|
|
527
|
+
errors.extend(result.errors)
|
|
528
|
+
else:
|
|
529
|
+
combined_plan.extend(result.short_id_plan)
|
|
530
|
+
if errors:
|
|
531
|
+
raise MoveError(errors)
|
|
532
|
+
|
|
533
|
+
# Validate BOTH the source and destination parents can hold their children in a
|
|
534
|
+
# sequence field BEFORE `_detach`/`_attach` splice anything (bug 17f05476 residue): a
|
|
535
|
+
# move's own rollback `log` below only unwinds mutations recorded inside the `try`
|
|
536
|
+
# block that follows, never a `sync_fields` failure raised later, back in
|
|
537
|
+
# `facade._commit_mutation`, once this function has already returned successfully --
|
|
538
|
+
# by then `_detach` has already dropped the moved node's identity from
|
|
539
|
+
# `source_document.nodes_by_id` with no rollback path left to reach it. Checked here,
|
|
540
|
+
# before either splice, exactly like `operations.insert`/`operations.delete` already
|
|
541
|
+
# do for their own single parent.
|
|
542
|
+
_single_sequence_field(src_parent)
|
|
543
|
+
_single_sequence_field(parent_node)
|
|
544
|
+
|
|
545
|
+
# Validation succeeded against the (self-excluded) target view: no
|
|
546
|
+
# mutation has happened yet. Everything from here is logged for
|
|
547
|
+
# rollback on any later failure.
|
|
548
|
+
log: List[Callable[[], None]] = []
|
|
549
|
+
try:
|
|
550
|
+
fragment_nodes = [n for root in resolved for n in _fragment_nodes(root)]
|
|
551
|
+
# Read once, before any mutation: the moved fragment's own byte length never
|
|
552
|
+
# changes (its text doesn't), so the same value is both what `_detach` removes from
|
|
553
|
+
# the source and what `_attach` inserts into the target -- intra- or cross-document
|
|
554
|
+
# alike (see `_attach`'s docstring note on bug baa7a7a4).
|
|
555
|
+
removed_length = _range_byte_length(resolved)
|
|
556
|
+
_detach(source_document, resolved, src_parent, start, end, log, removed_length)
|
|
557
|
+
_apply_short_id_plan(fragment_nodes, combined_plan, log)
|
|
558
|
+
_attach(target_document, parent_node, splice_index, resolved, log, removed_length)
|
|
559
|
+
reference_delta = None
|
|
560
|
+
if reconcile_references is not None:
|
|
561
|
+
reference_delta = reconcile_references(
|
|
562
|
+
source_document=source_document, target_document=target_document,
|
|
563
|
+
moved_roots=tuple(resolved), short_id_remap=tuple(combined_plan),
|
|
564
|
+
loaded_documents=loaded_documents,
|
|
565
|
+
)
|
|
566
|
+
apply = getattr(reference_delta, "apply", None)
|
|
567
|
+
if callable(apply):
|
|
568
|
+
apply(source_document, target_document, loaded_documents)
|
|
569
|
+
except Exception:
|
|
570
|
+
for undo in reversed(log):
|
|
571
|
+
undo()
|
|
572
|
+
raise
|
|
573
|
+
|
|
574
|
+
removed_addresses = tuple(_address(source_document, n) for n in resolved)
|
|
575
|
+
inserted_addresses = tuple(_address(target_document, n) for n in resolved)
|
|
576
|
+
first = resolved[0]
|
|
577
|
+
return MoveResult(
|
|
578
|
+
node_id=getattr(first, "node_id", None),
|
|
579
|
+
short_id=getattr(first, "short_id", None),
|
|
580
|
+
position=splice_index,
|
|
581
|
+
remap=tuple(combined_plan),
|
|
582
|
+
removed=removed_addresses,
|
|
583
|
+
inserted=inserted_addresses,
|
|
584
|
+
reference_delta=reference_delta,
|
|
585
|
+
)
|