{"record":{"id":"fd516a36e5d890cd","repo":"nautechsystems/nautilus_trader","slug":"failed-to-send-setclient-command-e-fd516a","errorCode":null,"errorMessage":"Failed to send SetClient command: {e}","messagePattern":"Failed to send SetClient command: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/adapters/lighter/src/websocket/client.rs","lineNumber":516,"sourceCode":"            anyhow::bail!(\"Lighter WebSocket initial connection cancelled\");\n        }\n\n        let (cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel::<HandlerCommand>();\n        let (out_tx, out_rx) = tokio::sync::mpsc::unbounded_channel::<NautilusWsMessage>();\n\n        // Capture the connection-mode atomic before moving `client` into the\n        // SetClient command below.\n        let connection_mode_atomic = client.connection_mode_atomic();\n        let connection_epoch_atomic = client.connection_epoch_atomic();\n\n        // Queue SetClient (and the instrument cache replay) onto the new\n        // command channel BEFORE publishing it to clones or marking the\n        // connection active. Otherwise a clone observing `is_active()` could\n        // race in and send a Subscribe before SetClient lands, and the\n        // handler would drop the subscription because `inner == None`.\n        let reconnect_handle = client.reconnect_handle();\n        if let Err(e) = cmd_tx.send(HandlerCommand::SetClient(client)) {\n            anyhow::bail!(\"Failed to send SetClient command: {e}\");\n        }\n\n        if let Some(control) = &self.socket_control {\n            control.register(move || reconnect_handle.request_reconnect());\n        }\n\n        let initial_instruments: Vec<(i16, InstrumentAny)> = self\n            .instruments\n            .iter()\n            .map(|entry| (*entry.key(), entry.value().clone()))\n            .collect();\n\n        if !initial_instruments.is_empty()\n            && let Err(e) = cmd_tx.send(HandlerCommand::InitializeInstruments(initial_instruments))\n        {\n            log::error!(\"Failed to send InitializeInstruments: {e}\");\n        }\n","sourceCodeStart":498,"sourceCodeEnd":534,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/adapters/lighter/src/websocket/client.rs#L498-L534","documentation":"Raised when sending the HandlerCommand::SetClient command over the internal unbounded command channel fails. SetClient must reach the handler task before the connection is marked active; a send failure means the receiver side (handler task) is already gone, so startup cannot proceed.","triggerScenarios":"Calling connect() when the handler task consuming cmd_tx has already terminated (panicked or exited) before consuming the SetClient command, causing tokio mpsc send to return SendError.","commonSituations":"A handler task panic immediately after spawn (e.g. a bug in message handling of an initial frame); calling connect() on a client whose previous handler crashed; resource exhaustion killing the tokio task.","solutions":["Look for a preceding panic log from the handler task — the receiver dying is the real cause; fix that panic first.","Recreate the client and call connect() again instead of reusing a client whose handler died.","Check the adapter version for known handler-task panics; upgrade if fixed upstream.","Enable panic hooks/backtrace logging (RUST_BACKTRACE=1) to capture the handler crash that precedes this error.","If reconnecting programmatically, ensure the old handler was fully drained (call disconnect()) before a new connect()."],"exampleFix":"// before: reusing a client after a crashed handler\nclient.connect().await?; // Failed to send SetClient command: channel closed\n\n// after: build a fresh client after a failure\nif client.is_failed() {\n    client = build_ws_client(config)?;\n}\nclient.connect().await?;","handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"match client.connect().await {\n    Err(e) if e.to_string().contains(\"Failed to send SetClient\") => {\n        log::error!(\"handler died before SetClient: {e:#}\");\n        let mut fresh = build_ws_client(cfg)?;\n        fresh.connect().await?; // recreate client, don't reuse\n    }\n    r => r?,\n}","preventionTips":["Investigate any handler-task panic logged just before this error","Run with RUST_BACKTRACE=1 to capture handler crashes","Call disconnect() and rebuild after any handler failure","Keep the adapter version current to avoid known handler panics"],"tags":["websocket","async","channel","rust"],"backgroundTag":"broken-pipe","analyzedSha":"18893faf8b356be3320add8de2f861b0b647cf06","analyzedAt":"2026-09-08T20:49:34.690Z","contentChangedAt":"2026-09-08T20:49:34.690Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}