[Bug] saveArtifact leaves orphan files on disk when DB insert fails
Problem
Both saveArtifact and saveArtifactFromBuffer write the file to disk first, then insert the metadata row into SQLite. If the insert fails (foreign key violation, disk full, constraint error), the file stays on disk with no database row pointing to it — orphan files accumulate in the task directory over time, consuming space the user cannot reclaim through the UI.
Location
File: packages/desktop/src/main/artifact/save.ts:68-113 and 125-170
// saveArtifact
copyFileSync(sourcePath, destPath);
// ... build artifact object ...
db.insert(artifacts).values({...}).run(); // throws → orphan file
// saveArtifactFromBuffer has the same pattern:
writeFileSync(destPath, buffer);
// ...
db.insert(artifacts).values({...}).run(); // throws → orphan file
Fix Approach
- Wrap each
db.insert(...).run()call in atry/catch. - On failure, call
fs.unlinkSync(destPath)(wrapped in its own try/catch to avoid masking the original error) to remove the orphan file. - Re-throw the original DB error so the caller still sees the failure.
- Apply the same fix to both
saveArtifactandsaveArtifactFromBuffer.
Verification
- Run
pnpm check— must pass. - Unit test: mock
db.insertto throw, callsaveArtifact, assert the destination file does not exist after the call.
Context
- WG: Artifact & File System
- Priority: Low
- Estimated effort: 20-30 minutes
Hi @samzong, Thanks for opening an issue! We will look into it as soon as possible.
Details
Instructions for interacting with me using comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the gh-ci-bot repository.
I looked at this — both saveArtifact and saveArtifactFromBuffer write the file before the DB insert, so any insert failure leaves the file dangling. I can wrap the insert calls in try/catch and unlink the destination file on failure (with its own guard so it doesn't mask the original error). I'll apply the same pattern to both functions. Sending a fix if that sounds right.
The orphan file issue when db.insert fails is clear. I'd handle this by wrapping the insert in try/catch with a cleanup unlinkSync to rollback the file write on error. Can have a PR with the fix and a unit test up in a few hours. I've implemented similar atomic file+DB operations in production systems before.
The orphan file issue in saveArtifact when the DB insert fails is a clear bug. I'd fix this by wrapping the insert in a try/catch and unlinking the written file on any error, then re-throwing. I can implement this for both functions and add a corresponding unit test. I'll have a PR ready for review within a few hours.