pdmlabs.energy.sink#

Append-only cross-process energy spool.

Sibling of pdmlabs.optimization.trial_sink, deliberately not an extension of it: that sink is a best-only high-water mark which keeps one record per process and overwrites it, whereas an energy study needs every record.

Invariants inherited from trial_sink (do not break them)#

  • EnergySink holds only str. It is cheap to pickle into the trial objective closure and owns no file descriptor, socket or thread.

  • _LOCAL_STATE is a module global of this importable module and is never pickled. cloudpickle serialises functions and classes of importable modules by reference, so record() running in a worker touches that worker’s own state. A registry captured in a closure, or defined in __main__, would be copied by value into every task: several processes would then share one file token and clobber each other.

    Corollary, repeated from trial_sink: never call cloudpickle.register_pickle_by_value("pdmlabs").

  • Keyed by (spool_dir, os.getpid()) so a forked child cannot inherit, and then append to, its parent’s file.

  • record() never raises. Failing to spool degrades the study; it must not abort an optimisation run.

Where this DIVERGES from trial_sink, and why each divergence matters#

  1. No ``atexit.register(cleanup)``. TrialSink.create registers one because its spool is scratch. This spool is the study data – copying that line would delete a multi-day run at interpreter exit, with no error. Cleanup is explicit and only valid after a successful export.

  2. One append-only ``.jsonl`` per process. Not one file per record (that burns an inode per trial), and not one shared file: O_APPEND atomicity is not guaranteed on NFS or Lustre, which is exactly where a SLURM spool lives. One writer per file needs no locking and assumes no atomicity.

  3. Torn-tail tolerance instead of a write-then-rename commit protocol. Each record is one json.dumps(...) + "\n" in a single write(). A killed worker can corrupt only the last line of its own file; the reader skips such lines and counts them, because silently dropping them would understate total energy with no signal.

Classes

EnergySink(spool_dir,Β study_id)

Spools every energy record from every process into one directory.

class pdmlabs.energy.sink.EnergySink(spool_dir, study_id)#

Bases: object

Spools every energy record from every process into one directory.

cleanup()#

Remove the spool. Call ONLY after a successful export.

classmethod create(study_id, base_dir=None)#
read_all()#

Return (records, n_torn_lines). Call only after all workers exit.

record(**fields)#

Append one record. Safe from any process, including the main one.

spool_dir#
study_id#