mesa icon indicating copy to clipboard operation
mesa copied to clipboard

Experimental `ContinuousState` descriptor for state handling

Open codebreaker32 opened this issue 5 months ago • 9 comments

This PR introduces an experimental Entity-Component-System (ECS) backend for modeling continuously evolving agent properties using a columnar NumPy architecture.

Architecture

  • StateTensor: Provides vectorized NumPy arrays to track values, rates, limits, and projections for ContinuousState attributes across all agents. Eager thresholds receive dedicated rows; lazy thresholds are evaluated on-read.

  • ContinuousScheduler: A priority-based scheduler that maintains a single master event pointed at the earliest projected crossing time across the entire tensor, re-targeting dynamically as writes occur.

  • ContinuousState: Descriptor for an agent attribute that evolves continuously. Extrapolates state based on elapsed model time and rate. Eager thresholds are projected and managed by the scheduler. Lazy thresholds are evaluated on read.

  • Threshold: A trigger condition attached to a ContinuousState attribute.

Notes

  • Sugarscape: Refactored the example to utilize ContinuousState for sugar and spice metabolism.

codebreaker32 avatar Jun 21 '26 08:06 codebreaker32

Some architectural challenges that I faced worth noting while reaching to this implementation are

Priority Queue Tombstone Bloat Discrete event scheduling uses a priority queue (heapq) to predict future threshold crossings. In highly volatile models where agent trajectories change constantly (e.g., rapid trading), continuous states must repeatedly schedule new events and cancel old ones. Because Python's heapq does not structurally delete canceled nodes but merely flags them as "tombstones," the scheduler rapidly accumulates hundreds of thousands of dead events, completely bottlenecking performance during heap traversal.

Execution Order vs. Continuous Decay Continuous math calculates resource decay or execute threshold callbacks between discrete steps, but agents execute sequentially. This creates a window where an active agent might attempt an interaction with a neighbor whose resources have mathematically dropped below zero, but who hasn't yet taken its turn to remove itself(if we rely on Threshold for agent deletion). This causes mathematical crashes (like negative fractional powers) unless preemptive flags or strict boundary checks are used.

Stale Object References Spatial queries return a static snapshot of surrounding agents. If a continuous threshold instantly deletes an agent mid-step(which only happens if you have explicitly performed a write operation on a ContinuousState and if it meets the Threshold criteria, callback will be executed immediately) , its Python reference still persists in the local arrays already queried by other active agents. Attempting to access attributes on these suddenly deleted objects causes missing attribute errors. One thing to note is if the given state crosses the threshold through its own decay then callback will be executed between two discrete steps

codebreaker32 avatar Jun 21 '26 09:06 codebreaker32

Please see https://github.com/mesa/mesa/discussions/3721#discussioncomment-17361534 also

codebreaker32 avatar Jun 21 '26 09:06 codebreaker32

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔴 +9.9% [+9.5%, +10.4%] 🔵 -1.7% [-1.9%, -1.4%]
BoltzmannWealth large 🔵 -2.6% [-3.6%, -1.8%] 🟢 -9.7% [-12.2%, -7.0%]
Schelling small 🔵 +0.5% [-0.0%, +0.9%] 🔵 +2.2% [+1.4%, +2.9%]
Schelling large 🔵 -0.1% [-0.7%, +0.4%] 🔵 -2.9% [-4.9%, -1.0%]
WolfSheep small 🔵 +1.7% [+1.1%, +2.2%] 🔵 +1.5% [-3.1%, +6.7%]
WolfSheep large 🔵 -2.1% [-4.3%, +0.1%] 🔵 -1.4% [-4.3%, +1.5%]
SugarscapeG1mt small 🔴 +42.0% [+41.1%, +42.9%] 🔴 +114.9% [+110.8%, +119.1%]
SugarscapeG1mt large 🔴 +89.2% [+87.7%, +90.6%] 🔴 +200.5% [+193.4%, +206.8%]
BoidFlockers small 🔴 +7.0% [+6.3%, +7.7%] 🔵 -0.1% [-0.3%, +0.2%]
BoidFlockers large 🔴 +5.4% [+5.0%, +5.9%] 🔵 +0.5% [+0.3%, +0.7%]

