Skip to content

initial implementation of DiskStore - #3771

Merged
quaquel merged 38 commits into
mesa:mainfrom
quaquel:DiskStore
Oct 27, 2026
Merged

quaquel merged 38 commits into
mesa:mainfrom
quaquel:DiskStore

Conversation

@quaquel

@quaquel quaquel commented Jul 6, 2026 •

Copy link
Copy Markdown
Member

summary from Claude, will write this out in more readable form later.

DiskStore: durable, resumable storage for parameter sweeps

Part 4 of the experimentation framework PR sequence. Adds a persistent Store
implementation backed by Arrow IPC streams and JSON manifests, designed for
HPC use: shared filesystems (Lustre/GPFS), SLURM timeouts, and multi-node
execution.

What this PR adds

Three new modules under mesa/experimental/scenarios/:

  • store_metadata.py — store-agnostic durable metadata: the store
    manifest (store.json), the scenario manifest (scenarios.json), and the
    status log (status.log). Reusable by any future persistent store including
    persisting InMemoryStore.
  • disk_writer.py — the worker-side DiskStreamWriter, which appends
    each completed run as one Arrow record batch to per-worker stream files.
  • disk_store.py — the root-side DiskStore, implementing the Store
    protocol: manifest writes, status recording, and the read path that
    assembles outcomes back from the worker files.

Plus a small change to runner.py: RunConfiguration.__call__ now enforces a
postcondition that every extracted output has at least one column (a
columnless frame is recorded as an EXTRACTING failure).

On-disk layout

    store_dir/
    ├── store.json          # format version, sessions, provenance (written once)
    ├── scenarios.json      # authoritative, seed-complete (written once)
    ├── status.log          # append-only, root-written, torn-tail-tolerant
    └── outputs/
        └── {output_name}/
            └── worker-{session}-{host}-{pid}.arrow

Key design decisions and their rationale

Data is written where it is produced

Workers write their own outcomes to disk; only a key-only DiskReference
(just a RunId) crosses back to the root. Nothing is funneled through the
root process, so result size does not bottleneck on the executor's return
pipe.

Arrow IPC stream format, one batch per run, no buffering

Each completed run is appended immediately as one record batch. The stream
format is append-native and every flushed batch is durable at once — a worker
killed by a SLURM timeout loses at most the batch being written.

The IPC file format is deliberately rejected: its footer is written at close, so a killed worker
would leave nothing readable. Reads in this implementation tolerate torn tails by keeping every
complete batch before the tear.

One file per worker per output

Bounds file count at workers × outputs regardless of run count — few metadata
operations, which is what shared parallel filesystems want. The filename
disambiguates along every axis that can collide: pid within a node, host
across nodes (pid spaces are per-node; relevant for the MPI backend),
and session across invocations. A resumed sweep opens new files rather
than appending: an IPC stream cannot be reopened once its end-of-stream marker
is written, and repairing a torn file would mean read-modify-write on a shared
filesystem.

Stateless writer + per-process stream registry

The writer is re-pickled with every job, but we need open streams on each worker. So open streams live in a module-level registry keyed by (session, output), reused across a worker's runs. The other design alternative is to use an initializer function but this makes using executors more complicated. The user has to specify the right function depending on what store she wants to use. The implementation here hides the complexity.

Per-run atomic pre-write validation

to_reference validates every output (safe name, Arrow-convertible, schema
stable within the worker) before writing any, so a run contributes a full
batch set or nothing. Output names must match a strict pattern (they become
directory names); unsafe names are rejected rather than encoded. Within-worker
schema deviation is a recorded WRITING failure; cross-worker deviation is
deferred to the reader. A future PR will expand RunConfiguration to include an
explicit schema instead of deriving it from the first run on each worker.

Status: append-only log, replayed

The root appends one JSON line per terminal transition (SUCCEEDED / FAILED /
ABORTED, with structured FailureInfo); PENDING is the absence of a line.
Reading back this log is last-write-wins and tolerates exactly one torn final line (the only
damage the write pattern can produce); a malformed earlier line raises as
corruption. In-process, status lives on the RunRecord — the log is its
write-through durable shadow, so query methods stay simple dict comprehensions
matching InMemoryStore.

Scenario manifest round-trips seeds exactly

scenarios.json stores each scenario's parameters plus SeedSequence
entropy, spawn key, and bit-generator class — enough to reconstruct RNGs
bit-exactly (required for cross-process resume correctness). No pickle
anywhere. Numpy scalar parameters are narrowed to Python natives on write.

Read path: fan-in with schema reconciliation

