Skip to content

Emit list snapshots in unbatched ObservableList SET signals - #3988

Merged
quaquel merged 2 commits into
mesa:mainfrom
ska2704:fix-observable-list-set-payload
Nov 23, 2026
Merged

quaquel merged 2 commits into
mesa:mainfrom
ska2704:fix-observable-list-set-payload

Conversation

@ska2704

@ska2704 ska2704 commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

Pre-PR Checklist

  • This PR is a bug fix, not a new feature or enhancement.

Summary

Assigning to an ObservableList outside of batch() emits a SET signal whose payload can be wrong or unsafe to keep. This makes both old and new plain list snapshots, which is what the batched SET already sends.

Bug / Issue

Fixes #3907

This picks up #3908, which was closed as stale, and includes the old follow-up mentioned in its review.

Outside a batch, ObservableList.__set__ passes the raw assigned object as new and whatever was stored before as old. That causes three problems:

  1. new for a generator has already been consumed by SignalingList, so handlers see an empty iterator.
  2. old is the replaced SignalingList. It still has the owner and name, so a handler that keeps and mutates it emits APPENDED/REPLACED/etc. on the owner even though the attribute now holds a different list.
  3. On the first assignment, old is the descriptor's fallback_value, one [] shared by every instance of the class. If a handler mutates it, later first assignments on other instances report that content as old.
from mesa.experimental.mesa_signals import HasEmitters, ListSignals, ObservableList

class A(HasEmitters):
    items = ObservableList()

received = []
def handler(message):
    received.append(message)

a, b = A(), A()
a.observe("items", ListSignals.SET, handler)
b.observe("items", ListSignals.SET, handler)

a.items = [1]
received[-1].additional_kwargs["old"].append("leak")
b.items = [5]
print(received[-1].additional_kwargs["old"])   # ['leak'] on main, [] here

a.items = (x * 2 for x in range(3))
print(list(received[-1].additional_kwargs["new"]))  # [] on main, [0, 2, 4] here

Implementation

In ObservableList.__set__ (mesa/experimental/mesa_signals/observable_collections.py):

  • The new SignalingList is built and stored first, then new=list(new_list.data) is emitted.
  • old is list(old_list.data), or [] when nothing was assigned before. The fallback list is no longer read here.
  • The same old snapshot is what gets captured into the batch context, so the batched and unbatched paths now agree on both values.
  • Snapshots copy .data directly. list(signaling_list) goes through the MutableSequence iterator, which calls __getitem__ once per item in Python and was roughly 20x slower for a 1000 item list.
  • If the assignment is not batched and nothing observes SET, the method returns right after storing the list, so assignments without listeners do no extra copying. BaseObservable.__set__ already does the same check.

Testing

  • test_observable_list_set_payload_is_snapshot, parametrized over batched and unbatched assignment: assigning a generator emits old=[1, 2], new=[0, 2, 4] in both cases, and appending to the stored list afterwards does not change the delivered new. On main the unbatched case fails because new is the generator.
  • test_observable_list_set_old_payload_is_detached: the first old is an empty list that is not shared between instances, and mutating a later old emits nothing on the owner. On main this fails with assert ['stale'] == [].
  • pytest tests/ -Werror -Wdefault::PendingDeprecationWarning: 936 passed (Python 3.12, macOS).
  • pytest --doctest-modules mesa/experimental/mesa_signals: passed.
  • ruff check mesa tests and ruff format --check on the changed files: clean.

Rough timing for a.items = list(range(1000)) with timeit: about 1.8 µs with no subscriber both before and after. With a SET subscriber it is 2.9 µs on main and 6.3 µs here, which is the cost of the two copies.

Additional Notes

new is now always a list. Before, a tuple or set assigned outside a batch was forwarded as is. Handlers that only read the values are not affected, and the batched signal already worked this way.

Assigning to an ObservableList outside of batch() sent the raw assigned
object as `new` and the replaced SignalingList (or the descriptor's
shared fallback list on first assignment) as `old`. A generator arrived
already consumed, mutating `old` still emitted signals on the owner,
and mutating the first `old` changed the fallback seen by every other
instance.

