Files
ThreadPilot/Tests/ThreadPilot.Core.Tests/ProcessMemoryPriorityServiceTests.cs
PrimeBuild-pc cb0c5c3efb feat: Game Boost scheduler hints and dynamic CPU Set release
Game Boost now gives Windows hints as well as constraints, and adapts
the game's CPU Set to its load instead of applying it once:

- the game gets high QoS (power throttling off), on every CPU, so
  Windows never throttles it while it is not in the foreground;
- in Isolation the listed background apps get EcoQoS, also on CPUs
  where CPU Sets are not applied;
- a game that keeps its confined CPUs saturated has its CPU Set
  released so Windows can use every core, and confined again after a
  minute of low load (hysteresis, at most two releases per session).

Same ownership rules as CPU Sets: only values Windows still manages
are changed, user rules and the app's own QoS win, everything is
journaled and restored on exit, toggle and after a crash.

Efficiency mode writes now keep the process's other power-throttling
flags: Windows replaces the whole state on set, so the old write wiped
a timer-resolution opt-out set by the process itself.
2026-10-22 10:54:37 +02:00

442 lines
19 KiB
C#

/*
* ThreadPilot - process memory priority service tests.
*/
namespace ThreadPilot.Core.Tests
{
using System.ComponentModel;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using ThreadPilot.Models;
using ThreadPilot.Platforms.Windows;
using ThreadPilot.Services;
public sealed class ProcessMemoryPriorityServiceTests
{
[Fact]
public async Task SetMemoryPriorityAsync_WithValidProcess_CallsNativeApi()
{
var nativeApi = new FakeProcessMemoryPriorityNativeApi();
var service = CreateService(nativeApi);
var process = CreateProcess();
var result = await service.SetMemoryPriorityAsync(process, ProcessMemoryPriority.Low);
Assert.True(result.Success);
Assert.Equal(ProcessMemoryPriority.Low, nativeApi.LastSetPriority);
Assert.Equal(ProcessAccessFlags.PROCESS_SET_INFORMATION, nativeApi.LastOpenAccess);
Assert.Equal("Memory priority applied.", result.UserMessage);
}
[Theory]
[InlineData(ProcessEfficiencyMode.On, 1u, 1u)]
[InlineData(ProcessEfficiencyMode.Off, 1u, 0u)]
[InlineData(ProcessEfficiencyMode.SystemManaged, 0u, 0u)]
public async Task SetEfficiencyModeAsync_MapsEachModeToItsThrottlingMasks(ProcessEfficiencyMode mode, uint control, uint state)
{
var nativeApi = new FakeProcessMemoryPriorityNativeApi();
var result = await CreateService(nativeApi).SetEfficiencyModeAsync(CreateProcess(), mode);
Assert.True(result.Success);
Assert.Equal(ProcessAccessFlags.PROCESS_SET_INFORMATION | ProcessAccessFlags.PROCESS_QUERY_LIMITED_INFORMATION, nativeApi.LastOpenAccess);
Assert.Equal(PowerThrottlingState.CurrentVersion, nativeApi.LastSetThrottling!.Value.Version);
Assert.Equal(control, nativeApi.LastSetThrottling.Value.ControlMask);
Assert.Equal(state, nativeApi.LastSetThrottling.Value.StateMask);
var readBack = await CreateService(new FakeProcessMemoryPriorityNativeApi { ThrottlingToReturn = nativeApi.LastSetThrottling.Value })
.GetEfficiencyModeAsync(CreateProcess());
Assert.Equal(mode, readBack);
}
[Theory]
[InlineData(ProcessEfficiencyMode.On, 5u, 5u)]
[InlineData(ProcessEfficiencyMode.Off, 5u, 4u)]
[InlineData(ProcessEfficiencyMode.SystemManaged, 4u, 4u)]
public async Task SetEfficiencyModeAsync_KeepsTheProcessesOtherThrottlingFlags(ProcessEfficiencyMode mode, uint control, uint state)
{
// 0x4 = PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, set by the process itself.
var nativeApi = new FakeProcessMemoryPriorityNativeApi
{
ThrottlingToReturn = new PowerThrottlingState { Version = 1, ControlMask = 0x5, StateMask = 0x5 },
};
await CreateService(nativeApi).SetEfficiencyModeAsync(CreateProcess(), mode);
Assert.Equal(control, nativeApi.LastSetThrottling!.Value.ControlMask);
Assert.Equal(state, nativeApi.LastSetThrottling.Value.StateMask);
}
[Fact]
public async Task SetEfficiencyModeAsync_WhenWindowsDenies_ReportsAccessDenied()
{
var nativeApi = new FakeProcessMemoryPriorityNativeApi { SetResult = false, LastError = 5 };
var result = await CreateService(nativeApi).SetEfficiencyModeAsync(CreateProcess(), ProcessEfficiencyMode.On);
Assert.False(result.Success);
Assert.True(result.IsAccessDenied);
}
[Fact]
public async Task GetMemoryPriorityAsync_WithValidProcess_ReadsNativeApi()
{
var nativeApi = new FakeProcessMemoryPriorityNativeApi
{
PriorityToReturn = ProcessMemoryPriority.BelowNormal,
};
var service = CreateService(nativeApi);
var priority = await service.GetMemoryPriorityAsync(CreateProcess());
Assert.Equal(ProcessMemoryPriority.BelowNormal, priority);
Assert.Equal(ProcessAccessFlags.PROCESS_QUERY_LIMITED_INFORMATION, nativeApi.LastOpenAccess);
}
[Fact]
public async Task IoPriority_WithValidProcess_RoundTripsThroughNativeApi()
{
var nativeApi = new FakeProcessMemoryPriorityNativeApi
{
IoPriorityToReturn = ProcessIoPriority.Low,
};
var service = CreateService(nativeApi);
var process = CreateProcess();
var observed = await service.GetIoPriorityAsync(process);
var result = await service.SetIoPriorityAsync(process, ProcessIoPriority.High);
Assert.Equal(ProcessIoPriority.Low, observed);
Assert.True(result.Success);
Assert.Equal(ProcessIoPriority.High, nativeApi.LastSetIoPriority);
}
[Fact]
public async Task SetIoPriorityAsync_WhenStatusPrivilegeNotHeld_ReturnsSafeAccessDeniedFailure()
{
var nativeApi = new FakeProcessMemoryPriorityNativeApi
{
SetIoPriorityStatus = unchecked((int)0xC0000061),
};
var service = CreateService(nativeApi);
var process = CreateProcess();
var result = await service.SetIoPriorityAsync(process, ProcessIoPriority.High);
Assert.False(result.Success);
Assert.True(result.IsAccessDenied);
Assert.Equal(AffinityApplyErrorCodes.AccessDenied, result.ErrorCode);
Assert.Equal(ProcessOperationUserMessages.AccessDenied, result.UserMessage);
Assert.Contains("0xC0000061", result.TechnicalMessage);
}
[Fact]
public async Task SetIoPriorityAsync_WhenHighPriority_AcquiresAndDisposesPrivilegeScope()
{
var nativeApi = new FakeProcessMemoryPriorityNativeApi();
var service = CreateService(nativeApi);
var process = CreateProcess();
var result = await service.SetIoPriorityAsync(process, ProcessIoPriority.High);
Assert.True(result.Success);
Assert.Contains(ProcessMemoryPriorityNativeMethods.SeIncreaseBasePriorityPrivilege, nativeApi.RequestedPrivileges);
Assert.Equal(0, nativeApi.ActivePrivilegeScopesCount);
Assert.Equal(1, nativeApi.TotalDisposedPrivilegeScopesCount);
}
[Fact]
public async Task SetIoPriorityAsync_WhenHighPriorityAndSetFails_StillDisposesPrivilegeScope()
{
var nativeApi = new FakeProcessMemoryPriorityNativeApi
{
SetIoPriorityStatus = unchecked((int)0xC0000061),
};
var service = CreateService(nativeApi);
var process = CreateProcess();
var result = await service.SetIoPriorityAsync(process, ProcessIoPriority.High);
Assert.False(result.Success);
Assert.True(result.IsAccessDenied);
Assert.Contains(ProcessMemoryPriorityNativeMethods.SeIncreaseBasePriorityPrivilege, nativeApi.RequestedPrivileges);
Assert.Equal(0, nativeApi.ActivePrivilegeScopesCount);
Assert.Equal(1, nativeApi.TotalDisposedPrivilegeScopesCount);
}
[Theory]
[InlineData(1, ProcessMemoryPriority.VeryLow)]
[InlineData(2, ProcessMemoryPriority.Low)]
[InlineData(3, ProcessMemoryPriority.Medium)]
[InlineData(4, ProcessMemoryPriority.BelowNormal)]
[InlineData(5, ProcessMemoryPriority.Normal)]
public void ProcessMemoryPriority_UsesDocumentedWindowsLevels(int windowsLevel, ProcessMemoryPriority priority)
{
Assert.Equal(windowsLevel, (int)priority);
}
[Fact]
public async Task SetMemoryPriorityAsync_WithNullProcess_ReturnsControlledFailure()
{
var service = CreateService(new FakeProcessMemoryPriorityNativeApi());
var result = await service.SetMemoryPriorityAsync(null!, ProcessMemoryPriority.Normal);
Assert.False(result.Success);
Assert.Equal("InvalidProcess", result.ErrorCode);
Assert.Equal(ProcessOperationUserMessages.ProcessExited, result.UserMessage);
Assert.NotEqual(ProcessMemoryPriorityService.UnsupportedUserMessage, result.UserMessage);
Assert.False(result.IsAccessDenied);
Assert.False(result.IsProcessExited);
}
[Fact]
public async Task SetMemoryPriorityAsync_WithInvalidProcess_DoesNotReturnUnsupportedWindowsMessage()
{
var service = CreateService(new FakeProcessMemoryPriorityNativeApi());
var result = await service.SetMemoryPriorityAsync(new ProcessModel { ProcessId = 0 }, ProcessMemoryPriority.Normal);
Assert.False(result.Success);
Assert.Equal("InvalidProcess", result.ErrorCode);
Assert.Equal(ProcessOperationUserMessages.ProcessExited, result.UserMessage);
Assert.NotEqual(ProcessMemoryPriorityService.UnsupportedUserMessage, result.UserMessage);
}
[Fact]
public async Task SetMemoryPriorityAsync_WithInvalidPriority_ReturnsInvalidPriorityMessage()
{
var service = CreateService(new FakeProcessMemoryPriorityNativeApi());
var result = await service.SetMemoryPriorityAsync(CreateProcess(), (ProcessMemoryPriority)99);
Assert.False(result.Success);
Assert.Equal("InvalidMemoryPriority", result.ErrorCode);
Assert.Equal("This memory priority value is not supported.", result.UserMessage);
Assert.NotEqual(ProcessMemoryPriorityService.UnsupportedUserMessage, result.UserMessage);
}
[Fact]
public async Task SetMemoryPriorityAsync_WhenProcessExited_ReturnsProcessExitedFailure()
{
var service = CreateService(new FakeProcessMemoryPriorityNativeApi
{
OpenException = new InvalidOperationException("The process has exited."),
});
var result = await service.SetMemoryPriorityAsync(CreateProcess(), ProcessMemoryPriority.Normal);
Assert.False(result.Success);
Assert.True(result.IsProcessExited);
Assert.Equal(AffinityApplyErrorCodes.ProcessExited, result.ErrorCode);
Assert.Equal(ProcessOperationUserMessages.ProcessExited, result.UserMessage);
}
[Fact]
public async Task SetMemoryPriorityAsync_WhenAccessDenied_ReturnsSafeAccessDeniedFailure()
{
var service = CreateService(new FakeProcessMemoryPriorityNativeApi
{
SetException = new Win32Exception(5, "Access is denied."),
});
var result = await service.SetMemoryPriorityAsync(CreateProcess(), ProcessMemoryPriority.Normal);
Assert.False(result.Success);
Assert.True(result.IsAccessDenied);
Assert.Equal(AffinityApplyErrorCodes.AccessDenied, result.ErrorCode);
Assert.Equal(ProcessOperationUserMessages.AccessDenied, result.UserMessage);
}
[Fact]
public async Task SetMemoryPriorityAsync_WhenProtectedByAntiCheat_ReturnsMessageWithoutBypassPromise()
{
var service = CreateService(new FakeProcessMemoryPriorityNativeApi
{
SetException = new UnauthorizedAccessException("Protected anti-cheat process."),
});
var result = await service.SetMemoryPriorityAsync(CreateProcess(), ProcessMemoryPriority.Normal);
Assert.False(result.Success);
Assert.True(result.IsAccessDenied);
Assert.True(result.IsAntiCheatLikely);
Assert.Equal(AffinityApplyErrorCodes.AntiCheatOrProtectedProcessLikely, result.ErrorCode);
Assert.Equal(ProcessOperationUserMessages.AntiCheatProtectedLikely, result.UserMessage);
Assert.Equal(
"The process appears protected by anti-cheat or process protection. ThreadPilot will not try to bypass it.",
ProcessOperationUserMessages.AntiCheatProtectedLikely);
Assert.DoesNotContain("disable anti-cheat", result.UserMessage, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("administrator", result.UserMessage, StringComparison.OrdinalIgnoreCase);
Assert.Contains("cannot bypass anti-cheat", ProcessOperationUserMessages.AdminClarification);
}
[Fact]
public async Task SetMemoryPriorityAsync_WhenUnsupported_ReturnsControlledFailure()
{
var service = CreateService(new FakeProcessMemoryPriorityNativeApi { IsSupported = false });
var result = await service.SetMemoryPriorityAsync(CreateProcess(), ProcessMemoryPriority.Normal);
Assert.False(result.Success);
Assert.Equal("Unsupported", result.ErrorCode);
Assert.Equal(ProcessMemoryPriorityService.UnsupportedUserMessage, result.UserMessage);
}
[Fact]
public async Task SetMemoryPriorityAsync_WhenNativeCallFails_ReturnsControlledFailure()
{
var service = CreateService(new FakeProcessMemoryPriorityNativeApi
{
SetResult = false,
LastError = 31,
});
var result = await service.SetMemoryPriorityAsync(CreateProcess(), ProcessMemoryPriority.Normal);
Assert.False(result.Success);
Assert.Equal(AffinityApplyErrorCodes.NativeApplyFailed, result.ErrorCode);
Assert.Contains("SetProcessInformation(ProcessMemoryPriority) failed", result.TechnicalMessage);
}
private static ProcessMemoryPriorityService CreateService(IProcessMemoryPriorityNativeApi nativeApi) =>
new(nativeApi, Microsoft.Extensions.Logging.Abstractions.NullLogger<ProcessMemoryPriorityService>.Instance);
private static ProcessModel CreateProcess() =>
new()
{
ProcessId = 42,
Name = "game.exe",
ExecutablePath = @"C:\Games\Game.exe",
};
private sealed class FakeProcessMemoryPriorityNativeApi : IProcessMemoryPriorityNativeApi
{
public bool IsSupported { get; init; } = true;
public ProcessAccessFlags LastOpenAccess { get; private set; }
public ProcessMemoryPriority? LastSetPriority { get; private set; }
public ProcessMemoryPriority PriorityToReturn { get; init; } = ProcessMemoryPriority.Normal;
public ProcessIoPriority IoPriorityToReturn { get; init; } = ProcessIoPriority.Normal;
public ProcessIoPriority? LastSetIoPriority { get; private set; }
public PowerThrottlingState ThrottlingToReturn { get; init; }
public PowerThrottlingState? LastSetThrottling { get; private set; }
public Exception? OpenException { get; init; }
public Exception? SetException { get; init; }
public bool SetResult { get; init; } = true;
public int LastError { get; init; }
public int SetIoPriorityStatus { get; init; }
public List<string> RequestedPrivileges { get; } = new();
public int ActivePrivilegeScopesCount { get; private set; }
public int TotalDisposedPrivilegeScopesCount { get; private set; }
public SafeProcessHandle OpenProcess(ProcessAccessFlags access, bool inheritHandle, uint processId)
{
this.LastOpenAccess = access;
if (this.OpenException != null)
{
throw this.OpenException;
}
return new SafeProcessHandle(new IntPtr(1), ownsHandle: false);
}
public bool GetProcessInformation(
SafeProcessHandle process,
ProcessInformationClass processInformationClass,
ref MemoryPriorityInformation processInformation,
uint processInformationSize)
{
processInformation.MemoryPriority = (uint)this.PriorityToReturn;
return true;
}
public bool SetProcessInformation(
SafeProcessHandle process,
ProcessInformationClass processInformationClass,
ref MemoryPriorityInformation processInformation,
uint processInformationSize)
{
if (this.SetException != null)
{
throw this.SetException;
}
this.LastSetPriority = (ProcessMemoryPriority)processInformation.MemoryPriority;
return this.SetResult;
}
public int GetLastWin32Error() => this.LastError;
public bool GetPowerThrottling(SafeProcessHandle process, ref PowerThrottlingState state)
{
state = this.ThrottlingToReturn;
return true;
}
public bool SetPowerThrottling(SafeProcessHandle process, ref PowerThrottlingState state)
{
this.LastSetThrottling = state;
return this.SetResult;
}
public int QueryIoPriority(SafeProcessHandle process, ref int priority, out uint returnLength)
{
priority = (int)this.IoPriorityToReturn;
returnLength = sizeof(int);
return 0;
}
public int SetIoPriority(SafeProcessHandle process, ref int priority)
{
this.LastSetIoPriority = (ProcessIoPriority)priority;
return this.SetIoPriorityStatus;
}
public IDisposable AcquirePrivilegeScope(string privilegeName)
{
this.RequestedPrivileges.Add(privilegeName);
this.ActivePrivilegeScopesCount++;
return new FakePrivilegeScope(() =>
{
this.ActivePrivilegeScopesCount--;
this.TotalDisposedPrivilegeScopesCount++;
});
}
private sealed class FakePrivilegeScope : IDisposable
{
private readonly Action onDispose;
private bool disposed;
public FakePrivilegeScope(Action onDispose)
{
this.onDispose = onDispose;
}
public void Dispose()
{
if (!this.disposed)
{
this.disposed = true;
this.onDispose();
}
}
}
}
}
}