ai-editor-tree-engine-dev 1.0.176__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. ai_editor_tree_engine_dev-1.0.176.dist-info/METADATA +35 -0
  2. ai_editor_tree_engine_dev-1.0.176.dist-info/RECORD +121 -0
  3. ai_editor_tree_engine_dev-1.0.176.dist-info/WHEEL +5 -0
  4. ai_editor_tree_engine_dev-1.0.176.dist-info/licenses/LICENSE +21 -0
  5. ai_editor_tree_engine_dev-1.0.176.dist-info/top_level.txt +1 -0
  6. tree_engine/PUBLIC_API.md +161 -0
  7. tree_engine/__init__.py +327 -0
  8. tree_engine/checks/__init__.py +60 -0
  9. tree_engine/checks/builtin/__init__.py +5 -0
  10. tree_engine/checks/builtin/compile_check.py +53 -0
  11. tree_engine/checks/builtin/csv_syntax.py +51 -0
  12. tree_engine/checks/builtin/docstrings.py +211 -0
  13. tree_engine/checks/builtin/encoding.py +55 -0
  14. tree_engine/checks/builtin/fleet_rules.py +227 -0
  15. tree_engine/checks/builtin/format_syntax.py +82 -0
  16. tree_engine/checks/builtin/jsonl_syntax.py +49 -0
  17. tree_engine/checks/builtin/shipped.py +52 -0
  18. tree_engine/checks/builtin/syntax.py +118 -0
  19. tree_engine/checks/builtin/xml_wellformed.py +51 -0
  20. tree_engine/checks/chain.py +332 -0
  21. tree_engine/checks/external/__init__.py +5 -0
  22. tree_engine/checks/external/_base.py +61 -0
  23. tree_engine/checks/external/bandit.py +53 -0
  24. tree_engine/checks/external/black.py +48 -0
  25. tree_engine/checks/external/flake8.py +38 -0
  26. tree_engine/checks/external/isort.py +38 -0
  27. tree_engine/checks/external/mypy.py +45 -0
  28. tree_engine/checks/external/ruff.py +45 -0
  29. tree_engine/checks/external/runner.py +197 -0
  30. tree_engine/checks/model.py +110 -0
  31. tree_engine/checks/options.py +73 -0
  32. tree_engine/checks/plugin.py +171 -0
  33. tree_engine/checks/registry.py +349 -0
  34. tree_engine/core/address.py +376 -0
  35. tree_engine/core/identifier_map.py +266 -0
  36. tree_engine/core/identity.py +226 -0
  37. tree_engine/core/instrumentation.py +399 -0
  38. tree_engine/core/integrity.py +341 -0
  39. tree_engine/core/integrity_full.py +382 -0
  40. tree_engine/core/journal.py +260 -0
  41. tree_engine/core/journal_compose.py +571 -0
  42. tree_engine/core/live_tree.py +785 -0
  43. tree_engine/core/locking.py +188 -0
  44. tree_engine/core/move.py +585 -0
  45. tree_engine/core/move_references.py +323 -0
  46. tree_engine/core/node_types.py +408 -0
  47. tree_engine/core/nodes.py +348 -0
  48. tree_engine/core/offsets.py +24 -0
  49. tree_engine/core/operations.py +825 -0
  50. tree_engine/core/plugin_boundary.py +160 -0
  51. tree_engine/core/position_map.py +263 -0
  52. tree_engine/core/position_transfer.py +512 -0
  53. tree_engine/core/range_refresh.py +366 -0
  54. tree_engine/core/reference_cache.py +360 -0
  55. tree_engine/core/references.py +223 -0
  56. tree_engine/core/reparse.py +378 -0
  57. tree_engine/core/short_id.py +296 -0
  58. tree_engine/core/subtree_apply.py +397 -0
  59. tree_engine/core/subtree_copy.py +399 -0
  60. tree_engine/core/transactions.py +397 -0
  61. tree_engine/core/trivia.py +396 -0
  62. tree_engine/core/updates.py +398 -0
  63. tree_engine/core/validation.py +377 -0
  64. tree_engine/errors.py +104 -0
  65. tree_engine/exceptions.py +376 -0
  66. tree_engine/facade.py +4524 -0
  67. tree_engine/plugins/_statements.py +369 -0
  68. tree_engine/plugins/bsl/block_edit.py +449 -0
  69. tree_engine/plugins/bsl/blocks.py +127 -0
  70. tree_engine/plugins/bsl/checker.py +297 -0
  71. tree_engine/plugins/bsl/dialects.py +303 -0
  72. tree_engine/plugins/bsl/generator.py +481 -0
  73. tree_engine/plugins/bsl/import_map.py +995 -0
  74. tree_engine/plugins/bsl/plugin.py +452 -0
  75. tree_engine/plugins/contract.py +355 -0
  76. tree_engine/plugins/cpp/import_map.py +505 -0
  77. tree_engine/plugins/cpp/languages.py +99 -0
  78. tree_engine/plugins/cpp/plugin.py +501 -0
  79. tree_engine/plugins/csv_format.py +676 -0
  80. tree_engine/plugins/detachable.py +156 -0
  81. tree_engine/plugins/fallback.py +421 -0
  82. tree_engine/plugins/ini_format.py +330 -0
  83. tree_engine/plugins/json_format.py +813 -0
  84. tree_engine/plugins/json_pointer.py +203 -0
  85. tree_engine/plugins/jsonl_format.py +392 -0
  86. tree_engine/plugins/markdown_format.py +748 -0
  87. tree_engine/plugins/onec_query_format.py +61 -0
  88. tree_engine/plugins/parse_position.py +54 -0
  89. tree_engine/plugins/plain_text.py +1543 -0
  90. tree_engine/plugins/python/export_map.py +306 -0
  91. tree_engine/plugins/python/import_map.py +429 -0
  92. tree_engine/plugins/python/plugin.py +1710 -0
  93. tree_engine/plugins/registry.py +497 -0
  94. tree_engine/plugins/scan.py +87 -0
  95. tree_engine/plugins/selection.py +228 -0
  96. tree_engine/plugins/sql_format.py +61 -0
  97. tree_engine/plugins/toml_format.py +1072 -0
  98. tree_engine/plugins/xml_format.py +911 -0
  99. tree_engine/plugins/yaml/builder.py +49 -0
  100. tree_engine/plugins/yaml/emitter.py +225 -0
  101. tree_engine/plugins/yaml/flow.py +227 -0
  102. tree_engine/plugins/yaml/plugin.py +458 -0
  103. tree_engine/plugins/yaml/ranges.py +52 -0
  104. tree_engine/plugins/yaml/reader.py +359 -0
  105. tree_engine/plugins/yaml/scanner.py +298 -0
  106. tree_engine/query/adapter.py +283 -0
  107. tree_engine/query/engine.py +853 -0
  108. tree_engine/query/inspection.py +498 -0
  109. tree_engine/query/outline.py +288 -0
  110. tree_engine/query/predicates.py +263 -0
  111. tree_engine/query/rendered_lines.py +46 -0
  112. tree_engine/query/results.py +206 -0
  113. tree_engine/query/selector.py +400 -0
  114. tree_engine/query/xml_query.py +747 -0
  115. tree_engine/storage/codec.py +400 -0
  116. tree_engine/storage/document_bridge.py +579 -0
  117. tree_engine/storage/file_txn.py +459 -0
  118. tree_engine/storage/history.py +106 -0
  119. tree_engine/storage/lifecycle.py +622 -0
  120. tree_engine/storage/schema.py +403 -0
  121. tree_engine/storage/session_guard.py +398 -0
