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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AhS1xyuMPFvxrojERQ4NuY
This commit is contained in:
committed by
Prime Build
parent
4360827c1a
commit
2ee397ac83
@@ -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]
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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.";
|
||||
|
||||
|
||||
@@ -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 =>
|
||||
{
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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<ILogger<ProcessService>>());
|
||||
|
||||
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()
|
||||
{
|
||||
|
||||
@@ -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(
|
||||
|
||||
Reference in New Issue
Block a user