mesa icon indicating copy to clipboard operation
mesa copied to clipboard

ContinuousState re-enters initialization through Threshold binding and registers duplicate rate observers

Open priyanshux-dev opened this issue 2 weeks ago • 1 comments

Describe the bug

In mesa/experimental/states/state.py, ContinuousState._get_state() binds declarative Threshold instances before it initializes and installs the instance’s backing state dictionary.

This initialization order allows _get_state() to be entered re-entrantly:

  1. The outer _get_state() call sees that _energy_continuous_state does not exist.
  2. It starts binding the declarative thresholds.
  3. Threshold.bind() calls recalculate().
  4. recalculate() calls _get_state() again.
  5. The re-entrant call initializes the state dictionary and registers the callable-rate observer.
  6. Control returns to the outer call, which initializes the state dictionary again and registers the same observer a second time.

This can overwrite the first initialized state dictionary and leave duplicate rate-observer entries in agent.subscribers.

Related issue: https://github.com/mesa/mesa/issues/3987

Related open PR: https://github.com/mesa/mesa/pull/4000

Expected Behavior

ContinuousState._get_state() should initialize and install all of the following before binding declarative thresholds:

  • The backing state dictionary.
  • The callable-rate ComputedState.
  • The rate CHANGED observer.

Once initialized, threshold binding should read the existing state rather than entering _get_state() re-entrantly.

To Reproduce

from mesa import Agent, Model
from mesa.experimental.mesa_signals import (
    HasEmitters,
    Observable,
    ObservableSignals,
)
from mesa.experimental.states import ContinuousState, Threshold


class DynamicAgent(Agent, HasEmitters):
    drain_factor = Observable(fallback_value=1.0)
    energy = ContinuousState(
        fallback_value=100.0,
        rate=lambda agent: -agent.drain_factor,
    )
    low_energy = Threshold(
        state=energy,
        limit=20.0,
        callback="on_low_energy",
        direction="falling",
    )

    def __init__(self, model: Model) -> None:
        super().__init__(model)
        self.drain_factor = 1.0
        self.energy = 100.0
        self.triggered = False

    def on_low_energy(self) -> None:
        self.triggered = True


model = Model(rng=42)
agent = DynamicAgent(model)

subscribers = agent.subscribers[
    ("energy_rate", ObservableSignals.CHANGED)
]

print(len(subscribers))
# Before fix: 2
# After fix: 1

model.run_until(100.0)
print(agent.triggered)
# True

Additional Context

Affected code:

  • ContinuousState._get_state() in mesa/experimental/states/state.py
  • Threshold.bind() in mesa/experimental/states/state.py

The practical impact is that first access can overwrite the initialized state dictionary and register duplicate callable-rate observer entries.

A possible fix is to move the declarative threshold-binding loop to the end of ContinuousState._get_state(), after:

  • The backing dictionary is installed.
  • The ComputedState is created.
  • The rate CHANGED observer is registered.

This report is related to #3987, because both involve threshold declarations interacting with ContinuousState initialization. However, this report specifically demonstrates re-entrant initialization and duplicate observer registrations. PR #4000 addresses rate anchoring rather than the threshold-binding initialization order, so it appears not to cover this case.

priyanshux-dev avatar Nov 18 '26 14:11 priyanshux-dev

Discovery update:

  • I found this issue during a static review of mesa/experimental/states/state.py, so I did not discover it by observing a runtime failure in a model.

  • I verified the behavior with the reproducer above. It confirms that the first access can initialize the backing state dictionary twice and register two entries for the "energy_rate" CHANGED observer. PR #4140 verifies that, after the fix, the state is reused and only one observer is registered.

  • I have not seen this produce incorrect energy values or callback times in my testing, so I am treating duplicate initialization and observer registration as the confirmed impact for now.

priyanshux-dev avatar Nov 19 '26 03:11 priyanshux-dev