{"record":{"id":"c213e7fff47eb473","repo":"nautechsystems/nautilus_trader","slug":"python-on-save-failed-e-c213e7","errorCode":null,"errorMessage":"Python on_save failed: {e}","messagePattern":"Python on_save failed: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/trading/src/python/strategy.rs","lineNumber":1096,"sourceCode":"\n    fn on_dispose(&mut self) -> anyhow::Result<()> {\n        self.dispatch_on_dispose()\n            .map_err(|e| anyhow::anyhow!(\"Python on_dispose failed: {e}\"))\n    }\n\n    fn on_degrade(&mut self) -> anyhow::Result<()> {\n        self.dispatch_on_degrade()\n            .map_err(|e| anyhow::anyhow!(\"Python on_degrade failed: {e}\"))\n    }\n\n    fn on_fault(&mut self) -> anyhow::Result<()> {\n        self.dispatch_on_fault()\n            .map_err(|e| anyhow::anyhow!(\"Python on_fault failed: {e}\"))\n    }\n\n    fn on_save(&self) -> anyhow::Result<IndexMap<String, Vec<u8>>> {\n        self.dispatch_on_save()\n            .map_err(|e| anyhow::anyhow!(\"Python on_save failed: {e}\"))\n    }\n\n    fn on_load(&mut self, state: IndexMap<String, Vec<u8>>) -> anyhow::Result<()> {\n        self.dispatch_on_load(&state)\n            .map_err(|e| anyhow::anyhow!(\"Python on_load failed: {e}\"))\n    }\n\n    fn on_time_event(&mut self, event: &TimeEvent) -> anyhow::Result<()> {\n        route_time_event(self, event);\n        self.dispatch_on_time_event(event)\n            .map_err(|e| anyhow::anyhow!(\"Python on_time_event failed: {e}\"))\n    }\n\n    #[allow(unused_variables)]\n    fn on_data(&mut self, data: &CustomData) -> anyhow::Result<()> {\n        Python::attach(|py| {\n            let py_data: Py<PyAny> = Py::new(py, data.clone())?.into_any();\n            self.dispatch_on_data(py_data)","sourceCodeStart":1078,"sourceCodeEnd":1114,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/trading/src/python/strategy.rs#L1078-L1114","documentation":"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}`.","triggerScenarios":"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).","commonSituations":"`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.","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."],"exampleFix":"// before\ndef on_save(self):\n    return {\"position\": str(self.position_qty)}  # str, not bytes\n\n// after\ndef on_save(self):\n    return {\"position\": str(self.position_qty).encode(\"utf-8\")}","handlingStrategy":"validation","validationCode":"def validate_on_save_state(state):\n    assert isinstance(state, dict), \"on_save must return a dict\"\n    for k, v in state.items():\n        assert isinstance(k, str), f\"key not str: {k!r}\"\n        assert isinstance(v, (bytes, bytearray)), f\"value not bytes for key {k!r}: {type(v)}\"","typeGuard":"def is_valid_state(state):\n    return isinstance(state, dict) and all(\n        isinstance(k, str) and isinstance(v, (bytes, bytearray))\n        for k, v in state.items())","tryCatchPattern":"try:\n    state = self.on_save()\n    validate_on_save_state(state)\nexcept Exception as e:\n    self.log.error(f\"on_save failed: {e}\")\n    state = {}","preventionTips":["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."],"tags":["python","strategy","state-persistence","serialization"],"backgroundTag":"python-callback-failed","analyzedSha":"18893faf8b356be3320add8de2f861b0b647cf06","analyzedAt":"2026-09-08T20:49:34.690Z","contentChangedAt":"2026-09-08T20:49:34.690Z","schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}