Both payloads are now plain list snapshots, matching what the batched
SET aggregation already emits. The snapshots are only built when the
assignment is batched or has SET subscribers.

Fixes mesa#3907
@github-actions github-actions Bot added experimental Release notes label testing Release notes label labels Oct 26, 2026
@mesa-triage-bot

Copy link
Copy Markdown

Thanks @ska2704 for picking up #3908 and covering both payloads. I reproduced the exhausted generator and shared old payload on current main. The failing examples check is stale: its October 26 log reports a missing mesa.meta_agents import, and the check now passes on main.

Before review:

  1. Please rebase onto main so CI reruns against the current examples.
  2. Please describe the model or subscriber workflow affected by ObservableList SET signal passes an exhausted generator as new when assigned a generator #3907, so reviewers can understand the practical impact alongside the minimal reproducer.

Automated note by an AI model; it can be wrong, and maintainers make the decisions. About this bot.

@quaquel
quaquel merged commit 8b4584a into mesa:main Nov 23, 2026
14 of 15 checks passed
quaquel added a commit to quaquel/mesa that referenced this pull request Nov 23, 2026
ObservableList no longer uses fallback_value as the old value of its
first assignment (mesa#3988), so the BaseObservable docstring now uses
ContinuousState, which uses it as its initial value, as the example.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RbrUQUQAArrpH7rYQFt6KW
quaquel added a commit that referenced this pull request Nov 25, 2026
* Document mesa_signals and add it to the API reference

- Add a Signals section to the experimental API reference, listing the
  public API in reading order with a short introduction.
- Observable: document that it signals on assignment only (changes made
  in place to a mutable value are not observed), that changes are
  detected with !=, how to set an initial value, and what subscribers
  receive; add an example.
- HasEmitters, observe, observe_class: document that handlers are held
  by weak reference, so a lambda or local function is silently dropped
  unless kept alive elsewhere; document the accepted names and signal
  types, including ALL.
- Message: document its fields.
- computed_property: document lazy recomputation, the CHANGED signal on
  invalidation (with only old), and the cyclical dependency error.
- BaseObservable: describe what an Observable is and fallback_value.
- Run the doctests in core.py as part of the test suite.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RbrUQUQAArrpH7rYQFt6KW

* Update fallback_value example after #3988

ObservableList no longer uses fallback_value as the old value of its
first assignment (#3988), so the BaseObservable docstring now uses
ContinuousState, which uses it as its initial value, as the example.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RbrUQUQAArrpH7rYQFt6KW

* Document what happens to subscriptions on copy and pickle

Since #4056, subscriptions survive deepcopy and pickle as far as their
handlers come along. Document this in the HasEmitters docstring, which
the API reference renders, including that a bound method stays
subscribed only if its object is copied along with the emitter.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RbrUQUQAArrpH7rYQFt6KW

* Document Observable fallback_value

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
EwoutH pushed a commit that referenced this pull request Nov 26, 2026
Assigning to an ObservableList outside of batch() sent the raw assigned
object as `new` and the replaced SignalingList (or the descriptor's
shared fallback list on first assignment) as `old`. A generator arrived
already consumed, mutating `old` still emitted signals on the owner,
and mutating the first `old` changed the fallback seen by every other
instance.

Both payloads are now plain list snapshots, matching what the batched
SET aggregation already emits. The snapshots are only built when the
assignment is batched or has SET subscribers.

Fixes #3907

Co-authored-by: Jan Kwakkel <[email protected]>

Adapted for 3.5.x: the fix applies unchanged. The tests use 3.5's HasObservables instead of HasEmitters and are placed before test_observable_list_mutation, since the batched reverse-slice tests they follow on main are not in 3.5.

(cherry picked from commit 8b4584a)

Assisted-by: Claude Opus 5.5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

experimental Release notes label testing Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ObservableList SET signal passes an exhausted generator as new when assigned a generator

2 participants