{"record":{"id":"1c710c6dc9d5b6ca","repo":"tracel-ai/burn","slug":"failed-to-get-cache-directory-for-gram-matrix-loss","errorCode":null,"errorMessage":"Failed to get cache directory for Gram Matrix Loss","messagePattern":"Failed to get cache directory for Gram Matrix Loss","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/burn-vision/src/loss/gram_matrix/weights.rs","lineNumber":19,"sourceCode":"use burn_core as burn;\n\nuse super::vgg19::Vgg19;\nuse burn::tensor::Device;\nuse burn_core::network::downloader::download_file_as_bytes;\nuse burn_store::{ModuleSnapshot, PytorchStore};\nuse std::fs::{File, create_dir_all, rename};\nuse std::io::Write;\nuse std::path::PathBuf;\n\nconst VGG19_URL: &str = \"https://download.pytorch.org/models/vgg19-dcbb9e9d.pth\";\n\n/// Resolves and returns the local cache directory for the VGG19 weights.\n///\n/// Creates the directory `~/.cache/burn-pretrained-models/loss/vgg19/`\n/// (or OS equivalent) if it does not already exist.\nfn get_cache_dir() -> PathBuf {\n    let cache_dir = dirs::cache_dir()\n        .expect(\"Failed to get cache directory for Gram Matrix Loss\")\n        .join(\"burn-pretrained-models\")\n        .join(\"loss\")\n        .join(\"vgg19\");\n\n    if !cache_dir.exists() {\n        create_dir_all(&cache_dir).expect(\"Failed to create cache directory for Gram Matrix Loss\");\n    }\n\n    cache_dir\n}\n\n/// Downloads the pretrained weights to the `cache_path` if they don't exist already.\n///\n/// Requires an active internet connection on the first run. Subsequent runs will\n/// use the locally cached `.pth` file.\nfn download_weights_if_not_saved(cache_path: &PathBuf) {\n    if !cache_path.exists() {\n        let bytes = download_file_as_bytes(","sourceCodeStart":1,"sourceCodeEnd":37,"githubUrl":"https://github.com/tracel-ai/burn/blob/d16f7ba2ed0d41408189384044cc886fb4c8f957/crates/burn-vision/src/loss/gram_matrix/weights.rs#L1-L37","documentation":"`get_cache_dir` in crates/burn-vision/src/loss/gram_matrix/weights.rs:19 panics when `dirs::cache_dir()` returns None, which is how the library resolves `~/.cache/burn-pretrained-models/loss/vgg19/`. The `dirs` crate cannot determine the user cache directory, typically because the environment (HOME / XDG_CACHE_HOME on Linux) is unset or invalid. Any call chain starting at `load_vgg19_weights` will hit this before any download happens.","triggerScenarios":"Calling `load_vgg19_weights` for the Gram Matrix Loss in a process where `dirs::cache_dir()` yields None — on Linux, no HOME or XDG_CACHE_HOME in the environment; on Windows, a missing/invalid FOLDERID_LocalAppData; or a service running with a cleared environment.","commonSituations":"Systemd services or cron jobs without HOME set; Docker containers run with `--env-` cleared or as a non-root user with no passwd entry; CI runners executing as a bare service account; macOS launchd jobs lacking user context.","solutions":["Set HOME to an existing writable user directory (e.g. `export HOME=/root` or `/home/<user>`) before running the program","On Linux, set `XDG_CACHE_HOME` explicitly (e.g. `XDG_CACHE_HOME=/tmp/.cache`) as a fallback the dirs crate honors","For services, configure the unit/job file to include a valid Environment=HOME=... or use EnvironmentFile","Patch the call site to fall back to std::env::temp_dir() instead of panicking when dirs::cache_dir() is None"],"exampleFix":"// before: panics with 'Failed to get cache directory for Gram Matrix Loss'\nlet cache_dir = dirs::cache_dir()\n    .expect(\"Failed to get cache directory for Gram Matrix Loss\")\n    .join(\"burn-pretrained-models\");\n// after: fall back to a temp dir\nlet cache_dir = dirs::cache_dir()\n    .or_else(|| std::env::var_os(\"XDG_CACHE_HOME\").map(PathBuf::from))\n    .unwrap_or_else(std::env::temp_dir)\n    .join(\"burn-pretrained-models\");","handlingStrategy":"validation","validationCode":"// Verify the cache-dir environment before calling load_vgg19_weights\nfn assert_cache_dir_env() {\n    match std::env::var(\"HOME\") {\n        Ok(h) if !h.is_empty() && std::path::Path::new(&h).is_dir() => {}\n        _ => panic!(\"HOME is unset/invalid; set HOME or XDG_CACHE_HOME so dirs::cache_dir() works\"),\n    }\n}\n// or on Linux specifically:\n// std::env::var_os(\"XDG_CACHE_HOME\").or_else(|| std::env::var_os(\"HOME\"))","typeGuard":"fn has_resolvable_cache_dir() -> bool {\n    std::env::var_os(\"XDG_CACHE_HOME\")\n        .filter(|p| !p.is_empty())\n        .or_else(|| std::env::var_os(\"HOME\").filter(|p| !p.is_empty()))\n        .map(|p| std::path::PathBuf::from(p).is_dir())\n        .unwrap_or(false)\n}","tryCatchPattern":"let result = std::panic::catch_unwind(|| {\n    burn_vision::loss::gram_matrix::load_vgg19_weights(device)\n});\nif result.is_err() {\n    eprintln!(\"cache dir unresolved — set HOME/XDG_CACHE_HOME and retry\");\n}","preventionTips":["Always set HOME (and XDG_CACHE_HOME on Linux) in service, cron, and container environments","Run services under a real user account with a home directory","Set XDG_CACHE_HOME explicitly in Dockerfiles/CI to a known writable path","Smoke-test library init early at startup so env problems surface immediately"],"tags":["environment","cache","panics","configuration","burn"],"backgroundTag":"missing-env-var","analyzedSha":"d16f7ba2ed0d41408189384044cc886fb4c8f957","analyzedAt":"2026-09-05T13:19:14.260Z","contentChangedAt":"2026-09-05T13:19:14.260Z","schemaVersion":2},"datasetVersion":"2026-09-12T17:17:11.597Z"}