From 2ee397ac8386660cd8f9df0bcfa23e629e210b17 Mon Sep 17 00:00:00 2001 From: PrimeBuild-pc Date: Wed, 26 Aug 2026 12:50:54 +0200 Subject: [PATCH] fix: apply real CPU affinity when a rule is applied A user reported that the CPU affinity feature did nothing when applying a rule. Two distinct defects were behind it. ProcessService.SetProcessorAffinity(process, long) silently substituted SetProcessDefaultCpuSets for the hard affinity write. CPU Sets are only a soft scheduling hint and leave the mask returned by GetProcessAffinityMask untouched, so the single caller - AffinityApplyService.ApplyAsync, which reads the mask back and compares - always reported VerificationMismatch. The Rules tab path (ProcessMonitorManagerService association core masks) therefore failed while the affinity never changed. Reproduced on a 16-CPU machine: requesting 0x3 left the process at 0xFFFF and returned a failure. The overload now writes the affinity mask it was asked for; soft assignment keeps its own entry points (CpuAssignmentMode.CpuSets, CpuSelectionAffinityApplier). The shipped DefaultCpuAssignmentMode was Automatic, which is CPU-Sets-first, so out of the box "Apply CPU Assignment" produced no change visible in Task Manager while reporting success. The default is now AffinityMask, and the CPU Sets result message states that it is a soft preference rather than claiming "Affinity applied successfully". Save Current Settings as Rule only captured the core selection while edits were staged, otherwise falling back to process.ProcessorAffinity - which soft modes never change - saving a rule pinned to every CPU. It now captures what the core checkboxes show. Adds a regression test that spawns a real process and asserts the hard affinity mask actually changes; it fails on the previous implementation. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01AhS1xyuMPFvxrojERQ4NuY --- Models/ApplicationSettingsModel.cs | 2 +- Services/AffinityApplyService.cs | 2 +- Services/ProcessOperationUserMessages.cs | 3 + Services/ProcessService.cs | 70 ++----------------- .../ApplicationSettingsModelTests.cs | 2 +- .../ApplicationSettingsServiceTests.cs | 2 +- .../ProcessServiceTests.cs | 42 +++++++++++ .../ProcessViewModel.Behaviors.partial.cs | 5 +- 8 files changed, 58 insertions(+), 70 deletions(-) diff --git a/Models/ApplicationSettingsModel.cs b/Models/ApplicationSettingsModel.cs index 094b9a9..7046a67 100644 --- a/Models/ApplicationSettingsModel.cs +++ b/Models/ApplicationSettingsModel.cs @@ -160,7 +160,7 @@ namespace ThreadPilot.Models private bool enableAutomationMonitoring = true; [ObservableProperty] - private CpuAssignmentMode defaultCpuAssignmentMode = CpuAssignmentMode.Automatic; + private CpuAssignmentMode defaultCpuAssignmentMode = CpuAssignmentMode.AffinityMask; // Advanced Settings [ObservableProperty] diff --git a/Services/AffinityApplyService.cs b/Services/AffinityApplyService.cs index 2f0e258..ae0cef9 100644 --- a/Services/AffinityApplyService.cs +++ b/Services/AffinityApplyService.cs @@ -88,7 +88,7 @@ namespace ThreadPilot.Services Success = true, FailureReason = AffinityApplyFailureReason.None, ErrorCode = AffinityApplyErrorCodes.None, - UserMessage = "Affinity applied successfully.", + UserMessage = ProcessOperationUserMessages.CpuSetsApplied, TechnicalMessage = technicalMessage, UsedCpuSets = true, EffectiveMode = CpuAssignmentMode.CpuSets, diff --git a/Services/ProcessOperationUserMessages.cs b/Services/ProcessOperationUserMessages.cs index 0cc3f70..84924ef 100644 --- a/Services/ProcessOperationUserMessages.cs +++ b/Services/ProcessOperationUserMessages.cs @@ -22,6 +22,9 @@ namespace ThreadPilot.Services public const string ProcessExited = "The process exited before ThreadPilot could apply the change."; + public const string CpuSetsApplied = + "CPU Sets assignment applied. This is a soft scheduling preference: the affinity mask shown in Task Manager stays unchanged. Use the Affinity Mask mode for a hard, visible restriction."; + public const string CpuSetsUnavailable = "Windows CPU Sets are unavailable or rejected this selection. ThreadPilot will use a safe fallback only when possible."; diff --git a/Services/ProcessService.cs b/Services/ProcessService.cs index 1002ebe..80a0257 100644 --- a/Services/ProcessService.cs +++ b/Services/ProcessService.cs @@ -429,30 +429,11 @@ namespace ThreadPilot.Services throw new InvalidOperationException("Affinity mask cannot be zero."); } - // Try using CPU Sets first (Windows 10+) - if (this.useCpuSets) - { - bool cpuSetSuccess = this.TrySetAffinityViaCpuSets(process, affinityMask); - if (cpuSetSuccess) - { - this.logger?.LogInformation( - "Successfully applied CPU Sets affinity 0x{AffinityMask:X} to process {ProcessName} (PID: {ProcessId})", - affinityMask, process.Name, process.ProcessId); - - // Update the model with the new affinity - process.ProcessorAffinity = affinityMask; - this.AuditProcessOperation("SetProcessAffinity", process.Name, success: true); - return; - } - else - { - this.logger?.LogDebug( - "CPU Sets failed for process {ProcessName} (PID: {ProcessId}), falling back to classic ProcessorAffinity", - process.Name, process.ProcessId); - } - } - - // Fallback to classic ProcessorAffinity method + // This overload means "hard affinity mask": callers verify the result against + // GetProcessAffinityMask. CPU Sets (SetProcessDefaultCpuSets) are only a soft + // scheduling hint and leave that mask untouched, so applying them here made every + // caller report a VerificationMismatch failure. Soft assignment keeps its own + // entry points (CpuAssignmentMode.CpuSets / CpuSelectionAffinityApplier). using var targetProcess = Process.GetProcessById(process.ProcessId); targetProcess.ProcessorAffinity = new IntPtr(affinityMask); @@ -527,47 +508,6 @@ namespace ThreadPilot.Services return await this.cpuSelectionAffinityApplier.ApplyAsync(process, selection).ConfigureAwait(false); } - private bool TrySetAffinityViaCpuSets(ProcessModel process, long affinityMask) - { - try - { - // Get or create CPU Set handler for this process - var handler = this.GetOrCreateCpuSetHandler(process); - - // Check if handler is valid - if (!handler.IsValid) - { - this.logger?.LogDebug( - "CPU Set handler for process {ProcessName} (PID: {ProcessId}) is invalid", - process.Name, process.ProcessId); - - // Remove invalid handler - this.cpuSetHandlers.TryRemove(process.ProcessId, out _); - return false; - } - - // Apply the CPU Set mask - bool success = handler.ApplyCpuSetMask(affinityMask, clearMask: false); - - if (!success) - { - // Remove failed handler so we can try again later if needed - this.cpuSetHandlers.TryRemove(process.ProcessId, out _); - } - - return success; - } - catch (Exception ex) - { - this.logger?.LogWarning(ex, "Exception while applying CPU Sets to process {ProcessName} (PID: {ProcessId})", - process.Name, process.ProcessId); - - // Remove handler on exception - this.cpuSetHandlers.TryRemove(process.ProcessId, out _); - return false; - } - } - private IProcessCpuSetHandler GetOrCreateCpuSetHandler(ProcessModel process) => this.cpuSetHandlers.GetOrAdd(process.ProcessId, pid => { diff --git a/Tests/ThreadPilot.Core.Tests/ApplicationSettingsModelTests.cs b/Tests/ThreadPilot.Core.Tests/ApplicationSettingsModelTests.cs index 818052c..29216ac 100644 --- a/Tests/ThreadPilot.Core.Tests/ApplicationSettingsModelTests.cs +++ b/Tests/ThreadPilot.Core.Tests/ApplicationSettingsModelTests.cs @@ -18,7 +18,7 @@ namespace ThreadPilot.Core.Tests Assert.True(settings.EnableAutomaticUpdateChecks); Assert.False(settings.IncludePrereleaseUpdates); Assert.Null(settings.LastUpdateCheckUtc); - Assert.Equal(CpuAssignmentMode.Automatic, settings.DefaultCpuAssignmentMode); + Assert.Equal(CpuAssignmentMode.AffinityMask, settings.DefaultCpuAssignmentMode); } [Fact] diff --git a/Tests/ThreadPilot.Core.Tests/ApplicationSettingsServiceTests.cs b/Tests/ThreadPilot.Core.Tests/ApplicationSettingsServiceTests.cs index b369a4a..42d85d2 100644 --- a/Tests/ThreadPilot.Core.Tests/ApplicationSettingsServiceTests.cs +++ b/Tests/ThreadPilot.Core.Tests/ApplicationSettingsServiceTests.cs @@ -40,7 +40,7 @@ namespace ThreadPilot.Core.Tests await service.LoadSettingsAsync(); Assert.True(service.Settings.EnableAutomationMonitoring); - Assert.Equal(CpuAssignmentMode.Automatic, service.Settings.DefaultCpuAssignmentMode); + Assert.Equal(CpuAssignmentMode.AffinityMask, service.Settings.DefaultCpuAssignmentMode); } [Fact] diff --git a/Tests/ThreadPilot.Core.Tests/ProcessServiceTests.cs b/Tests/ThreadPilot.Core.Tests/ProcessServiceTests.cs index f90db6a..1022c55 100644 --- a/Tests/ThreadPilot.Core.Tests/ProcessServiceTests.cs +++ b/Tests/ThreadPilot.Core.Tests/ProcessServiceTests.cs @@ -14,6 +14,48 @@ namespace ThreadPilot.Core.Tests public sealed class ProcessServiceTests { + [Fact] + public async Task SetProcessorAffinity_ActuallyChangesTheHardAffinityMask() + { + // Regression guard: this overload must write the mask Windows reports back through + // GetProcessAffinityMask. Applying CPU Sets here instead is a soft scheduling hint that + // leaves the mask untouched, which made every caller report a VerificationMismatch. + if (Environment.ProcessorCount < 2) + { + return; + } + + using var child = Process.Start(new ProcessStartInfo("cmd.exe", "/c pause") + { + RedirectStandardInput = true, + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true, + })!; + + try + { + var model = new ProcessModel + { + ProcessId = child.Id, + Name = child.ProcessName, + ProcessorAffinity = (long)child.ProcessorAffinity, + }; + + var service = new ProcessService(Mock.Of>()); + + await service.SetProcessorAffinity(model, 0x3); + + child.Refresh(); + Assert.Equal(0x3, (long)child.ProcessorAffinity); + Assert.Equal(0x3, model.ProcessorAffinity); + } + finally + { + child.Kill(); + } + } + [Fact] public async Task SaveProcessProfile_WritesExpectedJson() { diff --git a/ViewModels/ProcessViewModel.Behaviors.partial.cs b/ViewModels/ProcessViewModel.Behaviors.partial.cs index b2a357c..7afc9b2 100644 --- a/ViewModels/ProcessViewModel.Behaviors.partial.cs +++ b/ViewModels/ProcessViewModel.Behaviors.partial.cs @@ -810,7 +810,10 @@ namespace ThreadPilot.ViewModels await this.UpdateSelectedProcessSummaryAsync(targetProcess); - var currentCoreSelection = this.HasPendingAffinityEdits && this.CpuCores.Count > 0 + // Capture what the core checkboxes currently show, not only staged edits: soft modes + // (CPU Sets / Ideal Processor) leave ProcessorAffinity untouched, so falling back to it + // saved a rule pinned to every CPU - a rule that does nothing when applied. + var currentCoreSelection = this.CpuCores.Count > 0 ? this.GetPendingCoreSelectionMask() : null; var result = await this.processRuleCreationService.SaveCurrentSettingsAsRuleAsync(