diff --git a/docs/docs/execution/parallelism.md b/docs/docs/execution/parallelism.md index 84579d0cdf..13d045ce0a 100644 --- a/docs/docs/execution/parallelism.md +++ b/docs/docs/execution/parallelism.md @@ -264,7 +264,7 @@ Nothing is measured in the first 2 seconds of a run, so a test project that fini - **The limit that admits the load.** When most of the running tests are inside one `[ParallelLimiter]`, saturated CPUs lower that limiter's limit and leave the session-wide limit alone: a lower session-wide limit changes nothing for tests that a limiter already holds back. A limiter's limit can go below the processor count for this, down to its lowest limit, because its tests can each use several processors. A limiter that would not lower now (it is at its lowest limit, or is waiting after a lowering that was put back) is left out, and the session-wide limit is lowered as usual. - **Holding under other processes' load.** At the starting limit or below it, when the CPUs are saturated but the test process and the processes it started use less than half of the machine's CPU capacity, the limit stays where it is. Running fewer tests could not relieve the CPUs, and throughput measured while other processes move the load says little. This is the usual case on a CI runner that runs several test processes at once. Browsers and other programs the tests start count as the test process's own load, and so does whatever those start. Containers do not, because they are children of the container runtime, and neither does a process whose parent has exited. Suites that spend most of their CPU time in containers are therefore not lowered for CPU. When a container CPU quota is what throttles the test process, the share is measured against the quota instead of the machine, so a process at its quota always counts as the cause. - **Lowering for memory.** When the machine or container is nearly out of memory, TUnit halves the limit at once, without a trial, because swapping or an out-of-memory kill costs more than a slower run. -- **Returning.** After memory pressure, TUnit steps back up as soon as the machine has headroom. After a lowering for CPU that was kept, it steps back up once the CPUs have gone 15 seconds without being saturated, and otherwise tries the step up like any other raise after the same wait. The wait doubles, up to 2 minutes, each time the way back fails: the limit came back and was lowered again, or the trial was put back. Tests that alternate between CPU-bound work and waiting therefore settle at the lower limit and do not move back and forth. +- **Returning.** After memory pressure, TUnit steps back up as soon as the machine has headroom. After a lowering for CPU that was kept, it steps back up once the CPUs have gone 15 seconds without being saturated, and otherwise tries the step up like any other raise after the same wait. The wait doubles, up to 2 minutes, each time the way back fails: the limit came back and was lowered again, or the trial was put back. Tests that alternate between CPU-bound work and waiting therefore settle at the lower limit and do not move back and forth. There is one shortcut: when throughput falls below what the lowering was kept on, while tests wait for the limit and the CPUs are less than 50% busy, the limit steps back up after a quarter of the wait. The tests have changed, and the lower limit now holds back tests that would not load the CPUs. Running tests are never interrupted; a lower limit takes effect as they finish. @@ -295,9 +295,11 @@ A `[ParallelLimiter]` whose type implements only `IParallelLimit` keeps its d When tests waited for such a limiter for a tenth of the run or more, the summary says so. A shorter wait is written at `--log-level Debug` only, so a deliberate cap does not add a line to every run: ```text -[ParallelLimiter] DatabaseLimit: the limit stayed at 2. Tests waited for it for 2m 30s while the CPUs were 30% busy. Adaptive parallelism never raises a declared limit. If it is not a hard cap, a higher limit, or no limiter, may shorten the run. +[ParallelLimiter] DatabaseLimit (MyTests, net10.0): the limit stayed at 2. Tests waited for it for 2m 30s while the CPUs were 30% busy. Adaptive parallelism never raises a declared limit. If it is not a hard cap, a higher limit, or no limiter, may shorten the run. ``` +The last two sentences are advice that holds for every declared limit, so only the first such line of a run carries them. + If a limiter is there only to keep the load on the machine down, remove it and let adaptive parallelism manage the load. Keep limiters for hard caps. ### What TUnit measures @@ -306,7 +308,7 @@ The readings cover the whole machine, not only the test process, because other t | | CPU | Memory | |---|---|---| -| **Linux** | Busy time from `/proc/stat`. Work is waiting for a CPU when the kernel's pressure stall information reports tasks stalled, or a container's CPU quota throttled the process, for a tenth of the time or more. | Available memory from `/proc/meminfo`, or the container's limit and usage under cgroup v2. Nearly out of memory means 95% in use, or tasks repeatedly stalled waiting for memory to be reclaimed. | +| **Linux** | Busy time from `/proc/stat`. Work is waiting for a CPU when a container's CPU quota throttled the process for a tenth of the time or more, or when the kernel's pressure stall information reports tasks stalled for that long while the CPUs are at least 80% busy. Tasks that wait for a moment on a machine that is mostly idle do not count. | Available memory from `/proc/meminfo`, or the container's limit and usage under cgroup v2. Nearly out of memory means 95% in use, or tasks repeatedly stalled waiting for memory to be reclaimed. | | **Windows** | Busy time across all processor groups. | Physical memory in use; 95% counts as nearly out. | | **macOS** | Busy time across all processors. | The kernel's own memory pressure level: a warning stops the limit being raised, and critical counts as nearly out. | @@ -319,24 +321,33 @@ Machine load alone does not move the limit. Tests that wait on a shared resource The run ends with one line that says where the limit went and what held the run back the most. A limit that tests did not wait for is not worth tuning, so the line names what they did wait for: ```text -Adaptive parallelism: the parallel test limit went from 8 to 18 (lowest 6, highest 27, 12 changes, 5 put back). Tests waited for it for 9m 40s of 13m 10s, with the CPUs 24% busy; it was not raised mostly because throughput kept changing between measurements. +Adaptive parallelism (MyTests, net10.0): the parallel test limit went from 8 to 18 (lowest 6, highest 27, 12 changes, 5 put back). Tests waited for it for 9m 40s of 13m 10s, with the CPUs 64% busy; it was not raised further mostly because the CPUs had no headroom (93% busy at those times). ``` +Every line names the test project and target framework it is from, because `dotnet test` prints the lines of several test processes between each other's results. + | The line says | What it means | |---|---| | `Tests waited for it for ...` | The session-wide limit held tests back, with the CPU use over that time and the reason it was most often not raised. | +| `(93% busy at those times)` | The CPU use while that reason applied, when it differs from the figure for the whole wait. A suite that saturates the CPUs for part of the wait and idles for the rest has a low average and still had no headroom. | +| `most of their load came from other processes or containers` | The CPUs had no headroom, and the test process and the processes it started used less than half of what was in use. | +| `too few measurements completed to try a raise` | A raise is tried only on throughput that was measured twice. A short run, or one of slow tests, does not get that far. | +| `The run was too short to measure` | The run ended within the first 2 seconds, before anything is measured. | +| `Also, for ...` | What held tests back second-longest, when that was a fifth of the run or more. | | `tests marked [NotInParallel] ran one at a time` | Tests marked `[NotInParallel]` without a key ran alone for that long. No limit changes that. Give them constraint keys, or remove the attribute where it is not needed. | -| `tests waited for a [NotInParallel] key` | Tests that share a key ran one after another while the limit had room. The key that tests waited for the longest is named. | +| `tests waited for the [NotInParallel] key "X"` | Tests that share a key ran one after another while the limit had room. With several keys, the one that tests waited for the longest is named. | | `tests waited for [ParallelLimiter] X, not for this limit` | That limiter held tests back while the session-wide limit had room. The limiter has a line of its own. | | `Tests seldom waited for it` | Fewer tests were ready to run than the limit allows for most of the run. | -| `The tests are probably waiting on something other than the CPUs or this limit` | Raises brought nothing while the CPUs were mostly idle. The tests wait on something TUnit cannot see, such as a lock or a semaphore taken in a hook, a shared fixture, or an external service. | +| `The tests are probably waiting on something other than the CPUs or this limit` | Tests waited for the limit while the CPUs were mostly idle, and raises brought nothing or throughput never settled enough to try one. The tests wait on something TUnit cannot see, such as a lock or a semaphore taken in a hook, a shared fixture, or an external service. If it is a cap of your own, declare it with `[ParallelLimiter]` so the summary can name it. | -When the limit moved, a second line gives the figures: how long the run spent at each limit, the average CPU use of the machine and of the test process, and how long saturated CPUs were left alone because other processes caused the load. When the limit did not move, that line is written at `--log-level Debug`. +When the limit moved, a second line gives the figures: how long the run spent at each limit, how many changes of each kind were made, the average CPU use of the machine and of the test process, and how long saturated CPUs were left alone because other processes caused the load. When the limit did not move, that line is written at `--log-level Debug`. ```text -Adaptive parallelism details: time at each limit: 6 for 2s, 8 for 28s, 12 for 59s, 18 for 11m 18s, 27 for 19s. The machine's CPUs were 24% busy on average, and this process alone used 21% of them. +Adaptive parallelism details (MyTests, net10.0): time at each limit: 6 for 2s, 8 for 28s, 12 for 59s, 18 for 11m 18s, 27 for 19s. Changes: 7x raised to try more tests, 4x raise put back for no gain in throughput, 1x raise put back because it left the CPUs busy, 2x lowered for saturated CPUs, 2x raised back after pressure eased. The machine's CPUs were 64% busy on average, and this process alone used 58% of them. ``` +A limit that changed as the last tests finished reads `6 as the run ended`: that change never took effect. + Both lines are also shown when `dotnet test` runs several test projects at once. The test process's figure does not include the processes the tests start, such as browsers. TUnit reads those from the moment the CPUs are nearly saturated while the test process alone uses less than half of them, and for a minute after that. When it has read them, the details line adds their share over that time: @@ -376,7 +387,7 @@ wait The parts are equal whatever each process has left to run: a process whose remaining tests are few, or held by a `[NotInParallel]` constraint, keeps its part until it finishes. -With [adaptive parallelism](#adaptive-parallelism), a process's part is where its limit starts, not the most it runs. When another process joins, the limit comes down to the smaller part at once. From there it moves as the machine allows: while the CPUs are busy it stays at the part, and once they have room it returns to the limit the process would have alone, and goes beyond that on a measured gain. So test processes that use the CPUs keep to their parts, and test processes that mostly wait on I/O do not lose slots that nothing else can use. +With [adaptive parallelism](#adaptive-parallelism), a process's part is where its limit starts, not the most it runs. When another process joins, the limit comes down to the smaller part at once. From there it moves as the machine allows. Once the CPUs have room it returns to the limit the process would have alone, and goes beyond that on a measured gain. While the CPUs are busy it stays at the part when the processes that share the budget are what keeps them busy. TUnit takes that to be the case when this process's share of the machine's CPU capacity, times the number of processes in the budget, is half or more. The share includes the processes the tests start, such as browsers, and the limit does not leave its part before those have been read. Below that, the load comes from elsewhere, such as containers the tests start, and staying at the part would relieve nothing: when tests wait for the limit, it returns to the limit the process would have alone, as a process without a budget is not lowered for such load either. So test processes that use the CPUs keep to their parts, and test processes that mostly wait on I/O do not lose slots that nothing else can use. A test process that one of the tests starts does not join the budget, although it inherits the variable. It runs inside that test, and as a member it would take a part away from the process that started it. @@ -386,7 +397,7 @@ The processes find each other through files in the temporary directory that each Shared parallel budget 'ci-tests': up to 3 test processes shared a budget of 8, and this one ran at most 2 to 8 tests in parallel ``` -With adaptive parallelism it reads `this one had a part of 2 to 8 tests in parallel, which is where its adaptive limit starts`, and the adaptive parallelism summary says where the limit went. +With adaptive parallelism it reads `this one had a part of 2 to 8 tests in parallel (the part grows as other processes finish), which is where its adaptive limit starts`, and the adaptive parallelism summary says where the limit went. ## When to Use Which diff --git a/src/TUnit.Engine/Scheduling/AdaptiveLimiterTrials.cs b/src/TUnit.Engine/Scheduling/AdaptiveLimiterTrials.cs index 7b889814d8..7fe488b6c0 100644 --- a/src/TUnit.Engine/Scheduling/AdaptiveLimiterTrials.cs +++ b/src/TUnit.Engine/Scheduling/AdaptiveLimiterTrials.cs @@ -378,6 +378,10 @@ public void Stop(bool resetLimits = false) // A limiter whose first test arrived after the last update is reported too. AddNewLimiters(); + // What to do about a declared limit is said once, on the first line that needs + // it: on every line it was half of each of them (#7915). + var adviceGiven = false; + foreach (var limiter in _limiters) { if (resetLimits) @@ -392,21 +396,28 @@ public void Stop(bool resetLimits = false) // tests ran at once can only be understood from a log that says how many did. if (summary.IsWorthReporting(_elapsed)) { - _logger.LogSessionMessage(FormatSummary(summary)); + _logger.LogSessionMessage(FormatSummary(summary, TestProcessName.Current, includeAdvice: !adviceGiven)); + adviceGiven |= summary.HasAdvice; } else if (summary.Waited > TimeSpan.Zero && _logger.IsEnabled(LogLevel.Debug)) { // A deliberate cap that tests waited for a little: there for whoever asks. - _logger.LogDebug(FormatSummary(summary)); + // It neither carries the advice nor counts as having given it: the + // advice belongs on a line every run shows, and those say it once. + _logger.LogDebug(FormatSummary(summary, TestProcessName.Current, includeAdvice: false)); } } } } - internal static string FormatSummary(AdaptiveLimiterSummary summary) + /// Where the limiter's limit went. + /// The test process the line is from. + /// Whether to say what to do about a declared limit that tests waited for. False once another limiter's line has said it. + internal static string FormatSummary(AdaptiveLimiterSummary summary, string? processName = null, bool includeAdvice = true) { var text = new System.Text.StringBuilder(); - text.Append("[ParallelLimiter] ").Append(summary.Name).Append(": the limit "); + text.Append("[ParallelLimiter] ").Append(summary.Name); + TestProcessName.AppendTo(text, processName).Append(": the limit "); AdaptiveParallelismSummary.AppendLimit(text, summary.StartLimit, summary.CurrentLimit, summary.LowestLimit, summary.HighestLimit, summary.Changes, summary.ChangesPutBack); if (summary.Waited <= TimeSpan.Zero) @@ -429,18 +440,24 @@ internal static string FormatSummary(AdaptiveLimiterSummary summary) { // The limit is the user's to change, so say what the wait cost and what the // machine was doing meanwhile. - text.Append(System.Globalization.CultureInfo.InvariantCulture, $" while the CPUs were {summary.CpuUtilizationWhileWaiting * 100:0}% busy. "); + text.Append(System.Globalization.CultureInfo.InvariantCulture, $" while the CPUs were {summary.CpuUtilizationWhileWaiting * 100:0}% busy."); // Part of the wait is adaptive parallelism's own doing when it took the limit // down: say so before any advice about the limit as declared. if (summary.LowestLimit < summary.StartLimit) { - text.Append("Adaptive parallelism lowered it while its tests saturated the CPUs, which is part of that wait. "); + text.Append(" Adaptive parallelism lowered it while its tests saturated the CPUs, which is part of that wait."); } - text.Append(summary.DeclaredAdaptive - ? "Its MaximumLimit is not above the limit it starts at, so it could not be raised: set a higher MaximumLimit to let it." - : "Adaptive parallelism never raises a declared limit. If it is not a hard cap, a higher limit, or no limiter, may shorten the run."); + if (summary.DeclaredAdaptive) + { + // About this limiter's own bounds, so it is said for each. + text.Append(" Its MaximumLimit is not above the limit it starts at, so it could not be raised: set a higher MaximumLimit to let it."); + } + else if (includeAdvice && summary.HasAdvice) + { + text.Append(" Adaptive parallelism never raises a declared limit. If it is not a hard cap, a higher limit, or no limiter, may shorten the run."); + } } return text.ToString(); @@ -599,6 +616,12 @@ internal readonly record struct AdaptiveLimiterSummary( AdaptiveRaiseBlocker MostCommonRaiseBlocker = AdaptiveRaiseBlocker.None, double CpuUtilizationWhileWaiting = 0) { + /// + /// Whether the line ends with advice that is the same for every declared limit, so one + /// line of a run is enough to carry it. + /// + public bool HasAdvice => Waited > TimeSpan.Zero && !CanBeRaised && !DeclaredAdaptive; + /// /// Whether the limiter gets a line in the output of every run. /// diff --git a/src/TUnit.Engine/Scheduling/AdaptiveParallelismController.cs b/src/TUnit.Engine/Scheduling/AdaptiveParallelismController.cs index 269df25853..f6b6da48e1 100644 --- a/src/TUnit.Engine/Scheduling/AdaptiveParallelismController.cs +++ b/src/TUnit.Engine/Scheduling/AdaptiveParallelismController.cs @@ -72,6 +72,9 @@ internal sealed class AdaptiveParallelismController : IDisposable private int _highestLimit; private int _changes; private int _changesPutBack; + + // How many changes of each kind were made, for the summary's details. + private readonly int[] _changesByKind = new int[Enum.GetValues().Length]; private bool _stopped; private bool _failed; @@ -217,7 +220,7 @@ private void Run() { // Within this process's part of a shared budget, which is not a ceiling for // an adaptive limit: nothing else would keep it there from now on. - TrySetLimit(_limiter.FallbackLimit, putBack: false, expectedSlotChanges: null, out _, out _); + TrySetLimit(_limiter.FallbackLimit, AdaptiveLimitChange.None, expectedSlotChanges: null, out _, out _); // Nothing moves the limit from here on, so it follows the part again. _limiter.FollowShare(); @@ -324,8 +327,15 @@ private void Sample(ParallelismLimits limits) // Tests that drive browsers or other programs use most of their CPU time there. // It is this process's load all the same: fewer tests would start fewer of them. + // With a shared budget they are read from the level at which the CPUs have no + // headroom: from there the limit can leave its part on the strength of this + // process's share alone, which must not leave out the browsers its tests drive. + var childProcessSamplingFrom = _limiter.ShareMembers > 1 + ? AdaptiveParallelismPolicy.CpuHeadroomUtilization + : ChildProcessSamplingCpuUtilization; + if (GetProcessShare(processCores, ownCapacity, machineCpuCount, machineCpuUtilization, machineLoad.CpuThrottled) < AdaptiveParallelismPolicy.OwnSaturationShare - && (machineLoad.CpuStalled || cpuUtilization >= ChildProcessSamplingCpuUtilization)) + && (machineLoad.CpuStalled || cpuUtilization >= childProcessSamplingFrom)) { childProcessesWantedUntil = timestamp + (long) (ChildProcessSamplingHold.TotalSeconds * Stopwatch.Frequency); } @@ -365,6 +375,7 @@ private void Sample(ParallelismLimits limits) } var queueDelay = SampleQueueDelay(timestamp); + var cpuStalled = IsCpuStalled(machineLoad, cpuUtilization); _explorationBudget.Advance(elapsed); // The reading every limit is decided from. Each policy adds its own tests to it. @@ -376,7 +387,7 @@ private void Sample(ParallelismLimits limits) queueDelay, CompletedTests: 0, LimitReached: false, - machineLoad.CpuStalled, + cpuStalled, OwnCores: ownCores, OwnCoresChangedBasis: ownCoresChangedBasis); @@ -434,11 +445,13 @@ private void Sample(ParallelismLimits limits) TrialsBlocked = _limiterTrials?.IsBusy ?? false, PressureElsewhere = pressureOwner is not null, OverLimit = _limiter.HeldSlots > _limiter.CurrentLimit, + BudgetMembers = _limiter.ShareMembers, + ProcessShareCountsChildProcesses = childProcesses.HasReading || childProcesses.Unavailable, }); } if (decision.Change != AdaptiveLimitChange.None - && TrySetLimit(decision.Limit, AdaptiveParallelismSummary.IsPutBack(decision.Change), previousSlotChanges, out var previousLimit, out var limit)) + && TrySetLimit(decision.Limit, decision.Change, previousSlotChanges, out var previousLimit, out var limit)) { // One change of the number of slots, and this loop's own: counted here, // not read back, so a change from elsewhere in the meantime still shows @@ -475,7 +488,13 @@ private void Sample(ParallelismLimits limits) policy.HeldForOutsideLoad, childProcesses.HasReading ? childProcessCpu : null, bottleneck, - bindingLimiter?.LimitType.Name); + bindingLimiter?.LimitType.Name, + // The figure the policy decides from, which is the higher one for a + // process bound to some of the processors or held to a CPU quota. + decisionCpuUtilization: cpuUtilization, + cpuBusy: cpuStalled + || cpuUtilization >= AdaptiveParallelismPolicy.CpuHeadroomUtilization + || queueDelay >= AdaptiveParallelismPolicy.QueueDelayLimit); } // Said once: the state can come and go with every sample, and the summary has the total. @@ -537,11 +556,24 @@ internal static double GetProcessShare(double cores, double ownCapacity, int mac : Math.Min(1, cores / Math.Max(1, machineCpuCount)); } + /// + /// Whether tasks waiting for a CPU count as the CPUs being short. A quota that throttles + /// the process always does. Tasks that wait while the CPUs are mostly idle do not: on a + /// machine with a few processors, tests that wake up together wait for one for a moment + /// however little work there is, and a limit lowered for that ran half as many tests at + /// half the CPU use (#7915). + /// + /// The reading of the machine. + /// Share of the CPU capacity in use, 0 to 1. + internal static bool IsCpuStalled(MachineLoad load, double cpuUtilization) + => load.CpuThrottled + || (load.CpuStalled && cpuUtilization >= AdaptiveParallelismPolicy.CpuHeadroomUtilization); + /// /// Resizes the limiter unless the controller has stopped. Returns whether the limit changed. /// /// The limit the policy decided. - /// Whether the change undoes one that did not help. + /// Why it changes, or when no policy decided it. /// /// The count of slot changes the decision was made under, or null to resize /// whatever happened since. With another count the limit is left as it is: the sample @@ -549,7 +581,7 @@ internal static double GetProcessShare(double cores, double ownCapacity, int mac /// /// The limit before the call. /// The limit after it. - private bool TrySetLimit(int requestedLimit, bool putBack, long? expectedSlotChanges, out int previousLimit, out int limit) + private bool TrySetLimit(int requestedLimit, AdaptiveLimitChange change, long? expectedSlotChanges, out int previousLimit, out int limit) { lock (_stateLock) { @@ -574,8 +606,9 @@ private bool TrySetLimit(int requestedLimit, bool putBack, long? expectedSlotCha _lowestLimit = Math.Min(_lowestLimit, limit); _highestLimit = Math.Max(_highestLimit, limit); _changes++; + _changesByKind[(int) change]++; - if (putBack) + if (AdaptiveParallelismSummary.IsPutBack(change)) { _changesPutBack++; } @@ -699,12 +732,17 @@ public void Dispose() // Against the whole run, warm-up included: that is the duration the reader // sees next to this line. var statistics = _totals.ToStatistics() is { } totals - ? totals with { RunTime = Stopwatch.GetElapsedTime(_startedAt), MostWaitedKey = _limiter.Activity.MostWaitedKey?.Key } + ? totals with + { + RunTime = Stopwatch.GetElapsedTime(_startedAt), + MostWaitedKey = _limiter.Activity.MostWaitedKey?.Key, + KeysWaitedFor = _limiter.Activity.KeysWaitedFor, + } : (AdaptiveRunStatistics?) null; moved = _changes > 0; - summary = AdaptiveParallelismSummary.Format(_startLimit, _limiter.CurrentLimit, _lowestLimit, _highestLimit, _changes, _changesPutBack, statistics); - details = AdaptiveParallelismSummary.FormatDetails(_timeAtLimit, statistics); + summary = AdaptiveParallelismSummary.Format(_startLimit, _limiter.CurrentLimit, _lowestLimit, _highestLimit, _changes, _changesPutBack, statistics, TestProcessName.Current); + details = AdaptiveParallelismSummary.FormatDetails(_timeAtLimit, statistics, _changesByKind, _limiter.CurrentLimit, TestProcessName.Current); if (_failed) { diff --git a/src/TUnit.Engine/Scheduling/AdaptiveParallelismPolicy.cs b/src/TUnit.Engine/Scheduling/AdaptiveParallelismPolicy.cs index d4b21e6fb6..36340c86e5 100644 --- a/src/TUnit.Engine/Scheduling/AdaptiveParallelismPolicy.cs +++ b/src/TUnit.Engine/Scheduling/AdaptiveParallelismPolicy.cs @@ -17,6 +17,8 @@ namespace TUnit.Engine.Scheduling; /// Whether saturated CPUs are another limit's to relieve, because most of the running tests are inside it. /// Whether started or stopped including child processes with this sample, so it cannot be compared with the samples before it. /// Whether more tests are running than the limit admits: a lowered limit takes effect only as the tests that were already running finish. +/// How many test processes share the budget that this limit's start is a part of, this one included. 0 or 1 when it shares none. +/// Whether includes the child processes, or they cannot be read on this machine at all. False while they have not been read yet, when the figure may leave out most of this process's load. internal readonly record struct AdaptiveSample( TimeSpan Elapsed, double CpuUtilization, @@ -31,8 +33,11 @@ internal readonly record struct AdaptiveSample( double OwnCores = 0, bool PressureElsewhere = false, bool OverLimit = false, - bool OwnCoresChangedBasis = false); + bool OwnCoresChangedBasis = false, + int BudgetMembers = 0, + bool ProcessShareCountsChildProcesses = true); +// Values count up from 0 with no gaps: they index arrays that count changes by kind. internal enum AdaptiveLimitChange { None, @@ -72,6 +77,12 @@ internal enum AdaptiveLimitChange /// was being measured (this process's part of a shared budget), so the trial was dropped. /// TrialAbandoned, + + /// + /// Raised from this process's part of a shared budget toward the starting limit: tests + /// waited for the limit, and the busy CPUs were not the doing of the budget's members. + /// + PartOutgrown, } internal readonly record struct AdaptiveDecision(int Limit, AdaptiveLimitChange Change); @@ -109,6 +120,7 @@ internal sealed class AdaptiveExplorationBudget /// /// Why the latest measurement window did not end in a raise. /// +// Values count up from 0 with no gaps: they index arrays that add up time by reason. internal enum AdaptiveRaiseBlocker { /// No window has ended yet, or the latest one ended in a change. @@ -204,6 +216,13 @@ internal enum AdaptiveRaiseBlocker /// run of failed trials from costing much against a fixed limit. A lowering for saturated /// CPUs still starts: it has its own wait after one that was put back. /// +/// +/// A limit that starts below the starting one, at this process's part of a budget it shares +/// with other test processes, is there to keep the members from oversubscribing the CPUs +/// between them. It returns to the starting limit without a trial when the CPUs have +/// headroom, and also when they are busy with load that is not the members' own: the same +/// reasoning that holds a limit under other processes' load. +/// /// internal sealed class AdaptiveParallelismPolicy { @@ -224,6 +243,16 @@ internal sealed class AdaptiveParallelismPolicy // tests used it up, and from here they only take CPU time from each other. internal const double ProbeCpuCeiling = 0.9; + // CPUs less busy than this are idle: there is room for more tests that use them. + internal const double IdleCpuUtilization = 0.5; + + // A kept lowering is undone after this share of its wait when it has started to cost + // throughput while the CPUs are idle and tests wait for the limit. The lowering was to + // relieve saturated CPUs, and now they are unused with tests held back: slow tests that + // mostly wait fill the few slots, and every second at the lower limit is lost (#7915). + // A share of the wait, so a suite that goes back and forth still waits longer each time. + internal const double IdleRecoveryHoldShare = 0.25; + internal const double MemoryPressureLoad = 1.0; // Longer than OS scheduling jitter, shorter than a delay a timing-sensitive test would notice. @@ -412,6 +441,10 @@ internal sealed class AdaptiveParallelismPolicy private bool _keepingLowering; private bool _recoveredFromKeptLowering; + // Whether the limit is below the starting one because this process's part of a shared + // budget put it there, and not because of anything this policy measured. + private bool _belowStartForPart; + // While pressure is recent, the limit stays below the one that caused it. private int _pressureCap = int.MaxValue; private TimeSpan _pressureCapUntil; @@ -421,6 +454,13 @@ internal sealed class AdaptiveParallelismPolicy private TimeSpan _windowElapsed; private long _windowCompleted; private double _windowCpuSeconds; + // Over the samples since the figure last started or stopped including child processes, + // which can be fewer than the window's. + private double _windowProcessCpuSeconds; + private TimeSpan _windowProcessElapsed; + + // Whether any of those samples left the child processes out because they were not read. + private bool _windowProcessShareIncomplete; private double _windowMaxMemoryLoad; private int _windowSamples; private int _windowLimitReachedSamples; @@ -531,6 +571,13 @@ public AdaptiveDecision OnSample(AdaptiveSample sample) ResetWork(); _workBeforeLowering = 0; + // The share of the CPUs is the same figure, so its average starts over too: a + // window of two seconds without the child processes and one with them would + // read as a third of what they use. + _windowProcessCpuSeconds = 0; + _windowProcessElapsed = TimeSpan.Zero; + _windowProcessShareIncomplete = false; + if (_trial == AdaptiveLimitChange.CpuSaturation && _trialJudgedByWork) { return GiveUpLowering(); @@ -613,6 +660,16 @@ public AdaptiveDecision OnSample(AdaptiveSample sample) var measurable = _windowCompleted >= MinimumWindowCompletions && limitReached; var cpuUtilization = _windowCpuSeconds / _windowElapsed.TotalSeconds; + + // With nothing measured on the current basis, the share counts as all of the CPUs: + // nothing is done on the strength of a figure that is not there. + var processCpuUtilization = _windowProcessElapsed > TimeSpan.Zero + ? _windowProcessCpuSeconds / _windowProcessElapsed.TotalSeconds + : 1; + + // Tests that drive browsers use their CPU time in child processes. Until those have + // been read, a small share says nothing about whose load keeps the CPUs busy. + var processShareKnown = !_windowProcessShareIncomplete; var cpuStalled = _windowCpuStalledSamples * 4 >= _windowSamples; var hasMemoryHeadroom = _windowMaxMemoryLoad < MemoryHeadroomLoad; @@ -690,6 +747,7 @@ public AdaptiveDecision OnSample(AdaptiveSample sample) _memoryHold = MemoryPressureHold; _recoveryHold = InitialRecoveryHold; _strongGain = throughput >= _throughputBeforeTrial * (1 + change * StrongGainShare); + _belowStartForPart &= _limit < _limits.Initial; EndLoweringRunAt(_limit); } else @@ -741,6 +799,10 @@ public AdaptiveDecision OnSample(AdaptiveSample sample) : AdaptiveRaiseBlocker.WaitingAfterFailedRaise); } + // Whether only busy CPUs stand between a limit below the starting one and its return: + // with headroom it would go back without a trial. + var needsTrialForBusyCpus = false; + var higher = Math.Min(ceiling, Math.Max(_limit + 1, (int) Math.Ceiling(_limit * (_strongGain ? StrongIncreaseFactor : IncreaseFactor)))); if (_limit < _limits.Initial) @@ -750,7 +812,24 @@ public AdaptiveDecision OnSample(AdaptiveSample sample) if (_keepingLowering && (hasCpuHeadroom ? _clock - _lastSaturatedAt < _recoveryHold : _clock < _recoveryHoldUntil)) { - return NoRaise(AdaptiveRaiseBlocker.KeepingLowerLimit); + // The lowering was kept because it cost no throughput. Idle CPUs alone do not + // undo it early: tests that alternate between computing and waiting would + // take the limit down and up with every phase (#7889). Idle CPUs with + // tests waiting for the limit and throughput below what the lowering was + // judged against do: the tests have changed, the few slots are now full of + // ones that mostly wait, and the lower limit costs what it was kept for + // not costing. + var idleWhileTestsWait = hasCpuHeadroom + && measurable + && cpuUtilization < IdleCpuUtilization + && _throughputBeforeLowering > 0 + && throughput < _throughputBeforeLowering * (1 - (1 - CpuDecreaseFactor) * MinimumGainShare) + && (_clock - _lastSaturatedAt).Ticks >= _recoveryHold.Ticks * IdleRecoveryHoldShare; + + if (!idleWhileTestsWait) + { + return NoRaise(AdaptiveRaiseBlocker.KeepingLowerLimit); + } } higher = Math.Min(higher, _limits.Initial); @@ -762,9 +841,25 @@ public AdaptiveDecision OnSample(AdaptiveSample sample) return ChangeLimit(higher, AdaptiveLimitChange.Recovery); } + // A part of a shared budget is where the limit starts, to keep the budget's + // members from oversubscribing the CPUs between them. When the CPUs are busy + // and the members use little of them, the load is someone else's (containers, + // other programs), and staying at the part relieves nothing: a process without + // a budget is not lowered for such load either, and a trial could not show a + // gain while that load moves throughput about (#7915). The other members are + // taken to use what this one does, which is all it can know of them. + if (_belowStartForPart + && limitReached + && processShareKnown + && processCpuUtilization * Math.Max(1, sample.BudgetMembers) < OwnSaturationShare) + { + return ChangeLimit(higher, AdaptiveLimitChange.PartOutgrown); + } + // Busy CPUs are no reason to stay below the starting limit when the tests have // changed, or other processes are what keeps the CPUs busy. Without headroom the // way back is a trial like any other. + needsTrialForBusyCpus = limitReached; } else if (!hasCpuHeadroom) { @@ -773,8 +868,11 @@ public AdaptiveDecision OnSample(AdaptiveSample sample) if (_steadyLimit != _limit) { - return NoRaise(measurable - ? AdaptiveRaiseBlocker.ThroughputNotSteady + // Below the starting limit the busy CPUs are the reason, and the one to give: + // "throughput kept changing" at 97% CPU sends the reader looking for unsteady + // tests (#7915). + return NoRaise(needsTrialForBusyCpus ? AdaptiveRaiseBlocker.CpuBusy + : measurable ? AdaptiveRaiseBlocker.ThroughputNotSteady : limitReached ? AdaptiveRaiseBlocker.TooFewTests : AdaptiveRaiseBlocker.LimitNotReached); } @@ -876,6 +974,10 @@ private AdaptiveDecision RejectLowering() private void AcceptLowering() { _trial = AdaptiveLimitChange.None; + + // From here the limit is where this policy's own measurement put it. Not before: + // a lowering that is put back leaves the limit where the part put it. + _belowStartForPart = false; _lowerHold = InitialLowerHold; // The gain that earned a doubling was measured before the CPUs saturated: the next @@ -968,6 +1070,7 @@ public void Rebase(TimeSpan elapsed, int limit) ResetMeasurements(); _trial = AdaptiveLimitChange.None; ChangeLimit(Math.Min(Math.Max(limit, _limits.Minimum), _limits.Maximum), AdaptiveLimitChange.None); + _belowStartForPart = _limit < _limits.Initial; } private void ResetMeasurements() @@ -1166,6 +1269,7 @@ private AdaptiveDecision LowerForMemoryPressure() _pressureCooldownUntil = _clock + PressureCooldown; _saturatedSamples = 0; _trial = AdaptiveLimitChange.None; + _belowStartForPart = false; // Whatever run of lowerings was in progress is over: the next one is judged // against a fresh measurement, of throughput or of CPU time. @@ -1202,6 +1306,14 @@ private void HoldRaises() private AdaptiveDecision ChangeLimit(int limit, AdaptiveLimitChange change) { _limit = limit; + + // Not while a raise is on trial: one that reaches the starting limit and is put + // back leaves the limit where the part put it, and it must still count as that. + if (_trial == AdaptiveLimitChange.None) + { + _belowStartForPart &= limit < _limits.Initial; + } + RaiseBlocker = AdaptiveRaiseBlocker.None; _lastLimit = 0; _steadyLimit = 0; @@ -1221,6 +1333,9 @@ private void Accumulate(AdaptiveSample sample) _windowElapsed += sample.Elapsed; _windowCompleted += sample.CompletedTests; _windowCpuSeconds += sample.CpuUtilization * sample.Elapsed.TotalSeconds; + _windowProcessCpuSeconds += sample.ProcessCpuUtilization * sample.Elapsed.TotalSeconds; + _windowProcessElapsed += sample.Elapsed; + _windowProcessShareIncomplete |= !sample.ProcessShareCountsChildProcesses; _windowMaxMemoryLoad = Math.Max(_windowMaxMemoryLoad, sample.MemoryLoad); _windowSamples++; @@ -1282,6 +1397,9 @@ private void ResetWindow() _windowElapsed = TimeSpan.Zero; _windowCompleted = 0; _windowCpuSeconds = 0; + _windowProcessCpuSeconds = 0; + _windowProcessElapsed = TimeSpan.Zero; + _windowProcessShareIncomplete = false; _windowMaxMemoryLoad = 0; _windowSamples = 0; _windowLimitReachedSamples = 0; diff --git a/src/TUnit.Engine/Scheduling/AdaptiveParallelismSummary.cs b/src/TUnit.Engine/Scheduling/AdaptiveParallelismSummary.cs index da57572d23..fbd0c49156 100644 --- a/src/TUnit.Engine/Scheduling/AdaptiveParallelismSummary.cs +++ b/src/TUnit.Engine/Scheduling/AdaptiveParallelismSummary.cs @@ -37,6 +37,20 @@ internal sealed class AdaptiveRunTotals private double _machineCpuSeconds; private double _processCpuSeconds; private double _cpuSecondsWhileWaiting; + private readonly double[] _cpuSecondsNotRaising = new double[AdaptiveParallelismSummary.RaiseBlockerCount]; + + // Over the samples charged to "the CPUs had no headroom" only: what the machine used and + // what this process and its child processes used, to say whose load it was at those times. + private double _machineCpuSecondsWhileBusy; + private double _ownCpuSecondsWhileBusy; + + // Whether, in the latest sample in which tests waited for the limit, "the CPUs had no + // headroom" was still the policy's reason while they had it. Any later reason, or a + // change of the limit, means a measurement has ended since. + private bool _cpuBusyReasonIsStale; + + // Whether the policy ever gave a reason for not raising, in any sample. + private bool _measurementsCompleted; private TimeSpan _heldForOutsideLoad; private TimeSpan _childProcessesMeasured; private double _childProcessCpuSeconds; @@ -49,6 +63,12 @@ internal sealed class AdaptiveRunTotals /// Share of the machine's CPU capacity that this process's child processes used, 0 to 1, or null when it was not read for this sample. /// What kept more tests from running at once. /// The name of the limiter tests waited for, when that is the bottleneck. + /// + /// The CPU figure the limit is decided from, 0 to 1, when it differs from the machine's: + /// a process held to a quota, or bound to some of the processors, can be at its own + /// limit on a machine that is mostly idle. + /// + /// Whether the CPUs had no headroom in this sample. public void Add( TimeSpan elapsed, double machineCpuUtilization, @@ -57,8 +77,12 @@ public void Add( bool heldForOutsideLoad, double? childProcessCpuUtilization = null, ParallelismBottleneck bottleneck = ParallelismBottleneck.SessionLimit, - string? limiter = null) + string? limiter = null, + double? decisionCpuUtilization = null, + bool cpuBusy = true) { + var cpuForDecision = decisionCpuUtilization ?? machineCpuUtilization; + if (childProcessCpuUtilization is { } childProcessCpu) { _childProcessesMeasured += elapsed; @@ -70,6 +94,16 @@ public void Add( _processCpuSeconds += processCpuUtilization * elapsed.TotalSeconds; _timeByBottleneck[(int) bottleneck] += elapsed; + // Any other reason means a measurement has ended since the one that found the CPUs + // busy, whether or not tests wait for the limit in this sample. + if (raiseBlocker != AdaptiveRaiseBlocker.CpuBusy) + { + _cpuBusyReasonIsStale = false; + } + + // The policy gives a reason only when a measurement has ended. + _measurementsCompleted |= raiseBlocker != AdaptiveRaiseBlocker.None; + if (bottleneck == ParallelismBottleneck.SessionLimit) { // The reason counts only while tests wait for the limit. The rest of the time @@ -77,12 +111,37 @@ public void Add( // "the CPUs have no headroom" over a run that was mostly idle (#7915). And the // policy's reason is from its last whole window, so "fewer tests were ready" // cannot explain a sample in which tests are waiting. - if (raiseBlocker != AdaptiveRaiseBlocker.LimitNotReached) + // Nor can "the CPUs had no headroom" explain a sample in which they have it: + // the tests that fill the slots may have gone from computing to waiting since. + _cpuBusyReasonIsStale = raiseBlocker == AdaptiveRaiseBlocker.CpuBusy && !cpuBusy; + + if (_cpuBusyReasonIsStale) + { + // Charged to nothing. + } + else if (raiseBlocker != AdaptiveRaiseBlocker.LimitNotReached) { _timeNotRaising[(int) raiseBlocker] += elapsed; + _cpuSecondsNotRaising[(int) raiseBlocker] += cpuForDecision * elapsed.TotalSeconds; + + if (raiseBlocker == AdaptiveRaiseBlocker.CpuBusy) + { + // Child processes are read from the moment the CPUs are nearly + // saturated while this process alone uses little, their first reading + // comes a sample or two later, and a reading can fail. Without one, + // the whole load of the sample counts as this process's own: the + // line names other programs only when what was read leaves no doubt, + // whatever the unread samples held. + var own = childProcessCpuUtilization is { } children + ? processCpuUtilization + children + : Math.Max(processCpuUtilization, machineCpuUtilization); + + _machineCpuSecondsWhileBusy += machineCpuUtilization * elapsed.TotalSeconds; + _ownCpuSecondsWhileBusy += own * elapsed.TotalSeconds; + } } - _cpuSecondsWhileWaiting += machineCpuUtilization * elapsed.TotalSeconds; + _cpuSecondsWhileWaiting += cpuForDecision * elapsed.TotalSeconds; } else if (bottleneck == ParallelismBottleneck.Limiter && limiter is not null) { @@ -122,18 +181,27 @@ public void Add( } var waitedForLimit = _timeByBottleneck[(int) ParallelismBottleneck.SessionLimit]; + var mostCommonBlocker = AdaptiveParallelismSummary.MostCommon(_timeNotRaising); + var blockedFor = _timeNotRaising[(int) mostCommonBlocker]; return new AdaptiveRunStatistics( _machineCpuSeconds / _sampledTime.TotalSeconds, _processCpuSeconds / _sampledTime.TotalSeconds, _heldForOutsideLoad, - AdaptiveParallelismSummary.MostCommon(_timeNotRaising), + mostCommonBlocker, _childProcessesMeasured, _childProcessesMeasured > TimeSpan.Zero ? _childProcessCpuSeconds / _childProcessesMeasured.TotalSeconds : 0) { Sampled = _sampledTime, WaitedForLimit = waitedForLimit, CpuUtilizationWhileWaiting = waitedForLimit > TimeSpan.Zero ? _cpuSecondsWhileWaiting / waitedForLimit.TotalSeconds : 0, + CpuUtilizationWhileBlocked = mostCommonBlocker != AdaptiveRaiseBlocker.None && blockedFor > TimeSpan.Zero + ? _cpuSecondsNotRaising[(int) mostCommonBlocker] / blockedFor.TotalSeconds + : 0, + OutsideLoadWhileCpuBusy = _machineCpuSecondsWhileBusy > 0 + && _ownCpuSecondsWhileBusy < _machineCpuSecondsWhileBusy * AdaptiveParallelismPolicy.OwnSaturationShare, + CpuBusyWhenLastMeasured = _cpuBusyReasonIsStale, + MeasurementsCompleted = _measurementsCompleted, WaitedForLimiter = _timeByBottleneck[(int) ParallelismBottleneck.Limiter], MostWaitedLimiter = limiter, LimitersWaitedFor = _timeByLimiter?.Count ?? 0, @@ -177,6 +245,30 @@ internal readonly record struct AdaptiveRunStatistics( /// Average share of the machine's CPU capacity in use over that time, 0 to 1. public double CpuUtilizationWhileWaiting { get; init; } + /// + /// Average CPU use, 0 to 1, over the time kept the + /// limit from being raised. 0 when nothing did. + /// + public double CpuUtilizationWhileBlocked { get; init; } + + /// + /// Whether, over the time the CPUs had no headroom while tests waited for the limit, + /// this process and its child processes used less than half of what was in use. + /// + public bool OutsideLoadWhileCpuBusy { get; init; } + + /// + /// Whether, the last time tests waited for the limit, the policy's reason was still "the + /// CPUs had no headroom" while they had it: a measurement found them busy, the tests + /// have changed since, and no measurement has ended after that. + /// + public bool CpuBusyWhenLastMeasured { get; init; } + + /// + /// Whether any measurement ended during the run, whatever tests were waiting for then. + /// + public bool MeasurementsCompleted { get; init; } + /// How long tests waited for a [ParallelLimiter] while the session-wide limit had room. public TimeSpan WaitedForLimiter { get; init; } @@ -194,6 +286,9 @@ internal readonly record struct AdaptiveRunStatistics( /// The key they waited for the longest. public string? MostWaitedKey { get; init; } + + /// How many keys they waited for. + public int KeysWaitedFor { get; init; } } /// @@ -209,8 +304,16 @@ internal static class AdaptiveParallelismSummary // Below this share of the run, a bottleneck is not worth a sentence. internal const double NotableShare = 0.1; + // From this share of the run, what held tests back second-longest gets a clause too: a + // third of a run spent in [NotInParallel] tests matters to a reader whose tests waited + // for the limit a little longer than that. + internal const double SecondaryShare = 0.2; + // CPUs less busy than this have room for more tests that use them. - internal const double IdleCpuUtilization = 0.5; + internal const double IdleCpuUtilization = AdaptiveParallelismPolicy.IdleCpuUtilization; + + // Two CPU figures closer than this are the same figure to a reader. + private const double NotableCpuDifference = 0.1; internal static int RaiseBlockerCount { get; } = Enum.GetValues().Length; @@ -224,14 +327,21 @@ internal static string Format( int highestLimit, int changes, int changesPutBack, - AdaptiveRunStatistics? statistics = null) + AdaptiveRunStatistics? statistics = null, + string? processName = null) { - var summary = new StringBuilder("Adaptive parallelism: the parallel test limit "); + var summary = new StringBuilder("Adaptive parallelism"); + TestProcessName.AppendTo(summary, processName).Append(": the parallel test limit "); AppendLimit(summary, startLimit, currentLimit, lowestLimit, highestLimit, changes, changesPutBack); if (statistics is { } run && run.Sampled > TimeSpan.Zero) { - AppendBottleneck(summary, run); + AppendBottleneck(summary, run, raised: currentLimit > startLimit, moved: changes > 0); + } + else if (changes == 0) + { + // Without it the line gives no reason at all, and reads as if one were missing. + summary.Append(" The run was too short to measure."); } return summary.ToString(); @@ -275,102 +385,254 @@ internal static void AppendLimit(StringBuilder text, int startLimit, int current text.Append(")."); } - // One sentence, for whatever held tests back the longest. - private static void AppendBottleneck(StringBuilder summary, AdaptiveRunStatistics run) + // One sentence for whatever held tests back the longest, and a clause for the runner-up + // when that is a fair share of the run too. + private static void AppendBottleneck(StringBuilder summary, AdaptiveRunStatistics run, bool raised, bool moved) { - var longest = Max(run.WaitedForLimit, run.WaitedForLimiter, run.NotInParallel, run.WaitedForKeys); - var total = FormatDuration(run.RunTime > TimeSpan.Zero ? run.RunTime : run.Sampled); + // In the order that decides a tie: what no limit changes comes first. + ReadOnlySpan<(ParallelismBottleneck Kind, TimeSpan Time)> bottlenecks = + [ + (ParallelismBottleneck.NotInParallel, run.NotInParallel), + (ParallelismBottleneck.NotInParallelKey, run.WaitedForKeys), + (ParallelismBottleneck.Limiter, run.WaitedForLimiter), + (ParallelismBottleneck.SessionLimit, run.WaitedForLimit), + ]; + + var longest = 0; + + for (var i = 1; i < bottlenecks.Length; i++) + { + if (bottlenecks[i].Time > bottlenecks[longest].Time) + { + longest = i; + } + } - if (longest.Ticks < run.Sampled.Ticks * NotableShare) + var second = -1; + + for (var i = 0; i < bottlenecks.Length; i++) + { + if (i != longest && (second < 0 || bottlenecks[i].Time > bottlenecks[second].Time)) + { + second = i; + } + } + + var (kind, time) = bottlenecks[longest]; + + if (time.Ticks < run.Sampled.Ticks * NotableShare) { summary.Append(" Tests seldom waited for it: fewer were ready to run than it allows."); return; } - if (longest == run.NotInParallel) + if (!IsNotable(time, run, NotableShare)) + { + // A fair share of a measurement that lasted a second or two: tests did wait, + // so "seldom" would be wrong, and "for 0s" says nothing. + summary.Append(" The run was too short to measure."); + return; + } + + var total = FormatDuration(run.RunTime > TimeSpan.Zero ? run.RunTime : run.Sampled); + + if (kind == ParallelismBottleneck.SessionLimit) { - summary.Append(" For ").Append(FormatDuration(longest)).Append(" of ").Append(total) - .Append(", tests marked [NotInParallel] ran one at a time, which no limit changes."); + AppendWaitForLimit(summary, run, time, total, raised, moved); } - else if (longest == run.WaitedForKeys) + else { - summary.Append(" For ").Append(FormatDuration(longest)).Append(" of ").Append(total) - .Append(", tests waited for a [NotInParallel] key"); + summary.Append(" For ").Append(FormatDuration(time)).Append(" of ").Append(total).Append(", "); + AppendHeldBack(summary, kind, run); - if (run.MostWaitedKey is { } key) - { - summary.Append(" (\"").Append(key).Append("\" the most)"); - } + summary.Append(kind == ParallelismBottleneck.Limiter ? ", not for this limit." : ", which no limit changes."); + } - summary.Append(", which no limit changes."); + if (IsNotable(bottlenecks[second].Time, run, SecondaryShare)) + { + summary.Append(" Also, for ").Append(FormatDuration(bottlenecks[second].Time)).Append(", "); + AppendHeldBack(summary, bottlenecks[second].Kind, run); + summary.Append('.'); } - else if (longest == run.WaitedForLimiter) + } + + // A wait is worth a sentence from a share of the measured run, and from a second: "for + // 0s of 3s" says nothing. + private static bool IsNotable(TimeSpan time, AdaptiveRunStatistics run, double share) + => time.Ticks >= run.Sampled.Ticks * share && Math.Round(time.TotalSeconds) >= 1; + + // What held tests back, as a clause: "tests waited for the [NotInParallel] key "Db"". + private static void AppendHeldBack(StringBuilder summary, ParallelismBottleneck kind, AdaptiveRunStatistics run) + { + switch (kind) { - summary.Append(" For ").Append(FormatDuration(longest)).Append(" of ").Append(total) - .Append(", tests waited for "); + case ParallelismBottleneck.NotInParallel: + summary.Append("tests marked [NotInParallel] ran one at a time"); + break; - if (run.MostWaitedLimiter is not { } limiter) - { - summary.Append("a [ParallelLimiter]"); - } - else if (run.LimitersWaitedFor > 1) - { + case ParallelismBottleneck.NotInParallelKey when run.MostWaitedKey is { } key && run.KeysWaitedFor > 1: + summary.Append("tests waited for a [NotInParallel] key (\"").Append(key).Append("\" the most)"); + break; + + case ParallelismBottleneck.NotInParallelKey when run.MostWaitedKey is { } key: + summary.Append("tests waited for the [NotInParallel] key \"").Append(key).Append('"'); + break; + + case ParallelismBottleneck.NotInParallelKey: + summary.Append("tests waited for a [NotInParallel] key"); + break; + + case ParallelismBottleneck.Limiter when run.MostWaitedLimiter is { } limiter && run.LimitersWaitedFor > 1: // The time is the total over all of them, so it is not given to one. - summary.Append(run.LimitersWaitedFor).Append(" [ParallelLimiter] limits (").Append(limiter).Append(" the most)"); - } - else - { - summary.Append("[ParallelLimiter] ").Append(limiter); - } + summary.Append("tests waited for ").Append(run.LimitersWaitedFor).Append(" [ParallelLimiter] limits (").Append(limiter).Append(" the most)"); + break; + + case ParallelismBottleneck.Limiter when run.MostWaitedLimiter is { } limiter: + summary.Append("tests waited for [ParallelLimiter] ").Append(limiter); + break; + + case ParallelismBottleneck.Limiter: + summary.Append("tests waited for a [ParallelLimiter]"); + break; - summary.Append(", not for this limit."); + default: + summary.Append("tests waited for this limit"); + break; + } + } + + private static void AppendWaitForLimit(StringBuilder summary, AdaptiveRunStatistics run, TimeSpan waited, string total, bool raised, bool moved) + { + var invariant = CultureInfo.InvariantCulture; + + summary.Append(" Tests waited for it for ").Append(FormatDuration(waited)).Append(" of ").Append(total) + .Append(invariant, $", with the CPUs {run.CpuUtilizationWhileWaiting * 100:0}% busy"); + + var blocker = run.MostCommonRaiseBlocker; + + if (blocker == AdaptiveRaiseBlocker.None && run.CpuBusyWhenLastMeasured) + { + // Measurements did complete, and the last one found the CPUs busy. The tests + // went from computing to waiting after it, and no measurement has ended since. + summary.Append("; the CPUs had no headroom when it was last measured, and no measurement completed after they went idle."); + } + else if (blocker == AdaptiveRaiseBlocker.None && (moved || run.MeasurementsCompleted)) + { + // Measurements did end, in a change (the changes are in the line already, and + // in the details) or at a time when no test waited for the limit. No reason + // applied while tests waited, so none is given. + summary.Append('.'); + } + else if (blocker == AdaptiveRaiseBlocker.None) + { + // No measurement ended: a raise is tried only on throughput that has been + // measured twice, and a short run, or one of slow tests, never gets that far. + summary.Append("; too few measurements completed to try a raise."); } else { - summary.Append(" Tests waited for it for ").Append(FormatDuration(longest)).Append(" of ").Append(total) - .Append(CultureInfo.InvariantCulture, $", with the CPUs {run.CpuUtilizationWhileWaiting * 100:0}% busy"); + // "Further" after a raise that was kept: "went from 8 to 12 ... it was not raised" reads as a contradiction. + summary.Append(raised ? "; it was not raised further mostly because " : "; it was not raised mostly because ") + .Append(Describe(blocker)); - if (run.MostCommonRaiseBlocker != AdaptiveRaiseBlocker.None) + if (blocker == AdaptiveRaiseBlocker.CpuBusy) { - summary.Append("; it was not raised mostly because ").Append(Describe(run.MostCommonRaiseBlocker)); + // The average over the whole wait can be far below the figure at the times + // that counted: a suite that saturates the CPUs for half of it and idles + // for the rest is "42% busy" and had no headroom all the same. + if (run.CpuUtilizationWhileBlocked - run.CpuUtilizationWhileWaiting >= NotableCpuDifference) + { + summary.Append(invariant, $" ({run.CpuUtilizationWhileBlocked * 100:0}% busy at those times)"); + } + + // Containers and other programs are not this process's load, and nothing + // else in the line says where a busy machine's load came from. + if (run.OutsideLoadWhileCpuBusy) + { + summary.Append("; most of their load came from other processes or containers"); + } } summary.Append('.'); + } - // Raises that bring nothing on a machine with idle CPUs mean the tests wait for - // something this limit does not control and TUnit cannot see: a lock or a - // semaphore taken in a hook, a shared fixture, a service that is slow to answer. - if (run.CpuUtilizationWhileWaiting < IdleCpuUtilization - && run.MostCommonRaiseBlocker is AdaptiveRaiseBlocker.WaitingAfterFailedRaise or AdaptiveRaiseBlocker.ExplorationBudget) - { - summary.Append(" The tests are probably waiting on something other than the CPUs or this limit, such as a lock, a fixture or an external service."); - } + // Idle CPUs, every slot taken and no raise that helps mean the tests wait for + // something this limit does not control and TUnit cannot see: a lock or a semaphore + // taken in a hook, a shared fixture, a service that is slow to answer. A raise that + // failed says so, and so does throughput that never settles, or too few tests + // finishing to measure, when the CPUs have nothing to do. Those two only for a limit + // that did not end higher than it began: a raise that was kept shows that tests did + // wait for the limit. + var raisesBroughtNothing = blocker is AdaptiveRaiseBlocker.WaitingAfterFailedRaise or AdaptiveRaiseBlocker.ExplorationBudget; + var nothingToMeasure = !raised && blocker is AdaptiveRaiseBlocker.ThroughputNotSteady or AdaptiveRaiseBlocker.TooFewTests; + + if (run.CpuUtilizationWhileWaiting < IdleCpuUtilization && (raisesBroughtNothing || nothingToMeasure)) + { + summary.Append(" The tests are probably waiting on something other than the CPUs or this limit, such as a lock, a fixture or an external service."); } } /// - /// The figures behind the summary line: how long the run spent at each limit and how - /// busy the machine was. + /// The figures behind the summary line: how long the run spent at each limit, what + /// changed it and how busy the machine was. /// - internal static string FormatDetails(IEnumerable> timeAtLimit, AdaptiveRunStatistics? statistics) + /// How long the run spent at each limit. + /// What was measured over the run. + /// How many changes of each were made, indexed by it. + /// The limit the run ended at. + /// The test process the line is from. + internal static string FormatDetails( + IEnumerable> timeAtLimit, + AdaptiveRunStatistics? statistics, + IReadOnlyList? changesByKind = null, + int? finalLimit = null, + string? processName = null) { - var details = new StringBuilder("Adaptive parallelism details: time at each limit: "); + var details = new StringBuilder("Adaptive parallelism details"); + TestProcessName.AppendTo(details, processName).Append(": time at each limit: "); var first = true; foreach (var entry in timeAtLimit) { + var endedThere = entry.Key == finalLimit; + var none = Math.Round(entry.Value.TotalSeconds) < 1; + + // A limit the run only passed through says nothing. The one it ended at does, + // even then: the first line names it, and a change made as the last tests + // finished never took effect. + if (none && !endedThere) + { + continue; + } + if (!first) { details.Append(", "); } first = false; - details.Append(entry.Key).Append(" for ").Append(FormatDuration(entry.Value)); + details.Append(entry.Key); + + if (none) + { + details.Append(" as the run ended"); + } + else + { + details.Append(" for ").Append(FormatDuration(entry.Value)); + } + } + + if (first) + { + details.Append("none for a second or more"); } + AppendChanges(details, changesByKind); + if (statistics is not { } run) { - return details.ToString(); + return details.Append('.').ToString(); } var invariant = CultureInfo.InvariantCulture; @@ -388,15 +650,77 @@ internal static string FormatDetails(IEnumerable> ti .Append(" they were measured"); } - if (run.HeldForOutsideLoad > TimeSpan.Zero) + // "So the limit was not lowered" next to a limit that went down for another reason + // read as a contradiction (#7915): say what the time was, and what it was not a reason for. + if (Math.Round(run.HeldForOutsideLoad.TotalSeconds) >= 1) { details.Append(". For ").Append(FormatDuration(run.HeldForOutsideLoad)) - .Append(" the CPUs were saturated while this process and its child processes used less than half of them, so the limit was not lowered"); + .Append(" the CPUs were saturated mostly by other processes or containers (this process and its child processes used less than half of them), which is no reason to lower the limit"); } return details.Append('.').ToString(); } + // The order a reader follows a limit in: raises and what became of them, then lowerings. + private static readonly AdaptiveLimitChange[] ChangeOrder = + [ + AdaptiveLimitChange.Probe, + AdaptiveLimitChange.ProbeReverted, + AdaptiveLimitChange.ProbeAborted, + AdaptiveLimitChange.ProbeRevertedForFailures, + AdaptiveLimitChange.CpuSaturation, + AdaptiveLimitChange.LowerReverted, + AdaptiveLimitChange.LowerNotJudged, + AdaptiveLimitChange.MemoryPressure, + AdaptiveLimitChange.Recovery, + AdaptiveLimitChange.PartOutgrown, + AdaptiveLimitChange.TrialAbandoned, + ]; + + // Why the limit moved, and why it was put back: the first line counts the changes, and + // a reader of "lowest 2" wants to know what took it there (#7915). + private static void AppendChanges(StringBuilder details, IReadOnlyList? changesByKind) + { + if (changesByKind is null) + { + return; + } + + var first = true; + + foreach (var change in ChangeOrder) + { + var count = (int) change < changesByKind.Count ? changesByKind[(int) change] : 0; + + if (count == 0) + { + continue; + } + + details.Append(first ? ". Changes: " : ", ").Append(count).Append("x ").Append(DescribeCounted(change)); + first = false; + } + } + + // Each reads after a count: "3x raised to try more tests". + private static string DescribeCounted(AdaptiveLimitChange change) => change switch + { + AdaptiveLimitChange.Probe => "raised to try more tests", + AdaptiveLimitChange.ProbeReverted => "raise put back for no gain in throughput", + AdaptiveLimitChange.ProbeAborted => "raise put back because it left the CPUs busy", + AdaptiveLimitChange.ProbeRevertedForFailures => "raise put back after tests failed", + // Not "that its own tests saturated": above the starting limit, saturated CPUs + // send the limit back whoever uses them. + AdaptiveLimitChange.CpuSaturation => "lowered for saturated CPUs", + AdaptiveLimitChange.LowerReverted => "lowering put back because it cost throughput or left CPU time unused", + AdaptiveLimitChange.LowerNotJudged => "lowering put back because it could not be judged", + AdaptiveLimitChange.MemoryPressure => "lowered for memory pressure", + AdaptiveLimitChange.Recovery => "raised back after pressure eased", + AdaptiveLimitChange.PartOutgrown => "raised from its part of the shared budget", + AdaptiveLimitChange.TrialAbandoned => "trial dropped when its part of the shared budget changed", + _ => change.ToString(), + }; + internal static AdaptiveRaiseBlocker MostCommon(TimeSpan[] timeNotRaising) { // From 1: index 0 is the time when nothing stood in the way of a raise. @@ -457,14 +781,8 @@ internal static string FormatDuration(TimeSpan duration) AdaptiveLimitChange.LowerReverted => "the lower limit cost throughput or left CPU time unused", AdaptiveLimitChange.LowerNotJudged => "the tests that were running outlasted the measurement, so the lower limit could not be judged", AdaptiveLimitChange.TrialAbandoned => "the number of tests the session runs at once changed during the measurement", + AdaptiveLimitChange.PartOutgrown => "tests wait for the limit, and the busy CPUs are not the doing of the test processes that share the budget", _ => change.ToString(), }; - - private static TimeSpan Max(TimeSpan a, TimeSpan b, TimeSpan c, TimeSpan d) - { - var max = a > b ? a : b; - max = c > max ? c : max; - return d > max ? d : max; - } } #endif diff --git a/src/TUnit.Engine/Scheduling/MaxParallelismLimiter.cs b/src/TUnit.Engine/Scheduling/MaxParallelismLimiter.cs index d190d29d88..13b34dc59a 100644 --- a/src/TUnit.Engine/Scheduling/MaxParallelismLimiter.cs +++ b/src/TUnit.Engine/Scheduling/MaxParallelismLimiter.cs @@ -74,6 +74,9 @@ internal sealed class MaxParallelismLimiter private int _share = int.MaxValue; private bool _limitSetByShare; + // How many test processes share that budget, this one included. + private int _shareMembers = 1; + private long _slotChanges; private int _backlog; private int _dependencyWaits; @@ -340,14 +343,18 @@ public int SetCeiling(int ceiling) /// An adaptive limit comes down to its part when the part shrinks, which makes room for /// the process that has just started, and is free to move from there. While nothing has /// moved it, it follows a part that grows again, up to the limit the run starts at. With the machine - /// short of CPU it stays at its part, which is what the budget is for. With headroom it + /// short of CPU because of the budget's members it stays at its part, which is what the + /// budget is for. With headroom, or with CPUs that something else keeps busy, it /// returns to the limit it would have alone, and beyond that on a measured gain. An equal /// part that could never be exceeded took slots from a process that waited on I/O and gave /// them to one that could not use them, on a machine that was half idle (#7915). /// /// - public int SetShare(int share) + /// This process's part of the budget. + /// How many test processes share the budget, this one included. + public int SetShare(int share, int members = 1) { + Volatile.Write(ref _shareMembers, Math.Max(1, members)); var limits = _limits.Value; if (!limits.IsAdaptive) @@ -401,6 +408,12 @@ public int SetShare(int share) /// other test processes. The part is not a ceiling for an adaptive limit, so falling /// back to the starting limit alone would take the slots of the other processes. /// + /// + /// How many test processes share the budget this process has a part of, this one + /// included. 1 when it shares none. + /// + public int ShareMembers => Volatile.Read(ref _shareMembers); + public int FallbackLimit { get @@ -437,6 +450,7 @@ public void FollowShare() /// public int ClearShare() { + Volatile.Write(ref _shareMembers, 1); var limits = _limits.Value; if (!limits.IsAdaptive) diff --git a/src/TUnit.Engine/Scheduling/ParallelismActivity.cs b/src/TUnit.Engine/Scheduling/ParallelismActivity.cs index aa4269b4a1..21fb8fff44 100644 --- a/src/TUnit.Engine/Scheduling/ParallelismActivity.cs +++ b/src/TUnit.Engine/Scheduling/ParallelismActivity.cs @@ -89,6 +89,11 @@ public void EndKeyWait(long startedAt, IReadOnlyList keys) } } + /// + /// How many [NotInParallel] keys tests waited for. + /// + public int KeysWaitedFor => _keyWaitTicks?.Count ?? 0; + /// /// The [NotInParallel] key that tests waited for the longest in total, or null /// when none waited. diff --git a/src/TUnit.Engine/Scheduling/SharedParallelBudget.cs b/src/TUnit.Engine/Scheduling/SharedParallelBudget.cs index f63b56bbe9..12684bedb2 100644 --- a/src/TUnit.Engine/Scheduling/SharedParallelBudget.cs +++ b/src/TUnit.Engine/Scheduling/SharedParallelBudget.cs @@ -252,7 +252,7 @@ private void SetPart(int part, int members) var previous = _part; _part = part; - _limiter.SetShare(part); + _limiter.SetShare(part, members); _lowestPart = Math.Min(_lowestPart, part); _highestPart = Math.Max(_highestPart, part); _mostMembers = Math.Max(_mostMembers, members); @@ -270,17 +270,23 @@ private void SetPart(int part, int members) /// The largest part this process had. /// The most processes that shared the budget at once. /// Whether the limit is adaptive, so the part is where it starts and not the most tests that ran. - internal static string FormatSummary(string name, int budget, int lowestPart, int highestPart, int mostMembers, bool adaptive = false) + /// The test process the line is from. + internal static string FormatSummary(string name, int budget, int lowestPart, int highestPart, int mostMembers, bool adaptive = false, string? processName = null) { var range = lowestPart == highestPart ? $"{lowestPart}" : $"{lowestPart} to {highestPart}"; + // A range reads as a setting unless the line says what moved it. + var grows = lowestPart == highestPart ? "" : " (the part grows as other processes finish)"; + var parts = adaptive - ? $"had a part of {range} tests in parallel, which is where its adaptive limit starts" + ? $"had a part of {range} tests in parallel{grows}, which is where its adaptive limit starts" : $"ran at most {range} tests in parallel"; + var source = processName is null ? "" : $" ({processName})"; + return mostMembers <= 1 - ? $"Shared parallel budget '{name}': no other test process shared the budget of {budget}, so this one {parts}" - : $"Shared parallel budget '{name}': up to {mostMembers} test processes shared a budget of {budget}, and this one {parts}"; + ? $"Shared parallel budget '{name}'{source}: no other test process shared the budget of {budget}, so this one {parts}" + : $"Shared parallel budget '{name}'{source}: up to {mostMembers} test processes shared a budget of {budget}, and this one {parts}"; } public void Dispose() @@ -302,7 +308,7 @@ public void Dispose() // From here a refresh that outlived the join can no longer change the limit. _stopped = true; - summary = FormatSummary(_name, _budget, _lowestPart, _highestPart, _mostMembers, _limiter.Limits.IsAdaptive); + summary = FormatSummary(_name, _budget, _lowestPart, _highestPart, _mostMembers, _limiter.Limits.IsAdaptive, TestProcessName.Current); } // The other processes take this one's part once its file is closed. diff --git a/src/TUnit.Engine/Scheduling/TestProcessName.cs b/src/TUnit.Engine/Scheduling/TestProcessName.cs new file mode 100644 index 0000000000..faccfec23e --- /dev/null +++ b/src/TUnit.Engine/Scheduling/TestProcessName.cs @@ -0,0 +1,76 @@ +using System.Reflection; +using System.Text; + +namespace TUnit.Engine.Scheduling; + +/// +/// Names this test process in the lines it writes when the run ends. One dotnet test +/// call runs several test processes at once and prints their lines between each other's +/// results, so a line that does not say which project it is from cannot be matched to one +/// (#7915). +/// +internal static class TestProcessName +{ + private static readonly Lazy CurrentName = new( + static () => Format(Assembly.GetEntryAssembly()?.GetName().Name, AppContext.TargetFrameworkName)); + + /// + /// The test project and its target framework, such as "MyTests, net10.0", or null + /// when the process has no entry assembly to name. + /// + public static string? Current => CurrentName.Value; + + internal static string? Format(string? assemblyName, string? targetFrameworkName) + { + if (string.IsNullOrEmpty(assemblyName)) + { + return null; + } + + return GetShortFramework(targetFrameworkName) is { } framework + ? $"{assemblyName}, {framework}" + : assemblyName; + } + + /// + /// Appends the name in brackets to the start of a line, before its colon: + /// "Adaptive parallelism" becomes "Adaptive parallelism (MyTests, net10.0)". + /// + public static StringBuilder AppendTo(StringBuilder text, string? name) + => name is null ? text : text.Append(" (").Append(name).Append(')'); + + // ".NETCoreApp,Version=v10.0" is "net10.0", the name a project file and `dotnet test` use. + private static string? GetShortFramework(string? targetFrameworkName) + { + const string versionMarker = ",Version=v"; + + if (targetFrameworkName is null) + { + return null; + } + + var markerIndex = targetFrameworkName.IndexOf(versionMarker, StringComparison.Ordinal); + + if (markerIndex < 0) + { + return null; + } + + var identifier = targetFrameworkName.Substring(0, markerIndex); + var version = targetFrameworkName.Substring(markerIndex + versionMarker.Length); + var versionEnd = version.IndexOf(','); + + if (versionEnd >= 0) + { + version = version.Substring(0, versionEnd); + } + + return identifier switch + { + ".NETCoreApp" => "net" + version, + ".NETFramework" => "net" + version.Replace(".", ""), + ".NETStandard" => "netstandard" + version, + _ => null, + }; + } +} diff --git a/tests/TUnit.UnitTests/AdaptiveLimiterTrialsTests.cs b/tests/TUnit.UnitTests/AdaptiveLimiterTrialsTests.cs index 9c64eb4802..00f0234b30 100644 --- a/tests/TUnit.UnitTests/AdaptiveLimiterTrialsTests.cs +++ b/tests/TUnit.UnitTests/AdaptiveLimiterTrialsTests.cs @@ -102,7 +102,7 @@ public async Task Raises_A_Limiter_Whose_Tests_Finish_Faster_With_A_Higher_Limit trials.Stop(); - var summary = logger.Messages.Where(x => x.Level == LogLevel.Information).Select(x => x.Message).Single(); + var summary = logger.Messages.Where(x => x.Level == LogLevel.Information).Select(x => WithoutProcessName(x.Message)).Single(); await Assert.That(summary).StartsWith("[ParallelLimiter] FourToSixteen: the limit went from 4 to 16 (lowest 4, highest 16, "); await Assert.That(summary).Contains("Tests waited for it for 1m 0s"); @@ -207,7 +207,7 @@ public async Task A_Test_That_Fails_During_A_Raise_Still_Caps_The_Limit_When_The await Assert.That(limiter.Lock.CurrentLimit).IsEqualTo(4); trials.Stop(); - var summary = logger.Messages.Where(x => x.Level == LogLevel.Information).Select(x => x.Message).Single(); + var summary = logger.Messages.Where(x => x.Level == LogLevel.Information).Select(x => WithoutProcessName(x.Message)).Single(); await Assert.That(summary).StartsWith("[ParallelLimiter] FourToSixteen: the limit moved and ended back at 4 (lowest 4, highest 6, 2 changes, 1 put back)."); await Assert.That(summary).Contains("it was not raised mostly because tests failed after an earlier raise"); @@ -278,6 +278,13 @@ await Assert.That(AdaptiveLimiterTrials.FormatSummary(summary with { LowestLimit + "Adaptive parallelism lowered it while its tests saturated the CPUs, which is part of that wait. " + "Adaptive parallelism never raises a declared limit. If it is not a hard cap, a higher limit, or no limiter, may shorten the run."); + // The advice is the same for every declared limit, so only the first line of a + // run carries it. Each line names the test process it is from. + await Assert.That(summary.HasAdvice).IsTrue(); + await Assert.That(AdaptiveLimiterTrials.FormatSummary(summary, processName: "Suite.Tests, net10.0", includeAdvice: false)).IsEqualTo( + "[ParallelLimiter] PipelineTestParallelLimit (Suite.Tests, net10.0): the limit stayed at 2. " + + "Tests waited for it for 2m 30s while the CPUs were 30% busy."); + await Assert.That(summary.IsWorthReporting(TimeSpan.FromSeconds(159))).IsTrue(); await Assert.That(AdaptiveLimiterTrials.FormatSummary(summary)).IsEqualTo( "[ParallelLimiter] PipelineTestParallelLimit: the limit stayed at 2. " @@ -323,7 +330,7 @@ public async Task A_Declared_Limit_Is_A_Ceiling_That_Is_Never_Raised() trials.Stop(); - var summary = logger.Messages.Where(x => x.Level == LogLevel.Information).Select(x => x.Message).Single(); + var summary = logger.Messages.Where(x => x.Level == LogLevel.Information).Select(x => WithoutProcessName(x.Message)).Single(); await Assert.That(summary).StartsWith("[ParallelLimiter] FixedLimit: the limit stayed at 4. Tests waited for it for 2m 0s while the CPUs were 20% busy."); } @@ -352,7 +359,7 @@ public async Task A_Declared_Limit_Of_One_Is_Followed_So_It_Can_Be_Named_As_What trials.Stop(); - var summary = logger.Messages.Where(x => x.Level == LogLevel.Information).Select(x => x.Message).Single(); + var summary = logger.Messages.Where(x => x.Level == LogLevel.Information).Select(x => WithoutProcessName(x.Message)).Single(); await Assert.That(summary).StartsWith("[ParallelLimiter] LimitOfOne: the limit stayed at 1. Tests waited for it for 10s while the CPUs were 20% busy."); } @@ -506,7 +513,7 @@ public async Task A_Limiters_Wait_Is_Counted_In_A_Sample_In_Which_The_Session_Li trials.Stop(); - var summary = logger.Messages.Where(x => x.Level == LogLevel.Information).Select(x => x.Message).Single(); + var summary = logger.Messages.Where(x => x.Level == LogLevel.Information).Select(x => WithoutProcessName(x.Message)).Single(); await Assert.That(summary).StartsWith("[ParallelLimiter] FixedLimit: the limit stayed at 4. Tests waited for it for 10s"); } @@ -723,6 +730,10 @@ public async Task Saturated_Cpus_Do_Not_Lower_A_Limiter_That_Few_Running_Tests_A /// Tests behind a limiter that each take 100 ms: every sample, each place in the limiter /// completes two and a half of them, and the limiter stays full. /// + // The lines carry the test project's name and target framework, which differ by run. + private static string WithoutProcessName(string message) + => TestProcessName.Current is { } name ? message.Replace($" ({name})", "") : message; + private sealed class SimulatedLimiter(ParallelLimitLock parallelLimitLock) { private double _partialTests; diff --git a/tests/TUnit.UnitTests/AdaptiveParallelismControllerTests.cs b/tests/TUnit.UnitTests/AdaptiveParallelismControllerTests.cs index a5eb96900c..b876cc110f 100644 --- a/tests/TUnit.UnitTests/AdaptiveParallelismControllerTests.cs +++ b/tests/TUnit.UnitTests/AdaptiveParallelismControllerTests.cs @@ -30,7 +30,8 @@ public async Task Reports_The_Limit_When_It_Stops() // enough pressure to move the limit while the controller ran. var summaries = logger.Messages.Where(x => x.Level == LogLevel.Information).Select(x => x.Message).ToArray(); await Assert.That(summaries).HasSingleItem(); - await Assert.That(summaries[0]).StartsWith("Adaptive parallelism: the parallel test limit "); + // With the test project's name: several test processes print between each other's lines. + await Assert.That(summaries[0]).StartsWith($"Adaptive parallelism ({TestProcessName.Current}): the parallel test limit "); } [Test] @@ -67,7 +68,7 @@ public async Task Summary_Of_A_Limit_That_Never_Moved_Is_One_Sentence() { var summary = AdaptiveParallelismSummary.Format(36, 36, 36, 36, changes: 0, changesPutBack: 0); - await Assert.That(summary).IsEqualTo("Adaptive parallelism: the parallel test limit stayed at 36."); + await Assert.That(summary).IsEqualTo("Adaptive parallelism: the parallel test limit stayed at 36. The run was too short to measure."); } [Test] @@ -89,10 +90,10 @@ public async Task Summary_Of_A_Limit_That_A_Shared_Budget_Moved_Does_Not_Say_It_ { // No change of the policy's own, but this process's part of the budget went from 8 to 4. await Assert.That(AdaptiveParallelismSummary.Format(8, 4, 4, 8, changes: 0, changesPutBack: 0)) - .IsEqualTo("Adaptive parallelism: the parallel test limit went from 8 to 4 (lowest 4, highest 8)."); + .IsEqualTo("Adaptive parallelism: the parallel test limit went from 8 to 4 (lowest 4, highest 8). The run was too short to measure."); await Assert.That(AdaptiveParallelismSummary.Format(8, 8, 4, 8, changes: 0, changesPutBack: 0)) - .IsEqualTo("Adaptive parallelism: the parallel test limit moved and ended back at 8 (lowest 4, highest 8)."); + .IsEqualTo("Adaptive parallelism: the parallel test limit moved and ended back at 8 (lowest 4, highest 8). The run was too short to measure."); } [Test] @@ -128,7 +129,8 @@ public async Task Summary_Names_Tests_That_Ran_One_At_A_Time_When_They_Held_The_ await Assert.That(summary).IsEqualTo( "Adaptive parallelism: the parallel test limit went from 8 to 12 (lowest 6, highest 12, 5 changes, 2 put back). " - + "For 44s of 1m 49s, tests marked [NotInParallel] ran one at a time, which no limit changes."); + + "For 44s of 1m 49s, tests marked [NotInParallel] ran one at a time, which no limit changes. " + + "Also, for 30s, tests waited for this limit."); } [Test] @@ -145,6 +147,11 @@ public async Task Summary_Names_The_Key_That_Tests_Waited_For_The_Longest() var summary = AdaptiveParallelismSummary.Format(8, 8, 8, 8, changes: 0, changesPutBack: 0, statistics); await Assert.That(summary).IsEqualTo( + "Adaptive parallelism: the parallel test limit stayed at 8. " + + "For 10m 11s of 10m 50s, tests waited for the [NotInParallel] key \"Resilience\", which no limit changes."); + + // "The most" only when there was more than one. + await Assert.That(AdaptiveParallelismSummary.Format(8, 8, 8, 8, changes: 0, changesPutBack: 0, statistics with { KeysWaitedFor = 3 })).IsEqualTo( "Adaptive parallelism: the parallel test limit stayed at 8. " + "For 10m 11s of 10m 50s, tests waited for a [NotInParallel] key (\"Resilience\" the most), which no limit changes."); } @@ -177,13 +184,15 @@ public async Task Summary_Gives_The_Cpu_Use_While_Tests_Waited_For_The_Limit_Not Sampled = TimeSpan.FromSeconds(242), WaitedForLimit = TimeSpan.FromSeconds(240), CpuUtilizationWhileWaiting = 1.0, + OutsideLoadWhileCpuBusy = true, }; var summary = AdaptiveParallelismSummary.Format(8, 8, 8, 8, changes: 0, changesPutBack: 0, statistics); await Assert.That(summary).IsEqualTo( "Adaptive parallelism: the parallel test limit stayed at 8. " - + "Tests waited for it for 4m 0s of 4m 2s, with the CPUs 100% busy; it was not raised mostly because the CPUs had no headroom."); + + "Tests waited for it for 4m 0s of 4m 2s, with the CPUs 100% busy; it was not raised mostly because the CPUs had no headroom; " + + "most of their load came from other processes or containers."); } [Test] @@ -283,7 +292,7 @@ await Assert.That(AdaptiveParallelismSummary.FormatDetails(timeAtLimit, statisti "Adaptive parallelism details: time at each limit: 4 for 12s, 6 for 30s, 8 for 3m 10s. " + "The machine's CPUs were 98% busy on average, and this process alone used 12% of them. " + "Its child processes used 61% over the 2m 10s they were measured. " - + "For 3m 20s the CPUs were saturated while this process and its child processes used less than half of them, so the limit was not lowered."); + + "For 3m 20s the CPUs were saturated mostly by other processes or containers (this process and its child processes used less than half of them), which is no reason to lower the limit."); } [Test] @@ -456,6 +465,255 @@ public async Task Adaptive_Limits_Follow_The_Configured_Bounds( } #pragma warning disable TUNITEXP001 // Adaptive parallel limits are experimental + [Test] + public async Task Summary_Says_Not_Raised_Further_After_A_Raise_That_Was_Kept() + { + // The Kevlar report in #7915: "went from 8 to 12 ... it was not raised" read as a contradiction. + var statistics = new AdaptiveRunStatistics(0.5, 0.4, TimeSpan.Zero, AdaptiveRaiseBlocker.CpuBusy) + { + Sampled = TimeSpan.FromSeconds(15), + WaitedForLimit = TimeSpan.FromSeconds(9), + CpuUtilizationWhileWaiting = 0.76, + CpuUtilizationWhileBlocked = 0.8, + }; + + await Assert.That(AdaptiveParallelismSummary.Format(8, 12, 8, 12, changes: 1, changesPutBack: 0, statistics)).IsEqualTo( + "Adaptive parallelism: the parallel test limit went from 8 to 12 (lowest 8, highest 12, 1 change). " + + "Tests waited for it for 9s of 15s, with the CPUs 76% busy; it was not raised further mostly because the CPUs had no headroom."); + } + + [Test] + public async Task Summary_Says_So_When_Too_Little_Was_Measured_To_Try_A_Raise() + { + // The shared budget report in #7915: "waited for it for 24s of 30s, with the CPUs 100% busy." and no reason. + var statistics = new AdaptiveRunStatistics(1.0, 0.6, TimeSpan.Zero, AdaptiveRaiseBlocker.None) + { + Sampled = TimeSpan.FromSeconds(28), + RunTime = TimeSpan.FromSeconds(30), + WaitedForLimit = TimeSpan.FromSeconds(24), + CpuUtilizationWhileWaiting = 1.0, + }; + + await Assert.That(AdaptiveParallelismSummary.Format(8, 8, 8, 8, changes: 0, changesPutBack: 0, statistics)).IsEqualTo( + "Adaptive parallelism: the parallel test limit stayed at 8. " + + "Tests waited for it for 24s of 30s, with the CPUs 100% busy; too few measurements completed to try a raise."); + } + + [Test] + public async Task Summary_Points_Away_From_The_Limit_When_Throughput_Never_Settles_On_An_Idle_Machine() + { + // The Dekaf 1.90.1 report in #7915: the hook semaphore again, but no raise was tried + // this time, so the reason was "throughput kept changing" and the hint was missing. + var statistics = new AdaptiveRunStatistics(0.08, 0.03, TimeSpan.Zero, AdaptiveRaiseBlocker.ThroughputNotSteady) + { + Sampled = TimeSpan.FromSeconds(183), + WaitedForLimit = TimeSpan.FromSeconds(167), + CpuUtilizationWhileWaiting = 0.08, + }; + + await Assert.That(AdaptiveParallelismSummary.Format(8, 8, 8, 8, changes: 0, changesPutBack: 0, statistics)).IsEqualTo( + "Adaptive parallelism: the parallel test limit stayed at 8. " + + "Tests waited for it for 2m 47s of 3m 3s, with the CPUs 8% busy; it was not raised mostly because throughput kept changing between measurements. " + + "The tests are probably waiting on something other than the CPUs or this limit, such as a lock, a fixture or an external service."); + + // Not after a raise that was kept: more tests at once did help, so they waited for the limit. + await Assert.That(AdaptiveParallelismSummary.Format(8, 12, 8, 12, changes: 1, changesPutBack: 0, statistics)).IsEqualTo( + "Adaptive parallelism: the parallel test limit went from 8 to 12 (lowest 8, highest 12, 1 change). " + + "Tests waited for it for 2m 47s of 3m 3s, with the CPUs 8% busy; it was not raised further mostly because throughput kept changing between measurements."); + } + + [Test] + public async Task Summary_Leaves_Out_A_Wait_That_Rounds_To_No_Time() + { + // The Respire report in #7915: "For 0s of 3s, tests waited for [ParallelLimiter] ...". + var statistics = new AdaptiveRunStatistics(0.3, 0.2, TimeSpan.Zero, AdaptiveRaiseBlocker.None) + { + Sampled = TimeSpan.FromSeconds(3), + WaitedForLimiter = TimeSpan.FromSeconds(0.4), + MostWaitedLimiter = "StreamingTestParallelLimit", + LimitersWaitedFor = 1, + }; + + await Assert.That(AdaptiveParallelismSummary.Format(8, 8, 8, 8, changes: 0, changesPutBack: 0, statistics)).IsEqualTo( + "Adaptive parallelism: the parallel test limit stayed at 8. " + + "The run was too short to measure."); + } + + [Test] + public async Task Summary_Names_The_Test_Process_It_Is_From() + { + // The Relayer report in #7915: 18 lines from 4 test processes at a time, and nothing to match them by. + await Assert.That(AdaptiveParallelismSummary.Format(8, 8, 8, 8, changes: 0, changesPutBack: 0, processName: "Relayer.Kafka.Tests, net10.0")) + .IsEqualTo("Adaptive parallelism (Relayer.Kafka.Tests, net10.0): the parallel test limit stayed at 8. The run was too short to measure."); + + await Assert.That(TestProcessName.Format("MyTests", ".NETCoreApp,Version=v10.0")).IsEqualTo("MyTests, net10.0"); + await Assert.That(TestProcessName.Format("MyTests", ".NETFramework,Version=v4.7.2")).IsEqualTo("MyTests, net472"); + await Assert.That(TestProcessName.Format("MyTests", null)).IsEqualTo("MyTests"); + await Assert.That(TestProcessName.Format(null, ".NETCoreApp,Version=v10.0")).IsNull(); + } + + [Test] + public async Task No_Headroom_Is_Charged_Only_To_Samples_In_Which_The_Cpus_Were_Busy() + { + // The Dekaf and Relayer reports in #7915: "with the CPUs 42% busy; it was not raised + // mostly because the CPUs had no headroom". The reason is from the policy's last + // whole window, and the tests had gone from computing to waiting since. + var totals = new AdaptiveRunTotals(); + totals.Add(TimeSpan.FromSeconds(1), 0.95, 0.9, AdaptiveRaiseBlocker.CpuBusy, heldForOutsideLoad: false, cpuBusy: true); + totals.Add(TimeSpan.FromSeconds(3), 0.07, 0.02, AdaptiveRaiseBlocker.CpuBusy, heldForOutsideLoad: false, cpuBusy: false); + + var statistics = totals.ToStatistics()!.Value; + + await Assert.That(statistics.CpuUtilizationWhileBlocked).IsEqualTo(0.95).Within(0.0001); + await Assert.That(AdaptiveParallelismSummary.Format(8, 8, 8, 8, changes: 0, changesPutBack: 0, statistics)).IsEqualTo( + "Adaptive parallelism: the parallel test limit stayed at 8. " + + "Tests waited for it for 4s of 4s, with the CPUs 29% busy; it was not raised mostly because the CPUs had no headroom (95% busy at those times)."); + } + + [Test] + public async Task Whose_Load_Kept_The_Cpus_Busy_Is_Judged_Over_The_Time_They_Were_Busy() + { + // This process saturates the CPUs for 10 s while tests wait for the limit. Then + // other programs do for 90 s, while no test waits. Over the whole run this process + // used a tenth of the load, but the time the line is about was all its own. + var totals = new AdaptiveRunTotals(); + totals.Add(TimeSpan.FromSeconds(10), 0.9, 0.9, AdaptiveRaiseBlocker.CpuBusy, heldForOutsideLoad: false); + totals.Add(TimeSpan.FromSeconds(90), 0.9, 0.0, AdaptiveRaiseBlocker.CpuBusy, heldForOutsideLoad: false, bottleneck: ParallelismBottleneck.None); + + await Assert.That(totals.ToStatistics()!.Value.OutsideLoadWhileCpuBusy).IsFalse(); + + // And the other way round: containers keep the CPUs busy while tests wait, and + // the child processes that were read then count as this process's own. + var outside = new AdaptiveRunTotals(); + outside.Add(TimeSpan.FromSeconds(10), 0.95, 0.05, AdaptiveRaiseBlocker.CpuBusy, heldForOutsideLoad: true, childProcessCpuUtilization: 0.1); + await Assert.That(outside.ToStatistics()!.Value.OutsideLoadWhileCpuBusy).IsTrue(); + + // The same load before the child processes have been read is not known to be + // someone else's, so it is not said to be. + var unread = new AdaptiveRunTotals(); + unread.Add(TimeSpan.FromSeconds(10), 0.95, 0.05, AdaptiveRaiseBlocker.CpuBusy, heldForOutsideLoad: false); + await Assert.That(unread.ToStatistics()!.Value.OutsideLoadWhileCpuBusy).IsFalse(); + + // One sample that was read and shows outside load does not speak for nine that + // were not: child processes may have caused the load in those. + var mixed = new AdaptiveRunTotals(); + mixed.Add(TimeSpan.FromSeconds(1), 0.95, 0.05, AdaptiveRaiseBlocker.CpuBusy, heldForOutsideLoad: false, childProcessCpuUtilization: 0.1); + mixed.Add(TimeSpan.FromSeconds(9), 0.95, 0.05, AdaptiveRaiseBlocker.CpuBusy, heldForOutsideLoad: false); + await Assert.That(mixed.ToStatistics()!.Value.OutsideLoadWhileCpuBusy).IsFalse(); + + var children = new AdaptiveRunTotals(); + children.Add(TimeSpan.FromSeconds(10), 0.95, 0.05, AdaptiveRaiseBlocker.CpuBusy, heldForOutsideLoad: false, childProcessCpuUtilization: 0.7); + await Assert.That(children.ToStatistics()!.Value.OutsideLoadWhileCpuBusy).IsFalse(); + } + + [Test] + public async Task Summary_Does_Not_Say_Too_Little_Was_Measured_When_The_Last_Measurement_Found_The_Cpus_Busy() + { + // The policy's reason is from its last whole window. When the CPUs go idle after + // it, that reason is not charged, and nothing else is: measurements did complete. + var totals = new AdaptiveRunTotals(); + totals.Add(TimeSpan.FromSeconds(20), 0.1, 0.05, AdaptiveRaiseBlocker.CpuBusy, heldForOutsideLoad: false, cpuBusy: false); + + await Assert.That(AdaptiveParallelismSummary.Format(8, 8, 8, 8, changes: 0, changesPutBack: 0, totals.ToStatistics())).IsEqualTo( + "Adaptive parallelism: the parallel test limit stayed at 8. " + + "Tests waited for it for 20s of 20s, with the CPUs 10% busy; the CPUs had no headroom when it was last measured, and no measurement completed after they went idle."); + + // A later measurement ends in a raise, which clears the policy's reason. The old + // one no longer describes the run, and after a change "too few measurements" would not either. + totals.Add(TimeSpan.FromSeconds(5), 0.1, 0.05, AdaptiveRaiseBlocker.None, heldForOutsideLoad: false, cpuBusy: false); + + await Assert.That(totals.ToStatistics()!.Value.CpuBusyWhenLastMeasured).IsFalse(); + + // So does a later measurement that found fewer tests ready than the limit allows. + var later = new AdaptiveRunTotals(); + later.Add(TimeSpan.FromSeconds(20), 0.1, 0.05, AdaptiveRaiseBlocker.CpuBusy, heldForOutsideLoad: false, cpuBusy: false); + later.Add(TimeSpan.FromSeconds(5), 0.1, 0.05, AdaptiveRaiseBlocker.LimitNotReached, heldForOutsideLoad: false, cpuBusy: false); + await Assert.That(later.ToStatistics()!.Value.CpuBusyWhenLastMeasured).IsFalse(); + + // And one that ended after the tests had stopped waiting for the limit. + var stopped = new AdaptiveRunTotals(); + stopped.Add(TimeSpan.FromSeconds(20), 0.1, 0.05, AdaptiveRaiseBlocker.CpuBusy, heldForOutsideLoad: false, cpuBusy: false); + stopped.Add(TimeSpan.FromSeconds(5), 0.1, 0.05, AdaptiveRaiseBlocker.LimitNotReached, heldForOutsideLoad: false, bottleneck: ParallelismBottleneck.None, cpuBusy: false); + await Assert.That(stopped.ToStatistics()!.Value.CpuBusyWhenLastMeasured).IsFalse(); + + // With a limit that never moved, that run is not one in which too little was measured. + await Assert.That(AdaptiveParallelismSummary.Format(8, 8, 8, 8, changes: 0, changesPutBack: 0, stopped.ToStatistics())).IsEqualTo( + "Adaptive parallelism: the parallel test limit stayed at 8. " + + "Tests waited for it for 20s of 25s, with the CPUs 10% busy."); + await Assert.That(AdaptiveParallelismSummary.Format(8, 12, 8, 12, changes: 1, changesPutBack: 0, totals.ToStatistics())).IsEqualTo( + "Adaptive parallelism: the parallel test limit went from 8 to 12 (lowest 8, highest 12, 1 change). " + + "Tests waited for it for 25s of 25s, with the CPUs 10% busy."); + } + + [Test] + public async Task Change_Kinds_And_Raise_Reasons_Count_Up_From_Zero_Without_Gaps() + { + // Both index arrays in the sampling loop, where an index out of range would stop + // adaptive parallelism for the rest of the run. + await Assert.That(Enum.GetValues().Select(x => (int) x)) + .IsEquivalentTo(Enumerable.Range(0, Enum.GetValues().Length)); + await Assert.That(Enum.GetValues().Select(x => (int) x)) + .IsEquivalentTo(Enumerable.Range(0, Enum.GetValues().Length)); + } + + [Test] + public async Task Summary_Of_A_Wait_Too_Short_To_Give_Does_Not_Say_Tests_Seldom_Waited() + { + // One sample of a run that ended just after the warm-up: tests waited for all of it. + var statistics = new AdaptiveRunStatistics(0.9, 0.8, TimeSpan.Zero, AdaptiveRaiseBlocker.None) + { + Sampled = TimeSpan.FromMilliseconds(250), + WaitedForLimit = TimeSpan.FromMilliseconds(250), + CpuUtilizationWhileWaiting = 0.9, + }; + + await Assert.That(AdaptiveParallelismSummary.Format(8, 8, 8, 8, changes: 0, changesPutBack: 0, statistics)) + .IsEqualTo("Adaptive parallelism: the parallel test limit stayed at 8. The run was too short to measure."); + } + + [Test] + public async Task Details_Say_Why_The_Limit_Changed_And_Mark_A_Change_Made_As_The_Run_Ended() + { + // The Relayer report in #7915: lowered to 2 for 57 s with no reason given, and a + // line that said "went from 8 to 6" for a change with "6 for 0s". + var timeAtLimit = new SortedDictionary + { + [2] = TimeSpan.FromSeconds(57), + [3] = TimeSpan.FromSeconds(0.3), + [6] = TimeSpan.FromSeconds(0.2), + [8] = TimeSpan.FromSeconds(42), + }; + + var changes = new int[Enum.GetValues().Length]; + changes[(int) AdaptiveLimitChange.MemoryPressure] = 1; + changes[(int) AdaptiveLimitChange.Recovery] = 2; + changes[(int) AdaptiveLimitChange.Probe] = 1; + changes[(int) AdaptiveLimitChange.ProbeReverted] = 1; + + // Saturated by other processes for a third of a second: not worth a sentence. + var statistics = new AdaptiveRunStatistics(0.8, 0.06, TimeSpan.FromSeconds(0.3), AdaptiveRaiseBlocker.MemoryBusy); + + await Assert.That(AdaptiveParallelismSummary.FormatDetails(timeAtLimit, statistics, changes, finalLimit: 6)).IsEqualTo( + "Adaptive parallelism details: time at each limit: 2 for 57s, 6 as the run ended, 8 for 42s. " + + "Changes: 1x raised to try more tests, 1x raise put back for no gain in throughput, 1x lowered for memory pressure, 2x raised back after pressure eased. " + + "The machine's CPUs were 80% busy on average, and this process alone used 6% of them."); + } + + [Test] + [Arguments(true, false, 0.51, false)] + [Arguments(true, false, 0.85, true)] + [Arguments(true, true, 0.3, true)] + [Arguments(false, false, 0.99, false)] + public async Task Tasks_Waiting_For_A_Cpu_Count_Only_While_The_Cpus_Are_Busy_Or_A_Quota_Throttles( + bool stalled, bool throttled, double cpuUtilization, bool expected) + { + // The Dekaf report in #7915: the limit went 8 -> 6 -> 4 "for saturated CPUs" at 51% + // and 63% CPU, on the operating system's count of tasks that waited for a processor. + var load = new MachineLoad(cpuUtilization, MemoryUsed: null, CpuStalled: stalled, MemoryStalled: false, CpuThrottled: throttled); + + await Assert.That(AdaptiveParallelismController.IsCpuStalled(load, cpuUtilization)).IsEqualTo(expected); + } + private sealed class ThreeToNine : TUnit.Core.Interfaces.IAdaptiveParallelLimit { public int Limit => 3; diff --git a/tests/TUnit.UnitTests/AdaptiveParallelismPolicyTests.cs b/tests/TUnit.UnitTests/AdaptiveParallelismPolicyTests.cs index 53f19ba118..ac5fc89ad4 100644 --- a/tests/TUnit.UnitTests/AdaptiveParallelismPolicyTests.cs +++ b/tests/TUnit.UnitTests/AdaptiveParallelismPolicyTests.cs @@ -1306,6 +1306,213 @@ public async Task Keeps_A_Lowering_Through_An_Idle_Window() await Assert.That(simulation.Changes[1]).IsEqualTo(new AdaptiveDecision(16, AdaptiveLimitChange.Recovery)); } + [Test] + public async Task Undoes_A_Kept_Lowering_Early_When_It_Starts_To_Cost_Throughput_On_Idle_Cpus() + { + // The Dekaf unit test report in #7915: lowered while the CPUs were busy, then the + // slots filled with tests that wait on timeouts. For ten seconds 30 tests started + // where thousands had, at 2% CPU, and the limit stayed down for the whole wait. + var simulation = new Simulation(Limits) + { + CpuUtilization = 0.99, + QueueDelay = TimeSpan.FromMilliseconds(150), + Throughput = _ => 4 * TestsPerSecondPerSlot, + }; + simulation.RunUntilChange(); + await Assert.That(simulation.Changes).IsEquivalentTo([new AdaptiveDecision(12, AdaptiveLimitChange.CpuSaturation)]); + + // The lowering costs nothing and is kept. + simulation.CpuUtilization = 0.02; + simulation.QueueDelay = TimeSpan.Zero; + simulation.Run(TimeSpan.FromSeconds(3)); + await Assert.That(simulation.Changes.Count).IsEqualTo(1); + await Assert.That(simulation.Policy.RaiseBlocker).IsEqualTo(AdaptiveRaiseBlocker.KeepingLowerLimit); + + // Now slow tests hold the slots: a quarter of the throughput, with tests waiting. + simulation.Throughput = _ => TestsPerSecondPerSlot; + simulation.Run(TimeSpan.FromSeconds(5)); + + // Back up well inside InitialRecoveryHold, which idle CPUs alone must wait out. + await Assert.That(simulation.Changes.Count).IsEqualTo(2); + await Assert.That(simulation.Changes[1]).IsEqualTo(new AdaptiveDecision(16, AdaptiveLimitChange.Recovery)); + } + + [Test] + public async Task Leaves_Its_Part_Of_A_Shared_Budget_When_The_Busy_Cpus_Are_Not_The_Members_Doing() + { + // The shared budget report in #7915: two I/O-bound test processes on a runner that + // containers kept at 92% CPU. Each used 12% of it, started at a part of 4, and + // stayed there because no raise could show a gain. Without a budget they ran at 8 + // and finished 20 to 50 seconds sooner. + var simulation = new Simulation(new ParallelismLimits(Initial: 8, Minimum: 2, Maximum: 32)) + { + CpuUtilization = 0.92, + ProcessCpuUtilization = 0.12, + BudgetMembers = 2, + }; + simulation.Policy.Rebase(TimeSpan.Zero, 4); + + simulation.Run(TimeSpan.FromSeconds(30)); + + // Back to where it would be without a budget, and no further: above that a raise + // needs headroom and a measured gain, as for any process. + await Assert.That(simulation.Changes).IsEquivalentTo( + [ + new AdaptiveDecision(6, AdaptiveLimitChange.PartOutgrown), + new AdaptiveDecision(8, AdaptiveLimitChange.PartOutgrown), + ]); + } + + [Test] + public async Task Still_Leaves_Its_Part_After_A_Raise_To_The_Starting_Limit_Was_Put_Back() + { + // The members keep the CPUs busy, so the way up from the part is a trial. It + // reaches the starting limit, brings nothing, and is put back. + var simulation = new Simulation(new ParallelismLimits(Initial: 6, Minimum: 2, Maximum: 32)) + { + CpuUtilization = 0.97, + ProcessCpuUtilization = 0.45, + BudgetMembers = 2, + Throughput = _ => 4 * TestsPerSecondPerSlot, + }; + simulation.Policy.Rebase(TimeSpan.Zero, 4); + simulation.RunUntilChanges(2); + + await Assert.That(simulation.Changes).IsEquivalentTo( + [ + new AdaptiveDecision(6, AdaptiveLimitChange.Probe), + new AdaptiveDecision(4, AdaptiveLimitChange.ProbeReverted), + ]); + + // The limit is still where the part put it. When the load turns out to be someone + // else's, it leaves the part as it would have before the trial. + simulation.ProcessCpuUtilization = 0.12; + simulation.RunUntilChanges(3); + + await Assert.That(simulation.Changes[2]).IsEqualTo(new AdaptiveDecision(6, AdaptiveLimitChange.PartOutgrown)); + } + + [Test] + public async Task Still_Leaves_Its_Part_After_A_Lowering_From_It_Was_Put_Back() + { + // A part of 8 of a starting limit of 16. The process saturates the CPUs, so a + // lowering to 6 is tried. It costs throughput and is put back. + var simulation = new Simulation(Limits) + { + CpuUtilization = 0.99, + QueueDelay = TimeSpan.FromMilliseconds(150), + BudgetMembers = 2, + + // Too little free memory to try a raise, which would otherwise come first. + MemoryLoad = 0.9, + }; + simulation.Policy.Rebase(TimeSpan.Zero, 8); + simulation.RunUntilChanges(2); + + await Assert.That(simulation.Changes).IsEquivalentTo( + [ + new AdaptiveDecision(6, AdaptiveLimitChange.CpuSaturation), + new AdaptiveDecision(8, AdaptiveLimitChange.LowerReverted), + ]); + + // Back at the part, and still there because of the part: when other load is what + // keeps the CPUs busy, the limit leaves it. + simulation.CpuUtilization = 0.92; + simulation.QueueDelay = TimeSpan.Zero; + simulation.ProcessCpuUtilization = 0.12; + simulation.MemoryLoad = 0.3; + simulation.RunUntilChanges(3); + + await Assert.That(simulation.Changes[2]).IsEqualTo(new AdaptiveDecision(12, AdaptiveLimitChange.PartOutgrown)); + } + + [Test] + public async Task Does_Not_Leave_Its_Part_On_A_Cpu_Share_From_Before_Child_Processes_Were_Counted() + { + // Tests that drive browsers: the test process alone uses 2% of the CPUs, and with + // its child processes 45%. Their reading starts partway through a window, and the + // average over the whole window would pass for a process that causes little load. + var simulation = new Simulation(new ParallelismLimits(Initial: 8, Minimum: 2, Maximum: 32)) + { + CpuUtilization = 0.97, + ProcessCpuUtilization = 0.02, + BudgetMembers = 2, + + // Slow enough that a window lasts several samples, and the same at every + // limit, so a raise that is tried brings nothing and is put back. + Throughput = _ => 8, + }; + simulation.Policy.Rebase(TimeSpan.Zero, 4); + + // Past the settling time and into the first window, then the child processes are read. + simulation.Run(TimeSpan.FromSeconds(1.5)); + simulation.ProcessCpuUtilization = 0.45; + simulation.OwnCoresChangedBasis = true; + simulation.Step(); + simulation.OwnCoresChangedBasis = false; + + simulation.Run(TimeSpan.FromSeconds(30)); + + // Raises may be tried, as for any limit. The part is not left on the mixed figure. + await Assert.That(simulation.Changes.Select(x => x.Change)).DoesNotContain(AdaptiveLimitChange.PartOutgrown); + } + + [Test] + public async Task Does_Not_Leave_Its_Part_Before_Its_Child_Processes_Have_Been_Read() + { + // The CPUs are 85% busy and the test process alone uses 2% of them. Whether its + // browsers use the rest is not known yet, so the part holds. + var simulation = new Simulation(new ParallelismLimits(Initial: 8, Minimum: 2, Maximum: 32)) + { + CpuUtilization = 0.85, + ProcessCpuUtilization = 0.02, + ProcessShareCountsChildProcesses = false, + BudgetMembers = 2, + Throughput = _ => 4 * TestsPerSecondPerSlot, + }; + simulation.Policy.Rebase(TimeSpan.Zero, 4); + simulation.Run(TimeSpan.FromSeconds(20)); + + await Assert.That(simulation.Changes.Select(x => x.Change)).DoesNotContain(AdaptiveLimitChange.PartOutgrown); + + // Read, and they turn out to use little: the load is someone else's. + simulation.ProcessShareCountsChildProcesses = true; + simulation.OwnCoresChangedBasis = true; + simulation.Step(); + simulation.OwnCoresChangedBasis = false; + simulation.Run(TimeSpan.FromSeconds(20)); + + await Assert.That(simulation.Changes.Select(x => x.Change)).Contains(AdaptiveLimitChange.PartOutgrown); + } + + [Test] + public async Task Stays_At_Its_Part_Of_A_Shared_Budget_When_The_Members_Keep_The_Cpus_Busy() + { + // What the budget is for: two CPU-bound test processes that would oversubscribe the + // machine between them. More tests bring nothing, so the part holds. + var simulation = new Simulation(new ParallelismLimits(Initial: 8, Minimum: 2, Maximum: 32)) + { + CpuUtilization = 0.97, + ProcessCpuUtilization = 0.45, + BudgetMembers = 2, + Throughput = _ => 4 * TestsPerSecondPerSlot, + }; + simulation.Policy.Rebase(TimeSpan.Zero, 4); + + // The first window that ends says why: the CPUs, not "throughput kept changing". + for (var i = 0; i < 40 && simulation.Policy.RaiseBlocker == AdaptiveRaiseBlocker.None; i++) + { + simulation.Step(); + } + + await Assert.That(simulation.Policy.RaiseBlocker).IsEqualTo(AdaptiveRaiseBlocker.CpuBusy); + + simulation.Run(TimeSpan.FromSeconds(60)); + + await Assert.That(simulation.Changes.Select(x => x.Change)).DoesNotContain(AdaptiveLimitChange.PartOutgrown); + await Assert.That(simulation.Policy.Limit).IsLessThanOrEqualTo(6); + } + [Test] public async Task Settles_When_The_Cpus_Alternate_Between_Busy_And_Idle() { @@ -1446,6 +1653,10 @@ private sealed class Simulation(ParallelismLimits limits, int processorCount = 4 public bool OwnCoresChangedBasis { get; set; } + public int BudgetMembers { get; set; } + + public bool ProcessShareCountsChildProcesses { get; set; } = true; + public Func FailuresPerSample { get; set; } = _ => 0; // Processors' worth of CPU time the process and its child processes use at a limit. @@ -1471,7 +1682,9 @@ public bool Step() OwnCores(Policy.Limit), PressureElsewhere, OverLimit, - OwnCoresChangedBasis)); + OwnCoresChangedBasis, + BudgetMembers, + ProcessShareCountsChildProcesses)); if (decision.Change == AdaptiveLimitChange.None) { diff --git a/tests/TUnit.UnitTests/SharedParallelBudgetTests.cs b/tests/TUnit.UnitTests/SharedParallelBudgetTests.cs index bb8a80381f..780ce07a7d 100644 --- a/tests/TUnit.UnitTests/SharedParallelBudgetTests.cs +++ b/tests/TUnit.UnitTests/SharedParallelBudgetTests.cs @@ -137,6 +137,9 @@ public async Task Summary_Says_How_Many_Processes_Shared_The_Budget() await Assert.That(SharedParallelBudget.FormatSummary("ci", budget: 8, lowestPart: 2, highestPart: 8, mostMembers: 3)) .IsEqualTo("Shared parallel budget 'ci': up to 3 test processes shared a budget of 8, and this one ran at most 2 to 8 tests in parallel"); + await Assert.That(SharedParallelBudget.FormatSummary("ci", budget: 8, lowestPart: 8, highestPart: 8, mostMembers: 1, processName: "Suite.Tests, net10.0")) + .IsEqualTo("Shared parallel budget 'ci' (Suite.Tests, net10.0): no other test process shared the budget of 8, so this one ran at most 8 tests in parallel"); + await Assert.That(SharedParallelBudget.FormatSummary("ci", budget: 8, lowestPart: 8, highestPart: 8, mostMembers: 1)) .IsEqualTo("Shared parallel budget 'ci': no other test process shared the budget of 8, so this one ran at most 8 tests in parallel"); } @@ -263,7 +266,7 @@ public async Task Summary_With_Adaptive_Parallelism_Says_The_Part_Is_Where_The_L // The adaptive summary in #7915 said the limit "stayed at 8" while this line said // the process ran at most 4. await Assert.That(SharedParallelBudget.FormatSummary("ci", budget: 8, lowestPart: 2, highestPart: 4, mostMembers: 3, adaptive: true)) - .IsEqualTo("Shared parallel budget 'ci': up to 3 test processes shared a budget of 8, and this one had a part of 2 to 4 tests in parallel, which is where its adaptive limit starts"); + .IsEqualTo("Shared parallel budget 'ci': up to 3 test processes shared a budget of 8, and this one had a part of 2 to 4 tests in parallel (the part grows as other processes finish), which is where its adaptive limit starts"); } [Test]