Reading an output concatenates all its worker files
(promote_options="permissive" null-fills columns absent in some workers),
gated by an on_schema_conflict knob ("warn" | "raise").
retrieve_output(run_id) is status-gated like InMemoryStore and returns
every sweep output as a key; a zero-row frame means the run wrote a valid
empty batch or never wrote to that output — indistinguishable by design,
since the reference is key-only. Reads are uncached (whole-sweep reads
dominate; a RunId-list signature is noted as a future option).

Two construction paths

  • DiskStore(store_dir, ...) creates: writes store.json exclusively
    (open("x") — pointing a new sweep at an existing store fails loudly
    instead of clobbering it), mints a session token.
  • DiskStore.from_directory(store_dir, scenario_class) attaches for
    read-back: replays manifests and log, gates on the store format version,
    and has no session — writer() raises.

Provenance (informational, non-gating)

store.json records Mesa version, creation time, and a best-effort git
commit + dirty flag for the tree containing the user's model class (located
via inspect.getfile), Never gates any operation;
anything undeterminable is omitted.

Explicitly out of scope (later PRs)

  • Resume: re-dispatching pending runs, new-session minting on an
    existing store, and reconciling the window where a worker's batch landed but
    the root died before logging success. The format commitments resume needs
    (session tokens in filenames, ordered session list, format version) are
    already in place, since they cannot be retrofitted without a format bump.

Dependencies

Adds pyarrow>=14 (floor set by both Python 3.12 wheel availability and
concat_tables(promote_options=...); current stable is 24.x). Packaging as
an optional extra with guarded imports is handled in this PR / a follow-up
(TODO before merge).

@github-actions

github-actions Bot commented Jul 6, 2026

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 +0.3% [-0.3%, +1.0%] 🔵 +0.1% [-0.2%, +0.4%]
BoltzmannWealth large 🔵 -0.9% [-1.9%, -0.1%] 🔵 +4.3% [+2.8%, +5.7%]
Schelling small 🔵 +1.9% [+1.5%, +2.5%] 🔵 +2.3% [+1.5%, +3.2%]
Schelling large 🔵 +1.7% [+1.0%, +2.3%] 🔴 +5.4% [+4.2%, +6.6%]
WolfSheep small 🔵 +1.0% [+0.5%, +1.5%] 🔵 -1.6% [-5.8%, +2.5%]
WolfSheep large 🔵 -0.0% [-0.7%, +0.5%] 🔵 -0.3% [-1.6%, +1.0%]
SugarscapeG1mt small 🔵 +1.0% [+0.6%, +1.3%] 🔵 +1.3% [-0.4%, +2.9%]
SugarscapeG1mt large 🔵 -0.0% [-1.0%, +1.1%] 🔵 +1.2% [-0.7%, +3.0%]
BoidFlockers small 🔵 +1.8% [+1.4%, +2.3%] 🔵 +1.5% [+0.9%, +2.0%]
BoidFlockers large 🔵 +2.2% [+1.7%, +2.7%] 🔵 +1.2% [+1.0%, +1.4%]

@codebreaker32 codebreaker32 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I've gone through the DiskStreamWriter implementation for now and left some feedback regarding a few I/O edge cases. Fantastic work so far. I'll take a closer look at the rest of the PR soon.


# --- all validated; now write ---
for name, batch in batches.items():
self._append(name, batch)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

In the docstring, it states:

the check is atomic across the whole outcome, so a run either contributes a full batch to each of its streams or nothing at all, never a partial set.

While the validation is indeed atomic, the disk write phase is not. If "agents" appends successfully, but "model" throws an OSError (e.g., disk full, network drive blip, permission drop), the "agents" data is already permanently flushed to the Arrow stream.

The worker's _safe_call will correctly catch this and mark the run as FAILED. However, if the user later resumes the sweep to retry failed runs, the replacement run will execute and append the "agents" data again, resulting in silent duplicate data in that specific output file.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is an important corner case to consider in the future PR where I built the resume logic. I'll update the docs here and at a fixme as a reminder for this corner case.

In the resume situation, the best solution is to first clear out any data related to failed or abandoned runs.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

To actually clear out the failed data, the resume script would have to:

  1. Open the .arrow file.
  2. Read the entire thing into memory.
  3. Find the rows belonging to the failed RunId and drop them.
  4. Rewrite a brand new .arrow file to the disk.
    Doing this across hundreds of files before a sweep can resume is slow, memory-intensive, and risks corrupting the good data if the resume script crashes halfway through!

