Skip to content

fix(desktop): save files atomically to prevent data loss on crash - #4852

Merged
Jocs merged 3 commits into
developfrom
fix/3786-atomic-file-save
Jul 5, 2026
Merged

Jocs merged 3 commits into
developfrom
fix/3786-atomic-file-save

Conversation

@Jocs

@Jocs Jocs commented Jul 4, 2026

Copy link
Copy Markdown
Member

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 .md file comes back zero-filled (the #3786 reporter attached a 44393-byte file that is entirely 0x00, matching its character count).

Root cause: writeFile() in packages/desktop/src/main/filesystem/index.ts wrote straight to the destination via fs-extra outputFile, 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' own TODO(@fxha): "safeSaveDocuments" using temporary file and rename syscall. in writeMarkdownFile flagged, 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 rename it over the destination:

  • The rename is atomic on a single volume (same-directory guarantees same volume), so an interrupted write can only ever corrupt the throwaway temp file — the existing document is never truncated.
  • On failure the temp file is cleaned up and the error is re-thrown, so callers still see the failure.
  • outputFile still 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 in menu/actions/file.ts), since they all route through writeFile.

Tests

test/unit/specs/write-file-atomic.spec.ts:

  • leaves the existing file intact when the write fails partway — forces the rename step to reject and asserts the original file content survives and no temp file is left behind (RED against the old non-atomic impl, which never rejected and would have overwritten).
  • overwrites an existing file on success with no leftover temp file.
  • still recreates a missing parent directory (autosave re-creates files and folders when they are moved away #3509).

Existing write-file-missing-dir.spec.ts (#3509) stays green; pnpm typecheck and eslint pass.

)

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]>
@github-actions

github-actions Bot commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

Build artifacts for PR #4852:

Run: https://github.com/marktext/marktext/actions/runs/28726787211

Artifact Size Link
marktext-macos-x64 293.1 MB Download
marktext-windows-arm64 275.7 MB Download
marktext-linux 627.7 MB Download
marktext-windows-x64 283.9 MB Download
marktext-macos-arm64 282.7 MB Download

@Jocs

Jocs commented Jul 5, 2026

Copy link
Copy Markdown
Member Author

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 behaviors

Thanks for tackling this. The temp-file + rename change genuinely fixes the application-crash case (process killed while the OS keeps running): the target is never left truncated, because the OS still flushes the temp file's pages and the rename swaps atomically. The #3509 parent-dir behavior is preserved and the tests are honest.

But I don't think it robustly fixes the power-loss / OS-reboot case the linked issues actually describe, and the #3786 evidence points at a different root cause than the description states.

1. Missing fsync — the power-loss window is still open (this is the headline).

Neither outputFile nor rename calls fsync/fdatasync. rename(2) is atomic in the namespace (a reader sees old-or-new, never a half-written target), but it is not ordered with respect to data durability. After a power loss you can end up with the new directory entry (rename committed to the journal) pointing at an inode whose data blocks were never flushed — i.e. a full-length zero-filled file. That is exactly #3786's 44393-byte all-0x00 artifact.

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 fsync-ordering problem, not a truncate-window problem. So the reporter's own evidence points at the missing fsync, which this change doesn't add.

The durable recipe is: write temp → fsync(tempfd) → rename → fsync(dirfd). On Linux ext4 (data=ordered) a kernel heuristic flushes delayed-allocation blocks on rename-over-existing, so the window is largely masked there; it is not masked on macOS/APFS (which additionally needs fcntl(F_FULLFSYNC) for true durability), Windows/NTFS, btrfs, or network/overlay filesystems. The write-file-atomic package does exactly the fsync-then-rename dance and drops in cleanly.

