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,498 @@
|
|
|
1
|
+
"""Read-only ``drill_down`` inspection operation for concept C-018 (TreeInspection).
|
|
2
|
+
|
|
3
|
+
Scope ({p064}-{p071}): one public entry point, :func:`drill_down`, plus the
|
|
4
|
+
two exceptions it raises, :class:`NodeNotFoundError` and
|
|
5
|
+
:class:`DocumentVersionConflictError`. Turns an already loaded common-model
|
|
6
|
+
``Document`` into a compact ``model_outline`` response built exclusively
|
|
7
|
+
through the already-merged :mod:`tree_engine.query.outline` model -- this
|
|
8
|
+
file never redefines ``OutlineMeta``/``OutlineNodeRecord``/``OutlineStubRecord``/
|
|
9
|
+
``OutlineTruncation``/``OutlineResponse``, only assembles values via
|
|
10
|
+
``build_outline_response``. Selector/query-language parsing is entirely out
|
|
11
|
+
of scope (sibling TreeQueryEngine step).
|
|
12
|
+
|
|
13
|
+
Address resolution is delegated whole to the already-merged
|
|
14
|
+
``normalize_node_address``; this file only translates its
|
|
15
|
+
``NodeAddressError`` family into the dedicated, catalog-coded exception this
|
|
16
|
+
step requires. Depth control and ``expand_below_bytes`` auto-expansion
|
|
17
|
+
consume the already-merged ``subtree_bytes`` aggregate
|
|
18
|
+
(``tree_engine.core.positions.SubtreeBytesAggregate``) through one
|
|
19
|
+
duck-typed accessor, ``document.subtree_bytes_for(node_id)`` -- never by
|
|
20
|
+
re-serializing a subtree; a missing accessor reads back ``None`` for every
|
|
21
|
+
node, the safe "skip auto-expansion" case.
|
|
22
|
+
|
|
23
|
+
Read-only guarantee ({p064}): no helper below ever assigns to a ``Node``/
|
|
24
|
+
``Document`` attribute, a short_id map, a position index, or
|
|
25
|
+
``document_version`` -- only reads. Source text (``include_source``) comes
|
|
26
|
+
from ``document.source_for(node)`` if supplied, else from slicing
|
|
27
|
+
``document.buffer`` at ``node.buffer_range`` via its public ``iter_regions()``.
|
|
28
|
+
|
|
29
|
+
Non-addressable structural wrappers (bug 1f606df8): a format may parse a
|
|
30
|
+
semantic value under a wrapper node that itself carries no compact id --
|
|
31
|
+
``short_id=None`` BY DESIGN ({p097}), e.g. ``json:Member`` under a
|
|
32
|
+
``json_format`` document indexed with ``semantic_compact_ids=True``, per
|
|
33
|
+
``core.identifier_map``'s own module docstring ("Structural wrapper nodes
|
|
34
|
+
may deliberately have no compact id"). Every record/stub-building helper
|
|
35
|
+
below (:func:`_walk`, :func:`_build_stub`) reaches such a node only through
|
|
36
|
+
:func:`_addressable_children`, which transparently skips it and descends
|
|
37
|
+
into its own children instead -- so ``build_node_address_view`` is never
|
|
38
|
+
called on one. See :func:`_walk`'s own docstring for the depth-accounting
|
|
39
|
+
decision this implies.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
from __future__ import annotations
|
|
43
|
+
|
|
44
|
+
import json
|
|
45
|
+
from dataclasses import dataclass, replace
|
|
46
|
+
from typing import Any, Iterator, List, Mapping, Optional, Tuple, Union
|
|
47
|
+
from uuid import UUID
|
|
48
|
+
|
|
49
|
+
from tree_engine.core.address import (
|
|
50
|
+
NodeAddressError,
|
|
51
|
+
NodeAddressView,
|
|
52
|
+
build_node_address_view,
|
|
53
|
+
normalize_node_address,
|
|
54
|
+
)
|
|
55
|
+
from tree_engine.core.identity import NodeAddress
|
|
56
|
+
from tree_engine.core.nodes import Node, walk
|
|
57
|
+
from tree_engine.errors import ErrorCode
|
|
58
|
+
from tree_engine.query.outline import (
|
|
59
|
+
OutlineMeta,
|
|
60
|
+
OutlineNodeRecord,
|
|
61
|
+
OutlineResponse,
|
|
62
|
+
OutlineStubRecord,
|
|
63
|
+
OutlineTruncation,
|
|
64
|
+
TruncatedField,
|
|
65
|
+
build_outline_response,
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
__all__ = [
|
|
69
|
+
"SOURCE_NONE",
|
|
70
|
+
"SOURCE_PREVIEW",
|
|
71
|
+
"SOURCE_FULL",
|
|
72
|
+
"NodeNotFoundError",
|
|
73
|
+
"DocumentVersionConflictError",
|
|
74
|
+
"drill_down",
|
|
75
|
+
]
|
|
76
|
+
|
|
77
|
+
SOURCE_NONE = "none"
|
|
78
|
+
SOURCE_PREVIEW = "preview"
|
|
79
|
+
SOURCE_FULL = "full"
|
|
80
|
+
_VALID_SOURCE_MODES = (SOURCE_NONE, SOURCE_PREVIEW, SOURCE_FULL)
|
|
81
|
+
|
|
82
|
+
_ABSENT = object()
|
|
83
|
+
_OutlineEntry = Union[OutlineNodeRecord, OutlineStubRecord]
|
|
84
|
+
|
|
85
|
+
class NodeNotFoundError(Exception):
|
|
86
|
+
"""``address`` did not resolve to a node of ``document`` ({p065}).
|
|
87
|
+
|
|
88
|
+
Carries ``ErrorCode.NODE_NOT_FOUND`` as ``self.code``; never lets the
|
|
89
|
+
lower-level ``NodeAddressError`` it wraps escape :func:`drill_down`."""
|
|
90
|
+
def __init__(self, raw_address: Any) -> None:
|
|
91
|
+
self.code = ErrorCode.NODE_NOT_FOUND
|
|
92
|
+
self.raw_address = raw_address
|
|
93
|
+
super().__init__(f"[{self.code.value}] unknown node address: {raw_address!r}")
|
|
94
|
+
|
|
95
|
+
class DocumentVersionConflictError(Exception):
|
|
96
|
+
"""``expected_version`` did not match the document's current version.
|
|
97
|
+
|
|
98
|
+
Carries ``ErrorCode.DOCUMENT_VERSION_CONFLICT`` as ``self.code`` ({p065});
|
|
99
|
+
raised before any node is read."""
|
|
100
|
+
def __init__(self, expected_version: Any, current_version: Any) -> None:
|
|
101
|
+
self.code = ErrorCode.DOCUMENT_VERSION_CONFLICT
|
|
102
|
+
self.expected_version = expected_version
|
|
103
|
+
self.current_version = current_version
|
|
104
|
+
super().__init__(
|
|
105
|
+
f"[{self.code.value}] expected_version {expected_version!r} does not "
|
|
106
|
+
f"match current document_version {current_version!r}"
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
def _current_version(document: Any) -> Any:
|
|
110
|
+
current = getattr(document, "document_version", _ABSENT)
|
|
111
|
+
if current is _ABSENT:
|
|
112
|
+
current = getattr(document, "version", None)
|
|
113
|
+
return current
|
|
114
|
+
|
|
115
|
+
def _check_expected_version(document: Any, expected_version: Any) -> None:
|
|
116
|
+
if expected_version is None:
|
|
117
|
+
return
|
|
118
|
+
current = _current_version(document)
|
|
119
|
+
if current != expected_version:
|
|
120
|
+
raise DocumentVersionConflictError(expected_version, current)
|
|
121
|
+
|
|
122
|
+
def _subtree_bytes_for(document: Any, node_id: Any) -> Optional[int]:
|
|
123
|
+
accessor = getattr(document, "subtree_bytes_for", None)
|
|
124
|
+
return None if accessor is None else accessor(node_id)
|
|
125
|
+
|
|
126
|
+
def _slice_buffer_bytes(buffer: Any, start: int, end: int) -> bytes:
|
|
127
|
+
"""Read-only ``[start, end)`` slice via the public ``iter_regions()`` only."""
|
|
128
|
+
chunks: List[bytes] = []
|
|
129
|
+
offset = 0
|
|
130
|
+
for _is_original, chunk in buffer.iter_regions():
|
|
131
|
+
chunk_start, chunk_end = offset, offset + len(chunk)
|
|
132
|
+
offset = chunk_end
|
|
133
|
+
if chunk_end <= start:
|
|
134
|
+
continue
|
|
135
|
+
if chunk_start >= end:
|
|
136
|
+
break
|
|
137
|
+
chunks.append(chunk[max(start, chunk_start) - chunk_start : min(end, chunk_end) - chunk_start])
|
|
138
|
+
return b"".join(chunks)
|
|
139
|
+
|
|
140
|
+
def _source_for(document: Any, node: Node) -> Optional[str]:
|
|
141
|
+
accessor = getattr(document, "source_for", None)
|
|
142
|
+
if accessor is not None:
|
|
143
|
+
text = accessor(node)
|
|
144
|
+
if text is not None:
|
|
145
|
+
return text
|
|
146
|
+
buffer_range = getattr(node, "buffer_range", None)
|
|
147
|
+
buffer = getattr(document, "buffer", None)
|
|
148
|
+
if buffer_range is not None and buffer is not None:
|
|
149
|
+
start, end = buffer_range
|
|
150
|
+
try:
|
|
151
|
+
raw = _slice_buffer_bytes(buffer, start, end)
|
|
152
|
+
except Exception:
|
|
153
|
+
return None
|
|
154
|
+
return raw.decode("utf-8", "replace")
|
|
155
|
+
from tree_engine.facade import node_source_text
|
|
156
|
+
|
|
157
|
+
try:
|
|
158
|
+
result = node_source_text(document, node)
|
|
159
|
+
return result if isinstance(result, str) else (result.decode("utf-8", "replace") if isinstance(result, bytes) else None)
|
|
160
|
+
except Exception:
|
|
161
|
+
return None
|
|
162
|
+
|
|
163
|
+
def _name_or_value(node: Node) -> str:
|
|
164
|
+
for key in ("name", "value"):
|
|
165
|
+
candidate = node.fields.get(key)
|
|
166
|
+
if isinstance(candidate, str):
|
|
167
|
+
return candidate
|
|
168
|
+
return ""
|
|
169
|
+
|
|
170
|
+
def _select_attributes(node: Node) -> Mapping[str, Any]:
|
|
171
|
+
return {
|
|
172
|
+
key: value
|
|
173
|
+
for key, value in node.fields.items()
|
|
174
|
+
if value is None or isinstance(value, (str, int, float, bool, bytes))
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
def _source_preview(document: Any, node: Node, include_source: str, source_preview_bytes: int) -> Optional[TruncatedField]:
|
|
178
|
+
if include_source == SOURCE_NONE:
|
|
179
|
+
return None
|
|
180
|
+
text = _source_for(document, node)
|
|
181
|
+
if text is None:
|
|
182
|
+
return TruncatedField(value="", field_truncated=False, original_field_bytes=None)
|
|
183
|
+
if include_source == SOURCE_FULL:
|
|
184
|
+
return TruncatedField(value=text, field_truncated=False, original_field_bytes=None)
|
|
185
|
+
raw = text.encode("utf-8")
|
|
186
|
+
if len(raw) <= source_preview_bytes:
|
|
187
|
+
return TruncatedField(value=text, field_truncated=False, original_field_bytes=None)
|
|
188
|
+
trimmed = raw[:source_preview_bytes].decode("utf-8", "ignore")
|
|
189
|
+
return TruncatedField(value=trimmed, field_truncated=True, original_field_bytes=len(raw))
|
|
190
|
+
|
|
191
|
+
def _is_addressable(node: Node) -> bool:
|
|
192
|
+
"""Whether ``node`` itself can carry a {p021} address ({p097}).
|
|
193
|
+
|
|
194
|
+
A positive-int ``short_id`` is the sole test -- the same one
|
|
195
|
+
``core.identifier_map.IdentifierMap.entries`` already uses to enumerate
|
|
196
|
+
"every compact-ID-bearing node". A structural parser-only wrapper (a
|
|
197
|
+
``json:Member`` key+value pairing is the concrete case this bug fixes,
|
|
198
|
+
per bug 1f606df8; ``yaml:Pair`` is the analogous YAML wrapper) is built
|
|
199
|
+
with ``short_id=None`` BY DESIGN ({p097}, ``core.identifier_map``'s own
|
|
200
|
+
module docstring: "Structural wrapper nodes may deliberately have no
|
|
201
|
+
compact id"). ``bool`` is explicitly excluded even though it is an
|
|
202
|
+
``int`` subclass -- no code path is known to assign one, but a stray
|
|
203
|
+
``True``/``False`` must never be mistaken for a real id."""
|
|
204
|
+
short_id = getattr(node, "short_id", None)
|
|
205
|
+
return isinstance(short_id, int) and not isinstance(short_id, bool)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _addressable_children(node: Node) -> Iterator[Node]:
|
|
209
|
+
"""``node``'s children, transparently skipping non-addressable wrappers.
|
|
210
|
+
|
|
211
|
+
Per {p021}/{p097}, every record or stub this module emits must carry a
|
|
212
|
+
real ``short_id`` (:func:`_is_addressable`); a wrapper such as
|
|
213
|
+
``json:Member`` never does. Rather than emit a broken record for the
|
|
214
|
+
wrapper itself (bug 1f606df8: ``build_node_address_view`` raises
|
|
215
|
+
``TypeError`` on a ``None`` short_id), this presents the wrapper's own
|
|
216
|
+
addressable descendants as if they sat directly under ``node`` -- exactly
|
|
217
|
+
the transparency ``plugins.json_pointer.JsonPointerNotation._walk``
|
|
218
|
+
already establishes for the reference-notation index (a ``json:Member``
|
|
219
|
+
contributes its key but is not itself the node a pointer names; its
|
|
220
|
+
value child claims the pointer). A run of NESTED wrappers is skipped in
|
|
221
|
+
one pass (depth-first), and a wrapper with zero or several addressable
|
|
222
|
+
descendants yields exactly that many entries -- never assumed to be
|
|
223
|
+
exactly one, even though JSON's own ``Member`` always wraps exactly one
|
|
224
|
+
value."""
|
|
225
|
+
for child in node.children:
|
|
226
|
+
if _is_addressable(child):
|
|
227
|
+
yield child
|
|
228
|
+
else:
|
|
229
|
+
yield from _addressable_children(child)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _visible_child_count(node: Node) -> int:
|
|
233
|
+
"""The count :func:`_addressable_children` would yield for ``node``.
|
|
234
|
+
|
|
235
|
+
This is what ``child_count``/``shown_child_count`` report ({p070}): the
|
|
236
|
+
number of children a follow-up ``drill_down`` call could actually
|
|
237
|
+
address, not the raw ``len(node.children)`` -- which would count an
|
|
238
|
+
unaddressable wrapper itself. For every format with no wrapper kind
|
|
239
|
+
(Python, ...) every child is already addressable, so this is exactly
|
|
240
|
+
``len(node.children)`` and no existing behaviour changes."""
|
|
241
|
+
return sum(1 for _ in _addressable_children(node))
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _build_stub(node: Node, subtree_bytes: Optional[int]) -> OutlineStubRecord:
|
|
245
|
+
view = build_node_address_view(node.node_id, node.short_id)
|
|
246
|
+
return OutlineStubRecord(
|
|
247
|
+
node_id=view.node_id, short_id_hex=view.short_id_hex, type=str(node.kind),
|
|
248
|
+
child_count=_visible_child_count(node), subtree_node_count=sum(1 for _ in walk(node)),
|
|
249
|
+
subtree_bytes=subtree_bytes,
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
@dataclass(frozen=True)
|
|
253
|
+
class _Ctx:
|
|
254
|
+
document: Any
|
|
255
|
+
requested_depth: int
|
|
256
|
+
expand_below_bytes: int
|
|
257
|
+
include_attributes: bool
|
|
258
|
+
include_source: str
|
|
259
|
+
source_preview_bytes: int
|
|
260
|
+
|
|
261
|
+
def _walk(
|
|
262
|
+
ctx: _Ctx, node: Node, parent_view: Optional[NodeAddressView], child_index: int,
|
|
263
|
+
depth_from_view: int, blanket_auto: bool, emit: bool, entries: List[_OutlineEntry],
|
|
264
|
+
) -> None:
|
|
265
|
+
"""Depth-first preorder traversal, appending records/stubs to ``entries``.
|
|
266
|
+
|
|
267
|
+
``blanket_auto`` True means an ancestor already triggered unconditional
|
|
268
|
+
full expansion ({p067}): every node reached this way is shown in full
|
|
269
|
+
and marked ``auto_expanded``, no further check. Otherwise, within
|
|
270
|
+
``ctx.requested_depth`` children are shown normally ({p066}); once that
|
|
271
|
+
depth is reached, each child is gated by its *own* aggregate -- fully
|
|
272
|
+
revealed (entering blanket mode) or collapsed into a stub ({p067}).
|
|
273
|
+
|
|
274
|
+
``node`` itself is always addressable here ({p097}, :func:`_is_addressable`)
|
|
275
|
+
-- every recursive call below draws its ``child`` from
|
|
276
|
+
:func:`_addressable_children`, never from the raw ``node.children``, so a
|
|
277
|
+
non-addressable structural wrapper (``json:Member``, built with
|
|
278
|
+
``short_id=None`` BY DESIGN; bug 1f606df8) is never handed to
|
|
279
|
+
:func:`build_node_address_view` -- the one call whose bare
|
|
280
|
+
``int(None)`` used to raise ``TypeError``. Skipping a wrapper is
|
|
281
|
+
transparent to the caller: its addressable descendant(s) are presented
|
|
282
|
+
as if they sat directly under ``node``.
|
|
283
|
+
|
|
284
|
+
DEPTH-SEMANTICS DECISION (documented per this bug's own requirement):
|
|
285
|
+
stepping across a non-addressable wrapper costs NO depth level; only an
|
|
286
|
+
addressable-node-to-addressable-node edge increments ``depth_from_view``
|
|
287
|
+
(see the ``depth_from_view + 1`` passed to every recursive call below,
|
|
288
|
+
which fires once per entry drawn from ``_addressable_children``,
|
|
289
|
+
regardless of how many wrapper nodes were transparently skipped to reach
|
|
290
|
+
it). This matches how the rest of the engine already counts JSON
|
|
291
|
+
addressing levels: a JSON Pointer step from an object to one of its
|
|
292
|
+
member's values is ONE token (``plugins.json_format._pointer_step``
|
|
293
|
+
returns ``((key,), False)`` for the object->Member edge and ``((), True)``
|
|
294
|
+
for the Member->value edge -- one addressable-to-addressable hop, one
|
|
295
|
+
pointer token, and now, correspondingly, one ``depth_from_view`` unit).
|
|
296
|
+
A caller-requested ``depth=1`` therefore reveals a JSON object's own
|
|
297
|
+
member VALUES directly -- exactly the children a JSON Pointer or a
|
|
298
|
+
compact ``short_id`` could name -- never the invisible ``Member``
|
|
299
|
+
wrapper in between."""
|
|
300
|
+
view = build_node_address_view(node.node_id, node.short_id)
|
|
301
|
+
if emit:
|
|
302
|
+
agg = _subtree_bytes_for(ctx.document, node.node_id)
|
|
303
|
+
visible_children = _visible_child_count(node)
|
|
304
|
+
record = OutlineNodeRecord(
|
|
305
|
+
node_id=view.node_id, short_id_hex=view.short_id_hex, depth=depth_from_view,
|
|
306
|
+
parent_id=parent_view.node_id if parent_view else None,
|
|
307
|
+
parent_short_id_hex=parent_view.short_id_hex if parent_view else None,
|
|
308
|
+
child_index=child_index, type=str(node.kind), name_or_value=_name_or_value(node),
|
|
309
|
+
attributes=_select_attributes(node) if ctx.include_attributes else None,
|
|
310
|
+
child_count=visible_children, shown_child_count=visible_children, subtree_bytes=agg,
|
|
311
|
+
source_preview=_source_preview(ctx.document, node, ctx.include_source, ctx.source_preview_bytes),
|
|
312
|
+
expanded=blanket_auto or depth_from_view < ctx.requested_depth,
|
|
313
|
+
auto_expanded=blanket_auto, truncated=False,
|
|
314
|
+
)
|
|
315
|
+
entries.append(record)
|
|
316
|
+
this_view = record.address
|
|
317
|
+
else:
|
|
318
|
+
this_view = view
|
|
319
|
+
|
|
320
|
+
if blanket_auto or depth_from_view < ctx.requested_depth:
|
|
321
|
+
for index, child in enumerate(_addressable_children(node)):
|
|
322
|
+
_walk(ctx, child, this_view, index, depth_from_view + 1, blanket_auto, True, entries)
|
|
323
|
+
return
|
|
324
|
+
|
|
325
|
+
for index, child in enumerate(_addressable_children(node)):
|
|
326
|
+
child_agg = _subtree_bytes_for(ctx.document, child.node_id)
|
|
327
|
+
auto_ok = child_agg is not None and ctx.expand_below_bytes != 0 and child_agg <= ctx.expand_below_bytes
|
|
328
|
+
if auto_ok:
|
|
329
|
+
_walk(ctx, child, this_view, index, depth_from_view + 1, True, True, entries)
|
|
330
|
+
else:
|
|
331
|
+
entries.append(_build_stub(child, child_agg))
|
|
332
|
+
|
|
333
|
+
def _payload_bytes(payload: Any) -> int:
|
|
334
|
+
return len(json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str).encode("utf-8"))
|
|
335
|
+
|
|
336
|
+
def _entry_bytes(entry: _OutlineEntry) -> int:
|
|
337
|
+
"""Approximate per-entry cost, used only for the shrink heuristic below.
|
|
338
|
+
The ceiling decision itself never trusts a sum of these -- it always
|
|
339
|
+
re-measures the real assembled response (see ``_assemble``)."""
|
|
340
|
+
return _payload_bytes(entry)
|
|
341
|
+
|
|
342
|
+
def _mandatory_entry_bytes(entry: _OutlineEntry) -> int:
|
|
343
|
+
if isinstance(entry, OutlineStubRecord):
|
|
344
|
+
return _entry_bytes(entry)
|
|
345
|
+
return _entry_bytes(replace(entry, attributes=None, source_preview=None))
|
|
346
|
+
|
|
347
|
+
def _shrink_entry(entry: OutlineNodeRecord, budget: int) -> OutlineNodeRecord:
|
|
348
|
+
"""Truncate oversized optional fields to fit ``budget`` bytes ({p069}):
|
|
349
|
+
mandatory fields stay intact; only ``source_preview`` (then, as a last
|
|
350
|
+
resort, ``attributes``) is cut, marked ``field_truncated`` with size."""
|
|
351
|
+
budget = max(budget, 0)
|
|
352
|
+
preview = entry.source_preview
|
|
353
|
+
if preview is not None and preview.value:
|
|
354
|
+
raw = preview.value.encode("utf-8")
|
|
355
|
+
original = preview.original_field_bytes if preview.field_truncated else len(raw)
|
|
356
|
+
kept = raw[: max(budget - 32, 0)]
|
|
357
|
+
preview = TruncatedField(value=kept.decode("utf-8", "ignore"), field_truncated=True, original_field_bytes=original)
|
|
358
|
+
entry = replace(entry, source_preview=preview, truncated=True)
|
|
359
|
+
if entry.attributes and _entry_bytes(entry) - _mandatory_entry_bytes(entry) > budget:
|
|
360
|
+
entry = replace(entry, attributes={}, truncated=True)
|
|
361
|
+
return entry
|
|
362
|
+
|
|
363
|
+
def _truncation_for(entries: List[_OutlineEntry], kept_count: int, viewed: NodeAddressView) -> OutlineTruncation:
|
|
364
|
+
remainder = entries[kept_count:]
|
|
365
|
+
if not remainder:
|
|
366
|
+
return OutlineTruncation(truncated=False, omitted_nodes=0, omitted_bytes=0, continuation=None)
|
|
367
|
+
omitted_bytes = sum(_entry_bytes(e) for e in remainder)
|
|
368
|
+
return OutlineTruncation(
|
|
369
|
+
truncated=True, omitted_nodes=len(remainder), omitted_bytes=omitted_bytes, continuation=remainder[0].address
|
|
370
|
+
)
|
|
371
|
+
|
|
372
|
+
def _assemble(
|
|
373
|
+
kept: List[_OutlineEntry], truncation: OutlineTruncation, viewed: NodeAddressView,
|
|
374
|
+
depth: int, expand_below_bytes: int, version: Any,
|
|
375
|
+
) -> Tuple[int, OutlineMeta]:
|
|
376
|
+
"""The response's real, exact serialized size for a candidate ``kept``/
|
|
377
|
+
``truncation`` pair -- built and measured the same way a caller actually
|
|
378
|
+
receives it (``build_outline_response`` then ``_payload_bytes`` on the
|
|
379
|
+
real object), not estimated. ``response_bytes`` is self-referential (the
|
|
380
|
+
field reports the size of the response that contains it); this resolves
|
|
381
|
+
it by fixed point, which converges in a couple of steps since the digit
|
|
382
|
+
width of a byte count only changes at a power-of-ten boundary."""
|
|
383
|
+
response_bytes = 0
|
|
384
|
+
meta = OutlineMeta(
|
|
385
|
+
viewed=viewed, depth=depth, expand_below_bytes=expand_below_bytes,
|
|
386
|
+
document_version=version, node_count=len(kept), response_bytes=response_bytes,
|
|
387
|
+
)
|
|
388
|
+
for _ in range(6):
|
|
389
|
+
size = _payload_bytes(build_outline_response(meta, kept, truncation))
|
|
390
|
+
if size == response_bytes:
|
|
391
|
+
return size, meta
|
|
392
|
+
response_bytes = size
|
|
393
|
+
meta = replace(meta, response_bytes=response_bytes)
|
|
394
|
+
return response_bytes, meta
|
|
395
|
+
|
|
396
|
+
def _fits(
|
|
397
|
+
kept: List[_OutlineEntry], truncation: OutlineTruncation, viewed: NodeAddressView,
|
|
398
|
+
depth: int, expand_below_bytes: int, version: Any, max_output_bytes: int,
|
|
399
|
+
) -> bool:
|
|
400
|
+
size, _ = _assemble(kept, truncation, viewed, depth, expand_below_bytes, version)
|
|
401
|
+
return size <= max_output_bytes
|
|
402
|
+
|
|
403
|
+
def _apply_ceiling(
|
|
404
|
+
entries: List[_OutlineEntry], max_output_bytes: int, viewed: NodeAddressView, depth: int, expand_below_bytes: int, version: Any
|
|
405
|
+
) -> Tuple[List[_OutlineEntry], OutlineTruncation]:
|
|
406
|
+
"""Pick the largest prefix of ``entries`` whose real, exactly measured
|
|
407
|
+
response fits ``max_output_bytes`` ({p069}). A binary search over the
|
|
408
|
+
prefix length keeps this to O(log n) real (not estimated) measurements
|
|
409
|
+
for the common case; response size is non-decreasing in prefix length
|
|
410
|
+
for any realistic content, so the search is sound, and every candidate
|
|
411
|
+
it accepts is verified against the exact size a caller would see -- no
|
|
412
|
+
breach can hide behind an approximation. One shrink attempt on the
|
|
413
|
+
first excluded entry avoids wasting a large leftover budget on a bare
|
|
414
|
+
cutoff ({p069}); a final linear safety net re-verifies (and, if needed,
|
|
415
|
+
trims) the exact size, so the ceiling holds even if that shrink guess
|
|
416
|
+
was too optimistic."""
|
|
417
|
+
n = len(entries)
|
|
418
|
+
lo, hi, fit_k = 0, n, 0
|
|
419
|
+
while lo <= hi:
|
|
420
|
+
mid = (lo + hi) // 2
|
|
421
|
+
truncation = _truncation_for(entries, mid, viewed)
|
|
422
|
+
if _fits(entries[:mid], truncation, viewed, depth, expand_below_bytes, version, max_output_bytes):
|
|
423
|
+
fit_k, lo = mid, mid + 1
|
|
424
|
+
else:
|
|
425
|
+
hi = mid - 1
|
|
426
|
+
|
|
427
|
+
kept: List[_OutlineEntry] = list(entries[:fit_k])
|
|
428
|
+
truncation = _truncation_for(entries, fit_k, viewed)
|
|
429
|
+
|
|
430
|
+
if fit_k < n and not isinstance(entries[fit_k], OutlineStubRecord):
|
|
431
|
+
trial_truncation = _truncation_for(entries, fit_k + 1, viewed)
|
|
432
|
+
used, _ = _assemble(kept, trial_truncation, viewed, depth, expand_below_bytes, version)
|
|
433
|
+
mandatory = _mandatory_entry_bytes(entries[fit_k])
|
|
434
|
+
if used + mandatory <= max_output_bytes:
|
|
435
|
+
shrunk = _shrink_entry(entries[fit_k], max_output_bytes - used - mandatory)
|
|
436
|
+
if _fits(kept + [shrunk], trial_truncation, viewed, depth, expand_below_bytes, version, max_output_bytes):
|
|
437
|
+
kept.append(shrunk)
|
|
438
|
+
truncation = trial_truncation
|
|
439
|
+
|
|
440
|
+
while kept and not _fits(kept, truncation, viewed, depth, expand_below_bytes, version, max_output_bytes):
|
|
441
|
+
kept.pop()
|
|
442
|
+
truncation = _truncation_for(entries, len(kept), viewed)
|
|
443
|
+
|
|
444
|
+
return kept, truncation
|
|
445
|
+
|
|
446
|
+
def drill_down(
|
|
447
|
+
document: Any,
|
|
448
|
+
address: Optional[Union[UUID, int, str, NodeAddress]] = None,
|
|
449
|
+
*,
|
|
450
|
+
depth: int = 1,
|
|
451
|
+
expand_below_bytes: int = 8192,
|
|
452
|
+
expected_version: Optional[Any] = None,
|
|
453
|
+
include_self: bool = True,
|
|
454
|
+
include_attributes: bool = True,
|
|
455
|
+
include_source: str = SOURCE_PREVIEW,
|
|
456
|
+
source_preview_bytes: int = 256,
|
|
457
|
+
max_output_bytes: int = 65536,
|
|
458
|
+
) -> OutlineResponse:
|
|
459
|
+
"""Read-only compact-view inspection of ``document`` around ``address``.
|
|
460
|
+
|
|
461
|
+
Per {p064}: never mutates the tree, an index, ``document_version``, or
|
|
462
|
+
format-plugin state. ``expected_version``, when given, is checked first
|
|
463
|
+
-- before any node is read -- raising :class:`DocumentVersionConflictError`
|
|
464
|
+
on a mismatch ({p065}). ``address`` defaults to the root; otherwise
|
|
465
|
+
resolved via ``normalize_node_address`` (int/hex short_id or UUID4),
|
|
466
|
+
with an unresolvable address raised as :class:`NodeNotFoundError`. The
|
|
467
|
+
remaining parameters behave exactly as {p066}-{p069} specify; the
|
|
468
|
+
response is the compact ``model_outline`` shape from
|
|
469
|
+
``build_outline_response`` ({p070}, {p071})."""
|
|
470
|
+
if include_source not in _VALID_SOURCE_MODES:
|
|
471
|
+
raise ValueError(f"include_source must be one of {_VALID_SOURCE_MODES}, got {include_source!r}")
|
|
472
|
+
|
|
473
|
+
_check_expected_version(document, expected_version)
|
|
474
|
+
version = _current_version(document)
|
|
475
|
+
|
|
476
|
+
if address is None:
|
|
477
|
+
viewed_node = document.root
|
|
478
|
+
else:
|
|
479
|
+
current_document_id = getattr(document, "document_id", None)
|
|
480
|
+
try:
|
|
481
|
+
viewed_id = normalize_node_address(document, address, current_document_id=current_document_id)
|
|
482
|
+
except NodeAddressError as exc:
|
|
483
|
+
raise NodeNotFoundError(address) from exc
|
|
484
|
+
viewed_node = document.nodes_by_id[viewed_id]
|
|
485
|
+
|
|
486
|
+
depth = max(int(depth), 0)
|
|
487
|
+
ctx = _Ctx(
|
|
488
|
+
document=document, requested_depth=depth, expand_below_bytes=expand_below_bytes,
|
|
489
|
+
include_attributes=include_attributes, include_source=include_source, source_preview_bytes=source_preview_bytes,
|
|
490
|
+
)
|
|
491
|
+
entries: List[_OutlineEntry] = []
|
|
492
|
+
_walk(ctx, viewed_node, None, 0, 0, False, include_self, entries)
|
|
493
|
+
|
|
494
|
+
viewed_view = build_node_address_view(viewed_node.node_id, viewed_node.short_id)
|
|
495
|
+
kept, truncation = _apply_ceiling(entries, max_output_bytes, viewed_view, depth, expand_below_bytes, version)
|
|
496
|
+
_, meta = _assemble(kept, truncation, viewed_view, depth, expand_below_bytes, version)
|
|
497
|
+
|
|
498
|
+
return build_outline_response(meta, kept, truncation)
|