Instead of mutating the disk, we let the partial/failed data sit there. When the user eventually calls retrieve_output() to get their final Pandas dataframe, the reader simply looks at the status. If a RunId doesn't say SUCCEEDED, the reader just drops those rows instantly in memory using PyArrow or Pandas. It takes milliseconds and requires zero risky disk rewrites.

@codebreaker32

Copy link
Copy Markdown
Collaborator

One more thing worth noting is we currently utilize Python's ProcessPoolExecutor to spin up a worker for each core.
However, PyArrow uses its own underlying C++ thread pool for I/O and compression operations. By default, PyArrow allocates threads equal to the total number of system cores( see here.)

When these two interact on high-core machines, every single Python worker process spins up its own full-sized PyArrow C++ thread pool. On a 64-core node, this results in 4,096 active threads fighting for CPU time. This may cause thrashing.

We can fix this globally by:

pa.set_cpu_count(1)
pa.set_io_thread_count(1)

src : https://arrow.apache.org/docs/python/generated/pyarrow.set_cpu_count.html https://arrow.apache.org/docs/python/generated/pyarrow.set_io_thread_count.html#pyarrow.set_io_thread_count

@github-actions github-actions Bot added experimental Release notes label testing Release notes label labels Aug 27, 2026
@quaquel

quaquel commented Aug 28, 2026

Copy link
Copy Markdown
Member Author

The various issues addressed by @codebreaker32 have now been addressed as far as they relate to this PR. Resume is future work. Tests still need to come.

@github-actions github-actions Bot added the packaging Release notes label label Aug 31, 2026
@quaquel
quaquel marked this pull request as ready for review September 1, 2026 11:48
@quaquel

quaquel commented Sep 1, 2026

Copy link
Copy Markdown
Member Author

This PR is done code wise. I still aim to go through everything and clean up the docstring in places. There are some gen-AI artifacts or notes by myself left in them. Likewise, I'll clean up the start post to properly reflect the final implementation.

@quaquel

quaquel commented Oct 7, 2026

Copy link
Copy Markdown
Member Author

@codebreaker32, @EwoutH , @tpike3 this is gentle reminder that I can use a review of this so we can move on. I realize I still would like to clean up the starting post before merging, but the review can be done separately from it.

@codebreaker32

Copy link
Copy Markdown
Collaborator

I'd give it a thorough review first thing tomorrow morning.

@codebreaker32 codebreaker32 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This looks in good shape, especially given the size of the diff. I went through the modules, ran a few experiments against the branch. Most of my earlier threads are resolved but some handful of questions and smaller suggestions.

# write error) because it is a statement about what extraction produced, not
# about writing. A columned zero-row frame is valid and passes.
for name, frame in output.items():
if frame.shape[1] == 0:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

What if extract_output returns a Dataframe?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not sure I follow. extract_output returns a dict with a string as a key and a dataframe as a value. Shape is defined on the dataframe.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Sorry, I was unclear. I meant a user overriding extract_output and returning a DataFrame instead of a dict, which is an easy mistake. DataFrame.items() yields (column, Series), and Series.shape[1] raises IndexError. Because the check sits outside the try in __call__, _safe_call doesn't catch it: with executor=None the whole sweep crashes and every run stays PENDING; with a pool it's recorded as a WRITING failure.

class DemoRun(RunConfiguration):
    def extract_output(self, model):
        return pd.DataFrame({"x": [1]})

run_scenarios([Scenario(x=0)], DemoRun(M, until=1), progress=False)
# IndexError: tuple index out of range

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Ok, I understand it now.

  1. Doing this will trigger a typing warning, so a user will get at least something of a heads up something is not right here.
  2. I think with both a ProcessPoolEvaluator and its MPI equivalent, doing this will likewise bring down the entire pool on the first returned result. I would argue it iss desirable behavior: it fails fast. The other try catch are more about isolating individual runs that fail from bringing down the entire pool.

@codebreaker32 codebreaker32 Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

  1. Agreed, just a nitpick, In a notebook, or with a bare def extract_output(self, model):(no annotation), the first signal is the IndexError itself, raised from Series.shape, which says nothing about dicts or DataFrames.

  2. Fail fast is fine by me, but that's not what happens here. The IndexError comes back through future.result() and gets caught by the except blockk there, so each run is recorded as a WRITING failure and the sweep finishes normally. Only executor=None actually crashes. So right now the same mistake crashes sequentially and silently "succeeds" with N failed runs in parallel. Either way is defensible, but they should match.

