Repository navigation
fix(desktop): save files atomically to prevent data loss on crash - #4852
Conversation
) writeFile() wrote directly to the destination with fs-extra outputFile, which truncates the existing file before streaming the new content. A crash, BSOD, or power loss mid-write therefore left the user's document truncated to 0 bytes (one report attached a 44393-byte file that was entirely NUL). This is the data-loss the maintainers' own TODO in writeMarkdownFile flagged as "safeSaveDocuments". Write to a temp file in the same directory and rename it over the target instead. The rename is atomic on a single volume (guaranteed by keeping the temp file in the same directory), so an interrupted write can only corrupt the throwaway temp file, never the existing document. outputFile still recreates any missing parent directory first, preserving #3509. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Review — the atomic-rename change is a real improvement, but it doesn't yet close the power-loss window it targets, and it drops a few in-place-write behaviorsThanks for tackling this. The temp-file + But I don't think it robustly fixes the power-loss / OS-reboot case the linked issues actually describe, and the 1. Missing Neither Note the symptom carefully: a truncate-then-die-mid-write (the mechanism the description gives) produces a short / 0-byte file, not a full-length all-zeros file. A full-length zero-filled file is the classic delayed-allocation + power-loss + no-fsync signature (size/blocks committed to the journal, data never written) — an The durable recipe is: write temp → (FWIW the 2. File mode / ownership / hardlinks are no longer preserved. The old in-place 3. Windows: On Windows, replacing an existing file via 4. Symlinked targets are replaced, not written through.
5. (minor) Temp-name collision. The temp name is Net: good direction, and it does kill the app-crash truncation window and the "another reader sees a half-written file" window. But to actually close |
…3828) Addressing review: the temp-file + rename change fixed the application-crash case but not the power-loss / OS-reboot case the issues actually describe. A bare rename is namespace-atomic but not data-durable: after a power loss the new directory entry can point at an inode whose data blocks were never flushed — a full-length, zero-filled file, exactly the 44393-byte all-0x00 artifact in #3786. It also dropped the in-place write's mode/owner preservation, symlink follow-through, and unique temp naming. Delegate to write-file-atomic (fsync-before-rename), which closes the power-loss window and restores those behaviors: it stat/chmod/chowns the temp to match the target, writes through a symlink via realpath, and uses a collision-free temp name. ensureDir keeps the #3509 missing-directory behavior. Tests now cover overwrite/buffer/missing-dir and permission-mode preservation. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Reworked to delegate to 1. 2. mode / owner. Preserved. 3. Windows locked-target rename. Not changed. 4. symlinked "Save As". Fixed. 5. temp-name collision. Fixed. The temp name is
|
|
Website preview ready: https://pr-4852-marktext-website.ransixi.workers.dev Built from |
…shim @types/[email protected] declares the same public API write-file-atomic 7 exposes (its signature has been stable since v4), so drop the hand-rolled module shim for it. Every writeFile caller passes a BufferEncoding or nothing, so narrow the options parameter from WriteFileOptions to BufferEncoding — that also sidesteps the Node Mode (string | number) vs @types mode (number) mismatch cleanly. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… loss (#4864) * build(desktop): add write-file-atomic dependency Adds write-file-atomic (+ @types) for durable, atomic file writes. Used by the crash-recovery buffer store; the document save path adopts it separately in #4852. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(desktop): make crash-recovery buffer writes durable against power loss writeBufferStoreFile persists unsaved tab content (the crash-recovery buffer) with a temp-file + rename. That is namespace-atomic — safe against an application crash — but omits fsync, so a power loss / OS reboot can still commit the new directory entry while the data blocks were never flushed, leaving a truncated or full-length zero-filled buffer. This is the same gap the document save path had (#3786). Write through write-file-atomic's sync API (fsync before the atomic rename), which also removes the hand-rolled temp/rename/cleanup and the writeSequence counter (its unique temp naming is handled internally). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
…5520) * fix(desktop): retry a save whose rename an SMB share refused (#5322) On a Windows SMB share, MoveFileEx(REPLACE_EXISTING) — what fs.rename compiles to, and the last step of the atomic save — is refused with ACCESS_DENIED, surfaced as EPERM, while any handle is open on the target. MarkText's own file watcher stats the open document, so a save races its own watcher: the temp file is written, the rename over the document is rejected, and the edit is lost. Measured on a real Windows SMB share (loopback share, windows-latest): one open read handle held across every save 50/50 renames refused watcher stat storm at 1ms (~12000 stats) 102/300 refused watcher polling as the app configures it 1/200 refused no handle open at all 0/50 refused The same probes against Samba from a Linux client never fail, so this is the Windows SMB redirector's share-mode check, not a server-side one. This is a 0.19 -> 0.20 regression, and not from #4778 as the issue assumed. 0.19.x wrote the document in place with fs-extra's outputFile and never renamed, so it could not hit this. #4852 introduced the temp+rename atomic save (for #3786/#3828), which is what races; #4778 then forced usePolling for UNC paths, which raised the stat rate enough to turn an occasional lost save into a reliable one. Reverting #4778 would only push the failure back below the reporter's notice — it would not fix it, and it would leave mapped network drives (Z:\, not a UNC path, so never force-polled) failing occasionally either way. The handle is released within milliseconds, so back off and try the save again instead of dropping the edit. Retrying re-runs the whole atomic write, which is safe: write-file-atomic cleans up its temp file on failure. Three retries at 50/150/300ms take the 1ms-stat-storm failure rate from 102/300 to 3/300; at the app's real stat rate the remaining window is far smaller still. A process that holds a handle open continuously (an antivirus scanner, a sync client) is out of reach of any retry — that save still reports mt::tab-save-failure and the tab stays dirty, rather than silently losing the edit. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs: correct what the rename refusal actually depends on (#5322) A follow-up probe showed the earlier explanation was wrong on two counts: MoveFileEx(REPLACE_EXISTING) is refused for an open target on local NTFS just as on a share (50/50 either way), and asking for FILE_SHARE_DELETE makes no difference (err=5 with and without it). What separates the two is how long the handle stays open - microseconds for a local stat, a network round trip for one over SMB - so only shares lose the race in practice. The retry itself is unchanged; only the reasoning it records. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(desktop): pick retry delays that land on a different phase (#5322) The watcher stats on a fixed period, so a retry only helps if its cumulative offset lands on a phase the stat is not holding. 50/150/300 accumulates to 50/200/500 - the last two are multiples of chokidar's 100ms interval, i.e. exactly the phase that just failed, so only the first retry was ever doing anything. Simulated against both periods the app uses (100ms watchFile, 150ms awaitWriteFinish), that loses 33/57/75% of first failures once a stat holds the file for 60/70/80ms. 50/75/50 accumulates to 50/125/175 - three distinct phases - and clears every first failure up to a ~70ms stat, while finishing in 175ms instead of 500ms. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Problem
Fixes #3786, fixes #3828 (and directly addresses the long-standing #732 "File Recovery" root cause).
Multiple users report catastrophic content loss after a crash / OS-reboot mid-save: the
.mdfile comes back zero-filled (the #3786 reporter attached a 44393-byte file that is entirely0x00, matching its character count).Root cause:
writeFile()inpackages/desktop/src/main/filesystem/index.tswrote straight to the destination via fs-extraoutputFile, which opens the target with'w'— truncating it first, then streaming the new bytes. If the process dies between the truncate and the completed write, the document is left truncated/empty. This is exactly the gap the maintainers' ownTODO(@fxha): "safeSaveDocuments" using temporary file and rename syscall.inwriteMarkdownFileflagged, and the codebase already uses the safe pattern for the crash-recovery buffer (editorBufferStore/index.ts), just not for the user's markdown save path.Fix
Write the new content to a temp file in the same directory as the target, then
renameit over the destination:outputFilestill creates any missing parent directory first, preserving the autosave re-creates files and folders when they are moved away #3509 behavior (autosave into a moved/deleted folder recreates it).This is inherited by every save path (
writeMarkdownFile, Save / Save As inmenu/actions/file.ts), since they all route throughwriteFile.Tests
test/unit/specs/write-file-atomic.spec.ts:Existing
write-file-missing-dir.spec.ts(#3509) stays green;pnpm typecheckandeslintpass.