@@ -0,0 +1,226 @@
1
+ """Canonical node identity and atomic id-replacement subsystem.
2
+
3
+ Scope (concept C-004, narrowed to node identity assignment and atomic id
4
+ replacement only): this module owns the canonical ``NodeAddress`` value
5
+ type, the ``AddressRemap`` result type, fresh UUID4 generation, identifier
6
+ stability for unchanged nodes, and the atomic ``replace_node_id`` operation.
7
+
8
+ Explicitly out of scope here (delivered by sibling artifacts under
9
+ T-003/C-008): ``short_id`` allocation and its bidirectional map,
10
+ ``normalize_node_address``, and reference/object-cache index maintenance.
11
+
12
+ ACCEPTANCE NOTE (orchestrator integration decision): ``NodeAddress`` as
13
+ defined in this module is the single canonical NodeAddress for the whole
14
+ tree engine. Sibling artifacts (``address.py`` under T-003,
15
+ ``references.py`` under T-005) import it from here and must not redefine
16
+ it.
17
+
18
+ This module is self-contained: it depends only on the standard library
19
+ (``uuid``, ``dataclasses``, ``typing``) and imports nothing from any
20
+ sibling project module.
21
+
22
+ Source-of-truth requirement labels honored here: {p013}, {p080}, {p084},
23
+ {p097}, {p109}.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from dataclasses import dataclass
29
+ from typing import Any, Optional
30
+ from uuid import UUID, uuid4
31
+
32
+ __all__ = [
33
+ "NodeAddress",
34
+ "AddressRemap",
35
+ "NodeIdentityError",
36
+ "generate_node_id",
37
+ "assign_node_id",
38
+ "replace_node_id",
39
+ ]
40
+
41
+
42
+ class NodeIdentityError(Exception):
43
+ """Raised when a node-identity operation cannot be completed.
44
+
45
+ Covers a syntactically invalid new node_id and a new node_id that
46
+ already collides with an existing entry in the document's internal
47
+ id mapping. Raising this error guarantees the triggering operation
48
+ performed no partial mutation of the document.
49
+ """
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class NodeAddress:
54
+ """Canonical cross-document address of a node.
55
+
56
+ ``node_id`` is the required canonical UUID4 identifier of the node.
57
+ ``document_id`` is ``None`` for the implicit-current-document (local)
58
+ form used in memory per {p080}, or an explicit UUID4 document
59
+ identifier for a cross-document / external reference.
60
+
61
+ Immutable and hashable: safe as a dict key, and equality is defined
62
+ structurally over the ``(document_id, node_id)`` pair, so two
63
+ instances addressing the same document/node compare equal even if
64
+ constructed separately.
65
+ """
66
+
67
+ node_id: UUID
68
+ document_id: Optional[UUID] = None
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class AddressRemap:
73
+ """Result of a successful ``replace_node_id`` call.
74
+
75
+ ``old`` is the ``NodeAddress`` that identified the node before the
76
+ replacement; ``new`` is the ``NodeAddress`` that identifies it
77
+ afterwards. Both share the same ``document_id`` as the document the
78
+ replacement was performed against.
79
+ """
80
+
81
+ old: NodeAddress
82
+ new: NodeAddress
83
+
84
+
85
+ def generate_node_id() -> UUID:
86
+ """Return a fresh, randomly generated UUID4 node identifier.
87
+
88
+ Each call is independent and uses ``uuid.uuid4()``'s cryptographic
89
+ random source, so collisions across calls are not a practical
90
+ concern.
91
+ """
92
+
93
+ return uuid4()
94
+
95
+
96
+ def assign_node_id(existing_id: Optional[UUID] = None) -> UUID:
97
+ """Return the canonical node_id to use for a node.
98
+
99
+ Per {p013}, identifiers of unchanged nodes are preserved without any
100
+ global old/new tree mapping: when ``existing_id`` is provided it is
101
+ returned unchanged. When ``existing_id`` is ``None`` (a new node), a
102
+ fresh, unique UUID4 is generated and returned.
103
+ """
104
+
105
+ if existing_id is not None:
106
+ return existing_id
107
+ return generate_node_id()
108
+
109
+
110
+ def _validate_uuid4(value: Any, *, what: str) -> UUID:
111
+ """Validate that ``value`` is a syntactically valid UUID4.
112
+
113
+ Accepts a ``uuid.UUID`` instance directly, or a string/bytes-like
114
+ value that can be parsed into one. Raises ``NodeIdentityError`` when
115
+ the value is not a UUID at all, or is a well-formed UUID of a
116
+ version other than 4.
117
+ """
118
+
119
+ candidate: Optional[UUID]
120
+ if isinstance(value, UUID):
121
+ candidate = value
122
+ else:
123
+ try:
124
+ candidate = UUID(str(value))
125
+ except (ValueError, AttributeError, TypeError):
126
+ candidate = None
127
+
128
+ if candidate is None:
129
+ raise NodeIdentityError(
130
+ f"{what} is not a syntactically valid UUID: {value!r}"
131
+ )
132
+ if candidate.version != 4:
133
+ raise NodeIdentityError(
134
+ f"{what} is not a valid UUID4 (version={candidate.version}): "
135
+ f"{candidate!r}"
136
+ )
137
+ return candidate
138
+
139
+
140
+ def replace_node_id(document: Any, old_node_id: UUID, new_node_id: UUID) -> AddressRemap:
141
+ """Atomically replace a node's canonical id with a new UUID4.
142
+
143
+ ``document`` is assumed to already expose an internal id mapping
144
+ (e.g. a ``nodes_by_id`` dict-like attribute keyed by ``UUID`` and
145
+ valued by the node object) — this function reads and updates that
146
+ existing key, it does not redesign the mapping structure. The
147
+ document object may optionally expose a ``document_id`` attribute
148
+ (a UUID or ``None``); when absent it is treated as ``None`` (the
149
+ implicit-current-document / local form per {p080}).
150
+
151
+ Validation, performed before any mutation:
152
+ * ``new_node_id`` must be a syntactically valid UUID4.
153
+ * ``new_node_id`` must not already be present as a key in the
154
+ document's ``nodes_by_id`` mapping (no collisions).
155
+ * ``old_node_id`` must currently be present as a key in that
156
+ mapping (nothing to replace otherwise).
157
+
158
+ On any validation failure, ``NodeIdentityError`` is raised and the
159
+ document's mapping is left completely unchanged (no partial
160
+ mutation).
161
+
162
+ On success, per {p013}/{p109}, the following happen atomically (as
163
+ seen by any caller — no intermediate state is observable through the
164
+ mapping):
165
+ * the node object's own ``node_id`` field is updated to
166
+ ``new_node_id`` (if the node exposes such an attribute);
167
+ * the mapping's ``old_node_id`` key is removed and a
168
+ ``new_node_id`` key is inserted pointing at the same node
169
+ object;
170
+ * if the node (or its mapping entry) exposes a per-entry
171
+ ``generation`` counter, it is incremented by one, per {p084};
172
+ * the node's ``short_id`` (if present) is left completely
173
+ untouched, per {p097} — replace_node_id must never reassign or
174
+ clear it.
175
+
176
+ Returns an ``AddressRemap`` whose ``old`` and ``new`` addresses share
177
+ the document's ``document_id`` and carry ``old_node_id`` /
178
+ ``new_node_id`` respectively.
179
+ """
180
+
181
+ nodes_by_id = getattr(document, "nodes_by_id", None)
182
+ if nodes_by_id is None:
183
+ raise NodeIdentityError(
184
+ "document does not expose a 'nodes_by_id' internal id mapping"
185
+ )
186
+
187
+ validated_new_id = _validate_uuid4(new_node_id, what="new_node_id")
188
+
189
+ if old_node_id not in nodes_by_id:
190
+ raise NodeIdentityError(
191
+ f"old_node_id {old_node_id!r} is not present in the document's "
192
+ "id mapping"
193
+ )
194
+
195
+ if validated_new_id in nodes_by_id:
196
+ raise NodeIdentityError(
197
+ f"new_node_id {validated_new_id!r} already present in the "
198
+ "document's id mapping (collision)"
199
+ )
200
+
201
+ # All preconditions verified; perform the update atomically. Nothing
202
+ # above this point has mutated the document.
203
+ node = nodes_by_id[old_node_id]
204
+
205
+ if hasattr(node, "node_id"):
206
+ try:
207
+ node.node_id = validated_new_id
208
+ except AttributeError:
209
+ # Node forbids attribute assignment (e.g. frozen type); the
210
+ # mapping key swap below is still the authoritative update.
211
+ pass
212
+
213
+ if hasattr(node, "generation"):
214
+ try:
215
+ node.generation = node.generation + 1
216
+ except (AttributeError, TypeError):
217
+ pass
218
+
219
+ del nodes_by_id[old_node_id]
220
+ nodes_by_id[validated_new_id] = node
221
+
222
+ document_id = getattr(document, "document_id", None)
223
+ return AddressRemap(
224
+ old=NodeAddress(document_id=document_id, node_id=old_node_id),
225
+ new=NodeAddress(document_id=document_id, node_id=validated_new_id),
226
+ )
@@ -0,0 +1,399 @@
1
+ """Optional per-phase instrumentation for the tree engine (C-022, {p030}).
2
+
3
+ Author: Vasiliy Zdanovskiy
4
+ email: vasilyvz@gmail.com
5
+
6
+ Scope: the engine's optional measurement surface and nothing else. Per invocation
7
+ of one of the seven exposed phase boundaries -- ``load``, ``parse``, ``query``,
8
+ ``mutate``, ``index-update``, ``validate``, ``save`` -- it records wall-clock
9
+ duration, affected-node count, and changed-text volume, plus structural markers.
10
+ Per {p030} collection is DISABLED BY DEFAULT, turned on by one explicit
11
+ :func:`enable` call.
12
+
13
+ Zero cost when disabled: :func:`measure` returns a shared stateless no-op scope
14
+ whose methods do nothing -- no clock read, no per-call allocation, no storage
15
+ touched -- and :func:`record` returns at once. The only work left on the disabled
16
+ path is one frozenset test on the phase name.
17
+
18
+ Thread safety: every write goes into a per-thread store, so instrumented threads
19
+ never contend for one counter and no update can be lost. Each store carries its
20
+ own lock, held only for the statements updating its integers, so a reader merging
21
+ the stores never observes a half-updated dict. Stores live in a process-wide list
22
+ guarded by ``_REGISTRY_LOCK``; totals read once the writing threads joined are
23
+ exactly the sum of what those threads did.
24
+
25
+ Observation never mutates the observed: this module holds no reference to any
26
+ ``Document`` or ``Node`` and only accumulates integers handed to it, so node
27
+ identity, ``document_version``, and rendered bytes cannot be affected by it.
28
+ Standard library only: no ``ai_editor`` import, no parser library ({p003}).
29
+
30
+ Benchmark gate ({p029}): an invocation may carry :data:`MARKER_FULL_TRAVERSAL`,
31
+ :data:`MARKER_FULL_PARSE`, or :data:`MARKER_FULL_INDEX_REBUILD`. The gate
32
+ snapshots before and after a single local operation, subtracts with
33
+ :meth:`CounterSnapshot.delta_from`, then asserts
34
+ :meth:`CounterSnapshot.is_local_operation`.
35
+
36
+ Source-of-truth requirement labels honored here: {p029}, {p030}.
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ import threading
42
+ from dataclasses import dataclass
43
+ from functools import wraps
44
+ from time import perf_counter_ns
45
+ from types import MappingProxyType
46
+ from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Tuple
47
+
48
+ __all__ = [
49
+ "PHASE_LOAD", "PHASE_PARSE", "PHASE_QUERY", "PHASE_MUTATE", "PHASE_INDEX_UPDATE",
50
+ "PHASE_VALIDATE", "PHASE_SAVE", "PHASES", "MARKER_FULL_TRAVERSAL", "MARKER_FULL_PARSE",
51
+ "MARKER_FULL_INDEX_REBUILD", "STRUCTURAL_MARKERS", "SCOPE_GLOBAL", "SCOPE_THREAD",
52
+ "METRICS", "PhaseCounter", "CounterSnapshot", "enable", "disable", "is_enabled",
53
+ "reset", "measure", "record", "instrument", "query_counters",
54
+ ]
55
+
56
+ PHASE_LOAD, PHASE_PARSE, PHASE_QUERY = "load", "parse", "query"
57
+ PHASE_MUTATE, PHASE_INDEX_UPDATE = "mutate", "index-update"
58
+ PHASE_VALIDATE, PHASE_SAVE = "validate", "save"
59
+
60
+ #: Every phase boundary the engine exposes for measurement ({p030}).
61
+ PHASES: Tuple[str, ...] = (PHASE_LOAD, PHASE_PARSE, PHASE_QUERY, PHASE_MUTATE,
62
+ PHASE_INDEX_UPDATE, PHASE_VALIDATE, PHASE_SAVE)
63
+ _PHASE_SET = frozenset(PHASES)
64
+ _PHASE_ORDER = {name: position for position, name in enumerate(PHASES)}
65
+
66
+ #: The per-invocation metrics of {p030}; the names :meth:`CounterSnapshot.total` takes.
67
+ METRICS: Tuple[str, ...] = ("invocations", "duration_ns", "affected_nodes", "changed_text")
68
+
69
+ MARKER_FULL_TRAVERSAL, MARKER_FULL_PARSE = "full-traversal", "full-parse"
70
+ MARKER_FULL_INDEX_REBUILD = "full-index-rebuild"
71
+
72
+ #: The three markers a single local operation must never raise ({p029}).
73
+ STRUCTURAL_MARKERS: Tuple[str, ...] = (MARKER_FULL_TRAVERSAL, MARKER_FULL_PARSE,
74
+ MARKER_FULL_INDEX_REBUILD)
75
+
76
+ SCOPE_GLOBAL, SCOPE_THREAD = "global", "thread"
77
+
78
+ _EMPTY: Mapping[str, Any] = MappingProxyType({})
79
+
80
+ _ENABLED = False
81
+ _LOCAL = threading.local()
82
+ _STORES: List["_ThreadStore"] = []
83
+ _REGISTRY_LOCK = threading.Lock()
84
+
85
+
86
+ def _check_phase(phase: str) -> None: # reject a phase the engine does not expose
87
+ if phase not in _PHASE_SET:
88
+ raise ValueError(f"unknown instrumentation phase {phase!r}; expected one of {PHASES}")
89
+
90
+
91
+ def _text_volume(value: Any) -> int:
92
+ """Changed-text volume of ``value`` in bytes: ``None`` is zero, a ``str`` gives
93
+ its UTF-8 length, ``bytes``-like data its length, an ``int`` is already a volume."""
94
+ if value is None:
95
+ return 0
96
+ if isinstance(value, str):
97
+ return len(value.encode("utf-8"))
98
+ if isinstance(value, (bytes, bytearray, memoryview)):
99
+ return len(value)
100
+ if isinstance(value, int) and not isinstance(value, bool):
101
+ return value
102
+ raise TypeError(f"cannot measure changed-text volume of {type(value).__name__}")
103
+
104
+
105
+ class _PhaseAccumulator:
106
+ """Mutable per-phase totals; never touched without the owning store's lock."""
107
+
108
+ __slots__ = ("invocations", "duration_ns", "affected_nodes", "changed_text", "markers")
109
+
110
+ def __init__(self) -> None:
111
+ self.invocations = self.duration_ns = self.affected_nodes = self.changed_text = 0
112
+ self.markers: Dict[str, int] = {}
113
+
114
+ def absorb(self, other: "_PhaseAccumulator") -> None:
115
+ """Add another accumulator's totals into this one, marker counts included."""
116
+ self.invocations += other.invocations
117
+ self.duration_ns += other.duration_ns
118
+ self.affected_nodes += other.affected_nodes
119
+ self.changed_text += other.changed_text
120
+ for marker, count in other.markers.items():
121
+ self.markers[marker] = self.markers.get(marker, 0) + count
122
+
123
+ def to_counter(self, phase: str) -> "PhaseCounter": # freeze into an immutable counter
124
+ return PhaseCounter(phase, self.invocations, self.duration_ns, self.affected_nodes,
125
+ self.changed_text, MappingProxyType(dict(self.markers)))
126
+
127
+
128
+ class _ThreadStore:
129
+ """One writing thread's private counters plus the lock a reader must take. It is
130
+ uncontended in the common case -- only the owning thread writes -- and
131
+ :meth:`merge_into` takes it so a snapshot never iterates a resizing dict."""
132
+
133
+ __slots__ = ("lock", "phases")
134
+
135
+ def __init__(self) -> None:
136
+ self.lock = threading.Lock()
137
+ self.phases: Dict[str, _PhaseAccumulator] = {}
138
+
139
+ def add(self, phase: str, duration_ns: int, affected_nodes: int, changed_text: int,
140
+ markers: Iterable[str], invocations: int = 1) -> None: # one recorded invocation
141
+ with self.lock:
142
+ accumulator = self.phases.get(phase)
143
+ if accumulator is None:
144
+ accumulator = _PhaseAccumulator()
145
+ self.phases[phase] = accumulator
146
+ accumulator.invocations += invocations
147
+ accumulator.duration_ns += duration_ns
148
+ accumulator.affected_nodes += affected_nodes
149
+ accumulator.changed_text += changed_text
150
+ for marker in markers:
151
+ accumulator.markers[marker] = accumulator.markers.get(marker, 0) + 1
152
+
153
+ def merge_into(self, target: Dict[str, _PhaseAccumulator]) -> None:
154
+ """Add this store's totals into ``target``, under this store's own lock."""
155
+ with self.lock:
156
+ for phase, accumulator in self.phases.items():
157
+ destination = target.get(phase)
158
+ if destination is None:
159
+ destination = _PhaseAccumulator()
160
+ target[phase] = destination
161
+ destination.absorb(accumulator)
162
+
163
+ def clear(self) -> None: # Drop this store's counters.
164
+ with self.lock:
165
+ self.phases.clear()
166
+
167
+
168
+ def _current_store() -> _ThreadStore: # this thread's store, registered on first use
169
+ store = getattr(_LOCAL, "store", None)
170
+ if store is None:
171
+ store = _ThreadStore()
172
+ with _REGISTRY_LOCK:
173
+ _STORES.append(store)
174
+ _LOCAL.store = store
175
+ return store
176
+
177
+
178
+ @dataclass(frozen=True)
179
+ class PhaseCounter:
180
+ """Immutable totals for one phase: summed nanoseconds, summed affected-node count,
181
+ summed changed-text bytes, and how many invocations raised each marker."""
182
+
183
+ phase: str
184
+ invocations: int = 0
185
+ duration_ns: int = 0
186
+ affected_nodes: int = 0
187
+ changed_text: int = 0
188
+ markers: Mapping[str, int] = _EMPTY
189
+
190
+
191
+ def _freeze(counters: Dict[str, PhaseCounter]) -> Mapping[str, PhaseCounter]: # read-only
192
+ ordered = sorted(counters.items(), key=lambda item: _PHASE_ORDER.get(item[0], len(PHASES)))
193
+ return MappingProxyType(dict(ordered))
194
+
195
+
196
+ @dataclass(frozen=True)
197
+ class CounterSnapshot:
198
+ """An immutable read of the counters: ``phases`` maps a phase name to its
199
+ :class:`PhaseCounter`. A phase never recorded is absent, and :meth:`counter`
200
+ returns a zeroed counter for it, so a caller never tests membership."""
201
+
202
+ phases: Mapping[str, PhaseCounter] = _EMPTY
203
+
204
+ def counter(self, phase: str) -> PhaseCounter: # zeroed when never recorded
205
+ _check_phase(phase)
206
+ return self.phases.get(phase, PhaseCounter(phase=phase))
207
+
208
+ def total(self, metric: str, phase: Optional[str] = None) -> int:
209
+ """Sum one of :data:`METRICS` over ``phase``, or over every phase."""
210
+ if metric not in METRICS:
211
+ raise ValueError(f"unknown metric {metric!r}; expected one of {METRICS}")
212
+ if phase is not None:
213
+ return int(getattr(self.counter(phase), metric))
214
+ return sum(int(getattr(counter, metric)) for counter in self.phases.values())
215
+
216
+ def markers(self, phase: Optional[str] = None) -> Mapping[str, int]: # merged if no phase
217
+ if phase is not None:
218
+ return self.counter(phase).markers
219
+ merged: Dict[str, int] = {}
220
+ for counter in self.phases.values():
221
+ for marker, count in counter.markers.items():
222
+ merged[marker] = merged.get(marker, 0) + count
223
+ return MappingProxyType(merged)
224
+
225
+ def structural_markers(self, phase: Optional[str] = None) -> Tuple[str, ...]:
226
+ """Which of :data:`STRUCTURAL_MARKERS` this snapshot carries, in declared order."""
227
+ present = self.markers(phase)
228
+ return tuple(marker for marker in STRUCTURAL_MARKERS if present.get(marker, 0) > 0)
229
+
230
+ def is_local_operation(self, phase: Optional[str] = None) -> bool:
231
+ """True when no full-traversal, full-parse, or full-index-rebuild marker
232
+ was raised -- the structural assertion of {p029}."""
233
+ return not self.structural_markers(phase)
234
+
235
+ def delta_from(self, baseline: "CounterSnapshot") -> "CounterSnapshot":
236
+ """This snapshot minus ``baseline``, so the gate isolates exactly one operation
237
+ from counters already carrying earlier work; unmoved phases are dropped."""
238
+ result: Dict[str, PhaseCounter] = {}
239
+ for phase, counter in self.phases.items():
240
+ old = baseline.phases.get(phase, PhaseCounter(phase=phase))
241
+ markers = {marker: count - old.markers.get(marker, 0)
242
+ for marker, count in counter.markers.items()
243
+ if count > old.markers.get(marker, 0)}
244
+ values = {metric: getattr(counter, metric) - getattr(old, metric)
245
+ for metric in METRICS}
246
+ if markers or any(values.values()):
247
+ result[phase] = PhaseCounter(phase, **values, markers=MappingProxyType(markers))
248
+ return CounterSnapshot(_freeze(result))
249
+
250
+
251
+ def _noop(*args: Any, **kwargs: Any) -> None:
252
+ """The disabled-path no-op shared by every :class:`_NullScope` reporting method."""
253
+
254
+
255
+ class _NullScope:
256
+ """The shared stateless scope returned while collection is disabled: every
257
+ reporting method is :func:`_noop` and the instance carries no per-call state, so
258
+ one object is safely shared by every thread and nothing is allocated."""
259
+
260
+ __slots__ = ()
261
+ add_affected_nodes = _noop
262
+ add_changed_text = _noop
263
+ mark = _noop
264
+
265
+ def __enter__(self) -> "_NullScope":
266
+ return self
267
+
268
+ def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
269
+ return None
270
+
271
+
272
+ _NULL_SCOPE = _NullScope()
273
+
274
+
275
+ class _ActiveScope:
276
+ """A live measurement of one phase invocation. The clock starts in ``__enter__``
277
+ and the record is written in ``__exit__`` -- including when the body raised, so a
278
+ failed phase is still counted. Nested scopes are allowed; an outer scope's
279
+ duration includes its inner scopes."""
280
+
281
+ __slots__ = ("_phase", "_nodes", "_text", "_markers", "_start")
282
+
283
+ def __init__(self, phase: str, nodes: int, text: int, markers: List[str]) -> None:
284
+ self._phase = phase
285
+ self._nodes = nodes
286
+ self._text = text
287
+ self._markers = markers
288
+ self._start = 0
289
+
290
+ def __enter__(self) -> "_ActiveScope":
291
+ self._start = perf_counter_ns()
292
+ return self
293
+
294
+ def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
295
+ duration = perf_counter_ns() - self._start
296
+ _current_store().add(self._phase, duration, self._nodes, self._text, self._markers)
297
+
298
+ def add_affected_nodes(self, count: int = 1) -> None: # this invocation touched more nodes
299
+ self._nodes += int(count)
300
+
301
+ def add_changed_text(self, value: Any) -> None: # int, str, or bytes; see _text_volume
302
+ self._text += _text_volume(value)
303
+
304
+ def mark(self, *markers: str) -> None: # raise structural markers on this invocation
305
+ self._markers.extend(markers)
306
+
307
+
308
+ def enable(*, reset_counters: bool = True) -> None:
309
+ """Turn collection on -- the single explicit call of {p030}; ``reset_counters``
310
+ clears what an earlier run left behind."""
311
+ global _ENABLED
312
+ if reset_counters:
313
+ reset()
314
+ _ENABLED = True
315
+
316
+
317
+ def disable() -> None:
318
+ """Turn collection off, restoring the no-op fast path. Counters already collected
319
+ are kept; call :func:`reset` to drop them."""
320
+ global _ENABLED
321
+ _ENABLED = False
322
+
323
+
324
+ def is_enabled() -> bool: # True while collection is on
325
+ return _ENABLED
326
+
327
+
328
+ def reset() -> None: # drop every counter of every thread; the enabled state is untouched
329
+ with _REGISTRY_LOCK:
330
+ stores = list(_STORES)
331
+ for store in stores:
332
+ store.clear()
333
+
334
+
335
+ def measure(phase: str, *, affected_nodes: int = 0, changed_text: Any = None,
336
+ markers: Iterable[str] = ()) -> Any:
337
+ """A context manager measuring one invocation of ``phase``. While disabled it is
338
+ the shared no-op scope, allocating nothing and reading no clock; while enabled it
339
+ times the block and takes ``add_affected_nodes``, ``add_changed_text`` and
340
+ ``mark`` as the block runs, so a caller reports what it touched once it knows."""
341
+ if phase not in _PHASE_SET:
342
+ _check_phase(phase)
343
+ if not _ENABLED:
344
+ return _NULL_SCOPE
345
+ return _ActiveScope(phase, int(affected_nodes), _text_volume(changed_text), list(markers))
346
+
347
+
348
+ def record(phase: str, *, duration_ns: int = 0, affected_nodes: int = 0, changed_text: Any = None,
349
+ markers: Iterable[str] = (), invocations: int = 1) -> None:
350
+ """Record one already-measured invocation of ``phase``, for a caller that timed it
351
+ itself; ``invocations=0`` raises markers only. A no-op while disabled."""
352
+ if phase not in _PHASE_SET:
353
+ _check_phase(phase)
354
+ if not _ENABLED:
355
+ return
356
+ _current_store().add(phase, int(duration_ns), int(affected_nodes),
357
+ _text_volume(changed_text), tuple(markers), int(invocations))
358
+
359
+
360
+ def instrument(phase: str, *, markers: Iterable[str] = ()) -> Callable[[Callable], Callable]:
361
+ """Decorator wrapping a callable as one invocation of ``phase``, so the benchmark
362
+ suite or gate can attach instrumentation to an existing entry point without
363
+ editing it. While disabled the wrapper calls straight through."""
364
+ _check_phase(phase)
365
+ fixed = tuple(markers)
366
+
367
+ def decorator(function: Callable) -> Callable:
368
+ @wraps(function)
369
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
370
+ if not _ENABLED:
371
+ return function(*args, **kwargs)
372
+ with _ActiveScope(phase, 0, 0, list(fixed)):
373
+ return function(*args, **kwargs)
374
+ return wrapper
375
+
376
+ return decorator
377
+
378
+
379
+ def query_counters(*, phase: Optional[str] = None, scope: str = SCOPE_GLOBAL) -> CounterSnapshot:
380
+ """An immutable snapshot of the counters. ``scope`` is :data:`SCOPE_GLOBAL` (every
381
+ thread's counters merged, the default) or :data:`SCOPE_THREAD` (only the calling
382
+ thread's, what a structural assertion should use while other threads work);
383
+ ``phase`` narrows it to one phase. Callable enabled or not."""
384
+ if phase is not None:
385
+ _check_phase(phase)
386
+ if scope == SCOPE_THREAD:
387
+ stores = [_current_store()]
388
+ elif scope == SCOPE_GLOBAL:
389
+ with _REGISTRY_LOCK:
390
+ stores = list(_STORES)
391
+ else:
392
+ raise ValueError(
393
+ f"unknown counter scope {scope!r}; expected {SCOPE_GLOBAL!r} or {SCOPE_THREAD!r}")
394
+ merged: Dict[str, _PhaseAccumulator] = {}
395
+ for store in stores:
396
+ store.merge_into(merged)
397
+ counters = {name: accumulator.to_counter(name) for name, accumulator in merged.items()
398
+ if phase is None or name == phase}
399
+ return CounterSnapshot(_freeze(counters))