Skip to content

fix(config): Make config.xml saves durable and recover from crash damage - #306

Open
karlkeefer wants to merge 1 commit into
GermanCoding:mainfrom
karlkeefer:fix/config-durability
Open

karlkeefer wants to merge 1 commit into
GermanCoding:mainfrom
karlkeefer:fix/config-durability

Conversation

@karlkeefer

@karlkeefer karlkeefer commented Nov 10, 2026 •

Copy link
Copy Markdown

Note

Draft: I'm testing this by running a build of this branch on the affected machine. I'll mark it ready once it has survived some real unclean shutdowns.

AI disclosure: The diagnosis, code, tests and this description were written with Claude (via Claude Code). I've reviewed them, but please review with that in mind.

Problem

After an unclean shutdown, SyncTrayzor can refuse to start: config.xml is the right length but all 0x00 (hexadecimal value 0x00 is an invalid character). The only fix is deleting it and losing the settings. This looks like the same symptom as canton7/SyncTrayzor#471.

Cause: AtomicFileStream renames config.xml.tmp over config.xml without first flushing the temp file's data to disk. NTFS saves the rename and the file size before the contents, so a crash in that window leaves a zero-filled file.

Changes

  • Durable save: AtomicFileStream.Commit() calls FlushFileBuffers before the rename. Disposing without a commit discards the temp file instead of renaming a partial one, and nothing happens on the finalizer path.
  • Narrow recovery: each save keeps the previous version as config.xml.lastgood. That copy is used only when config.xml fails to parse and looks crash-damaged (empty or containing NULs) and the backup loads fully. Typos and a missing config.xml behave exactly as before.
  • Retry fixes: saves also retry on UnauthorizedAccessException, with a ~2 s backoff. The loop no longer throws after a retry has succeeded.
  • ⚠️ Behaviour change: failed renames used to be silently ignored (a Win32 code was passed to ThrowExceptionForHR). A save that keeps failing now goes through the existing retry loop and CouldNotSaveConfigurationExeption dialog.

16 new tests; 74 pass locally.

Environment, stack trace and crash timeline
  • SyncTrayzor 2.2.0.0 (x64, installed), .NET 10.0.10
  • Syncthing v2.1.6 (go1.27.1 windows-amd64)
  • Windows 10 Pro 22H2 build 19045.7807, NTFS on NVMe SSD
SyncTrayzor.Services.Config.BadConfigurationException: Error deserializing configuration file at C:\Users\<user>\AppData\Roaming\SyncTrayzor\config.xml
 ---> System.Xml.XmlException: '.', hexadecimal value 0x00, is an invalid character. Line 1, position 1.
   at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
   at System.Xml.Linq.XDocument.Load(Stream stream, LoadOptions options)
   at SyncTrayzor.Services.Config.ConfigurationProvider.LoadFromDisk(Configuration defaultConfiguration, Boolean& hadToCreate)
   --- End of inner exception stack trace ---
   at SyncTrayzor.Services.Config.ConfigurationProvider.Initialize(Configuration defaultConfiguration)
   at SyncTrayzor.Bootstrapper.Configure()

This machine has frequent unclean shutdowns: 36 Kernel-Power 41 events in 60 days. Some are recurring 0x3B bugchecks at the same offset (likely a third-party driver I'm still tracking down), and the rest are failed resumes from sleep. That's not SyncTrayzor's fault, but it shouldn't lose its config to them.

Time (local) Event
2026-10-15 08:03:19 SyncTrayzor last wrote config.xml
2026-10-15 08:05:58 Bugcheck 0x3B / Kernel-Power 41
next start config.xml = 2,706 × 0x00
Change details

AtomicFileStream

  • Commit() does Flush(flushToDisk: true), and only a committed stream is renamed into place on Dispose.
  • If not committed, the temp file is deleted, including when base.Dispose throws.
  • Dispose(false) (the finalizer) no longer renames anything.
  • The optional backup is a flushed copy of the existing file. A failed backup is logged and doesn't fail the save.
  • MoveFileEx errors now go through GetHRForLastWin32Error() and are actually thrown.
  • IFilesystemProvider.CreateAtomic returns AtomicFileStream, so its only caller can Commit().

ConfigurationProvider

  • Recovery moves the damaged file to config.xml.damaged for diagnosis, and only after the backup has fully loaded (parsed, migrated and deserialized).
  • If the backup is missing or fails to load, the original error is rethrown and nothing is moved.
  • The existing dialog's advice ("delete config.xml and let SyncTrayzor re-create it") stays correct.
Tests (ConfigurationDurabilityTests)
  • AtomicFileStream: commit replaces the file and keeps a backup; no commit leaves the destination untouched and removes the temp file; a missing destination works; a locked backup doesn't block the write; an unreplaceable destination throws.
  • Saving: keeps .lastgood; retries until a briefly locked file is released; a persistently locked file throws CouldNotSaveConfigurationExeption and is left intact.
  • Loading:
    • recovers from a fully zeroed, half-zeroed or empty file;
    • a hand-edit typo still errors and the file is left in place;
    • damaged with no backup, or with a damaged backup, still errors;
    • a backup that parses but can't load leaves config.xml in place;
    • a missing config.xml with a backup present still starts from defaults.

Real power-loss durability can't be unit-tested; that's what the draft period on the affected machine is for.

After a crash or power loss shortly after a save, config.xml could be left
at the right length but filled with NUL bytes, and SyncTrayzor then refused
to start until the user deleted it. AtomicFileStream wrote a temp file and
renamed it over config.xml, but never flushed the temp file's data to disk
first, so the rename could reach disk before the contents did.

AtomicFileStream:
- Add Commit(), which calls FlushFileBuffers before the rename. Disposing
  without committing (e.g. serialization threw) discards the temp file
  instead of replacing config.xml with a partial one.
- Never touch the filesystem from the finalizer.
- Optionally keep a flushed, best-effort copy of the previous file.
- Actually report MoveFileEx failures: a Win32 error code was being passed
  to ThrowExceptionForHR, which ignores positive values, so failed renames
  were silently dropped.

ConfigurationProvider:
- Keep the previous config as config.xml.lastgood.
- If config.xml fails to parse and looks crash-damaged (empty or contains
  NUL bytes), and the last-good copy loads fully, recover from it and move
  the damaged file to config.xml.damaged. Hand-edit typos and a missing
  config.xml behave as before.
- Retry saves on UnauthorizedAccessException too, with a linear backoff
  (~2s total), and fix the retry loop reporting failure after a retry
  succeeded.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@karlkeefer
karlkeefer marked this pull request as ready for review November 24, 2026 08:10
@karlkeefer

Copy link
Copy Markdown
Author

Zero crashes after ~14 days - prior it was multiple times per week. I'm satisfied this patch improved the situation - so undrafted just now!

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.

1 participant