From 9c78b47de7d04863a9e2985e0d3526c4eafa4df9 Mon Sep 17 00:00:00 2001 From: Matthew Edmondson Date: Wed, 14 Oct 2026 11:32:05 +0000 Subject: [PATCH] Time the save debounce on a monotonic clock [patch] SaveIfRequired measured the debounce as DateTime.UtcNow minus the time the save was queued. When the wall clock is set back after a queue (NTP correction, manual change, VM resume) that difference stays negative, so the queued save is held back for as long as the clock went back. QueueSave now also records Stopwatch.GetTimestamp(), and the debounce is measured from that. The pending-save state was already a flag (HasQueuedSave), so this completes the two halves the issue asked for. Fixes #324 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0157Qd7kTR3FKAkBCJVjNYAK --- AppDataStorage.Test/AppDataTests.cs | 31 +++++++++++++++++++++++++++++ AppDataStorage/AppData.cs | 16 ++++++++++++++- CLAUDE.md | 2 +- 3 files changed, 47 insertions(+), 2 deletions(-) diff --git a/AppDataStorage.Test/AppDataTests.cs b/AppDataStorage.Test/AppDataTests.cs index 0ca0a08..a5bef37 100644 --- a/AppDataStorage.Test/AppDataTests.cs +++ b/AppDataStorage.Test/AppDataTests.cs @@ -404,6 +404,37 @@ public void TestQueueSaveIsNotLostWhenTheClockHasNotAdvancedSinceTheLastSave() Assert.IsTrue(appData.IsSaveQueued(), "A save queued after the last save must be outstanding whatever the clock reads."); } + [TestMethod] + public void TestDisposeWritesAQueuedSaveWhenTheClockHasNotAdvancedSinceTheLastSave() + { + TestAppData appData = CreateTestAppDataWithContent("before"); + appData.Save(); + appData.LastSaveTime = DateTime.MaxValue; + appData.Data = "after"; + appData.QueueSave(); + + appData.Dispose(); + + TestAppData? onDisk = JsonSerializer.Deserialize(AppData.FileSystem.File.ReadAllText(appData.FilePath), AppData.JsonSerializerOptions); + Assert.AreEqual("after", onDisk?.Data, "Dispose should write the queued save whatever the clock read at the last save."); + } + + [TestMethod] + public async Task TestSaveIfRequiredSavesAfterTheDebounceWhenTheWallClockStepsBack() + { + using TestAppData appData = CreateTestAppDataWithContent(TestDataString); + appData.QueueSave(); + + // Stand in for the wall clock being set back an hour after the queue: on the wall clock the + // queue is now an hour in the future, and the time since it is negative until the hour passes. + appData.SaveQueuedTime = DateTime.UtcNow + TimeSpan.FromHours(1); + await Task.Delay(appData.SaveDebounceTime + TimeSpan.FromMilliseconds(100)).ConfigureAwait(false); + + appData.SaveIfRequired(); + + AssertFileExists(appData.FilePath, "The debounce should elapse on real time, not on a wall clock that was set back."); + } + [TestMethod] public void TestSaveClearsQueuedSave() { diff --git a/AppDataStorage/AppData.cs b/AppDataStorage/AppData.cs index d04c5a3..d793109 100644 --- a/AppDataStorage/AppData.cs +++ b/AppDataStorage/AppData.cs @@ -2,6 +2,7 @@ namespace ktsu.AppDataStorage; +using System.Diagnostics; using System.IO.Abstractions; using System.Text.Json; using System.Text.Json.Serialization; @@ -261,6 +262,7 @@ internal static AbsoluteFilePath Archive(AbsoluteFilePath filePath, string label lock (AppData.Lock) { appData.SaveQueuedTime = DateTime.UtcNow; + appData.SaveQueuedTimestamp = Stopwatch.GetTimestamp(); appData.HasQueuedSave = true; appData.EnsureDisposeOnExit(); } @@ -442,6 +444,17 @@ public static void ResetFileSystem() /// internal DateTime SaveQueuedTime { get; set; } = DateTime.MinValue; + /// + /// Gets or sets the reading taken when the save was queued. + /// + /// + /// The debounce is measured from this rather than from , because the wall + /// clock can be set back by an NTP correction, a manual change or a VM resume. Measured on the wall + /// clock, the time since the queue then stays negative, and SaveIfRequired holds the save back + /// for as long as the clock went back. The stopwatch only moves forward. + /// + internal long SaveQueuedTimestamp { get; set; } + /// /// Gets or sets a value indicating whether a save has been queued and not yet written. /// @@ -489,7 +502,8 @@ internal bool IsDoubounceTimeElapsed() { lock (Lock) { - return (DateTime.UtcNow - SaveQueuedTime) > SaveDebounceTime; + double elapsedSeconds = (double)(Stopwatch.GetTimestamp() - SaveQueuedTimestamp) / Stopwatch.Frequency; + return elapsedSeconds > SaveDebounceTime.TotalSeconds; } } diff --git a/CLAUDE.md b/CLAUDE.md index ff9d504..c13ee5d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -61,7 +61,7 @@ data.Save(); - Files stored in `%APPDATA%/{AppDomain.FriendlyName}/` as `{class_name_snake_case}.json` - Thread-safe with lock objects (uses `Lock` type on .NET 9+, `object` on earlier versions) -- Debounced saves via `QueueSave()` / `SaveIfRequired()` (3-second debounce) +- Debounced saves via `QueueSave()` / `SaveIfRequired()` (3-second debounce, timed with `Stopwatch.GetTimestamp()` so a wall-clock step back cannot hold a save back) - Whether a save is outstanding is the `HasQueuedSave` flag, set by `QueueSave()` and cleared by a successful `Save()`. It is not `SaveQueuedTime > LastSaveTime`: `DateTime.UtcNow` advances in whole microseconds on macOS, so a queue straight after a save can read the same instant and would be dropped - Automatic backup files (`.bk` suffix) with timestamped collision handling - Safe write pattern: write to `.tmp`, backup existing, move `.tmp` to final