Expand description
Save and restore VM instance state. Save and restore VM instance state.
This module provides Instance::save_state and
Instance::restore_state for pausing execution at bar N and resuming
from bar N+1 later.
§Server-side best practices
In a server deployment, each running script typically processes thousands of historical bars before reaching the live feed. Replaying all historical bars on every restart is expensive. Snapshots let you checkpoint the VM state after the historical replay, then reload it instantly on the next start.
§Recommended workflow
Cold start
│
├─ Build Instance (InstanceBuilder)
├─ Feed all historical bars (instance.run_bar(…))
├─ Call instance.save_state() → Vec<u8>
├─ Persist the bytes (database, object storage, local disk, …)
└─ Continue feeding live bars
Warm restart
│
├─ Load the persisted bytes
├─ Instance::restore_state(&bytes)?.build()?
└─ Continue feeding live bars from the next bar index§When to save
Save once after the last confirmed historical bar — i.e. after the final bar for which the data will never change — and resave whenever you want to advance the checkpoint. Prefer saving on a confirmed bar close rather than mid-bar: intrabar data can still be revised, and on restart you will typically resume from the next complete bar rather than replaying the remaining intrabar updates of a partial bar.
§Versioning and invalidation
Snapshots embed a format version (SNAPSHOT_VERSION) and the compiled
Program. A snapshot is only valid
for the exact binary that created it: a new OpenPine release, a changed
script, or modified inputs all require discarding the snapshot and
replaying history from scratch.
A simple invalidation strategy: store the snapshot alongside a hash of the Pine source (or the compiled program bytes). On startup, compare the hash; if it differs, delete the snapshot and do a full cold replay.
§Example
use openpine_vm::{Instance, snapshot::SnapshotError};
// --- Cold start: replay history and checkpoint ---
let mut instance = build_instance(script, symbol_info, timeframe);
for bar in historical_bars {
instance.run_bar(bar)?;
}
let snapshot: Vec<u8> = instance.save_state()?;
persist_to_storage(&snapshot); // store to DB / disk / S3 / …
// --- Warm restart: restore and continue ---
let snapshot: Vec<u8> = load_from_storage();
let mut instance = Instance::restore_state(&snapshot)?.build()?;
for bar in live_bars { // resume from bar_index + 1
instance.run_bar(bar)?;
}Structs§
- Restore
Builder - Builder returned by
Instance::restore_statefor configuring optional parameters before completing the restore.
Enums§
- Snapshot
Error - Errors that can occur during snapshot save/restore.