supplied separately at construction time, so recorded provenance can
never diverge from the config that actually ran.
"""
store_metadata.write_store_manifest(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The manifest is being written befire scenarios are serialised, an unserialisable scenario parameter raises TypeError but leaves store.json and a partial scenarios.json behind, so a retry on the same directory fails with FileExistsError. I confirmed this locally

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

It's even a bit worse after my check. Will update the code to address it.

)
try:
return pa.RecordBatch.from_pandas(
frame, schema=self._full_schema(name), preserve_index=False

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

retrieve_output on DiskStore returns frames with scenario_id and replication_id columns appended, while InMemoryStore returns the original column. If this is intended, should we document it?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

It is intended and inherent in the design. InMemoryStore just keeps all the stuff that the writer gave it. DiskStore writes it to disk and to avoid ragged data can't keep the raw stuff given to it by the writer. For example, if a given field is missing in one run, it is stored as being empty rather than as the key not being there at all. So, when retrieving output, you will get slightly different stuff back, potentially , than what was handed by the writer.

@tpike3

tpike3 commented Oct 9, 2026

Copy link
Copy Markdown
Member

I will get my review done by Sunday, excited to see where this ended up

@tpike3 tpike3 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Appreciating this is PR in progress for the larger add HPC capability I approve, so you are not held up.

The concerns I had, had an associated fixme. So my understanding is this PR is focused on the write-side and a future PR will update the read-side, if I am understanding the comments correctly?

My only comment for the read-side would be, don't you want to allow for a more compressed data structure like parquet?

My larger Mesa concern, which is my one inline comment (pyarrow install), and is a larger discussion that I am struggling with this on the meta-agents side (so I am poorly primed), is what is Mesa's future organization set up? As I have been doing a lot of containers lately, my bias right now would be for a feature approach so mesa["hpc"] would be a growing feature that users who need it can install, but it is not required. Please let me know

Finally, for Mesa's capability for large runs, if your general plan is write-side, read-side, I would ask to consider ensuring a docs PR to. I am concerned we have a lot of futures that users wont find or know if there is not associated documentation/example with them. Even with LLMs my experience has been you have to prime them to use new versions or specific features.

Comment thread pyproject.toml
"scipy",
"pythran>=0.17.0 ; sys_platform == 'darwin'", # required for darwin scipy overrides in nix

"pyarrow",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Can we make this an optional import, maybe start mesa["hpc"]? I think this goes to the larger question of what do we want the mesa organizational structure to look like.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

yes, I agree that we need a better way to handle this. It intersects with lazy imports as well.

@quaquel

quaquel commented Oct 26, 2026

Copy link
Copy Markdown
Member Author

Finally a bit of time. I addressed @codebreaker32 comments.

@tpike3, I agree with on pyarrow. But, changing it breaks all tests. Even moving it into the CI list won't work. This has to do with how the importing of the experimental stuff is handled. The longer term fix is probably in lazy loading and cleaner separation of experimental from non-experimental code. For example, scenario is already used in model even though it is still in experimental.

@quaquel

quaquel commented Oct 27, 2026

Copy link
Copy Markdown
Member Author

The concerns I had, had an associated fixme. So my understanding is this PR is focused on the write-side and a future PR will update the read-side, if I am understanding the comments correctly?

The main follow up is the resume side of things and that includes reading stuff back.

My only comment for the read-side would be, don't you want to allow for a more compressed data structure like parquet?

I have stayed away from that for now. In particular in a HPC context, there are challenges with using something like Parquet. PyArrow allows me to flush each result to disk and recover from a crash of the writer. I can't do that as cleanly as far as I know with parquet. However, this PR does provide 80% or so of what you would need if you want to add parquet. All that would be needed is a separate writer and and store.

My larger Mesa concern, which is my one inline comment (pyarrow install), and is a larger discussion that I am struggling with this on the meta-agents side (so I am poorly primed), is what is Mesa's future organization set up? As I have been doing a lot of containers lately, my bias right now would be for a feature approach so mesa["hpc"] would be a growing feature that users who need it can install, but it is not required. Please let me know

yes, see the lazy import conversation as well.

Finally, for Mesa's capability for large runs, if your general plan is write-side, read-side, I would ask to consider ensuring a docs PR to. I am concerned we have a lot of futures that users wont find or know if there is not associated documentation/example with them. Even with LLMs my experience has been you have to prime them to use new versions or specific features.

yes, docs are the final step

@quaquel
quaquel merged commit b4c2fbd into mesa:main Oct 27, 2026
14 of 15 checks passed
@EwoutH

EwoutH commented Oct 27, 2026

Copy link
Copy Markdown
Member

Cool to see this merged. Will try to find some time to play with it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

experimental Release notes label packaging Release notes label testing Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants