{"record":{"id":"0f67a69d9d8820c7","repo":"nautechsystems/nautilus_trader","slug":"python-on-load-failed-e-0f67a6","errorCode":null,"errorMessage":"Python on_load failed: {e}","messagePattern":"Python on_load failed: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/trading/src/python/strategy.rs","lineNumber":1101,"sourceCode":"\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)\n                .map_err(|e| anyhow::anyhow!(\"Python on_data failed: {e}\"))\n        })\n    }\n\n    fn on_signal(&mut self, signal: &Signal) -> anyhow::Result<()> {","sourceCodeStart":1083,"sourceCodeEnd":1119,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/trading/src/python/strategy.rs#L1083-L1119","documentation":"The strategy's Python-level `on_load` callback raised an exception. `dispatch_on_load()` (strategy.rs:396) converts the saved `IndexMap<String, Vec<u8>>` state to a Python dict via `state_to_pydict` and calls `on_load(py_state)`; any Python exception is wrapped at strategy.rs:1101 as `Python on_load failed: {e}`. The cause is inside the user's `on_load` (or, less commonly, in the state-to-dict conversion).","triggerScenarios":"Restoring a saved snapshot: the framework calls `on_load(state)` with a dict of bytes values; the Python method raises, e.g. by decoding bytes with the wrong codec, unpickling data written by an older schema, or assuming a key exists in the loaded state.","commonSituations":"Loading state saved by a previous strategy version (schema drift / missing keys); `json.loads` or `pickle.loads` on bytes that were saved differently; `KeyError` on a state key; trying to mutate frozen/None attributes during load.","solutions":["Read `{e}` for the underlying Python error; usually a decode/unpickle error or missing key in the passed state dict.","Use `.get(key, default)` for every state key in `on_load` so old snapshots load cleanly.","Decode bytes with the exact codec used in `on_save` (e.g. `bytes.decode(\"utf-8\")`), and version your saved state.","Write a round-trip test: run `on_save`, feed the result to `on_load` on a fresh strategy instance."],"exampleFix":"// before\ndef on_load(self, state):\n    self.position_qty = Decimal(state[\"position\"].decode())  # KeyError on old snapshots\n\n// after\ndef on_load(self, state):\n    raw = state.get(\"position\")\n    self.position_qty = Decimal(raw.decode()) if raw is not None else Decimal(0)","handlingStrategy":"validation","validationCode":"def validate_state_for_load(state):\n    required = {\"position\"}  # keys your on_load needs\n    missing = required - set(state)\n    assert not missing, f\"snapshot missing keys: {missing}\"\n    for v in state.values():\n        assert isinstance(v, (bytes, bytearray))","typeGuard":"def loadable(state, required_keys):\n    return isinstance(state, dict) and required_keys.issubset(state) and all(\n        isinstance(v, (bytes, bytearray)) for v in state.values())","tryCatchPattern":"try:\n    self.on_load(state)\nexcept Exception as e:\n    self.log.error(f\"state restore failed, starting fresh: {e}\")\n    self._init_default_state()","preventionTips":["Use state.get(key, default) for every key so old snapshots load.","Version your saved state and include a schema version key.","Round-trip test: on_save -> on_load on a fresh instance in CI.","Match decode codec exactly with what on_save encoded."],"tags":["python","strategy","state-restore","deserialization"],"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"}