{"record":{"id":"169949ad22dd2664","repo":"nautechsystems/nautilus_trader","slug":"failed-to-stop-prior-websocket-handler-e","errorCode":null,"errorMessage":"failed to stop prior WebSocket handler: {e}","messagePattern":"failed to stop prior WebSocket handler: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/adapters/deribit/src/websocket/client.rs","lineNumber":535,"sourceCode":"    /// # Errors\n    ///\n    /// Returns an error if the connection fails.\n    pub async fn connect(&mut self) -> anyhow::Result<()> {\n        let connect_lock = Arc::clone(&self.connect_lock);\n        let _connect_guard = connect_lock.lock().await;\n\n        log_debug!(\n            \"Connecting to WebSocket: {}\",\n            self.url,\n            color = LogColor::Blue\n        );\n\n        if !self.handler_tasks.is_open() || !self.handler_tasks.is_empty() {\n            self.handler_tasks.begin_shutdown();\n            self.signal.store(true, Ordering::Relaxed);\n            self.finish_handler()\n                .await\n                .map_err(|e| anyhow::anyhow!(\"failed to stop prior WebSocket handler: {e}\"))?;\n            self.handler_tasks.start_generation().map_err(|e| {\n                anyhow::anyhow!(\"failed to start WebSocket handler task generation: {e}\")\n            })?;\n        }\n        let handler_spawner = self.handler_tasks.spawner().map_err(|e| {\n            anyhow::anyhow!(\"failed to acquire WebSocket handler task spawner: {e}\")\n        })?;\n\n        // Reset stop signal and subscription state so callers can\n        // resubscribe cleanly after a manual disconnect/connect cycle.\n        self.signal.store(false, Ordering::Relaxed);\n        self.subscriptions_state.clear();\n\n        // Create message handler and channel\n        let (message_handler, raw_rx) = channel_message_handler();\n\n        // No-op ping handler: handler responds to pings directly\n        // Inbound Ping frames are answered by the transport, so no ping handler is needed;","sourceCodeStart":517,"sourceCodeEnd":553,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/adapters/deribit/src/websocket/client.rs#L517-L553","documentation":"In the Deribit WebSocket client's `connect`, any leftover handler tasks from a previous connection are shut down via `finish_handler()`. This error wraps the underlying failure of that shutdown, preventing a clean reconnect. It signals the internal task-generation manager could not be transitioned into shutdown.","triggerScenarios":"Calling `connect()` while `handler_tasks` is open or non-empty (a prior session's handler still exists) and the task group's shutdown/generation handshake fails (e.g. handler task hung, generation state corrupted, runtime shutdown in progress).","commonSituations":"Reconnecting after an unclean disconnect where the old message-handler task never completed; calling connect concurrently from two places; tearing down the tokio runtime while the handler is still draining; a bug in TaskGroup's generation lifecycle.","solutions":["Log the inner error `{e}` to see why finish_handler failed (hung task vs runtime issue).","Ensure the prior session was properly disconnected before calling connect again.","Check for concurrent connect()/disconnect() calls and serialize them with a lock.","If the handler task is stuck, add timeouts around the blocking part of the handler loop so shutdown can complete.","Upgrade/inspect the TaskGroup (handler_tasks) implementation if errors persist on a fresh client."],"exampleFix":"// before\nlet _ = client.connect().await;\n// after\nclient.disconnect().await?; // ensure prior handler fully stopped\nlet _ = client.connect().await?;","handlingStrategy":"try-catch","validationCode":"// Rust\nif client.handler_state_unclean() /* or track your own connected flag */ {\n    client.disconnect().await?;\n}","typeGuard":null,"tryCatchPattern":"match client.connect().await {\n    Err(e) if e.to_string().contains(\"failed to stop prior WebSocket handler\") => {\n        // rebuild client or retry after backoff\n    }\n    Ok(v) => v,\n    Err(e) => return Err(e),\n}","preventionTips":["Always await disconnect before reconnecting.","Serialize connect/disconnect behind one ownership point (actor/task).","Add timeouts to reconnect loops.","Log inner errors from anyhow chains for diagnosis."],"tags":["websocket","task-shutdown","connection-lifecycle"],"backgroundTag":"invalid-state-transition","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"}