(FWIW the editorBufferStore "safe pattern" cited as precedent — editorBufferStore/index.ts writeBufferStoreFile — also omits fsync, so it doesn't establish power-loss safety either; the two share the same gap.)

2. File mode / ownership / hardlinks are no longer preserved.

The old in-place outputFile truncated the existing inode, keeping its permissions, owner, macOS xattrs, and any hardlinks. rename installs a fresh inode created with the process umask, so a file that was 0600, group-shared, or hardlinked to a second path loses those properties on the next save (and a hardlinked twin keeps stale content while the saved path now points at a different inode). A stat of the original + fchmod/chown restore (what VS Code does) preserves them.

3. Windows: rename over a locked destination is a new failure mode.

On Windows, replacing an existing file via fs.rename (MoveFileEx) fails with EPERM/EBUSY when another process holds a handle to the target — antivirus, the search indexer, OneDrive/Dropbox sync, or the app's own file watcher. The old in-place write tolerated this more often, so autosave-heavy Windows users may see intermittent "save failed" where saves previously succeeded. A short retry loop around the rename (and/or documenting the tradeoff) would mitigate it.

4. Symlinked targets are replaced, not written through.

outputFile followed a final-component symlink and wrote to its target, keeping the link; rename replaces the symlink itself with a regular file. The common open→edit→save flow is mitigated because opened paths are symlink-resolved via normalizeAndResolvePath, but "Save As" onto an existing symlink (which only goes through path.resolve) detaches it. Resolving pathname with realpath before computing the temp path preserves it.

5. (minor) Temp-name collision.

The temp name is .${basename}.${pid}.${Date.now()}.tmp, but the editorBufferStore precedent deliberately appends .${++writeSequence} to avoid same-millisecond collisions. Two saves of the same path in the same process within one millisecond (e.g. autosave racing a manual save) can collide on the temp name here.


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 #3786 / #3828 (power-loss zero-fill) it needs the fsync before + after the rename, and ideally the mode/symlink preservation. Happy to help if useful.

…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]>
@Jocs

Jocs commented Jul 5, 2026

Copy link
Copy Markdown
Member Author

Reworked to delegate to write-file-atomic, as suggested. Point by point:

1. fsync — the power-loss window. Fixed. write-file-atomic fsyncs the temp fd before the rename, so the data blocks are durable before the directory entry is swapped — that closes the delayed-allocation window that produced the full-length zero-filled file. (It fsyncs the file, not the dir; a missing dir-fsync only affects whether the rename itself survives a power loss, which at worst leaves the old content, never a zero-fill.)

2. mode / owner. Preserved. write-file-atomic stats the existing target and chmod/chowns the temp to match before renaming (added a test asserting a 0600 file stays 0600 across a save). Hardlinks are not preserved — the rename still repoints the saved path at a fresh inode, so a hardlinked twin keeps the old content. That's inherent to any atomic-rename save (VS Code included); I don't think it's worth trading the durability guarantee for, but say the word if you disagree.

3. Windows locked-target rename. Not changed. write-file-atomic's rename has the same MoveFileEx semantics, and the old in-place outputFile also failed when the target couldn't be opened for write — so this isn't a new regression relative to either path. I deliberately didn't add a retry loop I can't exercise on a non-Windows machine (a new, untested branch on the save hot path is its own risk). Happy to add a bounded EPERM/EBUSY retry if you want it — I just didn't want to ship it blind.

4. symlinked "Save As". Fixed. write-file-atomic resolves realpath(filename) and renames onto the resolved target, so saving onto an existing symlink writes through it instead of replacing the link.

5. temp-name collision. Fixed. The temp name is <file>.<sha1(file, pid, threadId, ++counter)>, and it serializes concurrent writes to the same path, so two same-millisecond saves can't collide.

ensureDir keeps the #3509 missing-directory behavior. build:unpack confirms the dep externalizes cleanly; the fsync durability itself isn't unit-testable, so it rides on the library, but the observable contract (overwrite / Buffer / missing-dir / mode preservation) is covered by tests.

@github-actions

github-actions Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Website preview ready: https://pr-4852-marktext-website.ransixi.workers.dev

Built from af3e555343010346341bba4bde7e3e0db636dd87 · Worker: marktext-website · Version: a57c744b-54ab-4e0a-856c-bba23d720f4c · Alias: pr-4852

…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]>
@Jocs
Jocs merged commit 6c23b1b into develop Jul 5, 2026
18 checks passed
@Jocs
Jocs deleted the fix/3786-atomic-file-save branch July 5, 2026 02:58
Jocs added a commit that referenced this pull request Jul 5, 2026
… 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]>
Jocs added a commit that referenced this pull request Sep 23, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Lost my content 我的文本内容都丢失了 cannot open MD file correctly

1 participant