Skip to content

Free, open-source Windows optimization tool for performance, privacy, and simplicity.

fix(revert): keep a partial write undoable and stop guessing unknown state

fatDuck8da2f5722804
diff --git a/optimizerDuck.Test/Domain/Revert/Steps/HibernationRevertStepTests.cs b/optimizerDuck.Test/Domain/Revert/Steps/HibernationRevertStepTests.cs
new file mode 100644
index 0000000..40e50c0
--- /dev/null
+++ b/optimizerDuck.Test/Domain/Revert/Steps/HibernationRevertStepTests.cs
@@ -0,0 +1,62 @@
+using Microsoft.Extensions.Logging.Abstractions;
+using Newtonsoft.Json.Linq;
+using optimizerDuck.Domain.Revert.Steps;
+using optimizerDuck.Services.System.Primitives;
+using optimizerDuck.Test.TestDoubles;
+
+namespace optimizerDuck.Test.Domain.Revert.Steps;
+
+public class HibernationRevertStepTests
+{
+ [Fact]
+ public void ToData_And_FromData_RoundTripBothKnownStates()
+ {
+ foreach (var present in new[] { true, false })
+ {
+ var original = new HibernationRevertStep { WasPresent = present };
+
+ var restored = HibernationRevertStep.FromData(original.ToData());
+
+ Assert.Equal(present, restored.WasPresent);
+ }
+ }
+
+ [Fact]
+ public void FromData_PayloadWrittenBeforeTheChange_KeepsItsBoolean()
+ {
+ var payload = JObject.Parse("""{ "WasPresent": true }""");
+
+ Assert.True(HibernationRevertStep.FromData(payload).WasPresent);
+ }
+
+ [Fact]
+ public void FromData_MissingOrNullState_MeansUnknown()
+ {
+ Assert.Null(HibernationRevertStep.FromData(new JObject()).WasPresent);
+ Assert.Null(
+ HibernationRevertStep
+ .FromData(
+ new JObject
+ {
+ [nameof(HibernationRevertStep.WasPresent)] = JValue.CreateNull(),
+ }
+ )
+ .WasPresent
+ );
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_UnknownState_ChangesNothingAndSucceeds()
+ {
+ // The optimisation's own default is no longer "assume it was present": an unknown state
+ // restores nothing, so a revert cannot create a hibernation file that never existed.
+ var before = HibernationService.IsHibernationFilePresent();
+ var step = new HibernationRevertStep { WasPresent = null };
+
+ var result = await step.ExecuteAsync(TestShell.Context(), NullLogger.Instance);
+
+ Assert.True(result);
+ Assert.True(step.StateUnknown);
+ Assert.Equal(before, HibernationService.IsHibernationFilePresent());
+ }
+}
diff --git a/optimizerDuck.Test/Domain/Revert/Steps/RevertStepSerializationTests.cs b/optimizerDuck.Test/Domain/Revert/Steps/RevertStepSerializationTests.cs
index 317bf82..7b85b38 100644
--- a/optimizerDuck.Test/Domain/Revert/Steps/RevertStepSerializationTests.cs
+++ b/optimizerDuck.Test/Domain/Revert/Steps/RevertStepSerializationTests.cs
@@ -1,4 +1,4 @@
-using Microsoft.Win32;
+using Microsoft.Win32;
using Newtonsoft.Json.Linq;
using optimizerDuck.Domain.Exceptions;
using optimizerDuck.Domain.Optimizations.Models.Services;
@@ -39,12 +39,15 @@ public class RevertStepSerializationTests
}
[Fact]
- public void HibernationRevertStep_MissingFlag_DefaultsToPresent()
+ public void HibernationRevertStep_MissingFlag_MeansUnknown()
{
- // Fail-safe default shared with the optimization: restore hibernation when unknown.
+ // Deliberate reversal: the old fail-safe assumed hibernation was present, so a revert
+ // committed a hibernation file that may never have existed. Unknown now restores nothing
+ // and says so. HibernationRevertStepTests covers the three states in full.
var restored = HibernationRevertStep.FromData(new JObject());
- Assert.True(restored.WasPresent);
+ Assert.Null(restored.WasPresent);
+ Assert.True(restored.StateUnknown);
}
[Fact]
diff --git a/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs b/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
index 888910c..5c44137 100644
--- a/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
+++ b/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
@@ -9,6 +9,7 @@ using optimizerDuck.Domain.Optimizations.Models;
using optimizerDuck.Domain.Revert;
using optimizerDuck.Domain.Revert.Steps;
using optimizerDuck.Domain.UI;
+using optimizerDuck.Services.Optimization;
using optimizerDuck.Services.Revert;
using optimizerDuck.Services.System;
using optimizerDuck.Services.System.Primitives;
@@ -774,6 +775,156 @@ public class RevertIntegrityTests
Cleanup(id);
}
}
+
+ [Fact]
+ public async Task SaveRevertDataAsync_FailedChangeWithCompensation_IsStillPersisted()
+ {
+ // A step that was refused after it had already changed something still needs its
+ // previous state recorded, so the writer no longer requires a success flag.
+ var id = Guid.NewGuid();
+ var changes = new ChangeSet();
+ changes.Add(
+ "Registry",
+ "wrote a value, then the flag write was refused",
+ false,
+ new MockRevertStep(),
+ "refused"
+ );
+
+ try
+ {
+ await NewManager()
+ .SaveRevertDataAsync(
+ changes,
+ id,
+ "FailedStepTest",
+ TestContext.Current.CancellationToken
+ );
+
+ var data = await RevertManager.GetRevertDataAsync(id);
+ Assert.NotNull(data);
+ Assert.Single(data!.Steps, s => s != null);
+ }
+ finally
+ {
+ Cleanup(id);
+ }
+ }
+
+ [Fact]
+ public async Task RetryFailedSteps_PersistsEveryRecoveredCompensation()
+ {
+ var id = Guid.NewGuid();
+ var failed = new Change
+ {
+ Index = 1,
+ Name = "Step",
+ Description = "Step",
+ Ok = false,
+ Retry = call =>
+ {
+ call.Changes.Add("Registry", "first", true, new MockRevertStep());
+ call.Changes.Add("Registry", "second", true, new MockRevertStep());
+ return Task.FromResult(OpResult.Success());
+ },
+ };
+
+ try
+ {
+ var result = await OptimizationService.RetryFailedStepsWithResultsAsync(
+ [failed],
+ false,
+ NullLogger.Instance,
+ NewManager(),
+ id,
+ "RetryTest"
+ );
+
+ Assert.Empty(result.FailedSteps);
+ var data = await RevertManager.GetRevertDataAsync(id);
+ Assert.NotNull(data);
+ Assert.Equal(2, data!.Steps.Count(s => s != null));
+ }
+ finally
+ {
+ Cleanup(id);
+ }
+ }
+
+ [Fact]
+ public async Task RevertAsync_CleanupCannotTakeTheLock_ReturnsAResultWithAWarning()
+ {
+ var id = Guid.NewGuid();
+ var path = Path.Combine(Shared.RevertDirectory, id + ".json");
+ var cancellationToken = TestContext.Current.CancellationToken;
+ Directory.CreateDirectory(Shared.RevertDirectory);
+
+ // Hold the file lock so the prune after the revert cannot take it. One step succeeds and
+ // one fails, which is the case that reaches the prune instead of deleting the file.
+ var gate = RevertManager.FileLocks.GetOrAdd(id, _ => new SemaphoreSlim(1, 1));
+ await gate.WaitAsync(cancellationToken);
+ try
+ {
+ await File.WriteAllTextAsync(
+ path,
+ JsonConvert.SerializeObject(
+ new RevertData
+ {
+ SchemaVersion = 1,
+ OptimizationId = id,
+ OptimizationName = "LockTest",
+ AppliedAt = DateTime.UtcNow,
+ Steps = new RevertStepData?[]
+ {
+ new()
+ {
+ Index = 1,
+ Type = "Shell",
+ Data = new JObject
+ {
+ ["ShellType"] = "CMD",
+ ["Command"] = "exit 0",
+ },
+ },
+ new()
+ {
+ Index = 2,
+ Type = "Shell",
+ Data = new JObject
+ {
+ ["ShellType"] = "CMD",
+ ["Command"] = "exit 1",
+ },
+ },
+ },
+ }
+ ),
+ cancellationToken
+ );
+
+ var manager = new RevertManager(
+ NullLogger<RevertManager>.Instance,
+ TestShell.New(),
+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),
+ TimeProvider.System,
+ TimeSpan.FromMilliseconds(150)
+ );
+
+ var result = await manager.RevertAsync(
+ new MockOptimization(id),
+ cancellationToken: cancellationToken
+ );
+
+ Assert.True(result.CleanupFailed);
+ Assert.False(result.Success);
+ Assert.True(File.Exists(path));
+ }
+ finally
+ {
+ gate.Release();
+ Cleanup(id);
+ }
+ }
}
public class RetryableTestRevertStep : IRevertStep
diff --git a/optimizerDuck.Test/Services/OptimizationServices/ServiceProcessServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/ServiceProcessServiceTests.cs
index 6875286..79c8383 100644
--- a/optimizerDuck.Test/Services/OptimizationServices/ServiceProcessServiceTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServices/ServiceProcessServiceTests.cs
@@ -1,4 +1,4 @@
-using Microsoft.Extensions.Logging.Abstractions;
+using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Win32;
using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models.Services;
@@ -12,6 +12,22 @@ public class ServiceProcessServiceTests
private static OpCall NewCall() =>
new() { Changes = new ChangeSet(), Logger = NullLogger.Instance };
+ [Theory]
+ [InlineData(true, 5, "ChangeServiceConfig2")]
+ [InlineData(false, 5, "ChangeServiceConfig")]
+ public void BuildWriteErrorDetail_NamesTheCallThatFailed(
+ bool startTypeWritten,
+ int nativeError,
+ string expectedCall
+ )
+ {
+ // A refusal after the start type was written must not read like "nothing ran".
+ var detail = ServiceProcessService.BuildWriteErrorDetail(startTypeWritten, nativeError);
+
+ Assert.Contains(expectedCall, detail);
+ Assert.Contains(nativeError.ToString(), detail);
+ }
+
// =============================================
// Integration tests: GetStartupTypeAsync (real sc.exe)
// =============================================
diff --git a/optimizerDuck.Test/Services/OptimizationServices/UsbPowerServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/UsbPowerServiceTests.cs
index 94a41d4..cde4c62 100644
--- a/optimizerDuck.Test/Services/OptimizationServices/UsbPowerServiceTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServices/UsbPowerServiceTests.cs
@@ -1,3 +1,7 @@
+using Microsoft.Extensions.Logging.Abstractions;
+using optimizerDuck.Domain.Execution;
+using optimizerDuck.Domain.Optimizations.Categories;
+using optimizerDuck.Domain.Revert.Steps;
using optimizerDuck.Services.System;
using optimizerDuck.Services.System.Primitives;
@@ -84,4 +88,83 @@ public class UsbPowerServiceTests
Assert.True(hasPath, "the USB write query returned an instance without __PATH")
);
}
+
+ [Fact]
+ public void SelectChanges_DisableTargetsOnlyDevicesThatAreEnabled()
+ {
+ var current = new List<UsbPowerService.UsbPowerState>
+ {
+ new(@"USB\ROOT_HUB30\1", true),
+ new(@"USB\ROOT_HUB30\2", false),
+ };
+
+ var planned = UsbPowerService.SelectChanges(current, _ => false);
+
+ var only = Assert.Single(planned);
+ Assert.Equal(@"USB\ROOT_HUB30\1", only.InstanceName);
+ Assert.False(only.Enable);
+ }
+
+ [Fact]
+ public void SelectChanges_RestoreTargetsOnlyDevicesThatDiffer()
+ {
+ var current = new List<UsbPowerService.UsbPowerState>
+ {
+ new(@"USB\ROOT_HUB30\1", false),
+ new(@"USB\ROOT_HUB30\2", true),
+ };
+ var captured = new List<UsbPowerService.UsbPowerState>
+ {
+ new(@"USB\ROOT_HUB30\1", true),
+ new(@"USB\ROOT_HUB30\2", true),
+ new(@"USB\ROOT_HUB30\3", false),
+ };
+
+ var planned = UsbPowerService.SelectChanges(
+ current,
+ state => captured.FirstOrDefault(c => c.InstanceName == state.InstanceName)?.Enable
+ );
+
+ var only = Assert.Single(planned);
+ Assert.Equal(@"USB\ROOT_HUB30\1", only.InstanceName);
+ Assert.True(only.Enable);
+ }
+
+ [Fact]
+ public void SelectChanges_DeviceAlreadyInTheRequestedState_IsLeftAlone()
+ {
+ var current = new List<UsbPowerService.UsbPowerState>
+ {
+ new(@"USB\ROOT_HUB30\1", true),
+ };
+
+ Assert.Empty(UsbPowerService.SelectChanges(current, _ => true));
+ }
+
+ [Fact]
+ public void CategoryPartialWrite_RecordsTheRevertStepAndReportsTheFailure()
+ {
+ // The devices that were changed keep their recorded state, even though the outcome for
+ // the write is a failure because another device refused.
+ var call = new OpCall { Changes = new ChangeSet(), Logger = NullLogger.Instance };
+ var revertStep = new UsbPowerRevertStep
+ {
+ States =
+ [
+ new UsbPowerRevertStep.DeviceState
+ {
+ InstanceName = @"USB\ROOT_HUB30\1",
+ Enable = true,
+ },
+ ],
+ };
+ var write = new UsbPowerService.UsbPowerWriteResult(1, [@"USB\ROOT_HUB30\2"]);
+
+ var result = PowerManagement.DisableUSBPowerSaving.Apply(call, revertStep, write);
+
+ Assert.False(result.Ok);
+ var change = Assert.Single(call.Changes.Changes);
+ Assert.False(change.Ok);
+ Assert.Same(revertStep, change.Revert);
+ }
}
diff --git a/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs b/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs
index 38c9ec9..f9ce8e1 100644
--- a/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs
+++ b/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs
@@ -1,4 +1,4 @@
-using System.Collections.ObjectModel;
+using System.Collections.ObjectModel;
using System.IO;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
@@ -39,15 +39,20 @@ public class PowerManagement : LocalizedObject, IOptimizationCategory
OptimizationContext context
)
{
- // Fail-safe: when the previous state cannot be read, revert restores hibernation.
- var wasPresent = HibernationService.IsHibernationFilePresent() ?? true;
+ // An unreadable previous state is recorded as unknown, so a revert leaves the system
+ // alone instead of guessing and committing a hibernation file that never existed.
+ var wasPresent = HibernationService.IsHibernationFilePresent();
+ if (wasPresent is null)
+ context.Logger.LogWarning(
+ "Hibernation state could not be read, the recorded step will mark it unknown"
+ );
Apply(context, wasPresent);
return Task.FromResult(context.Changes.ToApplyResult());
}
- private static OpResult Apply(OpCall call, bool wasPresent)
+ internal static OpResult Apply(OpCall call, bool? wasPresent)
{
var result = HibernationService.SetHibernationFile(present: false);
var revert = new HibernationRevertStep { WasPresent = wasPresent };
@@ -62,7 +67,7 @@ public class PowerManagement : LocalizedObject, IOptimizationCategory
);
call.Logger.LogInformation(
"Disabled hibernation and Fast Startup. Previous state: {State}",
- wasPresent ? "Enabled" : "Disabled"
+ wasPresent is { } present ? present ? "Enabled" : "Disabled" : "Unknown"
);
return OpResult.Success(revert);
}
@@ -127,7 +132,7 @@ public class PowerManagement : LocalizedObject, IOptimizationCategory
return Task.FromResult(context.Changes.ToApplyResult());
}
- private static OpResult Apply(
+ internal static OpResult Apply(
OpCall call,
UsbPowerRevertStep revertStep,
UsbPowerService.UsbPowerWriteResult? result
@@ -138,6 +143,30 @@ public class PowerManagement : LocalizedObject, IOptimizationCategory
revertStep.States.Count
);
+ // Some devices refusing still leaves the others changed, so the recorded step keeps
+ // their previous state and the failure names the devices that refused.
+ if (result is { FailedDevices.Count: > 0 })
+ {
+ var detail = string.Join(", ", result.FailedDevices);
+ call.Logger.LogWarning(
+ "[USB][PARTIAL] {Count} device(s) changed, {Failed} refused: {Detail}",
+ result.ChangedCount,
+ result.FailedDevices.Count,
+ detail
+ );
+ call.Changes.Add(
+ ServiceStrings.UsbPowerName,
+ description,
+ false,
+ revertStep,
+ ServiceStrings.UsbPowerErrorChangeFailed,
+ detail,
+ retryCall =>
+ Task.FromResult(Apply(retryCall, revertStep, UsbPowerService.Disable()))
+ );
+ return OpResult.Fail(ServiceStrings.UsbPowerErrorChangeFailed, detail);
+ }
+
if (result is not null)
{
call.Changes.Add(ServiceStrings.UsbPowerName, description, true, revertStep);
diff --git a/optimizerDuck/Domain/Revert/RevertResult.cs b/optimizerDuck/Domain/Revert/RevertResult.cs
index 5eeb4e5..146d680 100644
--- a/optimizerDuck/Domain/Revert/RevertResult.cs
+++ b/optimizerDuck/Domain/Revert/RevertResult.cs
@@ -28,4 +28,11 @@ public class RevertResult
/// (that is, all individual steps failed).
/// </summary>
public bool AllStepsFailed { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value that indicates whether the steps ran but the revert data could
+ /// not be cleaned up, for example because the file lock timed out. The leftover file is
+ /// retried on the next revert.
+ /// </summary>
+ public bool CleanupFailed { get; set; }
}
diff --git a/optimizerDuck/Domain/Revert/Steps/HibernationRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/HibernationRevertStep.cs
index 4066ee6..5caceee 100644
--- a/optimizerDuck/Domain/Revert/Steps/HibernationRevertStep.cs
+++ b/optimizerDuck/Domain/Revert/Steps/HibernationRevertStep.cs
@@ -1,4 +1,4 @@
-using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Exceptions;
@@ -15,21 +15,36 @@ namespace optimizerDuck.Domain.Revert.Steps;
public class HibernationRevertStep : IRevertStep
{
/// <summary>
- /// Gets or sets a value that indicates whether the hibernation file existed before the
- /// change, so reverting commits it back.
+ /// Gets or sets whether the hibernation file existed before the change. Null means the
+ /// state could not be read, so there is nothing to restore and a revert leaves the
+ /// system alone instead of guessing and creating a multi gigabyte file.
/// </summary>
- public bool WasPresent { get; set; }
+ public bool? WasPresent { get; set; }
+
+ /// <summary>Whether the state could not be read when the change was applied.</summary>
+ public bool StateUnknown => WasPresent is null;
/// <inheritdoc />
public string Type => "Hibernation";
/// <inheritdoc />
- public string Description => Loc.Instance["Revert.Hibernation.Description"];
+ public string Description =>
+ StateUnknown
+ ? Loc.Instance["Revert.Hibernation.Description.Unknown"]
+ : Loc.Instance["Revert.Hibernation.Description"];
/// <inheritdoc />
public Task<bool> ExecuteAsync(RevertContext context, ILogger logger)
{
- var result = HibernationService.SetHibernationFile(WasPresent);
+ if (WasPresent is not { } present)
+ {
+ logger.LogWarning(
+ "[HIBERNATION][REVERT][SKIP] the previous state was unknown, nothing restored"
+ );
+ return Task.FromResult(true);
+ }
+
+ var result = HibernationService.SetHibernationFile(present);
if (!result.Succeeded)
{
@@ -52,18 +67,24 @@ public class HibernationRevertStep : IRevertStep
/// <inheritdoc />
public JObject ToData()
{
- return new JObject { [nameof(WasPresent)] = WasPresent };
+ return new JObject
+ {
+ [nameof(WasPresent)] = WasPresent is { } present ? new JValue(present) : JValue.CreateNull(),
+ };
}
/// <summary>
- /// Deserializes a <see cref="HibernationRevertStep" /> from JSON data. Defaults to
- /// "was present" when the flag is missing, matching the optimization's fail-safe default.
+ /// Deserializes a <see cref="HibernationRevertStep" /> from JSON data. Files written
+ /// before this change always carry a boolean; a missing or null value means the state was
+ /// not known, which restores nothing.
/// </summary>
public static HibernationRevertStep FromData(JObject data)
{
+ var token = data[nameof(WasPresent)];
return new HibernationRevertStep
{
- WasPresent = data[nameof(WasPresent)]?.Value<bool>() ?? true,
+ WasPresent =
+ token is null || token.Type == JTokenType.Null ? null : token.Value<bool>(),
};
}
}
diff --git a/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.cs
index 4565a9d..65bbf5e 100644
--- a/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.cs
+++ b/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.cs
@@ -1,4 +1,4 @@
-using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Exceptions;
@@ -54,12 +54,16 @@ public class UsbPowerRevertStep : IRevertStep
var result = UsbPowerService.Restore(captured);
- if (result is null)
+ if (result is null || result.FailedDevices.Count > 0)
{
- logger.LogWarning("[USB][REVERT][FAIL] WMI restore refused or unavailable");
+ var detail = result is null ? string.Empty : string.Join(", ", result.FailedDevices);
+ logger.LogWarning(
+ "[USB][REVERT][FAIL] WMI restore refused or unavailable for {Detail}",
+ detail
+ );
throw new StepExecutionException(
Loc.Instance["Revert.UsbPower.Error.RestoreFailed"],
- string.Empty
+ detail
);
}
diff --git a/optimizerDuck/Resources/Languages/Translations.ar-SA.resx b/optimizerDuck/Resources/Languages/Translations.ar-SA.resx
index 734c550..2a988ad 100644
--- a/optimizerDuck/Resources/Languages/Translations.ar-SA.resx
+++ b/optimizerDuck/Resources/Languages/Translations.ar-SA.resx
@@ -2267,5 +2267,8 @@
<data name="Revert.Error.UnreadableData" xml:space="preserve">
<value>تعذّرت قراءة بيانات التراجع الخاصة بـ {0}، لذلك لم يتم التراجع عن أي شيء. تم الاحتفاظ بالملف في {1}.</value>
</data>
+ <data name="Revert.Hibernation.Description.Unknown" xml:space="preserve">
+ <value>كانت حالة الإسبات غير معروفة عند تطبيق هذا، لذلك لا شيء يُستعاد</value>
+ </data>
</root>
diff --git a/optimizerDuck/Resources/Languages/Translations.de-DE.resx b/optimizerDuck/Resources/Languages/Translations.de-DE.resx
index 6e7b27d..0a119b3 100644
--- a/optimizerDuck/Resources/Languages/Translations.de-DE.resx
+++ b/optimizerDuck/Resources/Languages/Translations.de-DE.resx
@@ -2277,4 +2277,7 @@ Aktualisiere jetzt, um die neuesten Funktionen, Verbesserungen und Fehlerbehebun
<data name="Revert.Error.UnreadableData" xml:space="preserve">
<value>Die Wiederherstellungsdaten für {0} konnten nicht gelesen werden, es wurde also nichts zurückgesetzt. Die Datei bleibt unter {1} erhalten.</value>
</data>
+ <data name="Revert.Hibernation.Description.Unknown" xml:space="preserve">
+ <value>Der Ruhezustand war beim Anwenden unbekannt, es wird also nichts wiederhergestellt</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.es-ES.resx b/optimizerDuck/Resources/Languages/Translations.es-ES.resx
index 23a85ee..39f99ed 100644
--- a/optimizerDuck/Resources/Languages/Translations.es-ES.resx
+++ b/optimizerDuck/Resources/Languages/Translations.es-ES.resx
@@ -4030,4 +4030,7 @@ Actualiza ahora para disfrutar de las nuevas funciones y mejoras.</value>
<data name="Revert.Error.UnreadableData" xml:space="preserve">
<value>No se pudieron leer los datos de reversión de {0}, así que no se revirtió nada. El archivo se conservó en {1}.</value>
</data>
+ <data name="Revert.Hibernation.Description.Unknown" xml:space="preserve">
+ <value>El estado de hibernación era desconocido al aplicar esto, así que no se restaura nada</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.fr-FR.resx b/optimizerDuck/Resources/Languages/Translations.fr-FR.resx
index 0590c8f..ca72256 100644
--- a/optimizerDuck/Resources/Languages/Translations.fr-FR.resx
+++ b/optimizerDuck/Resources/Languages/Translations.fr-FR.resx
@@ -2225,4 +2225,7 @@ Mettez à jour maintenant pour profiter des dernières fonctionnalités, amélio
<data name="Revert.Error.UnreadableData" xml:space="preserve">
<value>Les données de restauration de {0} n'ont pas pu être lues, rien n'a donc été restauré. Le fichier a été conservé dans {1}.</value>
</data>
+ <data name="Revert.Hibernation.Description.Unknown" xml:space="preserve">
+ <value>L'état de veille prolongée était inconnu lors de l'application, rien n'est donc restauré</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.he-IL.resx b/optimizerDuck/Resources/Languages/Translations.he-IL.resx
index 4c20ee3..4c80925 100644
--- a/optimizerDuck/Resources/Languages/Translations.he-IL.resx
+++ b/optimizerDuck/Resources/Languages/Translations.he-IL.resx
@@ -2282,4 +2282,7 @@
<data name="Revert.Error.UnreadableData" xml:space="preserve">
<value>לא ניתן היה לקרוא את נתוני השחזור של {0}, ולכן דבר לא שוחזר. הקובץ נשמר במיקום {1}.</value>
</data>
+ <data name="Revert.Hibernation.Description.Unknown" xml:space="preserve">
+ <value>מצב השינה היה לא ידוע בעת ההחלה, ולכן דבר לא משוחזר</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.id-ID.resx b/optimizerDuck/Resources/Languages/Translations.id-ID.resx
index 90d7e06..a5fb056 100644
--- a/optimizerDuck/Resources/Languages/Translations.id-ID.resx
+++ b/optimizerDuck/Resources/Languages/Translations.id-ID.resx
@@ -2282,4 +2282,7 @@ Perbarui sekarang untuk menikmati fitur terbaru, peningkatan, dan perbaikan bug.
<data name="Revert.Error.UnreadableData" xml:space="preserve">
<value>Data pemulihan untuk {0} tidak dapat dibaca, jadi tidak ada yang dipulihkan. File tetap disimpan di {1}.</value>
</data>
+ <data name="Revert.Hibernation.Description.Unknown" xml:space="preserve">
+ <value>Status hibernasi tidak diketahui saat ini diterapkan, jadi tidak ada yang dipulihkan</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.it-IT.resx b/optimizerDuck/Resources/Languages/Translations.it-IT.resx
index e7c3f22..ad0a061 100644
--- a/optimizerDuck/Resources/Languages/Translations.it-IT.resx
+++ b/optimizerDuck/Resources/Languages/Translations.it-IT.resx
@@ -2233,4 +2233,7 @@ Aggiorna ora per godere delle ultime funzionalità, miglioramenti e correzioni.<
<data name="Revert.Error.UnreadableData" xml:space="preserve">
<value>Non è stato possibile leggere i dati di ripristino di {0}, quindi non è stato ripristinato nulla. Il file è stato conservato in {1}.</value>
</data>
+ <data name="Revert.Hibernation.Description.Unknown" xml:space="preserve">
+ <value>Lo stato di ibernazione era sconosciuto al momento dell'applicazione, quindi non viene ripristinato nulla</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.ja-JP.resx b/optimizerDuck/Resources/Languages/Translations.ja-JP.resx
index 893c62a..8c5a37c 100644
--- a/optimizerDuck/Resources/Languages/Translations.ja-JP.resx
+++ b/optimizerDuck/Resources/Languages/Translations.ja-JP.resx
@@ -2217,4 +2217,7 @@
<data name="Revert.Error.UnreadableData" xml:space="preserve">
<value>{0} の復元データを読み取れなかったため、何も復元していません。ファイルは {1} にそのまま残しています。</value>
</data>
+ <data name="Revert.Hibernation.Description.Unknown" xml:space="preserve">
+ <value>適用時の休止状態が不明だったため、復元する内容はありません</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.ko-KR.resx b/optimizerDuck/Resources/Languages/Translations.ko-KR.resx
index edc7514..e90311b 100644
--- a/optimizerDuck/Resources/Languages/Translations.ko-KR.resx
+++ b/optimizerDuck/Resources/Languages/Translations.ko-KR.resx
@@ -2216,4 +2216,7 @@
<data name="Revert.Error.UnreadableData" xml:space="preserve">
<value>{0}의 복원 데이터를 읽을 수 없어 아무것도 복원하지 않았습니다. 파일은 {1}에 그대로 보관했습니다.</value>
</data>
+ <data name="Revert.Hibernation.Description.Unknown" xml:space="preserve">
+ <value>적용할 때 최대 절전 상태를 알 수 없었으므로 복원할 내용이 없습니다</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.pl-PL.resx b/optimizerDuck/Resources/Languages/Translations.pl-PL.resx
index 9633e7e..449f4a9 100644
--- a/optimizerDuck/Resources/Languages/Translations.pl-PL.resx
+++ b/optimizerDuck/Resources/Languages/Translations.pl-PL.resx
@@ -2225,4 +2225,7 @@ Zaktualizuj teraz, aby korzystać z najnowszych funkcji, ulepszeń i poprawek b
<data name="Revert.Error.UnreadableData" xml:space="preserve">
<value>Nie można odczytać danych przywracania dla {0}, więc nic nie przywrócono. Plik zachowano w {1}.</value>
</data>
+ <data name="Revert.Hibernation.Description.Unknown" xml:space="preserve">
+ <value>Stan hibernacji był nieznany w momencie zastosowania, więc nic nie zostanie przywrócone</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.pt-BR.resx b/optimizerDuck/Resources/Languages/Translations.pt-BR.resx
index 8c0749a..3db2b69 100644
--- a/optimizerDuck/Resources/Languages/Translations.pt-BR.resx
+++ b/optimizerDuck/Resources/Languages/Translations.pt-BR.resx
@@ -2225,4 +2225,7 @@ Atualize agora para desfrutar das últimas funcionalidades, melhorias e correç
<data name="Revert.Error.UnreadableData" xml:space="preserve">
<value>Não foi possível ler os dados de reversão de {0}, então nada foi revertido. O arquivo foi mantido em {1}.</value>
</data>
+ <data name="Revert.Hibernation.Description.Unknown" xml:space="preserve">
+ <value>O estado de hibernação era desconhecido quando isto foi aplicado, então nada é restaurado</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.resx b/optimizerDuck/Resources/Languages/Translations.resx
index 9be952c..224730e 100644
--- a/optimizerDuck/Resources/Languages/Translations.resx
+++ b/optimizerDuck/Resources/Languages/Translations.resx
@@ -2283,4 +2283,7 @@ Update now to enjoy the latest features, improvements, and bug fixes.</value>
<data name="Revert.Error.UnreadableData" xml:space="preserve">
<value>Revert data for {0} could not be read, so nothing was reverted. The file was kept at {1}.</value>
</data>
+ <data name="Revert.Hibernation.Description.Unknown" xml:space="preserve">
+ <value>Hibernation state was unknown when this was applied, so nothing is restored</value>
+ </data>
</root>
diff --git a/optimizerDuck/Resources/Languages/Translations.ru-RU.resx b/optimizerDuck/Resources/Languages/Translations.ru-RU.resx
index 02f0a44..09eda27 100644
--- a/optimizerDuck/Resources/Languages/Translations.ru-RU.resx
+++ b/optimizerDuck/Resources/Languages/Translations.ru-RU.resx
@@ -2225,4 +2225,7 @@
<data name="Revert.Error.UnreadableData" xml:space="preserve">
<value>Не удалось прочитать данные восстановления для {0}, поэтому ничего не восстановлено. Файл сохранён в {1}.</value>
</data>
+ <data name="Revert.Hibernation.Description.Unknown" xml:space="preserve">
+ <value>Состояние спящего режима было неизвестно при применении, поэтому ничего не восстанавливается</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.tr-TR.resx b/optimizerDuck/Resources/Languages/Translations.tr-TR.resx
index 3411bb0..1629545 100644
--- a/optimizerDuck/Resources/Languages/Translations.tr-TR.resx
+++ b/optimizerDuck/Resources/Languages/Translations.tr-TR.resx
@@ -2216,4 +2216,7 @@ En son özelliklerden, iyileştirmelerden ve hata düzeltmelerinden yararlanmak
<data name="Revert.Error.UnreadableData" xml:space="preserve">
<value>{0} için geri alma verileri okunamadı, bu nedenle hiçbir şey geri alınmadı. Dosya {1} konumunda saklandı.</value>
</data>
+ <data name="Revert.Hibernation.Description.Unknown" xml:space="preserve">
+ <value>Bu uygulandığında hazırda bekletme durumu bilinmiyordu, bu nedenle hiçbir şey geri yüklenmez</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.vi-VN.resx b/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
index 3f526f6..e2a53af 100644
--- a/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
+++ b/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
@@ -2217,4 +2217,7 @@ Cập nhật ngay để trải nghiệm các tính năng mới, cải tiến và
<data name="Revert.Error.UnreadableData" xml:space="preserve">
<value>Không đọc được dữ liệu hoàn tác của {0}, nên chưa hoàn tác gì. Tệp vẫn được giữ tại {1}.</value>
</data>
+ <data name="Revert.Hibernation.Description.Unknown" xml:space="preserve">
+ <value>Không xác định được trạng thái hibernation khi áp dụng, nên không có gì để khôi phục</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.zh-CN.resx b/optimizerDuck/Resources/Languages/Translations.zh-CN.resx
index 1988c62..13907cd 100644
--- a/optimizerDuck/Resources/Languages/Translations.zh-CN.resx
+++ b/optimizerDuck/Resources/Languages/Translations.zh-CN.resx
@@ -2233,4 +2233,7 @@
<data name="Revert.Error.UnreadableData" xml:space="preserve">
<value>无法读取 {0} 的还原数据,因此未还原任何内容。文件保留在 {1}。</value>
</data>
+ <data name="Revert.Hibernation.Description.Unknown" xml:space="preserve">
+ <value>应用时 hibernation 状态未知,因此不会还原任何内容</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Resources/Languages/Translations.zh-TW.resx b/optimizerDuck/Resources/Languages/Translations.zh-TW.resx
index eb3956b..b006e49 100644
--- a/optimizerDuck/Resources/Languages/Translations.zh-TW.resx
+++ b/optimizerDuck/Resources/Languages/Translations.zh-TW.resx
@@ -2220,4 +2220,7 @@
<data name="Revert.Error.UnreadableData" xml:space="preserve">
<value>無法讀取 {0} 的還原資料,因此未還原任何內容。檔案保留在 {1}。</value>
</data>
+ <data name="Revert.Hibernation.Description.Unknown" xml:space="preserve">
+ <value>套用時 hibernation 狀態未知,因此不會還原任何內容</value>
+ </data>
</root>
\ No newline at end of file
diff --git a/optimizerDuck/Services/Optimization/OptimizationService.cs b/optimizerDuck/Services/Optimization/OptimizationService.cs
index ac03196..932756b 100644
--- a/optimizerDuck/Services/Optimization/OptimizationService.cs
+++ b/optimizerDuck/Services/Optimization/OptimizationService.cs
@@ -507,8 +507,8 @@ public class OptimizationService(
Exception? error = null;
try
{
- // Fresh call: retry is user-initiated, the original token may be dead.
- // Captured changes merge back into the apply set (first backup wins).
+ // Fresh call: retry is user-initiated, the original token may be dead. Whatever
+ // the retry records is appended to the revert data below, in the order it ran.
var retryChanges = new ChangeSet();
var retryCall = new OpCall { Changes = retryChanges, Logger = logger };
var retryOutcome = await step.Retry(retryCall).ConfigureAwait(false);
@@ -516,7 +516,8 @@ public class OptimizationService(
if (success)
{
- var capturedStep = retryChanges.SuccessfulSteps.LastOrDefault();
+ var capturedSteps = retryChanges.SuccessfulSteps;
+ var capturedStep = capturedSteps.LastOrDefault();
var capturedRevert = capturedStep?.Revert ?? retryOutcome.Revert;
var recoveredStep = new Change
{
@@ -527,30 +528,38 @@ public class OptimizationService(
Revert = capturedRevert,
};
- // Auto-persist recovered revert step if revertManager is available
- if (
- recoveredStep.Revert != null
- && revertManager != null
- && optimizationId.HasValue
- )
+ // A retry can recover more than one step, and each one carries the backup
+ // that makes it undoable, so all of them are persisted in the order they ran.
+ // Appending keeps the last in first out revert correct.
+ if (revertManager != null && optimizationId.HasValue)
{
- try
+ var compensations = capturedSteps
+ .Where(c => c.Revert != null)
+ .Select(c => c.Revert!)
+ .ToList();
+ if (compensations.Count == 0 && recoveredStep.Revert != null)
+ compensations.Add(recoveredStep.Revert);
+
+ foreach (var compensation in compensations)
{
- await revertManager
- .AppendRevertStepAsync(
- optimizationId.Value,
- optimizationKey ?? string.Empty,
- recoveredStep.Revert
- )
- .ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- logger.LogError(
- ex,
- "Failed to auto-persist recovered revert step for {Index}",
- step.Index
- );
+ try
+ {
+ await revertManager
+ .AppendRevertStepAsync(
+ optimizationId.Value,
+ optimizationKey ?? string.Empty,
+ compensation
+ )
+ .ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ logger.LogError(
+ ex,
+ "Failed to auto-persist recovered revert step for {Index}",
+ step.Index
+ );
+ }
}
}
diff --git a/optimizerDuck/Services/Revert/RevertManager.cs b/optimizerDuck/Services/Revert/RevertManager.cs
index 25403d5..5c5cce4 100644
--- a/optimizerDuck/Services/Revert/RevertManager.cs
+++ b/optimizerDuck/Services/Revert/RevertManager.cs
@@ -32,7 +32,23 @@ public class RevertManager(
private static readonly Lazy<Dictionary<string, Func<JObject, IRevertStep>>> _stepRegistry =
new(BuildStepRegistry);
- private static readonly ConcurrentDictionary<Guid, SemaphoreSlim> _fileLocks = new();
+ /// <summary>Per item file locks. Visible to the test assembly so a stuck lock can be simulated.</summary>
+ internal static readonly ConcurrentDictionary<Guid, SemaphoreSlim> FileLocks = new();
+
+ private readonly TimeSpan _fileLockTimeout = TimeSpan.FromSeconds(FileLockTimeoutSeconds);
+
+ /// <summary>Test seam: the same manager with a shorter file lock timeout.</summary>
+ internal RevertManager(
+ ILogger<RevertManager> logger,
+ ShellService shell,
+ PowerPlanService powerPlans,
+ TimeProvider time,
+ TimeSpan fileLockTimeout
+ )
+ : this(logger, shell, powerPlans, time)
+ {
+ _fileLockTimeout = fileLockTimeout;
+ }
/// <summary>
/// Persists revert steps from a <see cref="ChangeSet"/>. Appends every successful change as a new entry with a fresh index. No payload-based dedupe: two executions of the same command are two real executions; dropping either loses revert coverage.
@@ -45,8 +61,11 @@ public class RevertManager(
CancellationToken cancellationToken = default
)
{
+ // Compensation is persisted whenever it exists, whether the step reported success or a
+ // partial failure: a step that was refused after it had already changed something still
+ // needs its previous state recorded.
var incoming = changes
- .Changes.Where(c => c.Ok && c.Revert != null)
+ .Changes.Where(c => c.Revert != null)
.OrderBy(c => c.Index)
.ToList();
@@ -157,6 +176,7 @@ public class RevertManager(
}
var failedSteps = new List<Change>();
+ var cleanupFailed = false;
var sortedSteps = steps.OrderByDescending(s => s.Index).ToList();
var total = sortedSteps.Count;
@@ -242,13 +262,27 @@ public class RevertManager(
.ToList();
// CancellationToken.None: the prune must run to completion, otherwise the
// file would list steps that already reverted successfully.
- await RemoveRevertStepsAtIndexesAsync(
- optimization.Id,
- optimization.OptimizationKey,
- succeededIndexes,
- CancellationToken.None
- )
- .ConfigureAwait(false);
+ try
+ {
+ await RemoveRevertStepsAtIndexesAsync(
+ optimization.Id,
+ optimization.OptimizationKey,
+ succeededIndexes,
+ CancellationToken.None
+ )
+ .ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ // The steps themselves reverted, so the caller still gets a result. Only the
+ // cleanup of the data they came from failed, and a leftover file is retried.
+ _logger.LogError(
+ ex,
+ "Revert data for {Name} could not be cleaned up",
+ optimization.OptimizationKey
+ );
+ cleanupFailed = true;
+ }
}
return new RevertResult
@@ -266,6 +300,7 @@ public class RevertManager(
]
: Loc.Instance["Optimization.Revert.Success", optimization.Name],
FailedSteps = failedSteps,
+ CleanupFailed = cleanupFailed,
};
}
@@ -681,14 +716,10 @@ public class RevertManager(
}
}
- private static async Task<SemaphoreSlim> AcquireFileLockAsync(Guid id)
+ private async Task<SemaphoreSlim> AcquireFileLockAsync(Guid id)
{
- var lockObj = _fileLocks.GetOrAdd(id, _ => new SemaphoreSlim(1, 1));
- if (
- !await lockObj
- .WaitAsync(TimeSpan.FromSeconds(FileLockTimeoutSeconds))
- .ConfigureAwait(false)
- )
+ var lockObj = FileLocks.GetOrAdd(id, _ => new SemaphoreSlim(1, 1));
+ if (!await lockObj.WaitAsync(_fileLockTimeout).ConfigureAwait(false))
throw new TimeoutException(
string.Format("Timed out waiting for revert file lock ({0}).", id)
);
diff --git a/optimizerDuck/Services/System/Primitives/ServiceProcessService.cs b/optimizerDuck/Services/System/Primitives/ServiceProcessService.cs
index 33b2cdd..cb0b843 100644
--- a/optimizerDuck/Services/System/Primitives/ServiceProcessService.cs
+++ b/optimizerDuck/Services/System/Primitives/ServiceProcessService.cs
@@ -115,14 +115,15 @@ public static class ServiceProcessService
return MapToOpResult(ServiceChangeResult.AlreadyConfigured, null, null, null);
}
- var nativeError = SetStartupType(item.Name, item.StartupType);
+ var write = SetStartupType(item.Name, item.StartupType);
+ var nativeError = write.Error;
var success = nativeError == 0;
sw.Stop();
string? errorDetail = null;
if (!success)
- errorDetail = $"ChangeServiceConfig failed with Win32 error {nativeError}";
+ errorDetail = BuildWriteErrorDetail(write.StartTypeWritten, nativeError);
if (success)
{
@@ -165,6 +166,17 @@ public static class ServiceProcessService
);
}
+ // A delayed auto start flag that Windows refuses still leaves the start type
+ // written, so the recorded step carries the previous one and a revert can put it
+ // back even though the outcome is a failure.
+ ServiceRevertStep? partialRevert = null;
+ if (write.StartTypeWritten)
+ partialRevert = new ServiceRevertStep
+ {
+ ServiceName = item.Name,
+ OriginalStartupType = originalStartupType.Value,
+ };
+
var error = $"{ServiceStrings.ServiceErrorChangeStartupTypeFailed} '{item.Name}'";
call.Logger.LogInformation(
"[SERVICE][{Name}][FAIL][D={Duration}] startup -> {StartupType}",
@@ -176,12 +188,12 @@ public static class ServiceProcessService
ServiceStrings.ServiceName,
description,
false,
- null,
+ partialRevert,
error,
errorDetail,
retryCall => ChangeServiceStartupTypeAsync(retryCall, item)
);
- return MapToOpResult(ServiceChangeResult.Failed, null, error, errorDetail);
+ return MapToOpResult(ServiceChangeResult.Failed, partialRevert, error, errorDetail);
}
catch (Exception ex)
{
@@ -354,10 +366,24 @@ public static class ServiceProcessService
}
/// <summary>
- /// Writes the start type, then the delayed flag for auto-start targets. Returns a Win32
- /// error code (0 on success).
+ /// Outcome of a start type write: the Win32 error, and whether the start type itself was
+ /// written before a later call was refused.
+ /// </summary>
+ private readonly record struct StartTypeWrite(int Error, bool StartTypeWritten);
+
+ /// <summary>
+ /// Describes which call failed, so a partial write is never mistaken for "nothing ran".
+ /// </summary>
+ internal static string BuildWriteErrorDetail(bool startTypeWritten, int nativeError) =>
+ startTypeWritten
+ ? $"ChangeServiceConfig2 (delayed auto start) failed with Win32 error {nativeError}, after the start type was written"
+ : $"ChangeServiceConfig failed with Win32 error {nativeError}";
+
+ /// <summary>
+ /// Writes the start type, then the delayed flag for auto-start targets. Returns the Win32
+ /// error and whether the start type was written before the refusal.
/// </summary>
- private static int SetStartupType(string serviceName, ServiceStartupType startupType)
+ private static StartTypeWrite SetStartupType(string serviceName, ServiceStartupType startupType)
{
var desiredStart = startupType switch
{
@@ -370,7 +396,7 @@ public static class ServiceProcessService
var manager = OpenSCManager(null, null, ScManagerConnect);
if (manager == IntPtr.Zero)
- return Marshal.GetLastWin32Error();
+ return new StartTypeWrite(Marshal.GetLastWin32Error(), false);
try
{
@@ -380,7 +406,7 @@ public static class ServiceProcessService
ServiceQueryConfig | ServiceChangeConfig
);
if (service == IntPtr.Zero)
- return Marshal.GetLastWin32Error();
+ return new StartTypeWrite(Marshal.GetLastWin32Error(), false);
try
{
@@ -399,7 +425,7 @@ public static class ServiceProcessService
null
)
)
- return Marshal.GetLastWin32Error();
+ return new StartTypeWrite(Marshal.GetLastWin32Error(), false);
// The flag is ignored for non-auto-start services, and leaving a previous "delayed"
// flag behind would keep reporting the old state, so it is always written for
@@ -412,10 +438,11 @@ public static class ServiceProcessService
};
if (!ChangeServiceConfig2(service, ServiceConfigDelayedAutoStartInfo, ref info))
- return Marshal.GetLastWin32Error();
+ // The start type is already written at this point.
+ return new StartTypeWrite(Marshal.GetLastWin32Error(), true);
}
- return 0;
+ return new StartTypeWrite(0, true);
}
finally
{
diff --git a/optimizerDuck/Services/System/Primitives/UsbPowerService.cs b/optimizerDuck/Services/System/Primitives/UsbPowerService.cs
index f86ec7f..b5a9973 100644
--- a/optimizerDuck/Services/System/Primitives/UsbPowerService.cs
+++ b/optimizerDuck/Services/System/Primitives/UsbPowerService.cs
@@ -28,8 +28,11 @@ public static class UsbPowerService
/// <param name="Enable">Whether Windows may power the device down to save energy.</param>
public sealed record UsbPowerState(string InstanceName, bool Enable);
- /// <summary>How many devices a write pass actually changed (already-correct devices are left alone).</summary>
- public sealed record UsbPowerWriteResult(int ChangedCount);
+ /// <summary>
+ /// How many devices a write pass actually changed, and which devices refused the write.
+ /// The devices that were changed are still restorable, so a refusal never hides them.
+ /// </summary>
+ public sealed record UsbPowerWriteResult(int ChangedCount, IReadOnlyList<string> FailedDevices);
/// <summary>
/// Captures the current state of every USB root-hub device, which is what a revert restores.
@@ -80,29 +83,71 @@ public static class UsbPowerService
/// Applies <paramref name="target" /> to every matching device; a null target means "leave
/// this device alone". Devices already in the requested state are not written.
/// </summary>
+ /// <summary>
+ /// The devices a write pass has to touch, given the states Windows reports and the
+ /// requested target. A null target leaves a device alone, and a device already in the
+ /// requested state is not written again. Pure, so the choice is testable without WMI.
+ /// </summary>
+ internal static IReadOnlyList<UsbPowerState> SelectChanges(
+ IReadOnlyList<UsbPowerState> current,
+ Func<UsbPowerState, bool?> target
+ )
+ {
+ var selected = new List<UsbPowerState>();
+ foreach (var state in current)
+ {
+ var want = target(state);
+ if (want is null || want == state.Enable)
+ continue;
+
+ selected.Add(state with { Enable = want.Value });
+ }
+
+ return selected;
+ }
+
private static UsbPowerWriteResult? Write(Func<UsbPowerState, bool?> target)
{
return WmiHelper.Query(
DeviceQuery,
devices =>
{
- var changed = 0;
+ var byName = new Dictionary<string, ManagementObject>(
+ StringComparer.OrdinalIgnoreCase
+ );
+ var current = new List<UsbPowerState>(devices.Count);
foreach (var device in devices)
{
var state = ToState(device);
if (state is null)
continue;
- var want = target(state);
- if (want is null || want == state.Enable)
+ current.Add(state);
+ byName[state.InstanceName] = device;
+ }
+
+ var changed = 0;
+ var failed = new List<string>();
+ foreach (var planned in SelectChanges(current, target))
+ {
+ if (!byName.TryGetValue(planned.InstanceName, out var device))
continue;
- device["Enable"] = want.Value;
- device.Put();
- changed++;
+ try
+ {
+ device["Enable"] = planned.Enable;
+ device.Put();
+ changed++;
+ }
+ catch
+ {
+ // One device refusing must not throw away the devices that were already
+ // changed: the caller still has to record their previous state.
+ failed.Add(planned.InstanceName);
+ }
}
- return new UsbPowerWriteResult(changed);
+ return new UsbPowerWriteResult(changed, failed);
},
NamespacePath
);