From e27eb8cbb62fea1ebea3cc22780f6aabf8b6edf1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Sep 2026 14:18:29 +0000 Subject: [PATCH] recursion: skip the promise-replacement walk when no promise escaped `DynamicRecursionCache` hands out a `RecursionPromise` for the duration of a decorated call and then calls `replace_promise` unconditionally, which recursively `setattr`s its way through every object reachable from the result looking for that promise. The only way to obtain the promise is a cache hit in the wrapper, so when the graph being walked is not cyclic no object can hold one and the traversal is provably a no-op -- paid once per decorated call, over a graph that grows with the model, by both decorated functions (`path_instances_of_class`, `AbstractPriorModel.from_instance`). `RecursionPromise` now records whether it ever escaped and the wrapper walks only when it did. `__slots__` earns its place twice: it keeps the flag off the instance `__dict__`, and it makes `replace_promise` take its `AttributeError` branch immediately on a promise that *is* live. Measured on `autolens_workspace scripts/multi_galaxy/features/advanced/shapelets/modeling.py` under the smoke profile, warm second run: 10.58 s -> 6.73 s, with the script's whole stdout -- `print(model.info)` included -- byte-identical. `print(model.info)` appears in nearly every modeling script in every workspace. The regression tests compare the two implementations against each other rather than against a stored string: a fixture restores the unconditional behaviour, and `model.info` and the object graph must come back identical on both a genuinely self-referential model (the case the cache exists for, where the traversal must still run) and a flat one (where a counting fixture pins that it does not). Refs PyAutoLabs/PyAutoFit#1563 Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_0151gQm9fk3XGLi5f18Urdba --- autofit/mapper/prior_model/recursion.py | 35 +++++++- test_autofit/mapper/test_recursion.py | 113 ++++++++++++++++++++++++ 2 files changed, 145 insertions(+), 3 deletions(-) diff --git a/autofit/mapper/prior_model/recursion.py b/autofit/mapper/prior_model/recursion.py index 62a44f2d2..52082ad13 100644 --- a/autofit/mapper/prior_model/recursion.py +++ b/autofit/mapper/prior_model/recursion.py @@ -2,7 +2,28 @@ class RecursionPromise: - pass + """ + A placeholder standing in for an object that is still being computed. + + ``used`` records whether this placeholder was ever handed back to a caller. + The only way to obtain one is a cache hit in + :meth:`DynamicRecursionCache.__call__`'s wrapper, which sets the flag, so a + promise with ``used is False`` was never seen by any code outside the + wrapper that created it. No object in the result can then hold a reference + to it, and the ``replace_promise`` traversal below is provably a no-op -- + one that still walks (and ``setattr``s its way through) every object + reachable from the result, over a graph that grows with the model. + + ``__slots__`` is load-bearing twice over: it keeps the flag off the + instance ``__dict__``, and it means ``replace_promise`` takes its + ``AttributeError`` branch immediately on a promise that *is* live rather + than iterating a dict of its own. + """ + + __slots__ = ("used",) + + def __init__(self): + self.used = False def replace_promise(promise: RecursionPromise, obj, true_value, seen_objects=None): @@ -77,11 +98,19 @@ def wrapper(item, *args, **kwargs): item_id = id(item) if item_id in self.cache: - return self.cache[item_id] + recursion_promise = self.cache[item_id] + # The promise escapes here and only here, so this is the one + # place that can put it inside the result being built. + recursion_promise.used = True + return recursion_promise + recursion_promise = RecursionPromise() self.cache[item_id] = recursion_promise result = func(item, *args, **kwargs) - result = replace_promise(recursion_promise, result, result) + + if recursion_promise.used: + result = replace_promise(recursion_promise, result, result) + del self.cache[item_id] return result diff --git a/test_autofit/mapper/test_recursion.py b/test_autofit/mapper/test_recursion.py index ef7bb9518..6a931fa14 100644 --- a/test_autofit/mapper/test_recursion.py +++ b/test_autofit/mapper/test_recursion.py @@ -1,3 +1,8 @@ +import pytest + +import autofit as af +from autofit.example.model import Gaussian +from autofit.mapper.prior_model import recursion from autofit.mapper.prior_model.recursion import DynamicRecursionCache @@ -44,3 +49,111 @@ def test_sub_recursion(): result = dict_recurse(a) assert isinstance(result, Wrapper) + + +@DynamicRecursionCache() +def count_recurse(item): + """ + A decorated function whose result cannot contain a promise unless the graph + it is walking is genuinely cyclic -- the shape of `path_instances_of_class` + and `AbstractPriorModel.from_instance`, the two decorated functions in the + library. + """ + children = [] + + for value in getattr(item, "__dict__", {}).values(): + if isinstance(value, (A, B)): + children.append(count_recurse(value)) + + return children + + +@pytest.fixture(name="replace_promise_calls") +def make_replace_promise_calls(monkeypatch): + """ + Counts the `replace_promise` traversals the recursion cache performs, so a + test can assert the traversal is *skipped*, not merely that its result is + unchanged. + """ + calls = [] + original = recursion.replace_promise + + def counting_replace_promise(promise, obj, true_value, seen_objects=None): + calls.append(promise) + return original(promise, obj, true_value, seen_objects=seen_objects) + + monkeypatch.setattr(recursion, "replace_promise", counting_replace_promise) + + return calls + + +@pytest.fixture(name="force_traversal") +def make_force_traversal(monkeypatch): + """ + Restores the unconditional behaviour -- every promise reports itself as + used, so `replace_promise` runs on every decorated call as it did before + the `used` flag existed. The regression tests compare against this rather + than against a stored string, so they keep testing the two implementations + against each other rather than a snapshot. + """ + + def force_used(self): + self.used = True + + def _force(): + monkeypatch.setattr(recursion.RecursionPromise, "__init__", force_used) + + return _force + + +def test_promise_not_used_when_graph_is_flat(replace_promise_calls): + a = A(B()) + + assert count_recurse(a) == [[]] + assert replace_promise_calls == [] + + +def test_promise_used_when_graph_is_cyclic(replace_promise_calls): + a = A(B()) + a.b.a = a + + count_recurse(a) + + assert len(replace_promise_calls) > 0 + + +def test_flat_model_info_unchanged_and_traversal_skipped( + replace_promise_calls, force_traversal +): + model = af.Model(Gaussian) + + info = model.info + + assert replace_promise_calls == [] + + force_traversal() + + assert model.info == info + + +def test_self_referential_model_info_and_graph_unchanged( + replace_promise_calls, force_traversal +): + gaussian = af.Model(Gaussian) + model = af.Collection(gaussian=gaussian) + model.self_ref = model + + info = model.info + + # The case the cache exists for: the promise escapes, so the traversal must + # still run. + assert len(replace_promise_calls) > 0 + assert model.self_ref is model + assert model.gaussian is gaussian + assert model.prior_count == 3 + + force_traversal() + + assert model.info == info + assert model.self_ref is model + assert model.gaussian is gaussian