github-actions[bot] avatar Jun 21 '26 09:06 github-actions[bot]

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 +2.1% [+1.6%, +2.5%] 🟢 -13.9% [-14.0%, -13.8%]
BoltzmannWealth large 🟢 -16.0% [-16.5%, -15.4%] 🟢 -14.8% [-15.3%, -14.5%]
Schelling small 🟢 -11.4% [-11.7%, -11.0%] 🟢 -10.6% [-11.3%, -9.9%]
Schelling large 🟢 -9.3% [-10.1%, -8.6%] 🟢 -17.2% [-18.3%, -15.9%]
WolfSheep small 🟢 -8.1% [-8.4%, -7.8%] 🔵 -6.7% [-10.5%, -2.5%]
WolfSheep large 🟢 -10.5% [-11.0%, -10.2%] 🟢 -8.3% [-9.3%, -7.3%]
SugarscapeG1mt small 🔴 +17.2% [+16.9%, +17.6%] 🔴 +107.7% [+103.0%, +112.2%]
SugarscapeG1mt large 🔴 +44.9% [+43.5%, +46.3%] 🔴 +285.0% [+275.9%, +293.9%]
BoidFlockers small 🔴 +6.9% [+6.6%, +7.2%] 🔵 -0.9% [-1.2%, -0.5%]
BoidFlockers large 🔴 +3.8% [+3.4%, +4.2%] 🔵 -0.7% [-1.0%, -0.4%]

github-actions[bot] avatar Jun 21 '26 10:06 github-actions[bot]

Cool! Will try to dive in tomorrow or Tuesday.

EwoutH avatar Jun 21 '26 18:06 EwoutH

Columnar Memory Layout The StateTensor centralizes all continuous values, rates, limits, and projections into 1D NumPy arrays.

# L26-30
self.values = np.zeros(capacity, dtype=np.float64)
self.rates = np.zeros(capacity, dtype=np.float64)
self.last_update_times = np.zeros(capacity, dtype=np.float64)
self.limits = np.full(capacity, np.inf, dtype=np.float64)
self.projected_times = np.full(capacity, np.inf, dtype=np.float64)

To eliminate the severe performance penalty of resizing arrays mid-simulation, the tensor pre-allocates these arrays to a fixed capacity upfront (size=10_000) and manages active rows via a free_indices stack.

# L26
def __init__(self, capacity: int = 10_000) -> None:

# L49
# O(1) allocation stack
self.free_indices = list(range(capacity - 1, -1, -1))


The Projection Engine The projection mathematics are strictly vectorized, enabling the engine to calculate precise threshold intersection times for thousands of active agents simultaneously. The calculate_projections method utilizes bulk array division ((l - v) / r) wrapped in a NumPy error-state context manager (np.errstate(divide="ignore", invalid="ignore")) to safely process zero-rate trajectories.

# Lines 129-130
with np.errstate(divide="ignore", invalid="ignore"):
    delta_t = (l - v) / r

Once the raw time-deltas are computed, the engine applies an invalid_mask to filter out mathematically impossible trajectories, such as an agent assigned a rising threshold direction but possessing a negative or flat rate of change. These invalid projections are explicitly overwritten with np.inf to cleanly remove them from the scheduler's horizon.

# Lines 143-145
invalid_mask = np.isnan(delta_t) | (~active)
invalid_mask |= (d == DIR_RISING) & (r <= 0)
invalid_mask |= (d == DIR_FALLING) & (r >= 0)

# L150
projected[invalid_mask] = np.inf

Beyond raw projection, the implementation relies heavily on an already_past fallback net to catch critical state-change edge cases. When a modeler explicitly assigns a discrete value to an agent that instantly places it beyond its defined mathematical limit, standard intersection math would calculate a negative time-delta, incorrectly placing the crossing event in the past. The fallback net detects these specific directional breaches and aggressively forces their time-delta to 0.0.

