Repository navigation
initial implementation of DiskStore - #3771
Conversation
|
Performance benchmarks:
|
codebreaker32
left a comment
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
To actually clear out the failed data, the resume script would have to:
- Open the
.arrowfile. - Read the entire thing into memory.
- Find the rows belonging to the failed
RunIdand drop them. - Rewrite a brand new
.arrowfile 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.
|
One more thing worth noting is we currently utilize Python's When these two interact on high-core machines, every single Python worker process spins up its own full-sized 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 |
|
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. |
|
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. |
|
@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. |
|
I'd give it a thorough review first thing tomorrow morning. |
codebreaker32
left a comment
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
What if extract_output returns a Dataframe?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 rangeThere was a problem hiding this comment.
Ok, I understand it now.
- Doing this will trigger a typing warning, so a user will get at least something of a heads up something is not right here.
- I think with both a
ProcessPoolEvaluatorand 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.
There was a problem hiding this comment.
-
Agreed, just a nitpick, In a notebook, or with a bare
def extract_output(self, model):(no annotation), the first signal is theIndexErroritself, raised fromSeries.shape, which says nothing about dicts or DataFrames. -
Fail fast is fine by me, but that's not what happens here. The
IndexErrorcomes back throughfuture.result()and gets caught by theexceptblockk there, so each run is recorded as a WRITING failure and the sweep finishes normally. Onlyexecutor=Noneactually 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( |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
|
I will get my review done by Sunday, excited to see where this ended up |
tpike3
left a comment
There was a problem hiding this comment.
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.
| "scipy", | ||
| "pythran>=0.17.0 ; sys_platform == 'darwin'", # required for darwin scipy overrides in nix | ||
|
|
||
| "pyarrow", |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
yes, I agree that we need a better way to handle this. It intersects with lazy imports as well.
|
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. |
The main follow up is the resume side of things and that includes reading stuff back.
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.
yes, see the lazy import conversation as well.
yes, docs are the final step |
|
Cool to see this merged. Will try to find some time to play with it. |
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
Storeimplementation 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 storemanifest (
store.json), the scenario manifest (scenarios.json), and thestatus log (
status.log). Reusable by any future persistent store includingpersisting InMemoryStore.
disk_writer.py— the worker-sideDiskStreamWriter, which appendseach completed run as one Arrow record batch to per-worker stream files.
disk_store.py— the root-sideDiskStore, implementing theStoreprotocol: 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 apostcondition that every extracted output has at least one column (a
columnless frame is recorded as an
EXTRACTINGfailure).On-disk layout
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 theroot 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:
pidwithin a node,hostacross nodes (pid spaces are per-node; relevant for the MPI backend),
and
sessionacross invocations. A resumed sweep opens new files ratherthan 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_referencevalidates every output (safe name, Arrow-convertible, schemastable 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
WRITINGfailure; cross-worker deviation isdeferred 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 itswrite-through durable shadow, so query methods stay simple dict comprehensions
matching
InMemoryStore.Scenario manifest round-trips seeds exactly
scenarios.jsonstores each scenario's parameters plusSeedSequenceentropy, 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_conflictknob ("warn"|"raise").retrieve_output(run_id)is status-gated likeInMemoryStoreand returnsevery 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: writesstore.jsonexclusively(
open("x")— pointing a new sweep at an existing store fails loudlyinstead of clobbering it), mints a session token.
DiskStore.from_directory(store_dir, scenario_class)attaches forread-back: replays manifests and log, gates on the store format version,
and has no session —
writer()raises.Provenance (informational, non-gating)
store.jsonrecords Mesa version, creation time, and a best-effort gitcommit + 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)
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 andconcat_tables(promote_options=...); current stable is 24.x). Packaging asan optional extra with guarded imports is handled in this PR / a follow-up
(TODO before merge).