{"record":{"id":"96da57cd4fc01522","repo":"tonhowtf/omniget","slug":"failed-to-initialize-torrent-session-mod","errorCode":null,"errorMessage":"Failed to initialize torrent session: {}","messagePattern":"Failed to initialize torrent session: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"critical","filePath":"src-tauri/src/platforms/magnet/mod.rs","lineNumber":153,"sourceCode":"                            Err(e) => {\n                                tracing::warn!(\n                                    \"[magnet] persistent DHT init failed ({}); retrying without DHT persistence\",\n                                    e\n                                );\n                                match Session::new_with_opts(output_pb.clone(), make_opts(true, false)).await {\n                                    Ok(s) => Ok(s),\n                                    Err(e2) => {\n                                        tracing::warn!(\n                                            \"[magnet] DHT init failed ({}); retrying with DHT disabled (trackers/PEX only)\",\n                                            e2\n                                        );\n                                        Session::new_with_opts(output_pb, make_opts(true, true)).await\n                                    }\n                                }\n                            }\n                        }\n                    } => {\n                        result.map_err(|e| anyhow::anyhow!(\"Failed to initialize torrent session: {}\", e))?\n                    }\n                    _ = cancel_rx.cancelled() => {\n                        anyhow::bail!(\"Download cancelled during session creation\");\n                    }\n                };\n                *guard = Some(s.clone());\n                *dir_guard = Some(output_dir.clone());\n                s\n            } else {\n                tracing::info!(\"[magnet] reusing existing session\");\n                guard.as_ref().unwrap().clone()\n            }\n        };\n\n        let add_torrent = if url.starts_with(\"magnet:\")\n            || url.starts_with(\"http://\")\n            || url.starts_with(\"https://\")\n        {","sourceCodeStart":135,"sourceCodeEnd":171,"githubUrl":"https://github.com/tonhowtf/omniget/blob/8600b91f4246848bac346874daa9e61c1fc5677a/src-tauri/src/platforms/magnet/mod.rs#L135-L171","documentation":"Wraps any failure from the `libtorrent` (rust libtorrent / Session) async session-creation race in `download`. The `select!` block races session construction (possibly with fallback option permutations) against the cancel channel; a non-OK result is remapped to this message with the underlying libtorrent error interpolated. It means no torrent session could be established, so the download never starts.","triggerScenarios":"`Session::new_with_opts(output_pb, make_opts(true, true))` (or its retry variants) returns Err — e.g. the output path's .pb/resume state is corrupt or unwritable, no usable network interfaces, libtorrent build/runtime mismatch, or invalid session settings.","commonSituations":"Unwritable or nonexistent download directory; corrupted libtorrent session state file from a crashed prior run; port/interface configuration that libtorrent rejects; musl/glibc mismatch in the bundled libtorrent native library.","solutions":["Read the wrapped `{}` payload — the inner libtorrent error identifies the real cause (filesystem, settings, or native library)","Verify the output directory exists and is writable; clear stale `.pb`/resume state files for this torrent","Check session options (ports, listen interfaces, encryption settings) passed via `make_opts` are valid for the environment","Ensure the libtorrent native library matches the platform/arch of the build and retry after network stack changes"],"exampleFix":"// before\nlet session = init_session(&opts).await?;\n// after\nlet session = match init_session(&opts).await {\n    Ok(s) => s,\n    Err(e) => {\n        tracing::error!(\"torrent session init failed: {e:#}\");\n        std::fs::remove_dir_all(&stale_session_state).ok();\n        init_session(&opts).await.context(\"retry after clearing session state\")?\n    }\n};","handlingStrategy":"try-catch","validationCode":"// before download: validate session prerequisites\nfn validate_torrent_env(output_dir: &std::path::Path) -> Result<(), String> {\n    if !output_dir.is_dir() { return Err(format!(\"missing dir: {}\", output_dir.display())); }\n    let probe = output_dir.join(\".write_probe\");\n    std::fs::write(&probe, b\"x\").map_err(|e| e.to_string())?;\n    std::fs::remove_file(&probe).map_err(|e| e.to_string())?;\n    Ok(())\n}","typeGuard":null,"tryCatchPattern":"match result {\n    Err(e) if e.to_string().starts_with(\"Failed to initialize torrent session\") => {\n        // e's inner payload carries the libtorrent cause\n        tracing::error!(\"session init: {e:#}\");\n        clear_stale_session_state(&output_pb);\n        retry_init_with_default_opts().await\n    }\n    other => other,\n}","preventionTips":["Verify the download directory exists and is writable before starting a torrent download","Delete stale libtorrent .pb/resume state after crashes","Pin and test the libtorrent native build per platform/arch in CI","Validate session settings (ports, listen interfaces) against the host environment at startup"],"tags":["torrent","libtorrent","session","initialization"],"backgroundTag":"module-init-failed","analyzedSha":"8600b91f4246848bac346874daa9e61c1fc5677a","analyzedAt":"2026-09-12T14:29:19.317Z","contentChangedAt":"2026-09-12T14:29:19.317Z","schemaVersion":2},"datasetVersion":"2026-09-15T23:17:13.987Z"}