Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a look back constraint on spiral errors #1205

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## 41.5.0 [#1205](https://github.com/openfisca/openfisca-core/pull/1205)

#### New feature

- Add a look back constraint on spiral errors

### 41.4.2 [#1203](https://github.com/openfisca/openfisca-core/pull/1203)

#### Technical changes
Expand Down
20 changes: 8 additions & 12 deletions openfisca_core/simulations/simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ def __init__(

# controls the spirals detection; check for performance impact if > 1
self.max_spiral_loops: int = 1
self.max_spiral_lookback_months: int = 0
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What happens with days, weeks, years? Shouldn't we also cover for these? I'm still trying to grasp the desired behaviour in terms of the domain logic.


self.memory_config = None
self._data_storage_dir = None

Expand Down Expand Up @@ -400,8 +402,10 @@ def _check_for_cycle(self, variable: str, period):
raise errors.CycleError(
"Circular definition detected on formula {}@{}".format(variable, period)
)
spiral = len(previous_periods) >= self.max_spiral_loops
if spiral:

too_many_spirals = len(previous_periods) >= self.max_spiral_loops
Copy link
Member

@bonjourmauko bonjourmauko Mar 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

May I propose to give it another name and to extract it to a method? As it is a core domain rule that we're introducing here, it makes sense to me to be able to test it in isolation. Just an idea:

def spiral_loops_within_threshold(previous_periods: list[Period | str]) -> bool:
    return len(previous_periods) < self.max_spiral_loops

too_backward = (previous_periods[0].date - period.date).in_months() > self.max_spiral_lookback_months if previous_periods and self.max_spiral_lookback_months > 0 else False
Copy link
Member

@bonjourmauko bonjourmauko Mar 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand how this new domain rule relates to the previous one. Is it a specific check just for months that overrides the previous one? If it is, it makes all sense for me to allow contry package developers set thresholds for the period types that concern them independently (weeks, months, years...).

Beyond that, it would be great, as with the previous one, to extract it to a method to give it more visibility.

if too_many_spirals or too_backward:
self.invalidate_spiral_variables(variable)
message = "Quasicircular definition detected on formula {}@{} involving {}".format(
variable, period, self.tracer.stack
Expand All @@ -412,17 +416,9 @@ def invalidate_cache_entry(self, variable: str, period):
self.invalidated_caches.add(Cache(variable, period))

def invalidate_spiral_variables(self, variable: str):
# Visit the stack, from the bottom (most recent) up; we know that we'll find
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be great if you could instead update the documentation.

# the variable implicated in the spiral (max_spiral_loops+1) times; we keep the
# intermediate values computed (to avoid impacting performance) but we mark them
# for deletion from the cache once the calculation ends.
count = 0
for frame in reversed(self.tracer.stack):
first_variable_occurrence = next(index for (index, frame) in enumerate(self.tracer.stack) if frame["name"] == variable)
for frame in self.tracer.stack[first_variable_occurrence:]:
Copy link
Member

@bonjourmauko bonjourmauko Mar 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't quite get what this line changes compared to the previous one. Is it just a refactoring or the underlying logic is changed as well? (As this is already tested, I presume there is no change in logic here specifically. However, as you introduce a new constraint a couple of lines above, I'm not 100% sure).

self.invalidate_cache_entry(str(frame["name"]), frame["period"])
if frame["name"] == variable:
count += 1
if count > self.max_spiral_loops:
break

# ----- Methods to access stored values ----- #

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@

setup(
name="OpenFisca-Core",
version="41.4.2",
version="41.5.0",
author="OpenFisca Team",
author_email="[email protected]",
classifiers=[
Expand Down
16 changes: 11 additions & 5 deletions tests/core/test_tracers.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from openfisca_country_template.variables.housing import HousingOccupancyStatus

from openfisca_core.simulations import CycleError, Simulation, SpiralError
from openfisca_core.periods import period
from openfisca_core.tracers import (
FullTracer,
SimpleTracer,
Expand All @@ -28,13 +29,15 @@ class StubSimulation(Simulation):
def __init__(self):
self.exception = None
self.max_spiral_loops = 1
self.max_spiral_lookback_months = 0
self.invalidated_cache_items = []

def _calculate(self, variable, period):
if self.exception:
raise self.exception

def invalidate_cache_entry(self, variable, period):
pass
self.invalidated_cache_items.append((variable, period))

def purge_cache_of_invalid_values(self):
pass
Expand Down Expand Up @@ -120,12 +123,15 @@ def test_cycle_error(tracer):
def test_spiral_error(tracer):
simulation = StubSimulation()
simulation.tracer = tracer
tracer.record_calculation_start("a", 2017)
tracer.record_calculation_start("a", 2016)
tracer.record_calculation_start("a", 2015)
tracer.record_calculation_start("a", period(2017))
tracer.record_calculation_start("b", period(2016))
tracer.record_calculation_start("a", period(2016))

with raises(SpiralError):
simulation._check_for_cycle("a", 2015)
simulation._check_for_cycle("a", period(2016))

assert len(simulation.invalidated_cache_items) == 3
assert len(tracer.stack) == 3


def test_full_tracer_one_calculation(tracer):
Expand Down
Loading