Skip to content

Keep subscribers when a HasEmitters object is deep-copied or pickled - #4056

Merged
quaquel merged 10 commits into
mesa:mainfrom
dietcoke-17:HasEmitters
Nov 23, 2026
Merged

quaquel merged 10 commits into
mesa:mainfrom
dietcoke-17:HasEmitters

Conversation

@dietcoke-17

Copy link
Copy Markdown
Contributor

Part of #4023 (weak references are not rebuilt after a copy).

HasEmitters stores subscribers as weak references, which can be neither pickled nor deep-copied. Any model with a subscriber, e.g. one with a DataRecorder, failed with TypeError: cannot pickle 'WeakMethod' object. This affected BoltzmannWealth, MultiLevelAllianceModel and TransitSystem.

Changes

  • __getstate__ swaps live subscribers for strong references to their handlers and drops dead ones; __setstate__ rebuilds the weak references.
  • Unit tests for deepcopy and pickle, with and without __slots__.
  • A behavioural test: deep-copy the alliance model, step both, compare agents and RNG state.

Notes

  • Independent of Fix GridCell serialization and property-layer memory retention #4025; this does not touch grids or cells.
  • Handlers that are closures are shared by deepcopy, so they still point at the original. Threshold.bind and ContinuousState use closures, so a deep-copied TransitSystem no longer crashes, but its tram handlers still drive the original tram. This needs a follow-up (bound methods instead of closures).

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-09T12:53:22.635104Z e572ecf PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions github-actions Bot added experimental Release notes label testing Release notes label labels Nov 9, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e572ecf8c2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread mesa/experimental/mesa_signals/core.py Resolved
@arzaanxeng

Copy link
Copy Markdown
Contributor

Thanks for working on this. The approach looks sensible, but the file currently doesn't import.

In mesa/experimental/mesa_signals/core.py, line 393 has def __getstate__(self): indented 8 spaces, so it's nested inside __init__ while its docstring and body sit at the same level. That raises IndentationError: expected an indented block after function definition on line 393, which breaks the whole mesa_signals module. The def should be at 4 spaces, in line with __setstate__ below it.

Once that's fixed, it would be good to also have a test that subscribers which have already been garbage collected are dropped on copy/pickle, and one showing that a bound-method handler is re-bound to the copy.

@dietcoke-17

Copy link
Copy Markdown
Contributor Author

yep i got it and corrected it too but i have some conflicts at local branch so i havent updated it yet

@dietcoke-17 dietcoke-17 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

self review: lgtm and fine ready to ship to production

@mesa-triage-bot

Copy link
Copy Markdown

Thanks for the subscriber-restoration tests, @dietcoke-17. The branch is mergeable and checks pass. With this patch applied, I confirmed that copied TransitSystem rate-change handlers still capture the original tram, as your description notes.

@quaquel, should this proceed as a scoped bound-method fix under #4023, alongside the separate GridCell work in #4025, or must closure subscribers be safe first? I recommend requiring closure safety first: replacing a copy failure with handlers targeting the original model risks silent simulation errors.

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

@quaquel

quaquel commented Nov 23, 2026

Copy link
Copy Markdown
Member

@dietcoke-17, can you resolve the conflicts so this can move forward?

@quaquel
quaquel merged commit e288e96 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
Since mesa#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
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
…4056)


* Keep subscribers when a HasEmitters object is copied or pickled

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* small fix

* added 2 more tests

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

Adapted for 3.5.x: the fix applies unchanged to 3.5's HasObservables; the tests use HasObservables instead of HasEmitters. The alliance formation deepcopy test is left out: it uses 4.0's scenario API, and 3.5's alliance model has no subscribers, so it already deep-copies. On 3.5.3, deep-copying or pickling any HasObservables object with a subscriber, including a Model, raised TypeError: cannot pickle 'WeakMethod' object.

(cherry picked from commit e288e96)

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.

3 participants