← Back to PRs

#20022: Fix temp file leak on media download failure

by Clawborn open 2026-02-18 12:06 View on GitHub →
size: XS trusted-contributor
When `downloadToFile` throws (network error, size limit exceeded, SSRF block, etc.), the `.tmp` file at `tempDest` is left on disk. While `cleanOldMedia` eventually removes stale files, repeated failures can accumulate orphaned temp files. Wrap the download-and-rename sequence in try/catch and unlink the temp file before re-throwing. <!-- greptile_comment --> <h3>Greptile Summary</h3> Wraps the download-and-rename sequence in `saveMediaSource` with a try/catch to clean up the `.tmp` file when any step fails (network error, size limit, SSRF block, mime detection failure, etc.). The silent `.catch(() => {})` on `fs.unlink` correctly handles the case where the temp file was never created. - Adds try/catch around `downloadToFile` → `detectMime` → `fs.rename` in `src/media/store.ts` - On failure, `fs.unlink(tempDest)` removes the orphaned `.tmp` file before re-throwing - No test coverage for the new cleanup path — consider adding a test that mocks a `downloadToFile` failure and verifies no `.tmp` file remains on disk <h3>Confidence Score: 5/5</h3> - This PR is safe to merge — it adds defensive cleanup logic with no change to the happy path. - The change is minimal (wrapping existing code in try/catch with a single cleanup line), the logic is correct for all failure modes, and the silent .catch on unlink correctly handles edge cases. The happy path is unchanged. No new dependencies or architectural changes. - No files require special attention. <sub>Last reviewed commit: 5357841</sub> <!-- greptile_other_comments_section --> <!-- /greptile_comment -->

Most Similar PRs