# L132-135

# Flags agents already mathematically past their threshold bounds
already_past = (d == DIR_FALLING) & (v <= l)
already_past |= (d == DIR_RISING) & (v >= l)
already_past |= (d == DIR_BOTH) & ((v <= l) | (v >= l))

delta_t[already_past] = 0.0

A bitwise guard (invalid_mask &= ~already_past) ensures these immediate triggers are not accidentally suppressed by the broader trajectory filters, guaranteeing the scheduler executes the threshold callback right away.

# L148
invalid_mask &= ~already_past

For targeted writes, this bulk array logic is mirrored by update_single_projection, which isolates these identical directional and mathematical checks to a single tensor row, allowing the engine to instantaneously re-queue a specific agent without recalculating the entire grid.

def update_single_projection(self, idx: int, current_time: float) -> None:
    ...
    # The Single-Row Fallback
    if (
        (d == DIR_FALLING and val <= limit)
        or (d == DIR_RISING and val >= limit)
        or (d == DIR_BOTH and (val <= limit or val >= limit))
    ):
        self.projected_times[idx] = current_time
        return


Eager vs. Lazy Reactivity (Interrupts vs. Polling) Reactivity is bifurcated into two distinct evaluation modes - eager and lazy. Eager thresholds act like hardware interrupts and are evaluated strictly on write. When an attribute changes trajectory, the engine immediately calculates the exact future hit time and forces the scheduler to retarget its master event.

# Inside ContinuousState.__set__
if self._has_thresholds:
    tensor.update_single_projection(idx, instance.model.time)
    instance.model.continuous_scheduler.check_and_reschedule(
        tensor.projected_times[idx]
    )

Conversely, lazy thresholds operate via polling and are evaluated strictly on read. Writes bypass the scheduler entirely, and the descriptor mathematically extrapolates the current value on the fly, checking if a crossing occurred since the last cached read to prevent spamming the queue with false-positive projections.

Inside ContinuousState.__get__
if self.lazy_thresholds:
    # Prevents trigger spam by requiring an actual crossing between reads
    last_read_attr = self._lazy_cache_attr + "_last_val"
    old_val = getattr(instance, last_read_attr, base_val)

    lazy_list = getattr(instance, self._lazy_cache_attr, self.lazy_thresholds)
    for t in lazy_list:
        if self._check_triggered(t, old_val, current_val):
            ...


Deferred Execution Finally, the engine implements deferred execution to guarantee reentrancy safety and prevent mid-step simulation crashes. Triggering callbacks at the exact moment a variable is read introduces the risk of mutating the state tensor while the simulation is actively iterating over it. When a lazy threshold detects a crossing during a read operation, it does not fire the callback synchronously inline. Instead, it flags the agent and appends the callback to a queue, scheduling a micro-step event with a minute delay to flush the batch.

# Inside ContinuousState.__get__
if not getattr(instance, t._queued_flag, False):
    setattr(instance, t._queued_flag, True)
    tensor.deferred_callbacks.append(
        (instance, t.callback, t._queued_flag)
    )
    if not tensor._flush_scheduled:
        tensor._flush_scheduled = True
        instance.model.schedule_event(
            tensor.process_deferred_callbacks, after=1e-9
        )

codebreaker32 avatar Jun 23 '26 18:06 codebreaker32

Thanks for this PR. You're trying to solve a real problem in Mesa, and the architectural notes in your description show careful thinking. The eager/lazy insight in particular is useful. That said, I think the implementation can be significantly simplified by building on what Mesa 3.5 already provides, and I'd like to suggest an alternative direction before this moves forward.

The core need Stripped to its essence, what we want is: some agent attributes evolve continuously, and we want something to happen when they cross a threshold. That's two distinct problems:

  1. Extrapolating the current value from a stored baseline, rate, and elapsed time (generally simple math)
  2. Firing a callback at the exact moment a threshold is crossed (largely already solved by schedule_event)

