{"record":{"id":"1970f62762eca1ac","repo":"tracel-ai/burn","slug":"failed-to-rename-temporary-file-to-the-actual-vgg1","errorCode":null,"errorMessage":"Failed to rename temporary file to the actual VGG19 cache file name for Gram Matrix Loss","messagePattern":"Failed to rename temporary file to the actual VGG19 cache file name for Gram Matrix Loss","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/burn-vision/src/loss/gram_matrix/weights.rs","lineNumber":52,"sourceCode":"/// 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(\n            VGG19_URL,\n            \"Downloading VGG19 ImageNet weights for Gram Matrix Loss...\",\n        );\n\n        // Write to a temporary file. If writing gets completed, then rename to the actual/correct name.\n        // If writing is not completed, the file with the correct name (i.e. `cache_path`) will not exist\n        // so this code block can run again which is the desired behavior.\n        let temp_path = cache_path.with_extension(\"pth.tmp\");\n        let mut file = File::create(&temp_path)\n            .expect(\"Failed to create VGG19 cache file for Gram Matrix Loss\");\n        file.write_all(&bytes)\n            .expect(\"Failed to write VGG19 weights to the cache file for Gram Matrix Loss\");\n\n        rename(temp_path, cache_path)\n            .expect(\"Failed to rename temporary file to the actual VGG19 cache file name for Gram Matrix Loss\");\n    }\n}\n\n/// Loads ImageNet pretrained weights into the provided VGG19 feature extractor.\n///\n/// This function downloads the official PyTorch VGG19 weights, remaps the keys\n/// from PyTorch's `features.X` format to Burn's `convX_Y` format, and loads\n/// them into the module.\n///\n/// # Arguments\n///\n/// - `vgg19` - An initialized VGG19 module with random weights.\n///\n/// # Returns\n///\n/// The VGG19 module with pretrained ImageNet weights loaded.\npub fn load_vgg19_weights(mut vgg19: Vgg19) -> Vgg19 {\n    let cache_dir = get_cache_dir();","sourceCodeStart":34,"sourceCodeEnd":70,"githubUrl":"https://github.com/tracel-ai/burn/blob/d16f7ba2ed0d41408189384044cc886fb4c8f957/crates/burn-vision/src/loss/gram_matrix/weights.rs#L34-L70","documentation":"This panic occurs in `download_weights_if_not_saved` when the atomic rename of the freshly downloaded VGG19 weights (written to `vgg19.pth.tmp`) to its final cache path `~/.cache/burn-pretrained-models/loss/vgg19/vgg19.pth` fails. The library writes to a temp file first so that a partial download never masquerades as a complete cache; the rename is the commit step. `std::fs::rename` fails on OS-level issues such as permission problems, the temp file being removed, or the source and destination not being writable.","triggerScenarios":"Calling `load_vgg19_weights(vgg19)` (GramMatrixLoss initialization) on first run when `vgg19.pth` is not yet cached, the ~500MB download succeeds and is written to `vgg19.pth.tmp`, but `rename(temp_path, cache_path)` returns an Err (e.g. destination directory permissions changed mid-flight, temp file deleted by a concurrent cleaner, or the path is on a filesystem that disallows the operation).","commonSituations":"Running under a user whose cache dir (`~/.cache` or %LOCALAPPDATA%) is read-only; disk-full or quota situations where cleanup tools delete large .tmp files; running multiple processes concurrently that both download and one deletes the other's temp file; containers with read-only cache volumes mounted after File::create but before rename; antivirus quarantining the .tmp file.","solutions":["Check that the cache directory `~/.cache/burn-pretrained-models/loss/vgg19/` is writable by the current user and fix permissions (chmod/chown) or run with appropriate privileges.","Delete any leftover `vgg19.pth.tmp` and any partially written `vgg19.pth` in the cache dir, then retry `load_vgg19_weights`.","Verify free disk space / quota; free space if low and retry.","Avoid running multiple processes that trigger the first-time download simultaneously, or pre-seed the cache by copying a valid vgg19.pth into the cache path so the download path is skipped.","As a workaround, download https://download.pytorch.org/models/vgg19-dcbb9e9d.pth manually, place it at the cache path, and call the API again."],"exampleFix":"// before (panics on rename failure)\nlet cache_dir = dirs::cache_dir().expect(\"...\").join(\"burn-pretrained-models/loss/vgg19\");\nload_vgg19_weights(vgg19); // may panic: Failed to rename temporary file...\n\n// after (pre-seed or prepare the cache dir beforehand)\nlet cache_dir = dirs::cache_dir().unwrap().join(\"burn-pretrained-models/loss/vgg19\");\nstd::fs::create_dir_all(&cache_dir).unwrap();\nlet cache_path = cache_dir.join(\"vgg19.pth\");\nif !cache_path.exists() {\n    // ensure writable and no stale temp file blocks the rename\n    let _ = std::fs::remove_file(cache_path.with_extension(\"pth.tmp\"));\n    assert!(is_dir_writable(&cache_dir), \"cache dir not writable\");\n}\nlet vgg19 = load_vgg19_weights(vgg19);","handlingStrategy":"validation","validationCode":"// Run before calling load_vgg19_weights on first use\nuse std::path::Path;\nfn is_dir_writable(dir: &Path) -> bool {\n    let probe = dir.join(\".write_probe\");\n    match std::fs::File::create(&probe) {\n        Ok(_) => { let _ = std::fs::remove_file(&probe); true }\n        Err(_) => false,\n    }\n}\nlet cache_dir = dirs::cache_dir().unwrap().join(\"burn-pretrained-models/loss/vgg19\");\nassert!(is_dir_writable(&cache_dir), \"VGG19 cache dir not writable: {:?}\", cache_dir);\n// also clear any stale temp file that could break the rename\nlet _ = std::fs::remove_file(cache_dir.join(\"vgg19.pth.tmp\"));","typeGuard":null,"tryCatchPattern":"// load_vgg19_weights panics via expect; isolate it on a thread if you must recover\nlet result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| load_vgg19_weights(vgg19)));\nmatch result {\n    Ok(vgg) => vgg,\n    Err(_) => { /* fall back to random weights or repair the cache dir and retry */ }\n}","preventionTips":["Pre-provision the cache by placing a valid vgg19.pth at ~/.cache/burn-pretrained-models/loss/vgg19/vgg19.pth before first run (skips download+rename entirely).","In CI/containers, mount the cache dir as writable or set it via a writable HOME/XDG_CACHE_HOME.","Check free disk space before first-run downloads of large weight files.","Avoid concurrent first-time downloads from multiple processes; use a lock or pre-seeding."],"tags":["filesystem","rust","file-rename","cache","panic","network-download"],"backgroundTag":"file-rename-failed","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"}