Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 32 additions & 3 deletions autofit/mapper/prior_model/recursion.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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

Expand Down
113 changes: 113 additions & 0 deletions test_autofit/mapper/test_recursion.py
Original file line number Diff line number Diff line change
@@ -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


Expand Down Expand Up @@ -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
Loading