Skip to content

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

fix(execution): make every recorded change revertible

fatDuckc9d5df3b311b
diff --git a/.github/contributing/CONTRIBUTING.ja-JP.md b/.github/contributing/CONTRIBUTING.ja-JP.md
index a7c871f..32f508d 100644
--- a/.github/contributing/CONTRIBUTING.ja-JP.md
+++ b/.github/contributing/CONTRIBUTING.ja-JP.md
@@ -1010,7 +1010,7 @@ await context.Shell.CMDAsync("powercfg /h off", context, "powercfg /h on");
}
```
-成功したステップのみ永続化され、各エントリに新しい連番が振られます。失敗ステップ用の null ギャップはありません。再適用は新しいエントリを追記します。
+補償データを持つステップはすべて永続化され、各エントリに新しい連番が振られます。失敗ステップ用の null ギャップはありません。システムを変更した後に失敗したステップも永続化されるため、部分適用でも元に戻せます。再適用は新しいエントリを追記します。
<h3 id="key-details-jp">重要な詳細</h3>
@@ -1020,6 +1020,8 @@ await context.Shell.CMDAsync("powercfg /h off", context, "powercfg /h on");
- **明示的コンテキスト**:プロバイダーは `OpCall` をパラメーターで受け取り、`call.Changes` に記録、`call.Logger` でログします。環境的な共有状態はありません。
- **リバートは逆順で実行**(最後に適用 = 最初にリバート、LIFO)。
- **部分成功**:一部のステップが失敗しても続行。失敗ステップには `Func<OpCall, Task<OpResult>>` 型のリトライアクションが記録されます。
+- **システムを変更したステップは補償を保持する**:1 つのステップが複数の対象を書き込む場合、先の書き込みが成立していれば、ステップが失敗しても補償を必ず添付します。`ServiceProcessService`(開始種類を書き込んだ後に遅延自動開始フラグが拒否された場合)と `DisableUSBPowerSaving`(一部のデバイスを変更し、1 台が拒否した場合)がこの形の例です。エンジンは補償を保持するステップをそのまま保存するため、失敗したステップも元に戻せ、実行は「変更なし」ではなく部分成功として報告されます。
+- **書き込んでいないものを Change として記録しない**:既に目的の状態だった、対象が存在しない、Windows が拒否した、のいずれかならば、スキップ/該当なし/拒否として記録します。何も書いていないステップを Change として記録するのは欠陥です。
- **リトライ**:`OptimizationService.RetryFailedStepsWithResultsAsync()` が新しい `OpCall` で個別の失敗ステップを再実行し、回復したステップは `AppendRevertStepAsync()` で追記します(上書きしません — LIFO リバートが最新のバックアップを先に戻し、元のバックアップが真の初期状態を復元します)。
- **ステップレジストリ**:リバートステップのデシリアライズはリフレクションベースの `_stepRegistry` — 新しいステップ型は `IRevertStep` を実装し静的な `FromData(JObject)` メソッドを持つだけで自動登録。未知の型は明確なメッセージの失敗ステップになり、黙ってスキップされません(生ペイロードは保持)。
- **主要メソッド**:`SaveRevertDataAsync()`、`RevertAsync()`、`AppendRevertStepAsync()`、`RemoveRevertStepsAtIndexesAsync()`、`IsAppliedAsync(id)`、`GetRevertDataAsync(id)`、`ClearAllRevertData()`、`RemoveOrphanedTempFiles()`。
diff --git a/.github/contributing/CONTRIBUTING.tr-TR.md b/.github/contributing/CONTRIBUTING.tr-TR.md
index 93c0630..bae6d50 100644
--- a/.github/contributing/CONTRIBUTING.tr-TR.md
+++ b/.github/contributing/CONTRIBUTING.tr-TR.md
@@ -1025,7 +1025,7 @@ await context.Shell.CMDAsync("powercfg /h off", context, "powercfg /h on");
}
```
-Sıkı ve yalnızca eklemeli günlük: yalnızca **başarılı** adımlar kalıcılaşır, her biri taze bir dizinle. Başarısız adımlar için boş yuva ayrılmaz. Yeniden uygulama yeni girdiler ekler; dizinler asla yeniden kullanılmaz, böylece diskteki girdiler kayıtlar arasında kararlı kalır.
+Sıkı ve yalnızca eklemeli günlük: telafi verisi taşıyan her adım kalıcılaşır, her biri taze bir dizinle. Başarısız adımlar için boş yuva ayrılmaz. Sistemi değiştirdikten sonra başarısız olan bir adım da kalıcılaşır, böylece kısmi uygulama da geri alınabilir. Yeniden uygulama yeni girdiler ekler; dizinler asla yeniden kullanılmaz, böylece diskteki girdiler kayıtlar arasında kararlı kalır.
<h3 id="key-details-tr">Temel Detaylar</h3>
@@ -1035,6 +1035,8 @@ Sıkı ve yalnızca eklemeli günlük: yalnızca **başarılı** adımlar kalıc
- **Açık bağlam**: Her sağlayıcı çağrısı `OpCall` alır (`Changes`, `Logger`, `CancellationToken`). Ortamda taşınan duruma güvenmeyin — bağlamı parametreyle geçirin.
- **Geri alma adımları ters sırada çalışır** (en son uygulanan = ilk geri alınan).
- **Kısmi başarı**: bazı adımlar başarısız olsa bile geri alma devam eder. Başarısız adımlara yeniden deneme eylemleri kaydedilir.
+- **Sistemi değiştiren adım telafisini korur**: bir adım birden fazla hedefe yazıyorsa ve önceki yazım gerçekleştiyse, adım başarısız bitse bile telafi eklenmelidir. `ServiceProcessService` (başlangıç türü yazıldıktan sonra gecikmeli otomatik başlatma bayrağı reddedildiğinde) ve `DisableUSBPowerSaving` (bazı aygıtlar değişti, biri reddetti) bu biçimin iki örneğidir. Motor telafi taşıyan her adımı kaydeder, bu yüzden başarısız bir adım da geri alınabilir ve çalışma "değişiklik yok" yerine kısmi başarı olarak bildirilir.
+- **Hiçbir şey yazmadığınız adımı Change olarak kaydetmeyin**: makine zaten istenen durumdaysa, hedef yoksa veya Windows reddettiyse atlama, uygulanamaz veya ret olarak kaydedin. Hiçbir şey yazmayan bir adımı Change olarak kaydetmek bir kusurdur.
- **Yeniden deneme**: `OptimizationService.RetryFailedStepsWithResultsAsync()` başarısız adımları taze bir `OpCall` ile `Func<OpCall, Task<OpResult>>` üzerinden yeniden dener; kurtarılan adımlar `AppendRevertStepAsync()` ile sona eklenir (üzerine yazma yok — LIFO geri alma yine özgün yedekte biter).
- **Adım kaydı**: Geri alma adımı serisizleştirme yansıma tabanlı `_stepRegistry` kullanır — yeni adım türleri, `IRevertStep` uygulayıp statik bir `FromData(JObject)` metoduyla otomatik kaydolur.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 096a01b..0feeb6a 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1119,7 +1119,7 @@ await context.Shell.CMDAsync("powercfg /h off", context, "powercfg /h on");
}
```
-Compact layout: only successful steps persist, each with a fresh index — no null gaps. Re-apply appends; recovered retry steps append via `AppendRevertStepAsync` (never overwrite).
+Compact layout: every step that carries compensation persists, each with a fresh index — no null gaps. A step that changed the system and then failed persists too, so a partial apply stays undoable. Re-apply appends; recovered retry steps append via `AppendRevertStepAsync` (never overwrite).
### Key Details
@@ -1128,6 +1128,8 @@ Compact layout: only successful steps persist, each with a fresh index — no nu
- **Concurrent access**: per-file `SemaphoreSlim` locks prevent race conditions; 30-second timeout. Lock entries are never disposed while in use.
- **Revert executes steps in reverse order** (last applied = first reverted).
- **Partial success**: revert continues even if some steps fail. Failed steps carry retry actions.
+- **A step that changed the system keeps its compensation**: a step that writes more than one target must attach the compensation whenever an earlier write landed, including when the step ends as a failure. `ServiceProcessService` (a refused delayed auto-start flag after the start type was written) and `DisableUSBPowerSaving` (some devices changed, one refused) are the two providers that already do this. The engine persists every step that carries compensation, so a failed step stays undoable and the run is reported as a partial success instead of "nothing changed".
+- **Record a change only when you wrote something**: a provider that found the machine already correct, a target that does not exist, or a Windows refusal records a skip, a not-applicable outcome or a refusal, never a change. Recording a change for a step that wrote nothing is a defect.
- **Retry**: `OptimizationService.RetryFailedStepsWithResultsAsync()` re-invokes `Retry` with a fresh `OpCall`; recovered steps append via `AppendRevertStepAsync`.
- **Verification**: every revert step verifies its own effect inside `ExecuteAsync` (registry read-back, service re-query, task re-check). Access-denied is failure; unknown step types fail loudly instead of vanishing.
- **Step registry**: Revert step deserialization uses reflection-based `_stepRegistry` — new step types auto-register by implementing `IRevertStep` with a static `FromData(JObject)` method.
diff --git a/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs b/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs
index 82b008e..cbf5f1e 100644
--- a/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs
+++ b/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs
@@ -392,6 +392,58 @@ public class ApplyRevertComprehensiveTests
});
}
+ [Fact]
+ public async Task ApplyAsync_OnlyStepFailedAfterChangingTheSystem_PersistsItsCompensation()
+ {
+ await RunInStaThreadAsync(async () =>
+ {
+ var optimization = new TestOptimization
+ {
+ ApplyImpl = args =>
+ args.context.Changes.Add(
+ "USB power",
+ "Disable USB power saving: two devices changed, one refused",
+ false,
+ new ShellRevertStep { ShellType = ShellType.CMD, Command = "exit 0" },
+ "a device refused the write"
+ ),
+ };
+
+ var revertPath = GetRevertFilePath(optimization.Id);
+
+ try
+ {
+ if (File.Exists(revertPath))
+ File.Delete(revertPath);
+
+ var service = CreateService();
+ var progress = new Progress<ProcessingProgress>(_ => { });
+
+ var result = await service.ApplyAsync(optimization, progress);
+
+ // The machine changed, so this is a partial success, not "nothing changed", and
+ // the compensation the failed step recorded is what a revert runs on.
+ Assert.Equal(OptimizationSuccessResult.PartialSuccess, result.Status);
+ Assert.Single(result.FailedSteps);
+ Assert.True(File.Exists(revertPath));
+
+ var data = await RevertManager.GetRevertDataAsync(optimization.Id);
+ Assert.NotNull(data);
+ Assert.Single(data!.Steps, s => s != null);
+
+ var reverted = await service.RevertAsync(optimization, progress);
+
+ Assert.True(reverted.Success);
+ Assert.False(File.Exists(revertPath));
+ }
+ finally
+ {
+ if (File.Exists(revertPath))
+ File.Delete(revertPath);
+ }
+ });
+ }
+
[Fact]
public async Task RevertAsync_StepsExecutedInReverseOrder_LastStepFirst()
{
diff --git a/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs b/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
index 5c44137..ea53774 100644
--- a/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
+++ b/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
@@ -811,6 +811,119 @@ public class RevertIntegrityTests
}
}
+ [Fact]
+ public async Task RetryFailedSteps_WhenTheCompensationCannotBePersisted_ReportsTheStepAsStillFailed()
+ {
+ var id = Guid.NewGuid();
+ var failed = new Change
+ {
+ Index = 1,
+ Name = "Step",
+ Description = "Step",
+ Ok = false,
+ Retry = call =>
+ {
+ call.Changes.Add("Registry", "wrote a value", true, new MockRevertStep());
+ return Task.FromResult(OpResult.Success());
+ },
+ };
+
+ // Hold the file lock so the append cannot take it: the retry ran, but its compensation
+ // never reached the file, which must not be reported as a clean recovery.
+ var gate = RevertManager.FileLocks.GetOrAdd(id, _ => new SemaphoreSlim(1, 1));
+ await gate.WaitAsync(TestContext.Current.CancellationToken);
+ try
+ {
+ var manager = new RevertManager(
+ NullLogger<RevertManager>.Instance,
+ TestShell.New(),
+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),
+ TimeProvider.System,
+ TimeSpan.FromMilliseconds(1)
+ );
+
+ var result = await OptimizationService.RetryFailedStepsWithResultsAsync(
+ [failed],
+ false,
+ NullLogger.Instance,
+ manager,
+ id,
+ "RetryTest"
+ );
+
+ Assert.Empty(result.RecoveredSteps);
+ var stillFailed = Assert.Single(result.FailedSteps);
+ Assert.False(stillFailed.Ok);
+ Assert.Contains("lock", stillFailed.Error ?? string.Empty);
+ Assert.False(File.Exists(Path.Combine(Shared.RevertDirectory, id + ".json")));
+ }
+ finally
+ {
+ gate.Release();
+ Cleanup(id);
+ }
+ }
+
+ [Fact]
+ public async Task RevertAsync_KnownStepTypeWithUnreadablePayload_FailsLoudlyAndKeepsTheFile()
+ {
+ var id = Guid.NewGuid();
+ var path = Path.Combine(Shared.RevertDirectory, id + ".json");
+ var cancellationToken = TestContext.Current.CancellationToken;
+ Directory.CreateDirectory(Shared.RevertDirectory);
+
+ try
+ {
+ // A registered type whose payload is missing its required fields: that entry must stay
+ // loadable, so the rest of the file still reverts and the failure names the type.
+ await File.WriteAllTextAsync(
+ path,
+ JsonConvert.SerializeObject(
+ new RevertData
+ {
+ SchemaVersion = 1,
+ OptimizationId = id,
+ OptimizationName = "UnreadablePayloadTest",
+ AppliedAt = DateTime.UtcNow,
+ Steps = new RevertStepData?[]
+ {
+ new()
+ {
+ Index = 1,
+ Type = "Registry",
+ Data = new JObject(),
+ },
+ new()
+ {
+ Index = 2,
+ Type = "Shell",
+ Data = new JObject
+ {
+ ["ShellType"] = "CMD",
+ ["Command"] = "exit 0",
+ },
+ },
+ },
+ }
+ ),
+ cancellationToken
+ );
+
+ var result = await NewManager()
+ .RevertAsync(new MockOptimization(id), cancellationToken: cancellationToken);
+
+ Assert.False(result.Success);
+ var failed = Assert.Single(result.FailedSteps);
+ Assert.Equal("Registry", failed.Name);
+ Assert.Contains("Registry", failed.Error ?? string.Empty);
+ Assert.True(File.Exists(path));
+ }
+ finally
+ {
+ Cleanup(id);
+ }
+ }
+
[Fact]
public async Task RetryFailedSteps_PersistsEveryRecoveredCompensation()
{
diff --git a/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs b/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs
index 9f0af06..55c600a 100644
--- a/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs
@@ -46,6 +46,34 @@ public class ChangeSetTests
Assert.NotNull(changes.SuccessfulSteps[0].Revert);
}
+ [Fact]
+ public void DidApplyAnything_CountsAFailedStepThatCarriesCompensation()
+ {
+ var changes = new ChangeSet();
+
+ changes.Add(
+ "USB power",
+ "Two devices changed, a third refused",
+ false,
+ new MockRevertStep(),
+ "a device refused the write"
+ );
+
+ // The step changed the machine, so what it recorded is what a revert runs on.
+ Assert.True(changes.DidApplyAnything);
+ Assert.False(changes.HasSuccessfulSteps);
+ }
+
+ [Fact]
+ public void DidApplyAnything_IgnoresAFailedStepWithoutCompensation()
+ {
+ var changes = new ChangeSet();
+
+ changes.Add("Service", "Change startup type", false, error: "access denied");
+
+ Assert.False(changes.DidApplyAnything);
+ }
+
[Fact]
public void FailedSteps_ReturnsOnlyFailedChanges()
{
diff --git a/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs
index 53866ce..0dbe257 100644
--- a/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs
@@ -5,6 +5,7 @@ using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Win32;
using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models.Services;
+using optimizerDuck.Domain.Revert.Steps;
using optimizerDuck.Services.System.Primitives;
using optimizerDuck.Test.TestDoubles;
using Xunit;
@@ -42,6 +43,32 @@ public class RegistryServiceTests : IDisposable
}
}
+ [Fact]
+ public void Write_WhenTheValueWriteFailsAfterCreatingKeys_RecordsThoseKeysForCleanup()
+ {
+ var call = NewCall();
+ // A DWord given a string is refused by the write itself, after the key chain was created.
+ var item = new RegistryItem(
+ BaseTestKey + @"\CreatedByTest\Deeper",
+ "Value",
+ "not a number",
+ RegistryValueKind.DWord
+ );
+
+ var result = RegistryService.Write(call, item);
+
+ Assert.False(result.Ok);
+ var change = Assert.Single(call.Changes.Changes);
+ Assert.False(change.Ok);
+ var step = Assert.IsType<RegistryRevertStep>(change.Revert);
+ Assert.Equal(RevertAction.NoPreviousValue, step.Action);
+ Assert.NotNull(step.CreatedSubKeys);
+ Assert.Contains(
+ step.CreatedSubKeys,
+ path => path.EndsWith(@"TestOptimizerDuck\CreatedByTest\Deeper", StringComparison.Ordinal)
+ );
+ }
+
[Fact]
public void Read_WithInvalidRoot_ReturnsDefault()
{
diff --git a/optimizerDuck.Test/Services/OptimizationServices/ServiceProcessServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/ServiceProcessServiceTests.cs
index 6178e3e..dd3fbf7 100644
--- a/optimizerDuck.Test/Services/OptimizationServices/ServiceProcessServiceTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServices/ServiceProcessServiceTests.cs
@@ -28,6 +28,21 @@ public class ServiceProcessServiceTests
Assert.Contains(nativeError.ToString(), detail);
}
+ [Fact]
+ public void BuildWriteErrorDetail_WithAThrowAfterTheWrite_NamesTheThrow()
+ {
+ // The interop itself threw after the start type was written: the throw text is the only
+ // honest reason, so it is reported instead of the error code.
+ var detail = ServiceProcessService.BuildWriteErrorDetail(
+ true,
+ 5,
+ "LoadLibrary failed"
+ );
+
+ Assert.Contains("LoadLibrary failed", detail);
+ Assert.Contains("after the start type was written", detail);
+ }
+
// =============================================
// Integration tests: GetStartupTypeAsync (real sc.exe)
// =============================================
diff --git a/optimizerDuck.Test/Services/PowerPlanChangesTests.cs b/optimizerDuck.Test/Services/PowerPlanChangesTests.cs
index c373646..6940df1 100644
--- a/optimizerDuck.Test/Services/PowerPlanChangesTests.cs
+++ b/optimizerDuck.Test/Services/PowerPlanChangesTests.cs
@@ -74,6 +74,97 @@ public class PowerPlanChangesTests
private static OpCall NewCall() => new() { Logger = NullLogger.Instance };
+ [Fact]
+ public void WriteSetting_FailedWriteAfterReadingValues_RecordsThemForCompensation()
+ {
+ var setting = Guid.NewGuid();
+ var plans = new StubPowerPlanService
+ {
+ WriteFunc = (_, _, _, _, _) =>
+ new SettingWriteResult(OpResult.Fail("PowerWriteDCValueIndex failed", null), 5u, 10u),
+ };
+ var call = NewCall();
+
+ var result = PowerPlanChanges.WriteSetting(
+ call,
+ plans,
+ Guid.NewGuid(),
+ Guid.NewGuid(),
+ setting,
+ 7u,
+ 20u
+ );
+
+ Assert.False(result.Ok);
+ var change = Assert.Single(call.Changes.Changes);
+ Assert.False(change.Ok);
+ var step = Assert.IsType<PowerSettingRevertStep>(change.Revert);
+ Assert.Equal(5u, step.PreviousAcValue);
+ Assert.Equal(10u, step.PreviousDcValue);
+ Assert.Equal("AC 5 / DC 10", change.Detail!.PreviousValue);
+ Assert.False(change.Detail.HasValuePair);
+ }
+
+ [Fact]
+ public void WriteSetting_FailedWriteWithoutReadValues_RecordsNoCompensation()
+ {
+ var plans = new StubPowerPlanService
+ {
+ WriteFunc = (_, _, _, _, _) =>
+ new SettingWriteResult(OpResult.Fail("no previous value", null), null, null),
+ };
+ var call = NewCall();
+
+ var result = PowerPlanChanges.WriteSetting(
+ call,
+ plans,
+ Guid.NewGuid(),
+ Guid.NewGuid(),
+ Guid.NewGuid(),
+ 7u,
+ 20u
+ );
+
+ Assert.False(result.Ok);
+ var change = Assert.Single(call.Changes.Changes);
+ Assert.False(change.Ok);
+ Assert.Null(change.Revert);
+ }
+
+ [Fact]
+ public async Task Install_ActivationFailedAfterImport_RecordsTheImportedScheme()
+ {
+ var installed = Guid.NewGuid();
+ var previous = Guid.NewGuid();
+ var plans = new StubPowerPlanService
+ {
+ InstallFunc = (_, _) =>
+ Task.FromResult(
+ new InstallResult(
+ OpResult.Fail("PowerSetActiveScheme failed", null),
+ installed,
+ previous
+ )
+ ),
+ };
+ var call = NewCall();
+
+ var install = await PowerPlanChanges.InstallAsync(
+ call,
+ plans,
+ "x.pow",
+ installed,
+ TestContext.Current.CancellationToken
+ );
+
+ Assert.False(install.Result.Ok);
+ var change = Assert.Single(call.Changes.Changes);
+ Assert.False(change.Ok);
+ var step = Assert.IsType<PowerPlanRevertStep>(change.Revert);
+ Assert.Equal(installed, step.InstalledSchemeId);
+ Assert.Equal(previous, step.PreviousSchemeId);
+ }
+
[Fact]
public void Activate_Success_RecordsStepWithPreviousAndInstalled()
{
diff --git a/optimizerDuck/Domain/Execution/ChangeSet.cs b/optimizerDuck/Domain/Execution/ChangeSet.cs
index 644ca73..8236dd5 100644
--- a/optimizerDuck/Domain/Execution/ChangeSet.cs
+++ b/optimizerDuck/Domain/Execution/ChangeSet.cs
@@ -67,14 +67,16 @@ public sealed class ChangeSet
/// <summary>
/// Whether any step actually modified the system. Skips and irreversible actions
- /// did not leave something to undo, so they do not count as applied changes.
+ /// did not leave something to undo, so they do not count as applied changes. A step that
+ /// modified the system and then failed still counts, because it carries the compensation
+ /// for what it changed, and dropping it here would leave that work unrevertible.
/// </summary>
public bool DidApplyAnything
{
get
{
lock (_gate)
- return _changes.Any(c => c.Ok && c.Kind == ChangeKind.Change);
+ return _changes.Any(c => c.Kind == ChangeKind.Change && (c.Ok || c.Revert != null));
}
}
diff --git a/optimizerDuck/Services/Optimization/OptimizationService.cs b/optimizerDuck/Services/Optimization/OptimizationService.cs
index 0aa6389..0972e4a 100644
--- a/optimizerDuck/Services/Optimization/OptimizationService.cs
+++ b/optimizerDuck/Services/Optimization/OptimizationService.cs
@@ -285,11 +285,16 @@ public class OptimizationService(
var failedSteps = changes.FailedSteps.OrderBy(s => s.Index).ToList();
+ // A step that changed the system and then failed carries the compensation for what it
+ // changed, so the machine did change: such a run is a partial success, never a failure
+ // that reads as if nothing had been touched.
+ var changedSomething = changes.HasSuccessfulSteps || changes.DidApplyAnything;
+
if (exception != null)
{
return new OptimizationResult
{
- Status = changes.HasSuccessfulSteps
+ Status = changedSomething
? OptimizationSuccessResult.PartialSuccess
: OptimizationSuccessResult.Failed,
Message = Loc.Instance["Optimization.Apply.Error.Failed", optimization.Name],
@@ -308,7 +313,7 @@ public class OptimizationService(
return new OptimizationResult
{
- Status = changes.HasSuccessfulSteps
+ Status = changedSomething
? OptimizationSuccessResult.PartialSuccess
: OptimizationSuccessResult.Failed,
Message =
@@ -323,9 +328,11 @@ public class OptimizationService(
};
}
- // Every recorded step failed: nothing changed and nothing succeeded, so it stays a
- // failure with the failure dialog as before.
- if (changes.Changes.Count > 0 && !changes.HasSuccessfulSteps)
+ // Every recorded step failed and none of them carries compensation: nothing changed and
+ // nothing succeeded, so it stays a failure with the failure dialog as before. A failed step
+ // that recorded what it changed falls through to the partial success path below, because
+ // the machine did change and the revert file covers it.
+ if (changes.Changes.Count > 0 && !changedSomething)
{
return new OptimizationResult
{
@@ -599,6 +606,7 @@ public class OptimizationService(
// 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.
+ Exception? persistError = null;
if (revertManager != null && optimizationId.HasValue)
{
var compensations = capturedSteps
@@ -622,6 +630,7 @@ public class OptimizationService(
}
catch (Exception ex)
{
+ persistError = ex;
logger.LogError(
ex,
"Failed to auto-persist recovered revert step for {Index}",
@@ -631,7 +640,20 @@ public class OptimizationService(
}
}
- recoveredSteps.Add(recoveredStep);
+ // The step ran, but the machine cannot be undone for it: reporting it as
+ // recovered would claim coverage that is not on disk, so it comes back as a
+ // failed step naming why its compensation could not be written.
+ if (persistError is null)
+ recoveredSteps.Add(recoveredStep);
+ else
+ remainingFailedSteps.Add(
+ recoveredStep with
+ {
+ Ok = false,
+ Error = persistError.Message,
+ ErrorDetail = persistError.ToString(),
+ }
+ );
}
}
catch (Exception ex)
diff --git a/optimizerDuck/Services/Revert/RevertManager.cs b/optimizerDuck/Services/Revert/RevertManager.cs
index 5c5cce4..cdd104f 100644
--- a/optimizerDuck/Services/Revert/RevertManager.cs
+++ b/optimizerDuck/Services/Revert/RevertManager.cs
@@ -845,11 +845,28 @@ public class RevertManager(
{
if (data is not JObject obj)
return null;
- if (_stepRegistry.Value.TryGetValue(type, out var factory))
- return factory(obj);
+ if (!_stepRegistry.Value.TryGetValue(type, out var factory))
+ {
+ _logger.LogWarning("Unknown revert step type: {Type}", type);
+ return null;
+ }
- _logger.LogWarning("Unknown revert step type: {Type}", type);
- return null;
+ try
+ {
+ return factory(obj);
+ }
+ catch (Exception ex)
+ {
+ // A registered type whose payload cannot be read is as unloadable as an unknown one:
+ // the caller substitutes a placeholder, so the rest of the file still reverts.
+ var inner = (ex as TargetInvocationException)?.InnerException ?? ex;
+ _logger.LogWarning(
+ inner,
+ "Revert step of type {Type} could not be read from its stored payload",
+ type
+ );
+ return null;
+ }
}
/// <summary>
diff --git a/optimizerDuck/Services/System/PowerPlanService.cs b/optimizerDuck/Services/System/PowerPlanService.cs
index da553cb..53151ec 100644
--- a/optimizerDuck/Services/System/PowerPlanService.cs
+++ b/optimizerDuck/Services/System/PowerPlanService.cs
@@ -264,10 +264,13 @@ public class PowerPlanService
var failure = WriteValues(schemeId, subgroupId, settingId, acValue, dcValue);
if (failure is not null)
+ // Both values were read before the write and the first of the two native writes may
+ // have landed, so they are handed back for the caller to record compensation from.
+ // The service itself still records nothing.
return new SettingWriteResult(
OpResult.Fail(failure.Describe(), failure.Describe()),
- null,
- null
+ prevAc,
+ prevDc
);
logger?.LogInformation(
diff --git a/optimizerDuck/Services/System/Primitives/PowerPlanChanges.cs b/optimizerDuck/Services/System/Primitives/PowerPlanChanges.cs
index 0467ca8..ae661d4 100644
--- a/optimizerDuck/Services/System/Primitives/PowerPlanChanges.cs
+++ b/optimizerDuck/Services/System/Primitives/PowerPlanChanges.cs
@@ -87,11 +87,26 @@ public static class PowerPlanChanges
.ConfigureAwait(false);
if (!install.Result.Ok || install.InstalledId is null || install.PreviousId is null)
{
+ // The import can have landed even when the activation failed, so the scheme Windows
+ // reports is recorded whenever it is known: a revert then removes the plan this run
+ // added instead of leaving it behind. Without an id there is nothing to point at.
+ PowerPlanRevertStep? orphan = null;
+ string? orphanName = null;
+ if (install.InstalledId is not null)
+ {
+ orphan = new PowerPlanRevertStep
+ {
+ PreviousSchemeId = install.PreviousId ?? Guid.Empty,
+ InstalledSchemeId = install.InstalledId.Value,
+ };
+ orphanName = plans.GetSchemeName(install.InstalledId.Value);
+ }
+
call.Changes.Add(
ServiceStrings.PowerPlanName,
ServiceStrings.Format("Install power plan {0}", destinationId),
false,
- null,
+ orphan,
install.Result.Error,
install.Result.ErrorDetail,
async retryCall =>
@@ -149,13 +164,33 @@ public static class PowerPlanChanges
var result = write.Result;
var prevAc = write.PreviousAcValue;
var prevDc = write.PreviousDcValue;
- if (!result.Ok || prevAc is null || prevDc is null)
+
+ // Both values were read before any write, and the mains value may already have been
+ // written when the battery write failed, so the compensation is recorded whenever the
+ // values are known, whether the step succeeded or not. Restoring a value that was never
+ // written is a no-op, and keeping the entry is what lets a retry end at the true original.
+ PowerSettingRevertStep? step = null;
+ string? previousPair = null;
+ if (prevAc is not null && prevDc is not null)
+ {
+ previousPair = $"AC {prevAc.Value} / DC {prevDc.Value}";
+ step = new PowerSettingRevertStep
+ {
+ SchemeId = schemeId,
+ SubgroupId = subgroupId,
+ SettingId = settingId,
+ PreviousAcValue = prevAc.Value,
+ PreviousDcValue = prevDc.Value,
+ };
+ }
+
+ if (!result.Ok || step is null)
{
call.Changes.Add(
ServiceStrings.PowerPlanName,
description,
false,
- null,
+ step,
result.Error,
result.ErrorDetail,
retryCall =>
@@ -169,19 +204,20 @@ public static class PowerPlanChanges
acValue,
dcValue
)
- )
+ ),
+ detail:
+ previousPair is null
+ ? null
+ : new ChangeDetail
+ {
+ Operation = SettingAction,
+ Target = settingId.ToString(),
+ PreviousValue = previousPair,
+ }
);
return result;
}
- var step = new PowerSettingRevertStep
- {
- SchemeId = schemeId,
- SubgroupId = subgroupId,
- SettingId = settingId,
- PreviousAcValue = prevAc.Value,
- PreviousDcValue = prevDc.Value,
- };
call.Changes.Add(
ServiceStrings.PowerPlanName,
description,
@@ -191,7 +227,7 @@ public static class PowerPlanChanges
{
Operation = SettingAction,
Target = settingId.ToString(),
- PreviousValue = $"AC {prevAc.Value} / DC {prevDc.Value}",
+ PreviousValue = previousPair,
NewValue = $"AC {acValue} / DC {dcValue}",
HasValuePair = true,
}
diff --git a/optimizerDuck/Services/System/Primitives/RegistryService.cs b/optimizerDuck/Services/System/Primitives/RegistryService.cs
index 777fada..9ac6c39 100644
--- a/optimizerDuck/Services/System/Primitives/RegistryService.cs
+++ b/optimizerDuck/Services/System/Primitives/RegistryService.cs
@@ -457,7 +457,17 @@ public static class RegistryService
name,
description,
false,
- null,
+ // Subkeys created before the value write are this run's doing, so a
+ // failure still records how to remove exactly those keys.
+ createdSubKeys.Count > 0
+ ? new RegistryRevertStep
+ {
+ Action = RevertAction.NoPreviousValue,
+ Path = item.Path,
+ Name = null,
+ CreatedSubKeys = createdSubKeys,
+ }
+ : null,
error,
errorDetail,
(OpCall rc) => Task.FromResult(Write(rc, item))
@@ -478,7 +488,17 @@ public static class RegistryService
name,
description,
false,
- null,
+ // Subkeys created before the value write are this run's doing, so a
+ // failure still records how to remove exactly those keys.
+ createdSubKeys.Count > 0
+ ? new RegistryRevertStep
+ {
+ Action = RevertAction.NoPreviousValue,
+ Path = item.Path,
+ Name = null,
+ CreatedSubKeys = createdSubKeys,
+ }
+ : null,
error,
errorDetail,
(OpCall rc) => Task.FromResult(Write(rc, item))
diff --git a/optimizerDuck/Services/System/Primitives/ServiceProcessService.cs b/optimizerDuck/Services/System/Primitives/ServiceProcessService.cs
index 716f595..7aa079e 100644
--- a/optimizerDuck/Services/System/Primitives/ServiceProcessService.cs
+++ b/optimizerDuck/Services/System/Primitives/ServiceProcessService.cs
@@ -131,7 +131,11 @@ public static class ServiceProcessService
string? errorDetail = null;
if (!success)
- errorDetail = BuildWriteErrorDetail(write.StartTypeWritten, nativeError);
+ errorDetail = BuildWriteErrorDetail(
+ write.StartTypeWritten,
+ nativeError,
+ write.ExceptionText
+ );
if (success)
{
@@ -392,13 +396,23 @@ public static class ServiceProcessService
/// 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);
+ private readonly record struct StartTypeWrite(
+ int Error,
+ bool StartTypeWritten,
+ string? ExceptionText = null
+ );
/// <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
+ internal static string BuildWriteErrorDetail(
+ bool startTypeWritten,
+ int nativeError,
+ string? exceptionText = null
+ ) =>
+ exceptionText is not null
+ ? $"ChangeServiceConfig2 (delayed auto start) threw after the start type was written: {exceptionText}"
+ : startTypeWritten
? $"ChangeServiceConfig2 (delayed auto start) failed with Win32 error {nativeError}, after the start type was written"
: $"ChangeServiceConfig failed with Win32 error {nativeError}";
@@ -460,9 +474,25 @@ public static class ServiceProcessService
fDelayedAutostart = startupType == ServiceStartupType.AutomaticDelayedStart,
};
- if (!ChangeServiceConfig2(service, ServiceConfigDelayedAutoStartInfo, ref info))
- // The start type is already written at this point.
- return new StartTypeWrite(Marshal.GetLastWin32Error(), true);
+ try
+ {
+ if (
+ !ChangeServiceConfig2(
+ service,
+ ServiceConfigDelayedAutoStartInfo,
+ ref info
+ )
+ )
+ // The start type is already written at this point.
+ return new StartTypeWrite(Marshal.GetLastWin32Error(), true);
+ }
+ catch (Exception ex)
+ {
+ // The interop itself threw after the start type was written, which is the
+ // same partial write a refused flag is. The throw text is the only honest
+ // reason, so the caller reports it instead of the error code.
+ return new StartTypeWrite(Marshal.GetLastWin32Error(), true, ex.Message);
+ }
}
return new StartTypeWrite(0, true);