nautechsystems/nautilus_trader · error
Python on_save failed: {e}
Error message
Python on_save failed: {e} What it means
The strategy's Python-level `on_save` callback raised an exception (or returned data that could not be converted). `dispatch_on_save()` (strategy.rs:384) calls `on_save` on the Python instance, then `cast_bound::<PyDict>` and `pydict_to_state` to convert the returned dict into `IndexMap<String, Vec<u8>>`; any failure is wrapped at strategy.rs:1096 as `Python on_save failed: {e}`.
Source
Thrown at crates/trading/src/python/strategy.rs:1096
fn on_dispose(&mut self) -> anyhow::Result<()> {
self.dispatch_on_dispose()
.map_err(|e| anyhow::anyhow!("Python on_dispose failed: {e}"))
}
fn on_degrade(&mut self) -> anyhow::Result<()> {
self.dispatch_on_degrade()
.map_err(|e| anyhow::anyhow!("Python on_degrade failed: {e}"))
}
fn on_fault(&mut self) -> anyhow::Result<()> {
self.dispatch_on_fault()
.map_err(|e| anyhow::anyhow!("Python on_fault failed: {e}"))
}
fn on_save(&self) -> anyhow::Result<IndexMap<String, Vec<u8>>> {
self.dispatch_on_save()
.map_err(|e| anyhow::anyhow!("Python on_save failed: {e}"))
}
fn on_load(&mut self, state: IndexMap<String, Vec<u8>>) -> anyhow::Result<()> {
self.dispatch_on_load(&state)
.map_err(|e| anyhow::anyhow!("Python on_load failed: {e}"))
}
fn on_time_event(&mut self, event: &TimeEvent) -> anyhow::Result<()> {
route_time_event(self, event);
self.dispatch_on_time_event(event)
.map_err(|e| anyhow::anyhow!("Python on_time_event failed: {e}"))
}
#[allow(unused_variables)]
fn on_data(&mut self, data: &CustomData) -> anyhow::Result<()> {
Python::attach(|py| {
let py_data: Py<PyAny> = Py::new(py, data.clone())?.into_any();
self.dispatch_on_data(py_data)View on GitHub (pinned to 18893faf8b)
Solutions
- Check the `{e}` text: if it mentions a dict cast, ensure `on_save` returns `dict[str, bytes]` (encode strings, e.g. `value.encode()` or use pickle/json serialized to bytes).
- Ensure `on_save` explicitly returns the state mapping rather than None.
- Guard collection of each state key so a missing cache entry cannot raise.
- Test saving by calling the strategy's save path in a unit test before deploying.
Example fix
// before
def on_save(self):
return {"position": str(self.position_qty)} # str, not bytes
// after
def on_save(self):
return {"position": str(self.position_qty).encode("utf-8")} Defensive patterns
Strategy: validation
Validate before calling
def validate_on_save_state(state):
assert isinstance(state, dict), "on_save must return a dict"
for k, v in state.items():
assert isinstance(k, str), f"key not str: {k!r}"
assert isinstance(v, (bytes, bytearray)), f"value not bytes for key {k!r}: {type(v)}" Type guard
def is_valid_state(state):
return isinstance(state, dict) and all(
isinstance(k, str) and isinstance(v, (bytes, bytearray))
for k, v in state.items()) Try / catch
try:
state = self.on_save()
validate_on_save_state(state)
except Exception as e:
self.log.error(f"on_save failed: {e}")
state = {} Prevention
- Always return dict[str, bytes] from on_save; encode() or serialize explicitly.
- Add a round-trip save/load unit test for the strategy.
- Never return None implicitly — end on_save with a return statement.
- Guard each state-key collection with .get()/defaults.
When it happens
Trigger: A snapshot/save is requested (e.g. on stop or periodic state persistence) and the Python `on_save` raises, or returns something that is not a `dict` of `str` -> `bytes` (causing the PyDict cast or conversion to fail).
Common situations: `on_save` returning a plain dict of str->str/int instead of bytes; forgetting to `return` the state dict (returns None, cast fails); pickling state inside `on_save` with an unpicklable object; KeyError while collecting state from a cache that was never populated.
Related errors
- Python object has no to_json() method or __dict__ attribute
- Instances must have encode_record_batch_py method
- Invalid `strategy_id` type
- Failed to convert batched deltas to Python: {e}
- Failed to extract PyStrategy: {e}
AI-assisted analysis of nautechsystems/nautilus_trader@18893faf8b (2026-09-08).
Data as JSON: /api/errors/c213e7fff47eb473.
Report an issue: GitHub.