What Mesa 3.5 already gives us The event scheduling API in 3.5 can already express this directly:

model.schedule_event(self.die, at=current_time + self.sugar / self.metabolism)

That's essentially what ContinuousState is computing internally. The missing piece is ergonomics, having to compute and manage that crossing time manually every time is boilerplate worth abstracting. But the abstraction should sit on top of the existing event system, not alongside it.

Similarly, mesa_signals already has everything needed for reactive dependency tracking: Observable, HasEmitters, observe(), and crucially CURRENT_COMPUTED + ComputedState for automatic dependency discovery. When a callable rate function is evaluated inside a CURRENT_COMPUTED context, any Observable it touches is automatically registered as a dependency, exactly what's needed to reschedule when metabolism_sugar changes.

The problem with the current approach

The PR introduces a parallel execution engine: StateTensor, ContinuousScheduler, eager/lazy modes, a deferred callback queue, and JIT registration via metaclass patching of __init__. Each of those exists to solve a real problem, but together they create a second runtime running alongside Mesa's existing one. This has several costs:

  • Every Model now allocates a StateTensor of 10,000 rows regardless of whether it uses ContinuousState at all
  • Models with more than 10,000 agents will hit a MemoryError at runtime
  • The reentrancy hazard around eager thresholds means users must use flags rather than calling agent.remove() directly in a callback
  • The Sugarscape refactor in the diff ends up more complex than the original, not less

What I think we should be built instead A ContinuousState descriptor that does three things and nothing else:

  1. Extrapolates value on read from stored value, rate, and last update time
  2. On write, snapshots the current value, evaluates the (possibly callable) rate, and reschedules the threshold event via schedule_event
  3. Uses CURRENT_COMPUTED and ComputedState from mesa_signals to automatically discover which Observable attributes the rate function depends on, subscribing to ObservableSignals.CHANGED on each so that rate changes trigger automatic rescheduling

This covers the piecewise-constant-rate case, which is the vast majority of ABM use cases: metabolism, resource decay, disease progression. Rates generally change at discrete events (eating, trading, moving), not continuously. Except if you have continuous rates depending on other continuous rates, but let's not get into that rabbit hole (okay not now at least, at some point we might want to do step-level approximation or something).

Between those events the trajectory is a straight line, the crossing time is analytically exact, and schedule_event handles the rest.

The case this deliberately doesn't cover is rates that depend on other ContinuousState attributes (coupled ODEs). That's a genuinely hard problem requiring numerical integration, and it's out of scope for Mesa. If someone needs it, they're better served integrating scipy.solve_ivp directly.

Suggested direction The goal of Mesa is to provide uses with a set of building blocks to help start building ABMs. Building blocks should serve a relatively large group of users, with reasonable complexity (to keep it maintainable). I feel like this PR doesn't hit that balance.

So we basically want to try to catch 80% of the use-cases with 20% of the complexity/code. The easiest way to do that is by building on to the current event/signals code already in place.

EwoutH avatar Jun 24 '26 10:06 EwoutH

@quaquel also curious what you think.

EwoutH avatar Jun 24 '26 10:06 EwoutH

I appreciate all the work and thought that has gone into this PR. However, I also have some reservations.

I like the seperation between threshold and the evolving state. I also appreciate the use of a descriptor for the state. Together this nicely encapsulates the relevant behavior.

I am less sure about the tensor. The impression I have, but please correct me if I am wrong, is that you went down this route because of the poor performance on sugarscape. However, I am not sure whether sugarscape is the most appropriate model to test this kind of mechanism with.

As indicated in the conceptual discussion, I see a lot of potential for this approach in more discrete event style simulations. For example, imagine simulating trams or train. Here the acceleration and braking could nicely be expressed using continuous state and thresholds. Since the frequency of event cancelation is small, you don't get the bloat problem. And so, there is no need for the added complexity of the tensor stuff.

In contrast, in sugarscape, every trade invalidates the set thresholds. Since there are many trades each time step, event cancelation explodes.

quaquel avatar Jun 24 '26 17:06 quaquel