fixpoints 0.4.0.post85.dev0__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.
fixpoints/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Least-fixpoint cached-property infrastructure for mutual recursion.
2
+
3
+ Import the public symbols directly from :mod:`fixpoints._core`::
4
+
5
+ from fixpoints._core import fixpoint_cached_property
6
+ from fixpoints._core import fixpoint_dependent
7
+ from fixpoints._core import FixpointRecursionError
8
+ """
fixpoints/_core.py ADDED
@@ -0,0 +1,370 @@
1
+ """Least-fixpoint cached-property infrastructure for mutual recursion.
2
+
3
+ ``fixpoint_cached_property`` and ``fixpoint_dependent`` are drop-in
4
+ replacements for ``functools.cached_property`` that resolve mutually
5
+ recursive computations by least-fixpoint iteration. When reentry (a cycle)
6
+ is detected, the outermost caller drives a digest loop that re-evaluates
7
+ participants until their values stabilize, starting from a configurable
8
+ bottom value.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import itertools
14
+ import math
15
+ from collections import defaultdict
16
+ from contextvars import ContextVar
17
+ from enum import Enum
18
+ from functools import cached_property
19
+ from typing import Callable, ClassVar
20
+
21
+
22
+ class _FixpointContext:
23
+ """Tracks the state of a fixpoint iteration (digest cycle).
24
+
25
+ Stored in a ContextVar so that nested/concurrent fixpoint computations
26
+ are isolated per-thread/per-coroutine.
27
+ """
28
+
29
+ __slots__ = ("computing", "reentrant", "participant_ids", "participant_refs",
30
+ "_clearable_attr_names", "approximations")
31
+
32
+ def __init__(self, clearable_attr_names: frozenset[str]) -> None:
33
+ self.computing: set[tuple[int, str]] = set()
34
+ self.reentrant: bool = False
35
+ self.participant_ids: set[int] = set()
36
+ self.participant_refs: list[object] = []
37
+ self._clearable_attr_names = clearable_attr_names
38
+ self.approximations: dict[tuple[int, str], object] = {}
39
+
40
+ def add_participant(self, instance: object) -> None:
41
+ instance_id = id(instance)
42
+ if instance_id not in self.participant_ids:
43
+ self.participant_ids.add(instance_id)
44
+ self.participant_refs.append(instance)
45
+
46
+ def clear_participant_caches(self) -> None:
47
+ """Clear all fixpoint-related cached values on all participants.
48
+
49
+ Before clearing, save each value into ``approximations`` so that
50
+ intermediate fixpoint_cached_property computations can use their
51
+ previous iteration's result as an approximation instead of bottom
52
+ when they encounter reentry.
53
+ """
54
+ for instance in self.participant_refs:
55
+ instance_dict = instance.__dict__
56
+ instance_id = id(instance)
57
+ for attr_name in self._clearable_attr_names:
58
+ value = instance_dict.pop(attr_name, None)
59
+ if value is not None:
60
+ self.approximations[(instance_id, attr_name)] = value
61
+
62
+
63
+ _fixpoint_context_var: ContextVar[_FixpointContext | None] = ContextVar(
64
+ "_fixpoint_context_var", default=None
65
+ )
66
+
67
+
68
+ class FixpointRecursionError(RecursionError):
69
+ """Raised when fixpoint iteration is exhausted or reentry is detected with no iterations remaining.
70
+
71
+ Carries the best approximation computed so far in ``incomplete_result``.
72
+ As a ``RecursionError`` subclass, existing code that catches ``RecursionError``
73
+ will also catch ``FixpointRecursionError``.
74
+ """
75
+
76
+ incomplete_result: object
77
+
78
+ def __init__(self, message: str, *, incomplete_result: object) -> None:
79
+ super().__init__(message)
80
+ self.incomplete_result = incomplete_result
81
+
82
+
83
+ _FIXPOINT_SENTINEL = object()
84
+
85
+ # Registry of attribute names that need clearing during fixpoint digest cycles.
86
+ # Populated by fixpoint_cached_property and fixpoint_dependent decorators.
87
+ _fixpoint_clearable_attrs: set[str] = set()
88
+
89
+
90
+ def _accumulate_defaultdict_set(
91
+ accumulator: defaultdict[object, set[object]],
92
+ new_result: defaultdict[object, set[object]],
93
+ ) -> bool:
94
+ """Merge new_result into accumulator (pointwise set union).
95
+
96
+ Returns True if accumulator grew (new entries were added).
97
+ """
98
+ changed = False
99
+ for key, values in new_result.items():
100
+ existing = accumulator[key]
101
+ old_size = len(existing)
102
+ existing.update(values)
103
+ if len(existing) > old_size:
104
+ changed = True
105
+ return changed
106
+
107
+
108
+ class FixpointIterationSentinel(Enum):
109
+ UNLIMITED = math.inf
110
+
111
+
112
+ class fixpoint_cached_property:
113
+ """A cached_property that supports mutual-recursion via least fixpoint iteration.
114
+
115
+ API-compatible with functools.cached_property. When reentry is detected
116
+ (mutual recursion), returns the previous iteration's approximation
117
+ (or ``bottom()`` on the first iteration). The outermost caller drives
118
+ a digest loop until values stabilize (no reentry occurs in a round).
119
+
120
+ Usage::
121
+
122
+ @fixpoint_cached_property(bottom=lambda: defaultdict(set))
123
+ def qualified_this(self):
124
+ ...
125
+
126
+ The class-level ``max_fixpoint_iterations`` ContextVar controls the
127
+ maximum number of digest rounds. ``0`` disables fixpoint iteration
128
+ and raises ``FixpointRecursionError`` on reentry. Default
129
+ ``FixpointIterationSentinel.UNLIMITED`` iterates until convergence or
130
+ until Python's stack is exhausted::
131
+
132
+ fixpoint_cached_property.max_fixpoint_iterations.set(0) # single-pass
133
+ fixpoint_cached_property.max_fixpoint_iterations.set(100) # bounded multi-pass
134
+ fixpoint_cached_property.max_fixpoint_iterations.set(FixpointIterationSentinel.UNLIMITED) # unbounded (default)
135
+ """
136
+
137
+ max_fixpoint_iterations: ClassVar[ContextVar[int | FixpointIterationSentinel]] = ContextVar(
138
+ "fixpoint_cached_property.max_fixpoint_iterations", default=FixpointIterationSentinel.UNLIMITED
139
+ )
140
+
141
+ def __init__(
142
+ self,
143
+ func: Callable = None,
144
+ *,
145
+ bottom: Callable[[], object],
146
+ accumulate: Callable[[object, object], bool] | None = None,
147
+ ) -> None:
148
+ # Support both @fixpoint_cached_property(bottom=...) and direct call
149
+ self._bottom = bottom
150
+ self._accumulate = accumulate
151
+ if func is not None:
152
+ self.func: Callable = func
153
+ self.attrname: str = func.__name__
154
+ self.__doc__ = func.__doc__
155
+ _fixpoint_clearable_attrs.add(self.attrname)
156
+
157
+ def __call__(self, func: Callable) -> "fixpoint_cached_property":
158
+ """Support @fixpoint_cached_property(bottom=...) decorator syntax."""
159
+ self.func = func
160
+ self.attrname = func.__name__
161
+ self.__doc__ = func.__doc__
162
+ _fixpoint_clearable_attrs.add(self.attrname)
163
+ return self
164
+
165
+ def __set_name__(self, owner: type, name: str) -> None:
166
+ if not hasattr(self, "attrname"):
167
+ self.attrname = name
168
+ _fixpoint_clearable_attrs.add(self.attrname)
169
+
170
+ @classmethod
171
+ def _get_max_iterations(cls) -> int | float:
172
+ raw = cls.max_fixpoint_iterations.get()
173
+ if isinstance(raw, FixpointIterationSentinel):
174
+ return raw.value
175
+ return raw
176
+
177
+ def __get__(self, instance: object, owner: type = None) -> object:
178
+ if instance is None:
179
+ return self
180
+
181
+ # Fast path: already cached
182
+ cache = instance.__dict__
183
+ value = cache.get(self.attrname, _FIXPOINT_SENTINEL)
184
+ if value is not _FIXPOINT_SENTINEL:
185
+ max_iterations = self._get_max_iterations()
186
+ if max_iterations == 0:
187
+ return value
188
+ # Detect reentry: if this key is currently being computed
189
+ # (on the call stack), accessing its cached approximation
190
+ # means the fixpoint has not converged yet.
191
+ context = _fixpoint_context_var.get()
192
+ if context is not None:
193
+ key = (id(instance), self.attrname)
194
+ if key in context.computing:
195
+ context.reentrant = True
196
+ context.add_participant(instance)
197
+ return value
198
+
199
+ max_iterations = self._get_max_iterations()
200
+ context = _fixpoint_context_var.get()
201
+ instance_id = id(instance)
202
+ key = (instance_id, self.attrname)
203
+
204
+ if context is None:
205
+ # I am the driver — start a digest loop (or single-pass for max_iterations=0)
206
+ context = _FixpointContext(
207
+ clearable_attr_names=frozenset(_fixpoint_clearable_attrs)
208
+ )
209
+ token = _fixpoint_context_var.set(context)
210
+ try:
211
+ if max_iterations == 0:
212
+ # Zero-iteration mode: compute once with reentry detection.
213
+ # Reentry raises FixpointRecursionError instead of infinite recursion.
214
+ context.computing.add(key)
215
+ result = self.func(instance)
216
+ cache[self.attrname] = result
217
+ return result
218
+
219
+ approximation = self._bottom()
220
+ accumulator = self._bottom() if self._accumulate is not None else None
221
+ previous_result = _FIXPOINT_SENTINEL
222
+ for iteration in itertools.count():
223
+ context.computing.add(key)
224
+ context.add_participant(instance)
225
+ result = self.func(instance)
226
+
227
+ if not context.reentrant:
228
+ # No reentry this round — fixpoint reached
229
+ cache[self.attrname] = result
230
+ return result
231
+
232
+ if self._accumulate is not None:
233
+ # Monotonic accumulation: merge each iteration's
234
+ # result into an accumulator that only grows.
235
+ # This prevents oscillation when intermediate
236
+ # computations encounter cycles in varying order.
237
+ changed = self._accumulate(accumulator, result)
238
+ if not changed and iteration > 0:
239
+ cache[self.attrname] = accumulator
240
+ return accumulator
241
+ # Use the accumulator as next round's approximation
242
+ approximation = accumulator
243
+ else:
244
+ # Exact equality convergence (original behavior)
245
+ if result == previous_result:
246
+ cache[self.attrname] = result
247
+ return result
248
+ previous_result = result
249
+ approximation = result
250
+
251
+ # Cache current approximation, clear all intermediate
252
+ # caches, and re-run
253
+ cache[self.attrname] = approximation
254
+ context.clear_participant_caches()
255
+ # Restore driver's own approximation
256
+ cache[self.attrname] = approximation
257
+ context.computing.clear()
258
+ context.reentrant = False
259
+
260
+ if iteration + 1 >= max_iterations:
261
+ raise FixpointRecursionError(
262
+ f"fixpoint_cached_property '{self.attrname}' did not converge "
263
+ f"after {max_iterations} iterations",
264
+ incomplete_result=approximation,
265
+ )
266
+ finally:
267
+ _fixpoint_context_var.reset(token)
268
+ elif key in context.computing:
269
+ # Reentry detected — return previous approximation or bottom.
270
+ context.reentrant = True
271
+ context.add_participant(instance)
272
+ if max_iterations == 0:
273
+ raise FixpointRecursionError(
274
+ f"fixpoint_cached_property '{self.attrname}': "
275
+ f"reentry detected with max_fixpoint_iterations=0",
276
+ incomplete_result=self._bottom(),
277
+ )
278
+ # Check the instance cache first, then fall back to saved
279
+ # approximations from the previous iteration.
280
+ approximation = cache.get(self.attrname, _FIXPOINT_SENTINEL)
281
+ if approximation is not _FIXPOINT_SENTINEL:
282
+ return approximation
283
+ saved = context.approximations.get(key, _FIXPOINT_SENTINEL)
284
+ if saved is not _FIXPOINT_SENTINEL:
285
+ return saved
286
+ return self._bottom()
287
+ else:
288
+ # Inside a fixpoint context but this is a fresh (instance, attr)
289
+ # pair — compute normally. Keep the key in ``computing`` only
290
+ # while ``self.func`` runs so that cycles through this key are
291
+ # detected by the ``elif`` branch above. Once computation
292
+ # finishes, remove the key so the fast-path cache check does
293
+ # not misidentify a later read of this cached value as reentry.
294
+ context.computing.add(key)
295
+ context.add_participant(instance)
296
+ result = self.func(instance)
297
+ context.computing.discard(key)
298
+ cache[self.attrname] = result
299
+ return result
300
+
301
+ def __set__(self, instance: object, value: object) -> None:
302
+ """Data descriptor setter to ensure __get__ is always called."""
303
+ instance.__dict__[self.attrname] = value
304
+
305
+
306
+ class _fixpoint_dependent_property:
307
+ """A cached_property that registers its instance as a fixpoint participant.
308
+
309
+ Behaves like ``functools.cached_property`` but, when computed inside an
310
+ active fixpoint context, registers the instance so that
311
+ ``clear_participant_caches`` will clear the cached value between
312
+ iterations. Without this, stale values computed from an incomplete
313
+ fixpoint approximation survive across iterations.
314
+ """
315
+
316
+ def __init__(self, func: Callable) -> None:
317
+ self.func = func
318
+ self.attrname = func.__name__
319
+ self.__doc__ = func.__doc__
320
+ _fixpoint_clearable_attrs.add(self.attrname)
321
+
322
+ def __set_name__(self, owner: type, name: str) -> None:
323
+ if not hasattr(self, "attrname"):
324
+ self.attrname = name
325
+ _fixpoint_clearable_attrs.add(self.attrname)
326
+
327
+ def __get__(self, instance: object, owner: type = None) -> object:
328
+ if instance is None:
329
+ return self
330
+
331
+ cache = instance.__dict__
332
+ value = cache.get(self.attrname)
333
+ if value is not None:
334
+ return value
335
+
336
+ if fixpoint_cached_property._get_max_iterations() > 0:
337
+ # Register as participant so clear_participant_caches can
338
+ # invalidate this cached value between fixpoint iterations.
339
+ context = _fixpoint_context_var.get()
340
+ if context is not None:
341
+ context.add_participant(instance)
342
+
343
+ value = self.func(instance)
344
+ cache[self.attrname] = value
345
+ return value
346
+
347
+
348
+ def fixpoint_dependent(func: Callable) -> _fixpoint_dependent_property:
349
+ """Mark a cached_property as dependent on fixpoint_cached_property values.
350
+
351
+ During fixpoint digest cycles, these caches are cleared between iterations
352
+ so they are recomputed with updated approximations.
353
+
354
+ Usage::
355
+
356
+ @fixpoint_dependent
357
+ @cached_property
358
+ def symbol_kind(self):
359
+ ...
360
+
361
+ Or equivalently::
362
+
363
+ @fixpoint_dependent
364
+ def symbol_kind(self):
365
+ ...
366
+ """
367
+ if isinstance(func, cached_property):
368
+ return _fixpoint_dependent_property(func.func)
369
+ else:
370
+ return _fixpoint_dependent_property(func)
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.4
2
+ Name: fixpoints
3
+ Version: 0.4.0.post85.dev0
4
+ Summary: Least-fixpoint cached-property infrastructure for mutual recursion
5
+ Project-URL: Repository, https://github.com/Atry/MIXINv2
6
+ Author-email: "Yang, Bo" <yang-bo@yang-bo.com>
7
+ License-Expression: MIT
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3.13
11
+ Classifier: Programming Language :: Python :: 3.14
12
+ Requires-Python: >=3.13
13
+ Description-Content-Type: text/markdown
14
+
15
+ # fixpoints
16
+
17
+ Least-fixpoint cached-property infrastructure for mutual recursion.
18
+
19
+ `fixpoints` provides `fixpoint_cached_property` and `fixpoint_dependent`, drop-in
20
+ replacements for `functools.cached_property` that resolve mutually recursive
21
+ computations by least-fixpoint iteration. When reentry (a cycle) is detected, the
22
+ outermost caller drives a digest loop that re-evaluates participants until their
23
+ values stabilize, starting from a configurable bottom value.
24
+
25
+ This package depends only on the Python standard library.
@@ -0,0 +1,5 @@
1
+ fixpoints/__init__.py,sha256=2nreqLFGKrCPU-j419uMx6SLdQLw4OaaJYRuPvKz4Sk,305
2
+ fixpoints/_core.py,sha256=TpHj1NHiXhb65jLGIXm0Er4rG0Ba6udEp3alBvRChqQ,14979
3
+ fixpoints-0.4.0.post85.dev0.dist-info/METADATA,sha256=kUGA9ylQqNndMhiLtzM3cLv0zFpZAjReOmaCa-vKt5M,1055
4
+ fixpoints-0.4.0.post85.dev0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
5
+ fixpoints-0.4.0.post85.dev0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any