diff --git a/docs/docs/execution/parallelism.md b/docs/docs/execution/parallelism.md index 7f15b549a44..84579d0cdfc 100644 --- a/docs/docs/execution/parallelism.md +++ b/docs/docs/execution/parallelism.md @@ -205,19 +205,19 @@ A limiter's limit is often a guess. It usually protects something TUnit cannot o Use the type with `[ParallelLimiter]` as you would any other limiter. No command-line flag is needed, and adaptive parallelism does not have to be on. -TUnit measures how many of the tests behind the limiter finish per second, and only while the limiter is full, so that the limit is what holds tests back: +TUnit decides the limit of an adaptive limiter the same way it decides the session-wide limit under [adaptive parallelism](#adaptive-parallelism), from the same reading of the machine. The measure of throughput is how many of the tests behind the limiter finish per second, and it counts only while tests wait for the limiter, so that the limit is what holds them back: -- **Raising.** Once two measurements in a row agree, TUnit raises the limit by half and measures again. It keeps the raise only if throughput rose by a fair share of it: 15% more for a 50% raise. Otherwise it puts the limit back. -- **Lowering.** After a raise was put back, TUnit tries a quarter fewer from the same limit, and keeps the lower limit if throughput held: the tests are waiting on something other than the limiter, and fewer of them at once each spend less time waiting inside their bodies. A limit that has never had a raise rejected is not lowered. +- **Raising.** Once two measurements in a row agree, and the machine has CPU and memory to spare, TUnit raises the limit by half and measures again. It keeps the raise only if throughput rose by a fair share of it: 15% more for a 50% raise. Otherwise it puts the limit back. After a raise that brought most of itself in throughput, the next raise doubles the limit: from 16 to 24, then to 48. `MaximumLimit` caps every raise, so set it to what the protected resource can take. When too few tests finish to measure throughput, the limit is not raised. +- **Lowering.** The limit comes down only when the CPUs are saturated and most of the running tests are inside this limiter, so its tests are what causes the load. TUnit then tries a quarter fewer and keeps the lower limit if throughput fell by no more than 7.5%. Without that pressure the limit is never lowered, whatever throughput looks like: with a mix of quick and slow tests, a few seconds can look as fast with fewer tests while the whole run gets slower. - **Failing tests.** When tests behind the limiter fail during a raise that is being measured, and none failed in the measurements before it, TUnit puts the limit back at once and does not raise it past that point again in the run. Those tests still fail: set `MaximumLimit` to a value the protected resource can take. Tests that were already failing before the raise do not count against it, and then only throughput decides. -- **Waiting.** After a change that was put back, TUnit waits 10 seconds before trying the same direction again, doubling up to 2 minutes. +- **Waiting.** After a raise that was put back, TUnit waits 5 seconds before trying again, doubling up to 30 seconds. No raise is tried while changes that were put back, of this limit or any other, add up to more than a tenth of the run so far. Only one limit is tried at a time. While a limiter is being measured, no other limiter is, and adaptive parallelism does not start a trial of the session-wide limit, because each change would alter the throughput the other is judged by. When the number of tests the session runs at once changes anyway (memory pressure, or another process joining a [shared budget](#sharing-the-limit-between-test-processes)), the measurement in progress is dropped, the limit goes back, and the trial starts again later. -Each adaptive limiter gets a line at the end of the run, and `--log-level Debug` shows every change with its reason: +A limiter whose limit changed, or that tests waited for, gets a line at the end of the run. `--log-level Debug` shows every change with its reason: ```text -Adaptive [ParallelLimiter] PostgresHosts: the limit ranged from 4 to 9 over 3 changes (1 put back because it did not help) and ended at 6 +[ParallelLimiter] PostgresHosts: the limit went from 4 to 6 (lowest 4, highest 9, 3 changes, 1 put back). Tests waited for it for 1m 12s; it was not raised mostly because an earlier raise did not help, or memory was short. ``` Adaptive limiters require .NET 8 or later and run on Windows, Linux and macOS. Elsewhere the limit stays at `Limit`. @@ -254,10 +254,14 @@ TUNIT_ADAPTIVE_PARALLELISM=1 dotnet run --project MyTests You can also set `context.Settings.Parallelism.Adaptive = true` in a `[Before(HookType.TestDiscovery)]` hook. -The run starts at the limit a run without adaptive parallelism uses: `--maximum-parallel-tests` when you set it, or 2 x the processor count. A move away from that limit has to pay for itself in completed tests per second. TUnit measures throughput, changes the limit, measures again, and puts the limit back if the change did not help. It starts only once two measurements in a row agree, so a suite whose throughput is still changing (a shared fixture starting, for example) is left alone until it settles. After a change that did not help, it waits before trying another. For a raise the wait is 5 seconds at first, doubling up to 30 seconds. For a lowering it is 15 seconds at first, doubling up to 2 minutes. +The run starts at the limit a run without adaptive parallelism uses: `--maximum-parallel-tests` when you set it, or 2 x the processor count. While the limit stays there, the run costs what it costs with a fixed limit. A move away from that limit has to pay for itself. TUnit measures throughput, changes the limit, measures again, and puts the limit back if the change did not help. It starts only once two measurements in a row agree, so a suite whose throughput is still changing (a shared fixture starting, for example) is left alone until it settles. After a change that did not help, it waits before trying another. For a raise the wait is 5 seconds at first, doubling up to 30 seconds. For a lowering it is 15 seconds at first, doubling up to 2 minutes. No raise is tried while changes that were put back, of the session-wide limit or of any limiter, add up to more than a tenth of the run so far. That keeps a run of failed trials from costing much against a fixed limit. It is a rule for trying a raise, not a cap: a trial in progress runs to its end, and the first raise is always allowed, so a short run can spend a larger share on it. A lowering for saturated CPUs is never held back by it. -- **Raising.** When every slot is in use, CPU use is below 80%, memory use is below about 80%, and nothing is waiting for a CPU, TUnit raises the limit by half. It keeps the raise only if throughput rose by a fair share of it: 15% more for a 50% raise. A raise above the starting limit that leaves the CPUs 90% busy or more is put back within about half a second, without waiting for the measurement. -- **Lowering for CPU.** When the CPUs are saturated, work is waiting for one, and the test process together with the processes it started uses at least half of the machine's CPU capacity, TUnit lowers the limit by a quarter. It keeps the lower limit only if throughput held in two measurements in a row: one or more steps down may cost at most 7.5% in total. CPU-bound tests lose nothing with fewer running at once, so the lower limit stays. Tests that mostly wait on I/O do lose, so the limit goes back. Above the starting limit, saturated CPUs are enough to try a lower limit, whether or not work is waiting and whichever process uses them. TUnit never lowers the limit below the processor count for this reason. +Nothing is measured in the first 2 seconds of a run, so a test project that finishes within them is not affected at all. + +- **Raising.** When tests are waiting for the limit, CPU use is below 80%, memory use is below about 80%, and nothing is waiting for a CPU, TUnit raises the limit by half. It keeps the raise only if throughput rose by a fair share of it: 15% more for a 50% raise. After a raise that brought most of itself in throughput, the next raise doubles the limit. A raise above the starting limit that leaves the CPUs 90% busy or more is put back within about half a second, without waiting for the measurement. When too few tests finish to measure throughput, the limit is not raised. +- **Lowering for CPU.** When the CPUs are saturated, work is waiting for one, and the test process together with the processes it started uses at least half of the machine's CPU capacity, TUnit lowers the limit by a quarter. It keeps the lower limit only if throughput held in two measurements in a row: one or more steps down may cost at most 7.5% in total. CPU-bound tests lose nothing with fewer running at once, so the lower limit stays. Tests that mostly wait on I/O do lose, so the limit goes back. Above the starting limit, saturated CPUs are enough to try a lower limit, whether or not work is waiting and whichever process uses them. TUnit never lowers the limit below the processor count for this reason, and does not lower it for this reason in the first 10 seconds it measures, while the first tests are compiled and fixtures start. +- **Lowering for CPU with slow tests.** Tests that take many seconds finish too rarely for throughput to be compared. A lowering of the session-wide limit is then judged by the CPU time the test process and the processes it started use, once the tests that were already running have finished and the lower limit is the one in effect. When that CPU time stays within 7.5% of what it was, in two measurements of 5 seconds in a row, the CPUs stayed busy with fewer tests, so nothing was lost and the lower limit stays. When it falls further, the limit goes back. A limiter's limit is not judged this way: the slots it frees go to tests outside it, so the process's CPU time says nothing about its lowering. A limiter is lowered only when enough of its tests finish to compare throughput. +- **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. @@ -284,6 +288,18 @@ The highest bound wins when the two cross, and the start moves inside them. The Adaptive parallelism reacts to memory pressure after it appears, so tests that each start a large process (a browser, for example) can still exhaust memory before the limit comes down. For those, also start low with `--maximum-parallel-tests`, or cap them with `[ParallelLimiter]`. +### Limiters With a Declared Limit + +A `[ParallelLimiter]` whose type implements only `IParallelLimit` keeps its declared limit as a ceiling under adaptive parallelism. TUnit never raises it, because the limit can be a hard cap on something TUnit cannot see, such as the connections a database accepts, and exceeding it fails tests. TUnit can lower it while the CPUs are saturated and most of the running tests are inside it, and returns it to the declared limit afterwards. + +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. +``` + +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 The readings cover the whole machine, not only the test process, because other test processes, child processes and containers share it. @@ -298,27 +314,40 @@ On every system, thread pool work that waits 100 ms or more for a thread while t Machine load alone does not move the limit. Tests that wait on a shared resource, such as a database connection pool, leave the CPU idle, but running more of them only makes each one wait longer. Tests on a machine that other processes keep busy see saturated CPUs, but running fewer of them only gives throughput away, so TUnit holds the limit there. Because TUnit keeps a change only when the measurement supports it, such suites stay at the starting limit. `[ParallelLimiter]` is still the right tool when you know a group of tests shares limited capacity. -The summary at the end of the run reports the range the limit moved in, how many changes were put back, and how long the run spent at each limit. It then gives the average CPU use of the machine and of the test process, how long saturated CPUs were left alone because other processes caused the load, and the reason that most often kept the limit from being raised: +### The Summary + +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 ranged from 16 to 36 over 3 changes (1 put back because it did not help) and ended at 24. Time at each limit: 16 for 12s, 24 for 1m 40s, 36 for 4s. The machine's CPUs were 71% busy on average, and this process alone used 58% of them. Most common reason for not raising the limit: the CPUs have no headroom +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. ``` -On a machine that other test processes share, it reads like this: +| 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. | +| `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 [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. | + +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`. ```text -Adaptive parallelism: the parallel test limit stayed at 8. The machine's CPUs were 98% busy on average, and this process alone used 12% of them. 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 CPU saturation. Most common reason for not raising the limit: the CPUs have no headroom +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. ``` -The test process's figure does not include the processes the tests start, such as browsers. TUnit reads those only while the figure can change a decision: while the CPUs are nearly saturated and the test process alone uses less than half of them. When it has read them, the summary adds their share over that time: +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: ```text -The machine's CPUs were 97% busy on average, and this process alone used 4% of them. Its child processes used 61% in the 2m 10s they were measured, which is while the CPUs were nearly saturated +The machine's CPUs were 97% busy on average, and this process alone used 4% of them. Its child processes used 61% over the 2m 10s they were measured. ``` Containers are never included in either figure. A database or another service that the tests start in a container runs under the container runtime, not under the test process, so a suite whose CPU time goes to containers reads as a small share of a busy machine, and its limit is held, not lowered. -Run with `--log-level Debug`, or set `TUNIT_LOG_LEVEL=Debug` when you cannot change the arguments, to see each change and its reason, with the CPU use of the whole machine and of the test process. A busy machine with an idle test process means the load comes from elsewhere, such as other test processes on the same machine. The same log says why the limit is not being raised whenever that reason changes, for example `not raising the limit of 36: the CPUs have no headroom`, so a limit that never moved is explained too. If a test fails only under adaptive parallelism, rerun with `--maximum-parallel-tests` set to the highest limit reported to reproduce that level of concurrency with a fixed limit. +Run with `--log-level Debug`, or set `TUNIT_LOG_LEVEL=Debug` when you cannot change the arguments, to see each change and its reason, with the CPU use of the whole machine and of the test process. A busy machine with an idle test process means the load comes from elsewhere, such as other test processes on the same machine. The same log says why the limit is not being raised whenever that reason changes, for example `not raising the limit of 36: the CPUs had no headroom`, so a limit that never moved is explained too. If a test fails only under adaptive parallelism, rerun with `--maximum-parallel-tests` set to the highest limit reported to reproduce that level of concurrency with a fixed limit. Adaptive parallelism requires .NET 8 or later and runs on Windows, Linux and macOS. Elsewhere the limit stays fixed. @@ -347,7 +376,9 @@ 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 the most it runs, and the adaptive limit moves below it. +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. + +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. The processes find each other through files in the temporary directory that each holds open, so they must run on the same machine, as the same user, and see the same temporary directory. Processes in separate containers do not share a budget. When the temporary directory cannot be written, or is on a file system that does not lock open files, the process logs a warning and uses its whole limit. The summary at the end of the run says how the budget was split: @@ -355,6 +386,8 @@ 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. + ## When to Use Which | Scenario | Attribute | @@ -363,6 +396,7 @@ Shared parallel budget 'ci-tests': up to 3 test processes shared a budget of 8, | Groups of tests can overlap internally but must be isolated from other groups | `[ParallelGroup("key")]` | | Tests can overlap but you need to cap concurrency (e.g., limited external connections) | `[ParallelLimiter]` | | Same, but the right cap is a guess | `[ParallelLimiter]` with an [adaptive limiter](#adaptive-limiter) | +| Tests are heavy on CPU or memory and you only want to keep the load down | No attribute: [adaptive parallelism](#adaptive-parallelism) | | Several test processes run at once on one machine | [`TUNIT_SHARED_PARALLEL_BUDGET`](#sharing-the-limit-between-test-processes) | | Disable all parallelism for an assembly | `[assembly: NotInParallel]` | diff --git a/src/TUnit.Core/Interfaces/IAdaptiveParallelLimit.cs b/src/TUnit.Core/Interfaces/IAdaptiveParallelLimit.cs index e7bd3ce1e27..e8bee407cee 100644 --- a/src/TUnit.Core/Interfaces/IAdaptiveParallelLimit.cs +++ b/src/TUnit.Core/Interfaces/IAdaptiveParallelLimit.cs @@ -9,12 +9,24 @@ namespace TUnit.Core.Interfaces; /// /// /// -/// The run starts at . TUnit measures how many of the tests -/// behind this limit finish per second, changes the limit, measures again, and puts the limit -/// back when the change did not help. When tests fail while a raise is being measured, and -/// none failed in the measurements before it, the raise is put back and the limit is not -/// raised past that point again in the run. Tests that were already failing before the raise -/// do not count against it. +/// The run starts at . While tests wait for this limit and +/// the machine has CPU and memory to spare, TUnit measures how many of the tests behind it +/// finish per second, raises the limit, measures again, and puts the limit back when the +/// raise did not help. When tests fail while a raise is being measured, and none failed in +/// the measurements before it, the raise is put back and the limit is not raised past that +/// point again in the run. Tests that were already failing before the raise do not count +/// against it. +/// +/// +/// The limit is lowered only while the CPUs are saturated and most of the running tests are +/// behind it. The lower limit is kept when throughput fell by no more than 7.5%. When too few +/// of its tests finish to compare throughput, the limit is not lowered. It is never lowered +/// for throughput alone. A limit that was raised above +/// comes back down toward it for saturated CPUs whatever causes them. +/// +/// +/// A limiter that implements only is never raised: under +/// adaptive parallelism its limit is a ceiling. /// /// /// This needs .NET 8 or later. Elsewhere the limit stays at . diff --git a/src/TUnit.Core/ParallelLimitLockProvider.cs b/src/TUnit.Core/ParallelLimitLockProvider.cs index 695d288a5fc..fa5fbe6ef02 100644 --- a/src/TUnit.Core/ParallelLimitLockProvider.cs +++ b/src/TUnit.Core/ParallelLimitLockProvider.cs @@ -11,6 +11,13 @@ public class ParallelLimitLockProvider private readonly Lock _adaptiveLocksLock = new(); private volatile ParallelLimitLock[] _adaptiveLocks = []; + /// + /// Whether the limit of a [ParallelLimiter] that is not an + /// may be lowered while tests run, and never raised: adaptive parallelism treats the + /// declared limit as a ceiling. Set before the first lock is created. + /// + internal bool FixedLimitsAreCeilings { get; set; } + internal ParallelLimitLock GetLock(IParallelLimit parallelLimit) { if (parallelLimit.Limit <= 0) @@ -22,20 +29,21 @@ internal ParallelLimitLock GetLock(IParallelLimit parallelLimit) } /// - /// The locks created so far whose limit can be adjusted, in the order they were created. + /// The locks created so far that adaptive parallelism follows, in the order they were + /// created: those whose limit can be adjusted, and those it only reports on. /// internal ParallelLimitLock[] AdaptiveLocks => _adaptiveLocks; /// - /// Called each time a lock whose limit can be adjusted is created. + /// Called each time a lock that adaptive parallelism follows is created. /// internal Action? AdaptiveLockCreated { get; set; } private ParallelLimitLock CreateLock(IParallelLimit parallelLimit) { - var parallelLimitLock = ParallelLimitLock.Create(parallelLimit); + var parallelLimitLock = ParallelLimitLock.Create(parallelLimit, FixedLimitsAreCeilings); - if (parallelLimitLock.IsAdaptive) + if (parallelLimitLock.IsObserved) { lock (_adaptiveLocksLock) { @@ -61,31 +69,50 @@ internal sealed class ParallelLimitLock // in the high 32. One field, so a reader never sees a failure without the test it belongs to. private long _counts; - private ParallelLimitLock(Type limitType, int initial, int minimum, int maximum) + // Tests of this limiter that are queued behind its workers and have not started. + private int _backlog; + + private ParallelLimitLock(Type limitType, int initial, int minimum, int maximum, bool observed = false) { LimitType = limitType; Initial = initial; Minimum = minimum; Maximum = maximum; - _semaphore = new ResizableSemaphore(initial, maximum, resizable: minimum < maximum); + IsObserved = observed || minimum < maximum; + + // Resizable also when the limit cannot move: that is what makes the semaphore count + // the tests that wait for it, which is how a limit of 1 shows up as what held a run back. + _semaphore = new ResizableSemaphore(initial, maximum, resizable: IsObserved); } - public static ParallelLimitLock Create(IParallelLimit parallelLimit) + /// The limiter the lock is for. + /// + /// Whether a limit that is not an may be lowered + /// while tests run. It is never raised: a declared limit can be a hard cap, such as the + /// connections a database accepts, and exceeding it fails tests. + /// + public static ParallelLimitLock Create(IParallelLimit parallelLimit, bool fixedLimitIsCeiling = false) { var limit = parallelLimit.Limit; #pragma warning disable TUNITEXP001 // Adaptive parallel limits are experimental if (parallelLimit is IAdaptiveParallelLimit adaptive) { - return new ParallelLimitLock( - parallelLimit.GetType(), - limit, - Math.Max(1, Math.Min(adaptive.MinimumLimit, limit)), - Math.Max(adaptive.MaximumLimit, limit)); + var minimum = Math.Max(1, Math.Min(adaptive.MinimumLimit, limit)); + var maximum = Math.Max(adaptive.MaximumLimit, limit); + + // The bounds are the user's, also when they leave the limit no room: MinimumLimit + // is documented as the lowest limit TUnit goes to, so equal bounds pin it. Where + // adaptive parallelism is on, such a limiter is still followed, so the summary + // can say when tests waited for it. + return new ParallelLimitLock(parallelLimit.GetType(), limit, minimum, maximum, observed: fixedLimitIsCeiling) + { + IsDeclaredAdaptive = true, + }; } #pragma warning restore TUNITEXP001 - return new ParallelLimitLock(parallelLimit.GetType(), limit, limit, limit); + return new ParallelLimitLock(parallelLimit.GetType(), limit, fixedLimitIsCeiling ? 1 : limit, limit, observed: fixedLimitIsCeiling); } public Type LimitType { get; } @@ -102,6 +129,20 @@ public static ParallelLimitLock Create(IParallelLimit parallelLimit) /// public bool IsAdaptive => Minimum < Maximum; + /// + /// Whether adaptive parallelism follows this lock: it counts the tests that wait for it + /// and that leave it. True for every lock whose limit can change, and for a declared + /// limit of 1 under adaptive parallelism, which cannot go lower but can still be what + /// holds a run back. + /// + public bool IsObserved { get; } + + /// + /// Whether the limiter is an , whose own bounds + /// decide how far the limit can move. + /// + public bool IsDeclaredAdaptive { get; private init; } + public int CurrentLimit => _semaphore.CurrentLimit; /// @@ -111,8 +152,38 @@ public static ParallelLimitLock Create(IParallelLimit parallelLimit) public bool IsFull => _semaphore.AvailableSlots == 0; /// - /// The number of tests that have left an adaptive lock, and how many of them failed, read - /// together. A fixed lock does not count. + /// The number of tests inside the lock right now. + /// + public int HeldPlaces => _semaphore.HeldSlots; + + /// + /// The number of tests waiting to enter the lock right now. Counted only when . + /// + public int Waiting => _semaphore.Waiting; + + /// + public bool BeginWait(Task wait) => _semaphore.BeginWait(wait); + + /// + public void EndWait(bool counted) => _semaphore.EndWait(counted); + + /// + /// The number of this limiter's tests that are queued behind its workers and have not + /// started. Counted only for a lock whose tests are started by workers that follow a limit. + /// + public int Backlog => Volatile.Read(ref _backlog); + + public void AddBacklog(int tests) => Interlocked.Add(ref _backlog, tests); + + /// + /// Whether the lock is full while more of its tests could start at once: this limit, and + /// nothing else, is what holds them back. + /// + public bool HasUnmetDemand => IsFull && (Backlog > 0 || Waiting > 0); + + /// + /// The number of tests that have left the lock, and how many of them failed, read + /// together. Counted only when . /// public (long Finished, long Failed) ReadCounts() { @@ -128,10 +199,10 @@ public static ParallelLimitLock Create(IParallelLimit parallelLimit) public Task EnterAsync(CancellationToken cancellationToken) => _semaphore.WaitAsync(cancellationToken); - /// Whether the test that leaves failed. Counted for an adaptive lock only. + /// Whether the test that leaves failed. Counted only when . public void Exit(bool testFailed) { - if (IsAdaptive) + if (IsObserved) { Interlocked.Add(ref _counts, testFailed ? (1L << 32) + 1 : 1); } @@ -142,5 +213,22 @@ public void Exit(bool testFailed) /// /// Changes the limit, kept within and , and returns it. /// - public int SetLimit(int limit) => _semaphore.SetLimit(Math.Min(Math.Max(limit, Minimum), Maximum)); + public int SetLimit(int limit) + { + var previous = _semaphore.CurrentLimit; + var current = _semaphore.SetLimit(Math.Min(Math.Max(limit, Minimum), Maximum)); + + if (current != previous) + { + LimitChanged?.Invoke(); + } + + return current; + } + + /// + /// Raised after the limit has changed, on the thread that changed it. The workers that + /// start this limiter's tests follow it. + /// + public event Action? LimitChanged; } diff --git a/src/TUnit.Core/ResizableSemaphore.cs b/src/TUnit.Core/ResizableSemaphore.cs index 06b35e13c76..e0b7cbb7c8d 100644 --- a/src/TUnit.Core/ResizableSemaphore.cs +++ b/src/TUnit.Core/ResizableSemaphore.cs @@ -24,6 +24,9 @@ internal sealed class ResizableSemaphore private long _countedReleases; + // Callers that are waiting for a slot right now. Counted only when resizable. + private int _waiting; + /// The number of slots to start with. /// The most slots can ever grow to. /// Whether may be called. @@ -47,11 +50,59 @@ public ResizableSemaphore(int initial, int maximum, bool resizable) /// public long CountedReleases => Volatile.Read(ref _countedReleases); + /// + /// The number of slots that are held right now. A slot that a shrink is waiting to take + /// back still counts until its holder releases it. + /// + /// + /// Read without the resize lock, from three values that change separately, so it can be + /// off by a slot for a moment while a resize or a release is in progress. Adaptive + /// parallelism reads it once per sample to decide which limit most running tests are + /// inside and whether a lowered limit is in effect yet. Both are decisions over many + /// samples, which a reading that is off for one of them does not change. + /// + public int HeldSlots => Math.Max(0, Volatile.Read(ref _currentLimit) + Volatile.Read(ref _slotsToRetire) - _semaphore.CurrentCount); + + /// + /// The number of callers waiting for a slot right now. Always 0 unless resizable. + /// + public int Waiting => Volatile.Read(ref _waiting); + /// /// Waits for a slot. An uncontended wait completes synchronously without allocating. /// public Task WaitAsync(CancellationToken cancellationToken) => _semaphore.WaitAsync(cancellationToken); + /// + /// Counts the caller as waiting for a slot, when has to queue + /// and the semaphore is resizable. Returns whether it was counted, which the caller + /// hands to once the wait is over, however it ended. + /// + /// + /// The caller awaits the task itself, inside the async method it already is. Wrapping + /// the task here to keep the count would allocate a second state machine for every + /// test that has to queue. + /// + public bool BeginWait(Task wait) + { + if (!_resizable || wait.IsCompleted) + { + return false; + } + + Interlocked.Increment(ref _waiting); + return true; + } + + /// What returned for the wait. + public void EndWait(bool counted) + { + if (counted) + { + Interlocked.Decrement(ref _waiting); + } + } + /// /// Waits for a slot for at most . With 0 it never /// waits: the task is already complete, with false when no slot is free. diff --git a/src/TUnit.Engine/Configuration/EnvironmentConstants.cs b/src/TUnit.Engine/Configuration/EnvironmentConstants.cs index abebee626de..e068af9634b 100644 --- a/src/TUnit.Engine/Configuration/EnvironmentConstants.cs +++ b/src/TUnit.Engine/Configuration/EnvironmentConstants.cs @@ -37,6 +37,10 @@ internal static class EnvironmentConstants // Experimental. Names a parallel test budget that this process splits with the other test // processes on the machine that name the same one. public const string SharedParallelBudget = "TUNIT_SHARED_PARALLEL_BUDGET"; + + // Set by a test process for the processes it starts: the name of the budget it is a + // member of. Not for users to set. + public const string SharedParallelBudgetMember = "TUNIT_SHARED_PARALLEL_BUDGET_MEMBER"; // Opts out of the thread pool starvation monitor (raises min worker threads when tests block). // Takes precedence over TUnitSettings.Execution.ThreadPoolTuningEnabled. public const string DisableThreadPoolTuning = "TUNIT_DISABLE_THREADPOOL_TUNING"; diff --git a/src/TUnit.Engine/Logging/ISessionMessageLogger.cs b/src/TUnit.Engine/Logging/ISessionMessageLogger.cs new file mode 100644 index 00000000000..542f476aec5 --- /dev/null +++ b/src/TUnit.Engine/Logging/ISessionMessageLogger.cs @@ -0,0 +1,39 @@ +using TUnit.Core.Logging; + +namespace TUnit.Engine.Logging; + +/// +/// A logger that can write a line which stays in the output of the whole test run. +/// +/// +/// When dotnet test runs several test projects, it shows one result line for each and +/// drops what a test process writes as plain text. A session message is passed on, so a +/// line written this way is still there for the reader (#7915). +/// +internal interface ISessionMessageLogger +{ + /// + /// Writes at as a message + /// that belongs to the test session. + /// + void LogSessionMessage(string message); +} + +internal static class SessionMessageLoggerExtensions +{ + /// + /// Writes a line that ends the run: as a session message where the logger has them, and + /// as an ordinary line otherwise. + /// + public static void LogSessionMessage(this ILogger logger, string message) + { + if (logger is ISessionMessageLogger sessionMessageLogger) + { + sessionMessageLogger.LogSessionMessage(message); + } + else + { + logger.LogInformation(message); + } + } +} diff --git a/src/TUnit.Engine/Logging/TUnitFrameworkLogger.cs b/src/TUnit.Engine/Logging/TUnitFrameworkLogger.cs index 17c51f897ca..ca4e4304993 100644 --- a/src/TUnit.Engine/Logging/TUnitFrameworkLogger.cs +++ b/src/TUnit.Engine/Logging/TUnitFrameworkLogger.cs @@ -8,7 +8,7 @@ namespace TUnit.Engine.Logging; public class TUnitFrameworkLogger(IExtension extension, IOutputDevice outputDevice, ILogger logger, LogLevelProvider logLevelProvider) - : IOutputDeviceDataProducer, Core.Logging.ILogger + : IOutputDeviceDataProducer, Core.Logging.ILogger, ISessionMessageLogger { private readonly LogLevel _minimumLogLevel = logLevelProvider.LogLevel; @@ -64,6 +64,19 @@ public void Log(LogLevel logLevel, TState state, Exception? exception, F _adapter.Log(logLevel, state, exception, formatter); } + /// + void ISessionMessageLogger.LogSessionMessage(string message) + { + if (!IsEnabled(LogLevel.Information)) + { + return; + } + + outputDevice.DisplayAsync(this, new SessionMessageOutputDeviceData(message), CancellationToken.None); + + _adapter.Log(LogLevel.Information, message, null, static (text, _) => text); + } + private static ConsoleColor GetConsoleColor(LogLevel logLevel) { if (logLevel == LogLevel.Warning) diff --git a/src/TUnit.Engine/Scheduling/AdaptiveLimiterPolicy.cs b/src/TUnit.Engine/Scheduling/AdaptiveLimiterPolicy.cs deleted file mode 100644 index e4e86b6f207..00000000000 --- a/src/TUnit.Engine/Scheduling/AdaptiveLimiterPolicy.cs +++ /dev/null @@ -1,377 +0,0 @@ -namespace TUnit.Engine.Scheduling; - -/// -/// One observation of the tests behind an adaptive [ParallelLimiter] since the previous one. -/// -/// Time since the previous sample. -/// Tests that left the limiter since the previous sample. -/// How many of those failed. -/// Whether as many tests were inside the limiter as it admits. -internal readonly record struct AdaptiveLimiterSample(TimeSpan Elapsed, long FinishedTests, long FailedTests, bool LimitReached); - -internal enum AdaptiveLimiterChange -{ - None, - - /// Raised to find out whether more concurrent tests complete more tests per second. - Raise, - - /// Lowered to find out whether fewer concurrent tests complete as many tests per second. - Lower, - - /// The last raise did not bring enough throughput, so it was undone. - RaiseReverted, - - /// Tests started failing after the last raise, so it was undone, and the limit stays at or below this. - RaiseRevertedForFailures, - - /// The last lowering cost throughput, so it was undone. - LowerReverted, - - /// The number of tests the session runs at once changed while a trial was being measured, so the trial was dropped. - TrialAbandoned, -} - -internal readonly record struct AdaptiveLimiterDecision(int Limit, AdaptiveLimiterChange Change); - -/// -/// Decides the limit of one adaptive [ParallelLimiter] from a stream of -/// s. It holds no clock and does no I/O, so the same samples -/// always produce the same decisions. -/// -/// -/// -/// What the limiter protects (a database's connections, for example) cannot be observed, so -/// the only evidence is the tests themselves. Every change is a trial, judged the way -/// judges the session-wide limit: the policy measures -/// completed tests per second, changes the limit, measures again, and keeps a raise only when -/// throughput rose by a fair share of it, and a lowering only when throughput fell by less -/// than a fair share of it. -/// -/// -/// A raise is tried first. When it is rejected, the tests are held back by something other -/// than the limit, and a lowering is tried from the same limit: fewer tests that complete as -/// many per second each spend less time waiting inside their bodies. -/// -/// -/// A raise that overloads the protected resource shows up as failing tests, not as lower -/// throughput. When tests fail during a raise on trial, and none failed in the measurements -/// before it, the raise is undone and the limit is never raised past that point again. -/// -/// -internal sealed class AdaptiveLimiterPolicy -{ - // The same step sizes and verdicts as AdaptiveParallelismPolicy, so both limits behave alike. - internal const double IncreaseFactor = AdaptiveParallelismPolicy.IncreaseFactor; - internal const double DecreaseFactor = AdaptiveParallelismPolicy.CpuDecreaseFactor; - internal const double MinimumGainShare = AdaptiveParallelismPolicy.MinimumGainShare; - internal const double SteadyThroughputTolerance = AdaptiveParallelismPolicy.SteadyThroughputTolerance; - internal const int MinimumWindowCompletions = AdaptiveParallelismPolicy.MinimumWindowCompletions; - - internal static readonly TimeSpan MinimumWindow = AdaptiveParallelismPolicy.MinimumWindow; - internal static readonly TimeSpan MaximumWindow = AdaptiveParallelismPolicy.MaximumWindow; - internal static readonly TimeSpan MaximumSettle = AdaptiveParallelismPolicy.MaximumSettle; - - // After a rejected trial, how long before the next one in the same direction. Doubles each time. - internal static readonly TimeSpan InitialHold = TimeSpan.FromSeconds(10); - internal static readonly TimeSpan MaximumHold = AdaptiveParallelismPolicy.MaximumHold; - - private readonly int _minimum; - - // Comes down for good when a raise is followed by failing tests. - private int _maximum; - - private int _limit; - private TimeSpan _clock; - - private bool _settling; - private TimeSpan _settleRemaining; - - private AdaptiveLimiterChange _trial; - private int _limitBeforeTrial; - private double _throughputBeforeTrial; - private bool _failuresBeforeTrial; - private long _failuresDuringTrial; - - // Throughput of the latest window and the limit it was measured at (0 when it could not - // be compared with another), and whether a test failed in it. - private double _lastThroughput; - private int _lastLimit; - private bool _lastWindowHadFailures; - - // The mean of the latest two windows when they agree, the limit both were measured at - // (0 when they do not), and whether a test failed in either. - private double _steadyThroughput; - private int _steadyLimit; - private bool _steadyHadFailures; - - // The limit at which the last raise was rejected: the one a lowering may be tried from. - private int _raiseRejectedAt; - - // Throughput before the first of a run of lowerings, and the limit it was measured at. - // Every lowering is judged against it for as long as the limit stays below that one, so - // several steps down cannot each give a little throughput away. It lapses once the limit - // is back where the run began. - private double _throughputBeforeLowering; - private int _limitBeforeLowering; - - private TimeSpan _raiseHold = InitialHold; - private TimeSpan _raiseHoldUntil; - private TimeSpan _lowerHold = InitialHold; - private TimeSpan _lowerHoldUntil; - - // The limit divided by throughput: the average time a test spends inside the limiter. - private TimeSpan _averageTimeInside = MinimumWindow; - - private TimeSpan _windowElapsed; - private long _windowFinished; - private long _windowFailed; - private int _windowSamples; - private int _windowLimitReachedSamples; - - public AdaptiveLimiterPolicy(int initial, int minimum, int maximum) - { - _limit = initial; - _minimum = minimum; - _maximum = maximum; - } - - public int Limit => _limit; - - /// - /// Whether a change is being measured, so no other limit should change meanwhile. - /// - public bool IsBusy => _trial != AdaptiveLimiterChange.None || _settling; - - /// What happened since the previous sample. - /// - /// Whether a trial may start now. False while another limit is being tried: two trials at - /// once would each change the throughput the other is measured by. - /// - public AdaptiveLimiterDecision OnSample(AdaptiveLimiterSample sample, bool mayStartTrial) - { - _clock += sample.Elapsed; - - if (_trial == AdaptiveLimiterChange.Raise) - { - _failuresDuringTrial += sample.FailedTests; - - // Not held until the verdict: every test that fails meanwhile is a test the raise broke. - if (_failuresDuringTrial > 0 && !_failuresBeforeTrial) - { - _trial = AdaptiveLimiterChange.None; - _maximum = _limitBeforeTrial; - return ChangeLimit(_limitBeforeTrial, AdaptiveLimiterChange.RaiseRevertedForFailures); - } - } - - if (_settling) - { - _settleRemaining -= sample.Elapsed; - if (_settleRemaining <= TimeSpan.Zero) - { - _settling = false; - ResetWindow(); - } - - return NoChange(); - } - - _windowElapsed += sample.Elapsed; - _windowFinished += sample.FinishedTests; - _windowFailed += sample.FailedTests; - _windowSamples++; - - if (sample.LimitReached) - { - _windowLimitReachedSamples++; - } - - // Long enough to average over at least two tests per place in the limiter. Tests too - // long for that close the window at the maximum instead. - var windowComplete = _windowElapsed >= MaximumWindow - || (_windowElapsed >= MinimumWindow && _windowFinished >= Math.Max(MinimumWindowCompletions, _limit * 2L)); - - if (!windowComplete) - { - return NoChange(); - } - - var throughput = _windowFinished / _windowElapsed.TotalSeconds; - var hadFailures = _windowFailed > 0; - - // Throughput is comparable between windows only when the limit, not a shortage of - // tests ready to run, decided how many ran. - var measurable = _windowFinished >= MinimumWindowCompletions - && _windowLimitReachedSamples * 2 >= _windowSamples; - - ResetWindow(); - - if (measurable) - { - _averageTimeInside = TimeSpan.FromSeconds(_limit / throughput); - } - - if (_trial != AdaptiveLimiterChange.None) - { - var raised = _trial == AdaptiveLimiterChange.Raise; - _trial = AdaptiveLimiterChange.None; - - // A raise must bring a fair share of itself. One or more steps down may cost a - // fair share of one step in total, measured from before the first of them. - var requiredThroughput = raised - ? _throughputBeforeTrial * (1 + ((double) _limit / _limitBeforeTrial - 1) * MinimumGainShare) - : _throughputBeforeLowering * (1 - (1 - DecreaseFactor) * MinimumGainShare); - - if (!measurable || throughput < requiredThroughput) - { - if (raised) - { - _raiseRejectedAt = _limitBeforeTrial; - _raiseHoldUntil = _clock + _raiseHold; - _raiseHold = Double(_raiseHold); - return ChangeLimit(_limitBeforeTrial, AdaptiveLimiterChange.RaiseReverted); - } - - _lowerHoldUntil = _clock + _lowerHold; - _lowerHold = Double(_lowerHold); - EndLoweringRunAt(_limitBeforeTrial); - return ChangeLimit(_limitBeforeTrial, AdaptiveLimiterChange.LowerReverted); - } - - if (raised) - { - _raiseHold = InitialHold; - _raiseRejectedAt = 0; - EndLoweringRunAt(_limit); - } - else - { - // Fewer tests did as well, so trying more again straight away would only undo - // it, and a further step down may do as well again. - _lowerHold = InitialHold; - _raiseRejectedAt = _limit; - _raiseHoldUntil = _clock + _raiseHold; - } - } - - var steady = measurable - && _lastLimit == _limit - && Math.Abs(throughput - _lastThroughput) <= Math.Max(throughput, _lastThroughput) * SteadyThroughputTolerance; - - _steadyThroughput = steady ? (throughput + _lastThroughput) / 2 : 0; - _steadyLimit = steady ? _limit : 0; - _steadyHadFailures = hadFailures || _lastWindowHadFailures; - _lastThroughput = throughput; - _lastLimit = measurable ? _limit : 0; - _lastWindowHadFailures = hadFailures; - - if (!mayStartTrial || _steadyLimit != _limit) - { - return NoChange(); - } - - if (_limit < _maximum && _clock >= _raiseHoldUntil) - { - var higher = Math.Min(_maximum, Math.Max(_limit + 1, (int) Math.Ceiling(_limit * IncreaseFactor))); - return StartTrial(higher, AdaptiveLimiterChange.Raise); - } - - // At the highest limit nothing says that the limit is not what holds the tests back, - // so a lowering is tried only from a limit that a raise was rejected at. - if (_limit > _minimum && _raiseRejectedAt == _limit && _clock >= _lowerHoldUntil) - { - var lower = Math.Max(_minimum, Math.Min(_limit - 1, (int) (_limit * DecreaseFactor))); - return StartTrial(lower, AdaptiveLimiterChange.Lower); - } - - return NoChange(); - } - - /// - /// Drops the measurements in progress because something else has disturbed them (the - /// number of tests the session runs at once changed, for example), and puts the limit of - /// a trial back. Nothing was learned about throughput, so the next trial does not wait longer. - /// - /// Tests that failed since the previous sample. A failure during a raise still counts against it. - public AdaptiveLimiterDecision Abandon(long failedTests = 0) - { - ResetWindow(); - _lastLimit = 0; - _steadyLimit = 0; - - // Measured under the session limit that has just changed. The next lowering starts - // from a fresh measurement. - _throughputBeforeLowering = 0; - - if (_trial == AdaptiveLimiterChange.None) - { - return NoChange(); - } - - var failedAfterRaise = _trial == AdaptiveLimiterChange.Raise - && _failuresDuringTrial + failedTests > 0 - && !_failuresBeforeTrial; - - _trial = AdaptiveLimiterChange.None; - - if (failedAfterRaise) - { - _maximum = _limitBeforeTrial; - return ChangeLimit(_limitBeforeTrial, AdaptiveLimiterChange.RaiseRevertedForFailures); - } - - return ChangeLimit(_limitBeforeTrial, AdaptiveLimiterChange.TrialAbandoned); - } - - // The run of lowerings is over once the limit is back at, or above, where it began. - private void EndLoweringRunAt(int limit) - { - if (limit >= _limitBeforeLowering) - { - _throughputBeforeLowering = 0; - } - } - - private AdaptiveLimiterDecision StartTrial(int limit, AdaptiveLimiterChange change) - { - if (change == AdaptiveLimiterChange.Lower && _throughputBeforeLowering <= 0) - { - _throughputBeforeLowering = _steadyThroughput; - _limitBeforeLowering = _limit; - } - - _trial = change; - _limitBeforeTrial = _limit; - _throughputBeforeTrial = _steadyThroughput; - _failuresBeforeTrial = _steadyHadFailures; - _failuresDuringTrial = 0; - return ChangeLimit(limit, change); - } - - private AdaptiveLimiterDecision ChangeLimit(int limit, AdaptiveLimiterChange change) - { - _limit = limit; - _lastLimit = 0; - _steadyLimit = 0; - - // Tests admitted under the old limit are still running. Throughput reflects the new - // limit only once about one test duration has passed. - _settling = true; - _settleRemaining = TimeSpan.FromTicks(Math.Min(Math.Max(_averageTimeInside.Ticks, MinimumWindow.Ticks), MaximumSettle.Ticks)); - return new AdaptiveLimiterDecision(limit, change); - } - - private AdaptiveLimiterDecision NoChange() => new(_limit, AdaptiveLimiterChange.None); - - private static TimeSpan Double(TimeSpan hold) => TimeSpan.FromTicks(Math.Min(hold.Ticks * 2, MaximumHold.Ticks)); - - private void ResetWindow() - { - _windowElapsed = TimeSpan.Zero; - _windowFinished = 0; - _windowFailed = 0; - _windowSamples = 0; - _windowLimitReachedSamples = 0; - } -} diff --git a/src/TUnit.Engine/Scheduling/AdaptiveLimiterTrials.cs b/src/TUnit.Engine/Scheduling/AdaptiveLimiterTrials.cs index 274dfe05897..7b889814d80 100644 --- a/src/TUnit.Engine/Scheduling/AdaptiveLimiterTrials.cs +++ b/src/TUnit.Engine/Scheduling/AdaptiveLimiterTrials.cs @@ -1,17 +1,49 @@ +#if NET using TUnit.Core; using TUnit.Core.Logging; +using TUnit.Engine.Logging; namespace TUnit.Engine.Scheduling; /// -/// Runs an for each adaptive [ParallelLimiter] and applies -/// what it decides. Only one limit is on trial at a time, and none while the session-wide -/// limit is: two trials at once would each change the throughput the other is measured by. +/// Runs an for each [ParallelLimiter] whose limit can +/// change and applies what it decides. Only one limit is on trial at a time, and none while +/// the session-wide limit is: two trials at once would each change the throughput the other +/// is measured by. /// +/// +/// +/// A limiter is decided by the same policy as the session-wide limit, from the same reading +/// of the machine, with its own tests as the measure of throughput. So it is raised only for +/// a measured gain while the machine has headroom, and comes down only for saturated CPUs +/// that its own tests cause. +/// +/// +/// A limiter that is not an takes +/// part with its declared limit as the highest it can go: the limit may be a hard cap on +/// something TUnit cannot see, so it is never exceeded. +/// +/// internal sealed class AdaptiveLimiterTrials { + // Saturated CPUs are a limiter's to relieve when at least this share of the tests that + // are running are inside it. Below that, most of the load comes in through the + // session-wide limit, and that one is lowered instead. + internal const double PressureOwnerShare = 0.6; + + // A limiter keeps the pressure for this many samples after it last qualified. A limiter + // of short tests is not full at every sample, between one test ending and the next + // starting, and each side counts saturated samples in a row: ownership that came and + // went with every sample would leave neither with enough of them to act. + internal const int PressureOwnerHoldSamples = 4; + private readonly ParallelLimitLockProvider _lockProvider; private readonly ILogger _logger; + private readonly int _processorCount; + + // Shared with the session-wide limit's policy when there is one, which then advances it. + private readonly AdaptiveExplorationBudget _explorationBudget; + private readonly bool _ownsExplorationBudget; // Guards everything below, so no limit changes after Stop has reported the summaries. private readonly Lock _lock = new(); @@ -21,10 +53,28 @@ internal sealed class AdaptiveLimiterTrials // The limiter that gets the first chance to start a trial, so they take turns. private int _nextToTry; - public AdaptiveLimiterTrials(ParallelLimitLockProvider lockProvider, ILogger logger) + // The limiter that last owned saturated CPUs, and for how many samples it has not qualified. + private Limiter? _lastPressureOwner; + private int _samplesSincePressureOwner; + + // How long limits have been followed. A limiter whose first test arrives after the + // start of the run does not wait out the run's startup again. + private TimeSpan _elapsed; + + /// Where the limiters' locks are found. + /// Where changes and summaries are written. + /// The number of processors this process may use. The machine's unless given. + /// + /// The allowance for trials that are put back, shared with the session-wide limit, whose + /// owner advances it once per sample. Without one the limiters share their own. + /// + public AdaptiveLimiterTrials(ParallelLimitLockProvider lockProvider, ILogger logger, int? processorCount = null, AdaptiveExplorationBudget? explorationBudget = null) { _lockProvider = lockProvider; _logger = logger; + _processorCount = processorCount ?? Environment.ProcessorCount; + _explorationBudget = explorationBudget ?? new AdaptiveExplorationBudget(); + _ownsExplorationBudget = explorationBudget is null; } /// @@ -62,13 +112,173 @@ internal int BusyLimiters } } - /// Time since the previous call. + /// + /// The limiter that most of the running tests are inside and whose limit can still come + /// down, or null when there is none. Saturated CPUs are that limiter's to + /// relieve: lowering the session-wide limit would change nothing while its tests are the + /// ones that run. + /// + /// + /// A limiter whose policy would not lower it now is never the owner, however many tests + /// are inside it: nothing would relieve the CPUs then, because the session-wide limit, + /// which could, is told the pressure is another limit's. That covers a limit at its + /// lowest, and one that is waiting after a lowering that was put back or has no + /// measurement to judge a lowering against yet. + /// A limiter that is lowering already stays the owner until its verdict. While another + /// limiter is on trial, none is named, because only one limit changes at a time. + /// The same goes for a limiter that is not full. + /// With a limit of 16 it holds 8 tests only because the session-wide limit admits 8: a + /// cut to 12 would stop none of them, and the session-wide limit is the one to lower. + /// + /// The number of tests that hold a slot of the session-wide limit. + /// + /// Whether a change of the session-wide limit is being measured. No limiter starts a + /// lowering meanwhile, so none is named: an owner that cannot act would only make the + /// session-wide limit forget the saturation it has seen. + /// + public ParallelLimitLock? FindPressureOwner(int runningTests, bool sessionLimitBusy = false) + { + lock (_lock) + { + AddNewLimiters(); + + if (sessionLimitBusy) + { + _lastPressureOwner = null; + return null; + } + + // Only one limit is on trial at a time, so while one limiter is busy no other + // can start a lowering. Naming another as the owner would leave the pressure + // with a limit that cannot act, and take it from the session-wide limit, which can. + Limiter? busy = null; + + foreach (var limiter in _limiters) + { + if (limiter.Policy.IsBusy) + { + busy = limiter; + break; + } + } + + Limiter? owner = null; + var most = 0; + + foreach (var limiter in _limiters) + { + var inside = limiter.Lock.HeldPlaces; + + // Full, or one short of it: a test has just left and the next has not entered. + if (inside > most + && inside >= Math.Max(1, runningTests) * PressureOwnerShare + && inside >= Math.Max(1, limiter.Lock.CurrentLimit - 1) + && CouldLowerNow(limiter, busy)) + { + owner = limiter; + most = inside; + } + } + + if (owner is not null) + { + _lastPressureOwner = owner; + _samplesSincePressureOwner = 0; + return owner.Lock; + } + + // The last owner keeps the pressure for a few samples in which it is not full + // enough, as long as it could still act on it. + if (_lastPressureOwner is { } last + && ++_samplesSincePressureOwner <= PressureOwnerHoldSamples + && CouldLowerNow(last, busy)) + { + return last.Lock; + } + + _lastPressureOwner = null; + return null; + } + } + + // Whether the limiter's policy would start a lowering for saturated CPUs with its next + // samples, or is measuring one. Called with _lock held. + private static bool CouldLowerNow(Limiter limiter, Limiter? busy) + => (busy is null || ReferenceEquals(busy, limiter)) + && (limiter.Policy.IsReadyToLowerForCpu || limiter.Policy.IsLoweringForCpu); + + /// + /// Whether tests are queued behind a limiter that has places free. A lane behind a + /// limiter of 16 under a session-wide limit of 8 has 8 workers: its queued tests wait + /// for the session-wide limit, and without this nothing would ever ask for a raise. + /// + /// + /// A limiter that is full is left out. Its queued tests wait for the limiter, and a + /// raise of the session-wide limit would start none of them: put back, it would only + /// use up the allowance the limiter's own raise needs. + /// + public bool HasQueuedTestsWithFreePlaces() + { + lock (_lock) + { + AddNewLimiters(); + + foreach (var limiter in _limiters) + { + if (limiter.Lock.Backlog > 0 && !limiter.Lock.IsFull) + { + return true; + } + } + + return false; + } + } + + /// + /// Whether tests are waiting for a limiter right now, and for which one: the one with + /// the most tests held back, or null when none holds any back. + /// + public ParallelLimitLock? FindBindingLimiter() + { + lock (_lock) + { + AddNewLimiters(); + + ParallelLimitLock? binding = null; + var most = 0; + + foreach (var limiter in _limiters) + { + if (!limiter.Lock.HasUnmetDemand) + { + continue; + } + + var heldBack = limiter.Lock.Backlog + limiter.Lock.Waiting; + + if (heldBack > most) + { + binding = limiter.Lock; + most = heldBack; + } + } + + return binding; + } + } + + /// + /// The latest reading of the machine. Its test counts and flags are replaced with each + /// limiter's own. + /// /// Whether a change of the session-wide limit is being measured. /// /// Whether the number of tests the session runs at once has just changed, for any reason: /// adaptive parallelism, or another process joining or leaving a shared budget. /// - public void Update(TimeSpan elapsed, bool sessionLimitBusy, bool sessionLimitChanged) + /// What returned for this sample. + public void Update(AdaptiveSample machine, bool sessionLimitBusy, bool sessionLimitChanged, ParallelLimitLock? pressureOwner = null) { lock (_lock) { @@ -79,6 +289,13 @@ public void Update(TimeSpan elapsed, bool sessionLimitBusy, bool sessionLimitCha AddNewLimiters(); + _elapsed += machine.Elapsed; + + if (_ownsExplorationBudget) + { + _explorationBudget.Advance(machine.Elapsed); + } + if (_limiters.Count == 0) { return; @@ -92,9 +309,13 @@ public void Update(TimeSpan elapsed, bool sessionLimitBusy, bool sessionLimitCha foreach (var limiter in _limiters) { var (abandonedFinished, abandonedFailed) = limiter.Lock.ReadCounts(); - Apply(limiter, limiter.Policy.Abandon(abandonedFailed - limiter.PreviousFailed)); + Apply(limiter, limiter.Policy.Abandon(machine.Elapsed, abandonedFailed - limiter.PreviousFailed)); limiter.PreviousFinished = abandonedFinished; limiter.PreviousFailed = abandonedFailed; + + // The measurement is dropped, the wait is not: tests that waited for the + // limiter in this sample waited whatever the session-wide limit did. + limiter.Add(machine.Elapsed, limiter.Lock.HasUnmetDemand, machine.CpuUtilization); } return; @@ -108,15 +329,25 @@ public void Update(TimeSpan elapsed, bool sessionLimitBusy, bool sessionLimitCha var index = (first + i) % _limiters.Count; var limiter = _limiters[index]; var wasBusy = limiter.Policy.IsBusy; + var hasUnmetDemand = limiter.Lock.HasUnmetDemand; var (finished, failed) = limiter.Lock.ReadCounts(); - var decision = limiter.Policy.OnSample( - new AdaptiveLimiterSample(elapsed, finished - limiter.PreviousFinished, failed - limiter.PreviousFailed, limiter.Lock.IsFull), - mayStartTrial: !sessionLimitBusy && !anyBusy); + var decision = limiter.Policy.OnSample(machine with + { + CompletedTests = finished - limiter.PreviousFinished, + FailedTests = failed - limiter.PreviousFailed, + LimitReached = hasUnmetDemand, + + // Its own trial in progress is not blocked: only another limit's is. + TrialsBlocked = sessionLimitBusy || (anyBusy && !wasBusy), + PressureElsewhere = !ReferenceEquals(pressureOwner, limiter.Lock), + OverLimit = limiter.Lock.HeldPlaces > limiter.Lock.CurrentLimit, + }); limiter.PreviousFinished = finished; limiter.PreviousFailed = failed; + limiter.Add(machine.Elapsed, hasUnmetDemand, machine.CpuUtilization); Apply(limiter, decision); @@ -154,41 +385,83 @@ public void Stop(bool resetLimits = false) limiter.Lock.SetLimit(limiter.Lock.Initial); } - // Information, not Debug: a failure that depends on how many tests ran at - // once can only be understood from a log that says how many did. - _logger.LogInformation(FormatSummary( - limiter.Lock.LimitType.Name, - limiter.Lock.CurrentLimit, - limiter.Lowest, - limiter.Highest, - limiter.Changes, - limiter.ChangesPutBack)); + var summary = limiter.ToSummary(); + + // A limiter that never moved and that no test waited for has nothing to say. + // Information for the others, not Debug: a failure that depends on how many + // tests ran at once can only be understood from a log that says how many did. + if (summary.IsWorthReporting(_elapsed)) + { + _logger.LogSessionMessage(FormatSummary(summary)); + } + 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)); + } } } } - internal static string FormatSummary(string limiterName, int currentLimit, int lowestLimit, int highestLimit, int changes, int changesPutBack) + internal static string FormatSummary(AdaptiveLimiterSummary summary) { - if (changes == 0) + var text = new System.Text.StringBuilder(); + text.Append("[ParallelLimiter] ").Append(summary.Name).Append(": the limit "); + AdaptiveParallelismSummary.AppendLimit(text, summary.StartLimit, summary.CurrentLimit, summary.LowestLimit, summary.HighestLimit, summary.Changes, summary.ChangesPutBack); + + if (summary.Waited <= TimeSpan.Zero) { - return $"Adaptive [ParallelLimiter] {limiterName}: the limit stayed at {currentLimit}"; + return text.ToString(); } - var putBack = changesPutBack == 0 - ? "" - : $" ({changesPutBack} put back because {(changesPutBack == 1 ? "it" : "they")} did not help)"; + text.Append(" Tests waited for it for ").Append(AdaptiveParallelismSummary.FormatDuration(summary.Waited)); + + if (summary.CanBeRaised) + { + if (summary.MostCommonRaiseBlocker != AdaptiveRaiseBlocker.None) + { + text.Append("; it was not raised mostly because ").Append(AdaptiveParallelismSummary.Describe(summary.MostCommonRaiseBlocker)); + } + + text.Append('.'); + } + else + { + // 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. "); + + // 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(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."); + } - return $"Adaptive [ParallelLimiter] {limiterName}: the limit ranged from {lowestLimit} to {highestLimit} over {changes} {(changes == 1 ? "change" : "changes")}{putBack} and ended at {currentLimit}"; + return text.ToString(); } - // Limiters appear as their first test reaches them. Called with _lock held. + // A limiter appears when its lock is created: when the batch that holds its first test + // is split into lanes, which can be well before that test starts, or when a test reaches + // it by another path. The startup hold below is counted from the start of the run, not + // from here or from the limiter's first test. Called with _lock held. private void AddNewLimiters() { var locks = _lockProvider.AdaptiveLocks; for (var i = _limiters.Count; i < locks.Length; i++) { - _limiters.Add(new Limiter(locks[i])); + // The hold is for the start of the run, when compilation and fixtures saturate + // the CPUs whatever the limit. A limiter that appears later has only what is + // left of it to wait. + var startupLowerHold = AdaptiveParallelismPolicy.StartupLowerHold - _elapsed; + + _limiters.Add(new Limiter(locks[i], _processorCount, _explorationBudget, startupLowerHold > TimeSpan.Zero ? startupLowerHold : TimeSpan.Zero)); } } @@ -207,9 +480,9 @@ private bool IsAnyBusy() } // Called with _lock held. - private void Apply(Limiter limiter, AdaptiveLimiterDecision decision) + private void Apply(Limiter limiter, AdaptiveDecision decision) { - if (decision.Change == AdaptiveLimiterChange.None) + if (decision.Change == AdaptiveLimitChange.None) { return; } @@ -226,39 +499,130 @@ private void Apply(Limiter limiter, AdaptiveLimiterDecision decision) limiter.Highest = Math.Max(limiter.Highest, limit); limiter.Changes++; - if (decision.Change is AdaptiveLimiterChange.RaiseReverted - or AdaptiveLimiterChange.RaiseRevertedForFailures - or AdaptiveLimiterChange.LowerReverted) + if (AdaptiveParallelismSummary.IsPutBack(decision.Change)) { limiter.ChangesPutBack++; } if (_logger.IsEnabled(LogLevel.Debug)) { - _logger.LogDebug($"Adaptive [ParallelLimiter] {limiter.Lock.LimitType.Name}: limit {previous} -> {limit} ({Describe(decision.Change)})"); + _logger.LogDebug($"[ParallelLimiter] {limiter.Lock.LimitType.Name}: limit {previous} -> {limit} ({AdaptiveParallelismSummary.Describe(decision.Change)})"); } } - private static string Describe(AdaptiveLimiterChange change) => change switch - { - AdaptiveLimiterChange.Raise => "trying more tests at once", - AdaptiveLimiterChange.Lower => "checking that fewer tests at once cost no throughput", - AdaptiveLimiterChange.RaiseReverted => "the last raise did not improve throughput", - AdaptiveLimiterChange.RaiseRevertedForFailures => "tests failed after the last raise; the limit will not go higher again in this run", - AdaptiveLimiterChange.LowerReverted => "the lower limit cost throughput", - AdaptiveLimiterChange.TrialAbandoned => "the number of tests the session runs at once changed during the measurement", - _ => change.ToString(), - }; - - private sealed class Limiter(ParallelLimitLock parallelLimitLock) + private sealed class Limiter(ParallelLimitLock parallelLimitLock, int processorCount, AdaptiveExplorationBudget explorationBudget, TimeSpan startupLowerHold) { + private readonly TimeSpan[] _timeNotRaising = new TimeSpan[AdaptiveParallelismSummary.RaiseBlockerCount]; + private TimeSpan _waited; + private double _cpuSecondsWhileWaiting; + public ParallelLimitLock Lock { get; } = parallelLimitLock; - public AdaptiveLimiterPolicy Policy { get; } = new(parallelLimitLock.Initial, parallelLimitLock.Minimum, parallelLimitLock.Maximum); + + public AdaptiveParallelismPolicy Policy { get; } = new( + new ParallelismLimits(parallelLimitLock.Initial, parallelLimitLock.Minimum, parallelLimitLock.Maximum), + processorCount, + relievesMemoryPressure: false, + startupLowerHold, + explorationBudget, + oneTestPerProcessorIsEnough: false, + judgesLoweringByCpuTime: false); + public long PreviousFinished { get; set; } public long PreviousFailed { get; set; } public int Lowest { get; set; } = parallelLimitLock.Initial; public int Highest { get; set; } = parallelLimitLock.Initial; public int Changes { get; set; } public int ChangesPutBack { get; set; } + + public void Add(TimeSpan elapsed, bool hasUnmetDemand, double cpuUtilization) + { + if (!hasUnmetDemand) + { + return; + } + + // Only while tests wait for the limit: the rest of the time it holds nothing back, + // and whatever kept it from being raised then did not matter. + _waited += elapsed; + _cpuSecondsWhileWaiting += cpuUtilization * elapsed.TotalSeconds; + + // The policy's reason is from its last whole window. "Fewer tests were ready" + // cannot explain a sample in which tests are waiting, so it is not charged with it. + if (Policy.RaiseBlocker != AdaptiveRaiseBlocker.LimitNotReached) + { + _timeNotRaising[(int) Policy.RaiseBlocker] += elapsed; + } + } + + public AdaptiveLimiterSummary ToSummary() => new( + Lock.LimitType.Name, + Lock.Initial, + Lock.CurrentLimit, + Lowest, + Highest, + Changes, + ChangesPutBack, + CanBeRaised: Lock.Maximum > Lock.Initial, + DeclaredAdaptive: Lock.IsDeclaredAdaptive, + _waited, + AdaptiveParallelismSummary.MostCommon(_timeNotRaising), + _waited > TimeSpan.Zero ? _cpuSecondsWhileWaiting / _waited.TotalSeconds : 0); + } +} + +/// +/// Where the limit of one [ParallelLimiter] went over the run, for its summary line. +/// +/// The limiter's type name. +/// The limit the run started at. +/// The limit the run ended at. +/// The lowest limit of the run. +/// The highest limit of the run. +/// How many times the limit changed. +/// How many of those changes undid one that did not help. +/// Whether the limit may go above where it started: false for a limiter with a declared, fixed limit, and for an adaptive one whose highest limit is where it starts. +/// Whether the limiter is an , so its own bounds are what to change. +/// How long tests waited for the limiter while it was full. +/// The reason that kept the limit from being raised for the longest of that time. +/// Average share of the machine's CPU capacity in use over that time, 0 to 1. +internal readonly record struct AdaptiveLimiterSummary( + string Name, + int StartLimit, + int CurrentLimit, + int LowestLimit, + int HighestLimit, + int Changes, + int ChangesPutBack, + bool CanBeRaised, + bool DeclaredAdaptive, + TimeSpan Waited, + AdaptiveRaiseBlocker MostCommonRaiseBlocker = AdaptiveRaiseBlocker.None, + double CpuUtilizationWhileWaiting = 0) +{ + /// + /// Whether the limiter gets a line in the output of every run. + /// + /// How long limits were followed for. + /// + /// A limit that moved always does. One that can be raised does when tests waited for it: + /// a second is a couple of samples, and shorter than that is the limiter doing its job. + /// A declared limit that stayed where it was is often a deliberate cap, such as one + /// database connection, and its owner can do nothing with a line about it on every + /// run. It is reported only when the wait is a share of the run worth acting on. + /// + public bool IsWorthReporting(TimeSpan runTime) + { + if (Changes > 0) + { + return true; + } + + if (Waited < TimeSpan.FromSeconds(1)) + { + return false; + } + + return CanBeRaised || Waited.Ticks >= runTime.Ticks * AdaptiveParallelismSummary.NotableShare; } } +#endif diff --git a/src/TUnit.Engine/Scheduling/AdaptiveParallelismController.cs b/src/TUnit.Engine/Scheduling/AdaptiveParallelismController.cs index 257a9bc8654..269df258534 100644 --- a/src/TUnit.Engine/Scheduling/AdaptiveParallelismController.cs +++ b/src/TUnit.Engine/Scheduling/AdaptiveParallelismController.cs @@ -1,5 +1,6 @@ using TUnit.Core; using TUnit.Core.Logging; +using TUnit.Engine.Logging; #if NET using System.Diagnostics; using System.Runtime.Versioning; @@ -8,15 +9,32 @@ namespace TUnit.Engine.Scheduling; /// -/// Resizes the parallel test limit while tests run. It samples machine load and test progress -/// on its own thread and applies what decides to the -/// . +/// Resizes the parallel test limit, and the limit of each [ParallelLimiter] that can change, +/// while tests run. It samples machine load and test progress on its own thread and applies +/// what an for each limit decides. /// +/// +/// One loop serves every limit, so each is decided from the same reading of the machine and +/// only one of them is on trial at a time. Before a limit changes, the loop finds out which +/// limit tests are waiting for: a limit that nothing waits for is left alone, and saturated +/// CPUs lower the limit that admits the tests which cause them. +/// internal sealed class AdaptiveParallelismController : IDisposable { #if NET private static readonly TimeSpan SampleInterval = TimeSpan.FromMilliseconds(250); + // Nothing is measured for this long. The first seconds of a run are the runtime compiling + // the tests and fixtures coming up, which says nothing about the limit, and a test project + // that finishes within them pays for a parked thread and no more: reading the machine for + // the first time opens files and loads code while the tests need the CPUs (#7915). + internal static readonly TimeSpan WarmUp = TimeSpan.FromSeconds(2); + + // Once the CPU time of child processes has been wanted, it is read for this long after. + // A lowering is judged by the CPU time this process and its child processes use, so the + // figure must not come and go within the measurement. + private static readonly TimeSpan ChildProcessSamplingHold = TimeSpan.FromSeconds(60); + // The CPU time of child processes is read only from here up, and only while this process // alone uses too little to count as the cause: the one case where it changes the decision. // Reading it walks the process tree, which is too much work for every sample of every @@ -33,12 +51,15 @@ internal sealed class AdaptiveParallelismController : IDisposable private readonly ILogger _logger; private Thread? _thread; - // The limits of adaptive [ParallelLimiter]s, when the session has a place to find them. + // The limits of [ParallelLimiter]s that can change, when the session has a place to find them. private readonly AdaptiveLimiterTrials? _limiterTrials; private readonly ParallelLimitLockProvider? _lockProvider; - // 1 once the thread that only adjusts limiters has been started. - private int _limiterThreadStarted; + // One allowance for trials that are put back, whichever limit they were of. + private readonly AdaptiveExplorationBudget _explorationBudget = new(); + + // 1 once the thread has been started. + private int _threadStarted; // Timestamp of the queued probe work item, or 0 once a pool thread has run it. private long _probeQueuedAt; @@ -46,6 +67,7 @@ internal sealed class AdaptiveParallelismController : IDisposable // Guards the fields below, so no limit change lands after Dispose has reported the summary. private readonly Lock _stateLock = new(); + private readonly int _startLimit; private int _lowestLimit; private int _highestLimit; private int _changes; @@ -56,6 +78,7 @@ internal sealed class AdaptiveParallelismController : IDisposable // How long the run spent at each limit, for the summary. private readonly SortedDictionary _timeAtLimit = []; private long _limitSince = Stopwatch.GetTimestamp(); + private readonly long _startedAt = Stopwatch.GetTimestamp(); // What the samples added up to, for the summary. private readonly AdaptiveRunTotals _totals = new(); @@ -65,8 +88,9 @@ private AdaptiveParallelismController(MaxParallelismLimiter limiter, ILogger log _limiter = limiter; _logger = logger; _lockProvider = lockProvider; - _limiterTrials = lockProvider is null ? null : new AdaptiveLimiterTrials(lockProvider, logger); - _lowestLimit = _highestLimit = limiter.CurrentLimit; + _limiterTrials = lockProvider is null ? null : new AdaptiveLimiterTrials(lockProvider, logger, explorationBudget: _explorationBudget); + // The limit as it is now: this process's part, when it shares a budget. + _startLimit = _lowestLimit = _highestLimit = limiter.CurrentLimit; } #endif @@ -118,16 +142,18 @@ public static bool IsSupported if (adjustsSessionLimit) { - controller.StartThread(controller.Run); + // From here the scheduler records what holds tests back that no limit can change. + limiter.Activity.IsObserved = true; + controller.StartThread(); } else { // Most suites have no adaptive limiter, so the thread starts with the first one. - lockProvider!.AdaptiveLockCreated = controller.StartLimiterThread; + lockProvider!.AdaptiveLockCreated = controller.StartThread; if (lockProvider.AdaptiveLocks.Length > 0) { - controller.StartLimiterThread(); + controller.StartThread(); } } @@ -143,9 +169,14 @@ public static bool IsSupported [SupportedOSPlatform("windows")] [SupportedOSPlatform("linux")] [SupportedOSPlatform("macos")] - private void StartThread(ThreadStart run) + private void StartThread() { - var thread = new Thread(run) + if (Interlocked.Exchange(ref _threadStarted, 1) != 0) + { + return; + } + + var thread = new Thread(Run) { IsBackground = true, Name = "TUnit adaptive parallelism controller", @@ -157,71 +188,41 @@ private void StartThread(ThreadStart run) [SupportedOSPlatform("windows")] [SupportedOSPlatform("linux")] [SupportedOSPlatform("macos")] - private void StartLimiterThread() + private void Run() { - if (Interlocked.Exchange(ref _limiterThreadStarted, 1) == 0) - { - StartThread(RunLimitersOnly); - } - } + var limits = _limiter.Limits; - /// - /// The loop for a session whose own limit is fixed: only the limiters are adjusted, which - /// takes no reading of the machine. - /// - [SupportedOSPlatform("windows")] - [SupportedOSPlatform("linux")] - [SupportedOSPlatform("macos")] - private void RunLimitersOnly() - { try { - var previousTimestamp = Stopwatch.GetTimestamp(); - var previousSlotChanges = _limiter.SlotChanges; - - while (!_stopSignal.Wait(SampleInterval)) + // Woken at once when the run ends first, so Dispose never waits for the warm-up. + if (_stopSignal.Wait(WarmUp)) { - var timestamp = Stopwatch.GetTimestamp(); - - // The number of slots is fixed here, except for this process's part of a - // budget it shares with other test processes, which changes as they start - // and finish. A count of the changes, not the number itself: a part that - // went down and came back between two samples still spoils the measurement. - var slotChanges = _limiter.SlotChanges; - - _limiterTrials!.Update(Stopwatch.GetElapsedTime(previousTimestamp, timestamp), sessionLimitBusy: false, sessionLimitChanged: slotChanges != previousSlotChanges); - previousTimestamp = timestamp; - previousSlotChanges = slotChanges; + return; } - } - catch (Exception ex) - { - // An exception escaping a dedicated thread terminates the process. - _logger.LogDebug($"Adaptive [ParallelLimiter] limits stopped after an error and were reset: {ex}"); - _limiterTrials!.Stop(resetLimits: true); - } - } -#endif -#if NET - [SupportedOSPlatform("windows")] - [SupportedOSPlatform("linux")] - [SupportedOSPlatform("macos")] - private void Run() - { - var limits = _limiter.Limits; - _logger.LogDebug($"Adaptive parallelism enabled: limit starts at {limits.Initial} and moves between {limits.Minimum} and {limits.Maximum}"); + if (limits.IsAdaptive) + { + _logger.LogDebug($"Adaptive parallelism enabled: limit starts at {limits.Initial} and moves between {limits.Minimum} and {limits.Maximum}"); + } - try - { Sample(limits); } catch (Exception ex) { // An exception escaping a dedicated thread terminates the process. Fall back to the - // limit a run without adaptive parallelism uses. - _logger.LogDebug($"Adaptive parallelism stopped after an error; limit reset to {limits.Initial}: {ex}"); - TrySetLimit(limits.Initial, putBack: false, out _, out _); + // limits a run without adaptive parallelism uses. + _logger.LogDebug($"Adaptive parallelism stopped after an error; limits reset to where they started: {ex}"); + + if (limits.IsAdaptive) + { + // 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 _); + + // Nothing moves the limit from here on, so it follows the part again. + _limiter.FollowShare(); + } + _limiterTrials?.Stop(resetLimits: true); lock (_stateLock) @@ -251,13 +252,30 @@ private void Sample(ParallelismLimits limits) machine?.Sample(); var childProcesses = new ChildProcessLoadTracker(ProcessTreeCpuSampler.Create(), SamplesPerChildProcessSample); var saidChildProcessesUnavailable = false; + long childProcessesWantedUntil = 0; + var ownCoresIncludeChildProcesses = false; var processorCount = Environment.ProcessorCount; - var policy = new AdaptiveParallelismPolicy(limits, processorCount); + + // Null when only the limits of [ParallelLimiter]s can change. + var policy = limits.IsAdaptive ? new AdaptiveParallelismPolicy(limits, processorCount, explorationBudget: _explorationBudget) : null; + // One snapshot of the two, so the count this loop starts from belongs to the limit + // the policy starts from. + var (previousSlotChanges, knownLimit) = _limiter.ReadSlots(); + + // The limit can have moved during the warm-up, when another process joined the + // budget: the summary's range has to include where it is now. + NoteLimitSetElsewhere(_startLimit, knownLimit); + + if (policy is not null && knownLimit != limits.Initial) + { + // A budget shared with other test processes has this one start at its part. + policy.Rebase(TimeSpan.Zero, knownLimit); + } + var activity = _limiter.Activity; var previousCpuTime = getProcessCpuTime(); var previousTimestamp = Stopwatch.GetTimestamp(); var previousReleasedSlots = _limiter.ReleasedSlots; - var previousSlotChanges = _limiter.SlotChanges; var machineCpuUtilization = 0d; // False until the operating system gives a first reading, and for good without a reader. @@ -306,12 +324,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. - var childProcessesWanted = GetProcessShare(processCores, ownCapacity, machineCpuCount, machineCpuUtilization, machineLoad.CpuThrottled) < AdaptiveParallelismPolicy.OwnSaturationShare - && (machineLoad.CpuStalled || cpuUtilization >= ChildProcessSamplingCpuUtilization); + if (GetProcessShare(processCores, ownCapacity, machineCpuCount, machineCpuUtilization, machineLoad.CpuThrottled) < AdaptiveParallelismPolicy.OwnSaturationShare + && (machineLoad.CpuStalled || cpuUtilization >= ChildProcessSamplingCpuUtilization)) + { + childProcessesWantedUntil = timestamp + (long) (ChildProcessSamplingHold.TotalSeconds * Stopwatch.Frequency); + } var childProcessCores = childProcesses.Update( timestamp, - childProcessesWanted); + wanted: timestamp < childProcessesWantedUntil); if (childProcesses.Unavailable && !saidChildProcessesUnavailable) { @@ -319,7 +340,13 @@ private void Sample(ParallelismLimits limits) _logger.LogDebug("Adaptive parallelism: the CPU time of child processes cannot be read on this machine, so only the test process's own CPU time counts as its load"); } - var processShare = GetProcessShare(processCores + childProcessCores, ownCapacity, machineCpuCount, machineCpuUtilization, machineLoad.CpuThrottled); + var ownCores = processCores + childProcessCores; + + // Whether the figure covers child processes changes when their reading starts or + // stops. Samples on either side of that cannot be compared. + var ownCoresChangedBasis = childProcesses.HasReading != ownCoresIncludeChildProcesses; + ownCoresIncludeChildProcesses = childProcesses.HasReading; + var processShare = GetProcessShare(ownCores, ownCapacity, machineCpuCount, machineCpuUtilization, machineLoad.CpuThrottled); // For the log and the summary, both as shares of the machine. var processCpu = Math.Min(1, processCores / machineCpuCount); @@ -337,77 +364,149 @@ private void Sample(ParallelismLimits limits) memoryLoad = Math.Max(memoryLoad, 1); } - // The last sample ended with this count, after the policy's own change. A - // different count now means this process's part of a shared budget changed the - // number of slots since, so this sample was measured under more than one limit. - // It is discarded, along with the trial and the measurements it would add to. var queueDelay = SampleQueueDelay(timestamp); + _explorationBudget.Advance(elapsed); + + // The reading every limit is decided from. Each policy adds its own tests to it. + var reading = new AdaptiveSample( + elapsed, + cpuUtilization, + processShare, + memoryLoad, + queueDelay, + CompletedTests: 0, + LimitReached: false, + machineLoad.CpuStalled, + OwnCores: ownCores, + OwnCoresChangedBasis: ownCoresChangedBasis); + + // Saturated CPUs lower the limit that admits the tests which cause them. While + // most of the running tests are inside one [ParallelLimiter], that is its limit: + // a lower session-wide limit would change nothing for tests that are already + // held back further down. + var pressureOwner = _limiterTrials?.FindPressureOwner(_limiter.HeldSlots, sessionLimitBusy: policy?.IsBusy ?? false); + + // Read once for the sample. The count this loop expects is the last one it read + // plus the changes it made itself, so any other count means the number of slots + // was changed from elsewhere: this process's part of a budget it shares with + // other test processes. A count of the changes, not the number of slots: a part + // that went down and came back between two samples still spoils the measurement. + // A change that lands after this read is seen by the next sample, which is why + // the count is never read again further down. The number of slots is read with + // it, as one snapshot: a resize counts itself before it moves the slots, and a + // new count paired with the old number would leave the policy at a limit that + // is no longer applied, with no difference left for the next sample to see. + var (slotChanges, limitNow) = _limiter.ReadSlots(); + var slotsSetElsewhere = slotChanges != previousSlotChanges; + var slotsSetHere = false; + previousSlotChanges = slotChanges; - var decision = _limiter.SlotChanges != previousSlotChanges - ? policy.Abandon(elapsed) - : policy.OnSample(new AdaptiveSample( - elapsed, - cpuUtilization, - processShare, - memoryLoad, - queueDelay, - releasedSlots - previousReleasedSlots, - LimitReached: _limiter.AvailableSlots == 0, - machineLoad.CpuStalled, - TrialsBlocked: _limiterTrials?.IsBusy ?? false)); - - if (decision.Change != AdaptiveLimitChange.None - && TrySetLimit(decision.Limit, IsPutBack(decision.Change), out var previousLimit, out var limit) - && _logger.IsEnabled(LogLevel.Debug)) + if (policy is not null) { - // Both CPU figures: a busy machine with an idle test process means the load - // comes from elsewhere, such as other test processes. - _logger.LogDebug($"Adaptive parallelism: limit {previousLimit} -> {limit} ({Describe(decision.Change)}); CPU {cpuUtilization * 100:0}% in the latest sample ({processCpu * 100:0}% from this process, {childProcessCpu * 100:0}% from its child processes), memory load {memoryLoad * 100:0}%"); - } + // Every slot in use is not enough: with fewer tests ready to run than the + // limit allows, a higher limit would start nothing. + var hasUnmetDemand = _limiter.HasUnmetDemand(_limiterTrials?.HasQueuedTestsWithFreePlaces() ?? false); - lock (_stateLock) - { - _totals.Add( - elapsed, - hasMachineCpuReading ? machineCpuUtilization : cpuUtilization, - processCpu, - policy.RaiseBlocker, - policy.HeldForOutsideLoad, - childProcesses.HasReading ? childProcessCpu : null); - } + AdaptiveDecision decision; - // The number of slots, which is what the limiters' tests compete for. It changes - // with this policy's decisions, and with this process's part of a budget it - // shares with other test processes. - // A count of the changes, not the number itself: a part that went down and came - // back between two samples still spoils the measurement. - var slotChanges = _limiter.SlotChanges; - _limiterTrials?.Update(elapsed, policy.IsBusy, sessionLimitChanged: slotChanges != previousSlotChanges); - previousSlotChanges = slotChanges; + if (slotsSetElsewhere) + { + // This sample was measured under more than one limit. It is discarded, + // along with the trial and the measurements it would add to, and the + // policy goes on from the limit the part left it at. + policy.Rebase(elapsed, limitNow); + NoteLimitSetElsewhere(knownLimit, limitNow); + decision = new AdaptiveDecision(limitNow, AdaptiveLimitChange.None); + + if (_logger.IsEnabled(LogLevel.Debug)) + { + _logger.LogDebug($"Adaptive parallelism: limit {knownLimit} -> {limitNow} (this process's part of the shared parallel budget changed)"); + } + + knownLimit = limitNow; + } + else + { + decision = policy.OnSample(reading with + { + CompletedTests = releasedSlots - previousReleasedSlots, + LimitReached = hasUnmetDemand, + TrialsBlocked = _limiterTrials?.IsBusy ?? false, + PressureElsewhere = pressureOwner is not null, + OverLimit = _limiter.HeldSlots > _limiter.CurrentLimit, + }); + } - // Said once: the state can come and go with every sample, and the summary has the total. - if (policy.HeldForOutsideLoad && !saidHeldForOutsideLoad) - { - saidHeldForOutsideLoad = true; + if (decision.Change != AdaptiveLimitChange.None + && TrySetLimit(decision.Limit, AdaptiveParallelismSummary.IsPutBack(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 + // as a difference to the next sample. + previousSlotChanges++; + slotsSetHere = true; + knownLimit = limit; + + if (_logger.IsEnabled(LogLevel.Debug)) + { + // Both CPU figures: a busy machine with an idle test process means the load + // comes from elsewhere, such as other test processes. + _logger.LogDebug($"Adaptive parallelism: limit {previousLimit} -> {limit} ({AdaptiveParallelismSummary.Describe(decision.Change)}); CPU {cpuUtilization * 100:0}% in the latest sample ({processCpu * 100:0}% from this process, {childProcessCpu * 100:0}% from its child processes), memory load {memoryLoad * 100:0}%"); + } + } - if (_logger.IsEnabled(LogLevel.Debug)) + // What holds tests back right now, for the summary. The session-wide limit + // first: when tests wait for it, it is the one this controller can move. + ParallelLimitLock? bindingLimiter = null; + + var bottleneck = activity.InSequentialPhase ? ParallelismBottleneck.NotInParallel + : hasUnmetDemand ? ParallelismBottleneck.SessionLimit + : (bindingLimiter = _limiterTrials?.FindBindingLimiter()) is not null ? ParallelismBottleneck.Limiter + : activity.WaitingForKeys > 0 ? ParallelismBottleneck.NotInParallelKey + : ParallelismBottleneck.None; + + lock (_stateLock) { - _logger.LogDebug($"Adaptive parallelism: not lowering the limit of {decision.Limit} for CPU saturation: the CPUs are saturated, but this process and its child processes use only {processShare * 100:0}% of them, so running fewer tests would not relieve them. Containers, and processes whose parent has exited, are not counted as child processes"); + _totals.Add( + elapsed, + hasMachineCpuReading ? machineCpuUtilization : cpuUtilization, + processCpu, + policy.RaiseBlocker, + policy.HeldForOutsideLoad, + childProcesses.HasReading ? childProcessCpu : null, + bottleneck, + bindingLimiter?.LimitType.Name); } - } - // Said once each time the reason changes, so a limit that never moves still - // shows why in the log. - if (policy.RaiseBlocker != raiseBlocker) - { - raiseBlocker = policy.RaiseBlocker; + // Said once: the state can come and go with every sample, and the summary has the total. + if (policy.HeldForOutsideLoad && !saidHeldForOutsideLoad) + { + saidHeldForOutsideLoad = true; - if (raiseBlocker != AdaptiveRaiseBlocker.None && _logger.IsEnabled(LogLevel.Debug)) + if (_logger.IsEnabled(LogLevel.Debug)) + { + _logger.LogDebug($"Adaptive parallelism: not lowering the limit of {decision.Limit} for CPU saturation: the CPUs are saturated, but this process and its child processes use only {processShare * 100:0}% of them, so running fewer tests would not relieve them. Containers, and processes whose parent has exited, are not counted as child processes"); + } + } + + // Said once each time the reason changes, so a limit that never moves still + // shows why in the log. + if (policy.RaiseBlocker != raiseBlocker) { - _logger.LogDebug($"Adaptive parallelism: not raising the limit of {decision.Limit}: {Describe(raiseBlocker)}"); + raiseBlocker = policy.RaiseBlocker; + + if (raiseBlocker != AdaptiveRaiseBlocker.None && _logger.IsEnabled(LogLevel.Debug)) + { + _logger.LogDebug($"Adaptive parallelism: not raising the limit of {decision.Limit}: {AdaptiveParallelismSummary.Describe(raiseBlocker)}"); + } } } + // The number of slots is what the limiters' tests compete for. It changes with + // the policy's decisions, and with this process's part of a budget it shares + // with other test processes. + _limiterTrials?.Update(reading, policy?.IsBusy ?? false, sessionLimitChanged: slotsSetElsewhere || slotsSetHere, pressureOwner); + previousCpuTime = cpuTime; previousTimestamp = timestamp; previousReleasedSlots = releasedSlots; @@ -441,7 +540,16 @@ internal static double GetProcessShare(double cores, double ownCapacity, int mac /// /// Resizes the limiter unless the controller has stopped. Returns whether the limit changed. /// - private bool TrySetLimit(int requestedLimit, bool putBack, out int previousLimit, out int limit) + /// The limit the policy decided. + /// Whether the change undoes one that did not help. + /// + /// 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 + /// after this one sees the difference and rebases the policy. + /// + /// The limit before the call. + /// The limit after it. + private bool TrySetLimit(int requestedLimit, bool putBack, long? expectedSlotChanges, out int previousLimit, out int limit) { lock (_stateLock) { @@ -452,9 +560,12 @@ private bool TrySetLimit(int requestedLimit, bool putBack, out int previousLimit return false; } - limit = _limiter.SetLimit(requestedLimit); + // Whether this call changed the slots is the limiter's to say: a change of this + // process's part of a shared budget just before it must not be counted as this + // controller's own, or the sample after it would not rebase the policy. + limit = _limiter.SetLimit(requestedLimit, expectedSlotChanges, out previousLimit, out var changed); - if (limit == previousLimit) + if (!changed) { return false; } @@ -473,147 +584,31 @@ private bool TrySetLimit(int requestedLimit, bool putBack, out int previousLimit } } - // Called with _stateLock held. - private void AddTimeAtLimit(int limit) - { - var now = Stopwatch.GetTimestamp(); - _timeAtLimit[limit] = _timeAtLimit.GetValueOrDefault(limit) + Stopwatch.GetElapsedTime(_limitSince, now); - _limitSince = now; - } - - private static bool IsPutBack(AdaptiveLimitChange change) - => change is AdaptiveLimitChange.ProbeReverted or AdaptiveLimitChange.ProbeAborted or AdaptiveLimitChange.LowerReverted; - - /// - /// The line that ends the run: where the limit went, how many of its changes were undone, - /// and how long the run spent at each limit. - /// - internal static string FormatSummary( - int currentLimit, - int lowestLimit, - int highestLimit, - int changes, - int changesPutBack, - IEnumerable> timeAtLimit, - AdaptiveRunStatistics? statistics = null) - { - var summary = new System.Text.StringBuilder(); - - if (changes == 0) - { - summary.Append("Adaptive parallelism: the parallel test limit stayed at ").Append(currentLimit); - } - else - { - AppendChanges(summary, currentLimit, lowestLimit, highestLimit, changes, changesPutBack, timeAtLimit); - } - - if (statistics is { } run) - { - AppendStatistics(summary, run); - } - - return summary.ToString(); - } - - private static void AppendChanges( - System.Text.StringBuilder summary, - int currentLimit, - int lowestLimit, - int highestLimit, - int changes, - int changesPutBack, - IEnumerable> timeAtLimit) + // The limit moved without a decision of this controller: counted for the summary's + // range and its time at each limit, not as one of its changes. + private void NoteLimitSetElsewhere(int previousLimit, int limit) { - summary - .Append("Adaptive parallelism: the parallel test limit ranged from ").Append(lowestLimit) - .Append(" to ").Append(highestLimit) - .Append(" over ").Append(changes).Append(changes == 1 ? " change" : " changes"); - - if (changesPutBack > 0) - { - summary.Append(" (").Append(changesPutBack).Append(" put back because ").Append(changesPutBack == 1 ? "it" : "they").Append(" did not help)"); - } - - summary.Append(" and ended at ").Append(currentLimit).Append(". Time at each limit: "); - - var first = true; - foreach (var entry in timeAtLimit) + lock (_stateLock) { - if (!first) + if (_stopped || limit == previousLimit) { - summary.Append(", "); + return; } - first = false; - summary.Append(entry.Key).Append(" for ").Append(FormatDuration(entry.Value)); - } - } - - // Both CPU figures, because the limit is read differently on a machine that other - // processes keep busy, and the reason the limit most often stayed where it was. - private static void AppendStatistics(System.Text.StringBuilder summary, AdaptiveRunStatistics run) - { - var invariant = System.Globalization.CultureInfo.InvariantCulture; - - summary.Append(invariant, $". The machine's CPUs were {run.MachineCpuUtilization * 100:0}% busy on average, and this process alone used {run.ProcessCpuUtilization * 100:0}% of them"); - - // Child processes are read only while the figure can change a decision, so there is - // no average over the whole run to give. - if (run.ChildProcessesMeasured > TimeSpan.Zero) - { - summary.Append(invariant, $". Its child processes used {run.ChildProcessCpuUtilization * 100:0}% in the ") - .Append(FormatDuration(run.ChildProcessesMeasured)) - .Append(" they were measured, which is while the CPUs were nearly saturated"); - } - - if (run.HeldForOutsideLoad > TimeSpan.Zero) - { - summary.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 for CPU saturation"); - } - - if (run.MostCommonRaiseBlocker != AdaptiveRaiseBlocker.None) - { - summary.Append(". Most common reason for not raising the limit: ").Append(Describe(run.MostCommonRaiseBlocker)); + AddTimeAtLimit(previousLimit); + _lowestLimit = Math.Min(_lowestLimit, limit); + _highestLimit = Math.Max(_highestLimit, limit); } } - private static string FormatDuration(TimeSpan duration) + // Called with _stateLock held. + private void AddTimeAtLimit(int limit) { - var seconds = (long) Math.Round(duration.TotalSeconds); - return seconds < 60 - ? string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{seconds}s") - : string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{seconds / 60}m {seconds % 60}s"); + var now = Stopwatch.GetTimestamp(); + _timeAtLimit[limit] = _timeAtLimit.GetValueOrDefault(limit) + Stopwatch.GetElapsedTime(_limitSince, now); + _limitSince = now; } - private static string Describe(AdaptiveRaiseBlocker blocker) => blocker switch - { - AdaptiveRaiseBlocker.LimitNotReached => "fewer tests are ready to run than the limit allows, so the limit is not what holds them back", - AdaptiveRaiseBlocker.TooFewTests => "too few tests finish to measure throughput", - AdaptiveRaiseBlocker.ThroughputNotSteady => "throughput is still changing between measurements", - AdaptiveRaiseBlocker.CpuBusy => "the CPUs have no headroom", - AdaptiveRaiseBlocker.MemoryBusy => "memory has no headroom", - AdaptiveRaiseBlocker.WaitingAfterFailedRaise => "waiting after a raise that did not help, or after memory pressure", - AdaptiveRaiseBlocker.KeepingLowerLimit => "a lower limit cost no throughput and the CPUs have been saturated recently", - AdaptiveRaiseBlocker.AtMaximum => "it is the highest limit allowed", - AdaptiveRaiseBlocker.LimiterTrial => "the limit of a [ParallelLimiter] is being tried", - _ => blocker.ToString(), - }; - - private static string Describe(AdaptiveLimitChange change) => change switch - { - AdaptiveLimitChange.Probe => "probing for more throughput", - AdaptiveLimitChange.ProbeReverted => "the last raise did not improve throughput", - AdaptiveLimitChange.ProbeAborted => "the last raise left the CPUs busy", - AdaptiveLimitChange.Recovery => "pressure eased", - AdaptiveLimitChange.MemoryPressure => "memory pressure", - AdaptiveLimitChange.CpuSaturation => "CPUs saturated; checking that fewer tests cost no throughput", - AdaptiveLimitChange.LowerReverted => "the lower limit cost throughput", - AdaptiveLimitChange.TrialAbandoned => "this process's part of the shared parallel budget changed during the measurement", - _ => change.ToString(), - }; - // The share of memory in use that counts as memory pressure. Lowering for memory is the // one change made without a trial, so it takes strong evidence: below this, a machine or // container that merely runs full (a CI runner with many processes, for one) is left alone. @@ -667,8 +662,9 @@ public void Dispose() #if NET _stopSignal.Set(); - // The thread wakes on the signal and a sample takes microseconds, so this returns at - // once. The timeout only guards against a sample stuck in the operating system. + // The thread wakes on the signal, in its warm-up as much as between samples, and a + // sample takes microseconds, so this returns at once. The timeout only guards against + // a sample stuck in the operating system. _thread?.Join(TimeSpan.FromSeconds(1)); if (_lockProvider is not null) @@ -685,6 +681,8 @@ public void Dispose() } string summary; + string details; + bool moved; lock (_stateLock) { @@ -697,102 +695,37 @@ public void Dispose() _stopped = true; AddTimeAtLimit(_limiter.CurrentLimit); - summary = FormatSummary(_limiter.CurrentLimit, _lowestLimit, _highestLimit, _changes, _changesPutBack, _timeAtLimit, _totals.ToStatistics()); + + // 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 } + : (AdaptiveRunStatistics?) null; + + moved = _changes > 0; + summary = AdaptiveParallelismSummary.Format(_startLimit, _limiter.CurrentLimit, _lowestLimit, _highestLimit, _changes, _changesPutBack, statistics); + details = AdaptiveParallelismSummary.FormatDetails(_timeAtLimit, statistics); if (_failed) { - summary += ". It stopped adjusting early after an error; run with --log-level Debug for details"; + summary += " It stopped adjusting early after an error; run with --log-level Debug for details."; } } // Information, not Debug: a failure that depends on how many tests ran at once can // only be understood from a log that says how many did. - _logger.LogInformation(summary); -#endif - } -} - -/// -/// Adds up what each sample measured. Not thread-safe. -/// -internal sealed class AdaptiveRunTotals -{ - private readonly TimeSpan[] _timeNotRaising = new TimeSpan[Enum.GetValues().Length]; - private TimeSpan _sampledTime; - private double _machineCpuSeconds; - private double _processCpuSeconds; - private TimeSpan _heldForOutsideLoad; - private TimeSpan _childProcessesMeasured; - private double _childProcessCpuSeconds; - - /// How long the sample covers. - /// Share of the machine's CPU capacity in use, 0 to 1. - /// Share of the machine's CPU capacity that this process used, 0 to 1. - /// Why the limit was not being raised, if anything stood in the way. - /// Whether saturated CPUs were left alone because other processes caused the load. - /// 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. - public void Add(TimeSpan elapsed, double machineCpuUtilization, double processCpuUtilization, AdaptiveRaiseBlocker raiseBlocker, bool heldForOutsideLoad, double? childProcessCpuUtilization = null) - { - if (childProcessCpuUtilization is { } childProcessCpu) - { - _childProcessesMeasured += elapsed; - _childProcessCpuSeconds += childProcessCpu * elapsed.TotalSeconds; - } - - _sampledTime += elapsed; - _machineCpuSeconds += machineCpuUtilization * elapsed.TotalSeconds; - _processCpuSeconds += processCpuUtilization * elapsed.TotalSeconds; - _timeNotRaising[(int) raiseBlocker] += elapsed; - - if (heldForOutsideLoad) - { - _heldForOutsideLoad += elapsed; - } - } + _logger.LogSessionMessage(summary); - /// - /// The averages and totals so far, or null before the first sample. - /// - public AdaptiveRunStatistics? ToStatistics() - { - if (_sampledTime <= TimeSpan.Zero) + // The figures behind it matter when the limit moved. For a limit that stayed where a + // fixed one would be, they are there for whoever asks for them. + if (moved) { - return null; + _logger.LogSessionMessage(details); } - - // From 1: index 0 is the time when nothing stood in the way of a raise. - var mostCommon = 0; - for (var i = 1; i < _timeNotRaising.Length; i++) + else { - if (_timeNotRaising[i] > (mostCommon == 0 ? TimeSpan.Zero : _timeNotRaising[mostCommon])) - { - mostCommon = i; - } + _logger.LogDebug(details); } - - return new AdaptiveRunStatistics( - _machineCpuSeconds / _sampledTime.TotalSeconds, - _processCpuSeconds / _sampledTime.TotalSeconds, - _heldForOutsideLoad, - (AdaptiveRaiseBlocker) mostCommon, - _childProcessesMeasured, - _childProcessesMeasured > TimeSpan.Zero ? _childProcessCpuSeconds / _childProcessesMeasured.TotalSeconds : 0); +#endif } } - -/// -/// What the controller measured over the whole run, for its summary line. -/// -/// Average share of the machine's CPU capacity in use, 0 to 1. -/// Average share of the machine's CPU capacity that this process used, 0 to 1, without its child processes. -/// How long the CPU use of this process's child processes was read for. They are read only while the CPUs are nearly saturated and this process alone uses too little to be the cause. -/// Average share of the machine's CPU capacity that the child processes used over that time, 0 to 1. -/// How long the CPUs were saturated while this process and its child processes used too small a share of them to lower the limit. -/// The reason that kept the limit from being raised for the longest. -internal readonly record struct AdaptiveRunStatistics( - double MachineCpuUtilization, - double ProcessCpuUtilization, - TimeSpan HeldForOutsideLoad, - AdaptiveRaiseBlocker MostCommonRaiseBlocker, - TimeSpan ChildProcessesMeasured = default, - double ChildProcessCpuUtilization = 0); diff --git a/src/TUnit.Engine/Scheduling/AdaptiveParallelismPolicy.cs b/src/TUnit.Engine/Scheduling/AdaptiveParallelismPolicy.cs index bf7ab62841a..d4b21e6fb61 100644 --- a/src/TUnit.Engine/Scheduling/AdaptiveParallelismPolicy.cs +++ b/src/TUnit.Engine/Scheduling/AdaptiveParallelismPolicy.cs @@ -10,8 +10,13 @@ namespace TUnit.Engine.Scheduling; /// How long work queued to the thread pool waited for a thread. /// Whether the operating system reported tasks waiting for a CPU, or a CPU quota throttling the process. /// Tests that finished since the previous sample. -/// Whether every slot of the parallel limit was in use. -/// Whether the limit of a [ParallelLimiter] is on trial, so this limit must not start one or come back up: each would change the throughput the other is measured by. +/// Whether every slot of the limit was in use while more tests could have started: the limit, and nothing else, held them back. +/// Whether another limit is on trial, so this limit must not start one or come back up: each would change the throughput the other is measured by. +/// How many of failed, when the limit counts them. +/// How many processors' worth of CPU time this process and its child processes used. +/// 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. internal readonly record struct AdaptiveSample( TimeSpan Elapsed, double CpuUtilization, @@ -21,7 +26,12 @@ internal readonly record struct AdaptiveSample( long CompletedTests, bool LimitReached, bool CpuStalled = false, - bool TrialsBlocked = false); + bool TrialsBlocked = false, + long FailedTests = 0, + double OwnCores = 0, + bool PressureElsewhere = false, + bool OverLimit = false, + bool OwnCoresChangedBasis = false); internal enum AdaptiveLimitChange { @@ -36,6 +46,9 @@ internal enum AdaptiveLimitChange /// The last probe left the CPUs busy, so its raise was undone without waiting for a verdict. ProbeAborted, + /// Tests started failing after the last probe, so its raise was undone, and the limit stays at or below this. + ProbeRevertedForFailures, + /// Raised back toward the starting limit after pressure eased. Recovery, @@ -48,6 +61,12 @@ internal enum AdaptiveLimitChange /// The last lowering for CPU saturation cost throughput, so it was undone. LowerReverted, + /// + /// The tests that were running outlasted the measurement of the last lowering, so nothing + /// was learned and it was undone. + /// + LowerNotJudged, + /// /// The number of tests the session runs at once changed for another reason while a trial /// was being measured (this process's part of a shared budget), so the trial was dropped. @@ -57,6 +76,36 @@ internal enum AdaptiveLimitChange internal readonly record struct AdaptiveDecision(int Limit, AdaptiveLimitChange Change); +/// +/// How much of a run trials that were put back have taken up, counted across every limit of +/// the run: the session-wide one and each [ParallelLimiter]. Only one limit is on trial at a +/// time, but trials of different limits add up, so they are held to one allowance together. +/// +/// +/// It decides whether a raise may be tried, and no more than that. A trial in progress runs +/// to its verdict, a lowering for saturated CPUs is never held back by it, and the first +/// raise of a run is always allowed, so a short run can spend +/// a larger share than on it. +/// Not thread-safe: every policy of a run is driven from one thread. +/// +internal sealed class AdaptiveExplorationBudget +{ + private TimeSpan _elapsed; + private TimeSpan _putBack; + + /// Time since the previous sample of the run. + public void Advance(TimeSpan elapsed) => _elapsed += elapsed; + + /// How long a trial that was put back lasted. + public void AddPutBack(TimeSpan trial) => _putBack += trial; + + /// + /// Whether trials that were put back have taken more than their share of the run so far, + /// so no new trial should start. + /// + public bool IsSpent => _putBack.Ticks > _elapsed.Ticks * AdaptiveParallelismPolicy.ExplorationShare; +} + /// /// Why the latest measurement window did not end in a raise. /// @@ -86,8 +135,14 @@ internal enum AdaptiveRaiseBlocker AtMaximum, - /// The limit of a [ParallelLimiter] is being tried, and two trials at once cannot be told apart. + /// Another limit is being tried, and two trials at once cannot be told apart. LimiterTrial, + + /// Tests failed after an earlier raise, so the limit stays at or below where it was before it. + PinnedAfterFailures, + + /// Trials that were put back, raises or lowerings of any limit, have used up their share of the run so far. + ExplorationBudget, } /// @@ -129,6 +184,26 @@ internal enum AdaptiveRaiseBlocker /// out-of-memory kill costs far more than a trial. And the starting limit needs no proof: the /// policy returns to it once the machine has headroom again. /// +/// +/// One policy decides one limit: the session-wide one, or that of a [ParallelLimiter]. The +/// rules are the same for both, so both behave alike. A limit is never lowered below where it +/// started without a reason to: saturated CPUs that are its own tests' doing, or memory +/// pressure. Throughput alone never takes it down, because a suite with a mix of quick and +/// slow tests can look as fast with fewer of them for a few seconds and be a third slower over +/// the run (#7915). +/// +/// +/// Tests that take many seconds finish too rarely for throughput to be compared. A lowering +/// for saturated CPUs is then judged by the CPU time this process and its child processes +/// use: when that does not fall, no capacity was left idle, so nothing was lost by running +/// fewer tests. A raise always needs a measured gain in throughput. +/// +/// +/// Trials that are put back cost time at a limit that did not help. While they add up to more +/// than of the run so far, no raise is tried, which keeps a +/// 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. +/// /// internal sealed class AdaptiveParallelismPolicy { @@ -165,6 +240,21 @@ internal sealed class AdaptiveParallelismPolicy // Large enough that its effect on throughput stands out from window-to-window noise. internal const double IncreaseFactor = 1.5; + // After a raise that brought at least StrongGainShare of itself, the next one doubles: + // tests that scale this well are far from the limit that suits them, and reaching it in + // steps of a half takes a long run (#7915). + internal const double StrongIncreaseFactor = 2; + internal const double StrongGainShare = 0.7; + + // No raise is tried while trials that were put back add up to more than this share of + // the run so far. A lowering for saturated CPUs is not held back by it. A trial holds the limit where it did not help for its whole length, + // and a lowering that is put back ran a quarter fewer tests meanwhile. Short trials stay + // under the share through their waits alone. It is what holds back a suite of slow + // tests, where one trial takes most of a minute. + // A threshold for starting a trial, not a cap on the time spent: a trial in progress + // runs to its verdict, and the first trial of a run is always allowed. + internal const double ExplorationShare = 0.1; + // A raise is kept when throughput rose by at least this share of it: a 50% raise must // bring 15% more completed tests per second. A lowering is kept when throughput fell by // less than this share of it: a 25% lowering may cost at most 7.5%. Measurement noise then @@ -187,6 +277,16 @@ internal sealed class AdaptiveParallelismPolicy // Fewer completed tests than this in a whole window is too few to compare throughput. internal const int MinimumWindowCompletions = 8; + // How long the CPU time of this process and its child processes is averaged over when a + // lowering has to be judged by it. Long enough to cover a few garbage collections and + // the start of a child process, short enough to act within a group of slow tests. + internal static readonly TimeSpan WorkWindow = TimeSpan.FromSeconds(5); + + // No lowering for saturated CPUs this early in the run: while the first tests start, the + // runtime compiles them and fixtures come up, which saturates the CPUs whatever the limit. + // Memory pressure is not held back. + internal static readonly TimeSpan StartupLowerHold = TimeSpan.FromSeconds(10); + // A lower limit takes effect only as running tests finish, so wait before lowering again. internal static readonly TimeSpan PressureCooldown = TimeSpan.FromSeconds(3); @@ -216,6 +316,8 @@ internal sealed class AdaptiveParallelismPolicy internal static readonly TimeSpan MaximumSettle = TimeSpan.FromSeconds(15); private readonly ParallelismLimits _limits; + private readonly bool _relievesMemoryPressure; + private readonly bool _judgesLoweringByCpuTime; // Lowering for CPU saturation stops here. With no more tests running than there are // processors, this process is not what oversubscribes them, and going lower would only @@ -255,6 +357,7 @@ internal sealed class AdaptiveParallelismPolicy // throughput away. It lapses once the limit is back where the run began. private double _throughputBeforeLowering; private int _limitBeforeLowering; + private bool _inLoweringRun; // The limit divided by throughput: the average time a test holds a slot. private TimeSpan _averageSlotTime = MinimumWindow; @@ -268,6 +371,37 @@ internal sealed class AdaptiveParallelismPolicy private TimeSpan _memoryHold = MemoryPressureHold; private TimeSpan _lowerHoldUntil; + // Whether tests failed in the windows a raise is compared with, and how many have failed + // since it began. A raise followed by failures, where there were none, is put back. + private bool _lastWindowHadFailures; + private bool _steadyHadFailures; + private bool _failuresBeforeTrial; + private long _failuresDuringTrial; + + // The highest limit a raise may reach after one was followed by failing tests. + private int _failureCeiling = int.MaxValue; + + // Whether the last raise that was kept brought most of itself in throughput. + private bool _strongGain; + + // When the trial in progress began, and what trials that were put back have taken of + // the run, across every limit of it. + private TimeSpan _trialStartedAt; + private readonly AdaptiveExplorationBudget _explorationBudget; + private readonly bool _ownsExplorationBudget; + + // CPU time this process and its child processes used, as processors' worth, over the + // latest whole WorkWindow, and the limit it was measured at: 0 when there is none. + private double _workCores; + private int _workLimit; + private TimeSpan _workElapsed; + private double _workCoreSeconds; + + // Whether the lowering on trial is judged by CPU time instead of throughput, and the + // CPU time before the first of a run of such lowerings. + private bool _trialJudgedByWork; + private double _workBeforeLowering; + // How long the CPUs must stay unsaturated before a kept lowering is undone, and how long // a trial of the way back waits. private TimeSpan _recoveryHold = InitialRecoveryHold; @@ -288,20 +422,85 @@ internal sealed class AdaptiveParallelismPolicy private long _windowCompleted; private double _windowCpuSeconds; private double _windowMaxMemoryLoad; - private TimeSpan _windowMaxQueueDelay; private int _windowSamples; private int _windowLimitReachedSamples; private int _windowCpuStalledSamples; - - public AdaptiveParallelismPolicy(ParallelismLimits limits, int processorCount) + private int _windowQueueDelayedSamples; + private long _windowFailed; + + /// The limits to move between, and where to start. + /// The number of processors this process may use. + /// + /// Whether this limit comes down at once under memory pressure. Only the session-wide + /// limit does: it covers every test, so it is the one that frees memory. + /// + /// How long no lowering for saturated CPUs starts. unless given. + /// + /// The allowance for trials that are put back, shared by every limit of the run. Whoever + /// shares it advances it once per sample. A policy without one keeps its own. + /// + /// + /// Whether a lowering may be judged by the CPU time of the process when too few tests + /// finish to compare throughput. True for the session-wide limit, which admits every + /// test, so the process's CPU time is its tests'. False for a [ParallelLimiter]: the + /// slots its lowering frees go to tests outside it, the process uses as much CPU time as + /// before, and the lowering would be kept every time while relieving nothing. + /// + /// + /// Whether lowering for saturated CPUs stops at one test per processor. True for the + /// session-wide limit: with no more tests than processors, this process is not what + /// oversubscribes them. False for a [ParallelLimiter]: its tests are few and can each + /// use several processors (a browser, a compiler), so four of them saturate eight, and + /// a floor of one per processor would mean the limit is never lowered at all (#7915). + /// + public AdaptiveParallelismPolicy( + ParallelismLimits limits, + int processorCount, + bool relievesMemoryPressure = true, + TimeSpan? startupLowerHold = null, + AdaptiveExplorationBudget? explorationBudget = null, + bool oneTestPerProcessorIsEnough = true, + bool judgesLoweringByCpuTime = true) { + _judgesLoweringByCpuTime = judgesLoweringByCpuTime; + _explorationBudget = explorationBudget ?? new AdaptiveExplorationBudget(); + _ownsExplorationBudget = explorationBudget is null; _limits = limits; + _relievesMemoryPressure = relievesMemoryPressure; + _lowerHoldUntil = startupLowerHold ?? StartupLowerHold; _limit = limits.Initial; - _cpuSaturationFloor = Math.Max(limits.Minimum, Math.Min(processorCount, limits.Initial)); + _cpuSaturationFloor = oneTestPerProcessorIsEnough + ? Math.Max(limits.Minimum, Math.Min(processorCount, limits.Initial)) + : limits.Minimum; } public int Limit => _limit; + /// + /// Whether saturated CPUs could take this limit lower. False at the lowest the limit + /// goes for them: its minimum, and for the session-wide limit one test per processor. + /// + public bool CanLowerForCpu => _limit > _cpuSaturationFloor; + + /// + /// Whether a lowering for saturated CPUs could start with the next saturated samples: + /// the limit can go lower, there is a measurement to judge it against, and no wait or + /// spent allowance stands in the way. What leaves out is + /// everything that makes a policy decline for now, and a limit that declines must not + /// be the one the pressure is left to. + /// + public bool IsReadyToLowerForCpu + => CanLowerForCpu + && _trial == AdaptiveLimitChange.None + && !_settling + && (_steadyLimit == _limit || (_judgesLoweringByCpuTime && _workLimit == _limit && _workCores > 0)) + && _clock >= _lowerHoldUntil; + + /// + /// Whether a lowering for saturated CPUs is being measured. + /// + public bool IsLoweringForCpu => _trial == AdaptiveLimitChange.CpuSaturation; + /// /// Whether a change is being measured, so no other limit should change meanwhile. /// @@ -320,7 +519,29 @@ public AdaptiveParallelismPolicy(ParallelismLimits limits, int processorCount) public AdaptiveDecision OnSample(AdaptiveSample sample) { - _clock += sample.Elapsed; + Advance(sample.Elapsed); + + // Child processes are read only from the moment the CPUs are nearly saturated, which + // is also when a lowering can start. CPU time from before is this process alone, + // and from then on it includes the child processes: compared, every lowering would + // be kept on CPU time that was there all along but not counted. So what was + // measured before is dropped, and a lowering that is being judged by it is given up. + if (sample.OwnCoresChangedBasis) + { + ResetWork(); + _workBeforeLowering = 0; + + if (_trial == AdaptiveLimitChange.CpuSaturation && _trialJudgedByWork) + { + return GiveUpLowering(); + } + } + + // Not held until the verdict: every test that fails meanwhile is a test the raise broke. + if (TryRevertForFailures(sample.FailedTests) is { } failedRaise) + { + return failedRaise; + } if (TryRelievePressure(sample) is { } relieved) { @@ -337,16 +558,46 @@ public AdaptiveDecision OnSample(AdaptiveSample sample) if (_settling) { _settleRemaining -= sample.Elapsed; - if (_settleRemaining <= TimeSpan.Zero) + + if (_settleRemaining > TimeSpan.Zero) { - _settling = false; - ResetWindow(); + return NoChange(); } + // A lowered limit admits fewer tests only once the tests that were running have + // finished. Until then nothing measured is measured under it, and with tests that + // run for a minute a lowering would be judged, and kept, on the CPU time of the + // limit it came from. + if (sample.OverLimit) + { + if (_settleRemaining > -MaximumWindow) + { + return NoChange(); + } + + // The tests run too long for this trial to learn anything. Nothing spoke + // against the lowering either, so it is not held against later trials. + if (_trial == AdaptiveLimitChange.CpuSaturation) + { + return GiveUpLowering(); + } + } + + _settling = false; + ResetWindow(); + ResetWork(); return NoChange(); } Accumulate(sample); + var workWindowClosed = AccumulateWork(sample); + + if (_trial == AdaptiveLimitChange.CpuSaturation && _trialJudgedByWork) + { + // Too few tests finish for throughput to say anything, so the verdict waits for + // a whole window of CPU time, and the throughput windows are left out of it. + return workWindowClosed ? JudgeLoweringByWork() : NoChange(); + } if (!IsWindowComplete()) { @@ -354,6 +605,7 @@ public AdaptiveDecision OnSample(AdaptiveSample sample) } var throughput = _windowCompleted / _windowElapsed.TotalSeconds; + var hadFailures = _windowFailed > 0; // Throughput is comparable between windows only when the limit, not a shortage of // tests ready to run, decided how many ran. @@ -364,8 +616,12 @@ public AdaptiveDecision OnSample(AdaptiveSample sample) var cpuStalled = _windowCpuStalledSamples * 4 >= _windowSamples; var hasMemoryHeadroom = _windowMaxMemoryLoad < MemoryHeadroomLoad; + // A quarter of the samples, as for stalls: one slow thread-pool hand-over in a window + // is a hiccup, and does not make an idle machine busy. + var queueDelayed = _windowQueueDelayedSamples * 4 >= _windowSamples; + var hasCpuHeadroom = cpuUtilization < CpuHeadroomUtilization - && _windowMaxQueueDelay < QueueDelayLimit + && !queueDelayed && !cpuStalled; ResetWindow(); @@ -409,6 +665,7 @@ public AdaptiveDecision OnSample(AdaptiveSample sample) if (raised) { HoldRaises(); + CountRevertedRaise(); if (_keepingLowering && _limitBeforeTrial < _limits.Initial) { @@ -420,11 +677,7 @@ public AdaptiveDecision OnSample(AdaptiveSample sample) return ChangeLimit(_limitBeforeTrial, AdaptiveLimitChange.ProbeReverted); } - _lowerHoldUntil = _clock + _lowerHold; - _lowerHold = Double(_lowerHold); - _recoveryHold = InitialRecoveryHold; - EndLoweringRunAt(_limitBeforeTrial); - return ChangeLimit(_limitBeforeTrial, AdaptiveLimitChange.LowerReverted); + return RejectLowering(); } if (lowerPending) @@ -436,22 +689,12 @@ public AdaptiveDecision OnSample(AdaptiveSample sample) _raiseHold = InitialRaiseHold; _memoryHold = MemoryPressureHold; _recoveryHold = InitialRecoveryHold; + _strongGain = throughput >= _throughputBeforeTrial * (1 + change * StrongGainShare); EndLoweringRunAt(_limit); } - else if (_limitBeforeTrial > _limits.Initial) - { - // Fewer tests did as well above the starting limit, so the raise that led - // there was a mistake, and the next one waits like any failed raise. - _lowerHold = InitialLowerHold; - HoldRaises(); - } else { - // Fewer tests did as well, so trying more again straight away would only - // undo it. The wait does not grow: nothing failed. - _lowerHold = InitialLowerHold; - HoldRaisesUntil(_clock + _raiseHold); - KeepLowering(); + AcceptLowering(); } } @@ -461,8 +704,10 @@ public AdaptiveDecision OnSample(AdaptiveSample sample) _steadyThroughput = steady ? (throughput + _lastThroughput) / 2 : 0; _steadyLimit = steady ? _limit : 0; + _steadyHadFailures = hadFailures || _lastWindowHadFailures; _lastThroughput = throughput; _lastLimit = measurable ? _limit : 0; + _lastWindowHadFailures = hadFailures; if (lowerPending) { @@ -474,21 +719,29 @@ public AdaptiveDecision OnSample(AdaptiveSample sample) return NoRaise(AdaptiveRaiseBlocker.LimiterTrial); } + // A machine without headroom is a reason only while tests wait for the limit. When + // they do not, the limit is not what holds them back, whatever the machine is doing, + // and saying "the CPUs have no headroom" on an idle machine sends the reader the + // wrong way (#7915). if (!hasMemoryHeadroom) { - return NoRaise(AdaptiveRaiseBlocker.MemoryBusy); + return NoRaise(limitReached ? AdaptiveRaiseBlocker.MemoryBusy : AdaptiveRaiseBlocker.LimitNotReached); } + var highest = Math.Min(_limits.Maximum, _failureCeiling); var ceiling = _clock < _pressureCapUntil - ? Math.Min(_limits.Maximum, _pressureCap) - : _limits.Maximum; + ? Math.Min(highest, _pressureCap) + : highest; if (_limit >= ceiling) { - return NoRaise(_limit >= _limits.Maximum ? AdaptiveRaiseBlocker.AtMaximum : AdaptiveRaiseBlocker.WaitingAfterFailedRaise); + return NoRaise( + _limit >= _limits.Maximum ? AdaptiveRaiseBlocker.AtMaximum + : _limit >= _failureCeiling ? AdaptiveRaiseBlocker.PinnedAfterFailures + : AdaptiveRaiseBlocker.WaitingAfterFailedRaise); } - var higher = Math.Min(ceiling, Math.Max(_limit + 1, (int) Math.Ceiling(_limit * IncreaseFactor))); + var higher = Math.Min(ceiling, Math.Max(_limit + 1, (int) Math.Ceiling(_limit * (_strongGain ? StrongIncreaseFactor : IncreaseFactor)))); if (_limit < _limits.Initial) { @@ -515,7 +768,7 @@ public AdaptiveDecision OnSample(AdaptiveSample sample) } else if (!hasCpuHeadroom) { - return NoRaise(AdaptiveRaiseBlocker.CpuBusy); + return NoRaise(limitReached ? AdaptiveRaiseBlocker.CpuBusy : AdaptiveRaiseBlocker.LimitNotReached); } if (_steadyLimit != _limit) @@ -530,9 +783,146 @@ public AdaptiveDecision OnSample(AdaptiveSample sample) return NoRaise(AdaptiveRaiseBlocker.WaitingAfterFailedRaise); } + if (IsOverExplorationBudget) + { + return NoRaise(AdaptiveRaiseBlocker.ExplorationBudget); + } + return StartTrial(higher, AdaptiveLimitChange.Probe, _steadyThroughput); } + /// + /// Puts back a raise on trial when tests fail during it and none failed in the + /// measurements before it: what the limit protects (a database's connections, for + /// example) cannot be observed, so failing tests are the evidence that it was overloaded. + /// The limit is not raised past that point again in the run. + /// + private AdaptiveDecision? TryRevertForFailures(long failedTests) + { + _windowFailed += failedTests; + + if (_trial != AdaptiveLimitChange.Probe) + { + return null; + } + + _failuresDuringTrial += failedTests; + + if (_failuresDuringTrial == 0 || _failuresBeforeTrial) + { + return null; + } + + return RevertRaiseForFailures(); + } + + private AdaptiveDecision RevertRaiseForFailures() + { + _trial = AdaptiveLimitChange.None; + + // Never below the starting limit: that one is the user's own choice, and tests that + // fail at it fail without adaptive parallelism too. + _failureCeiling = Math.Max(_limitBeforeTrial, _limits.Initial); + HoldRaises(); + CountRevertedRaise(); + return ChangeLimit(_limitBeforeTrial, AdaptiveLimitChange.ProbeRevertedForFailures); + } + + private void CountRevertedRaise() + { + _strongGain = false; + _explorationBudget.AddPutBack(_clock - _trialStartedAt); + } + + // Nothing is spent until a trial has been put back, so the first trial is always allowed. + private bool IsOverExplorationBudget => _explorationBudget.IsSpent; + + private void Advance(TimeSpan elapsed) + { + _clock += elapsed; + + if (_ownsExplorationBudget) + { + _explorationBudget.Advance(elapsed); + } + } + + /// + /// Puts back a lowering that could not be judged. Unlike one that was judged and lost, + /// it is not counted toward the allowance for trials that are put back, and the wait + /// before the next lowering does not grow: nothing was learned, as when a trial is + /// abandoned. The next lowering still waits, so tests that always outlast the + /// measurement do not have the limit going down and back without end. + /// + private AdaptiveDecision GiveUpLowering() + { + _trial = AdaptiveLimitChange.None; + _lowerHoldUntil = _clock + _lowerHold; + EndLoweringRunAt(_limitBeforeTrial); + return ChangeLimit(_limitBeforeTrial, AdaptiveLimitChange.LowerNotJudged); + } + + private AdaptiveDecision RejectLowering() + { + _trial = AdaptiveLimitChange.None; + _explorationBudget.AddPutBack(_clock - _trialStartedAt); + _lowerHoldUntil = _clock + _lowerHold; + _lowerHold = Double(_lowerHold); + _recoveryHold = InitialRecoveryHold; + EndLoweringRunAt(_limitBeforeTrial); + return ChangeLimit(_limitBeforeTrial, AdaptiveLimitChange.LowerReverted); + } + + private void AcceptLowering() + { + _trial = AdaptiveLimitChange.None; + _lowerHold = InitialLowerHold; + + // The gain that earned a doubling was measured before the CPUs saturated: the next + // raise from here is an ordinary one. + _strongGain = false; + + if (_limitBeforeTrial > _limits.Initial) + { + // Fewer tests did as well above the starting limit, so the raise that led there + // was a mistake, and the next one waits like any failed raise. + HoldRaises(); + } + else + { + // Fewer tests did as well, so trying more again straight away would only undo + // it. The wait does not grow: nothing failed. + HoldRaisesUntil(_clock + _raiseHold); + KeepLowering(); + } + } + + /// + /// The verdict on a lowering for saturated CPUs when too few tests finish to compare + /// throughput. The lowering is kept when this process and its child processes used as + /// much CPU time as before: the CPUs stayed busy with fewer tests, so no capacity was + /// left idle. It is put back when they used less, which is CPU time the lowering gave away. + /// + private AdaptiveDecision JudgeLoweringByWork() + { + // A fresh start for the throughput windows, which were not what this trial waited for. + ResetWindow(); + + var requiredWork = _workBeforeLowering * (1 - (1 - CpuDecreaseFactor) * MinimumGainShare); + + if (_workCores < requiredWork) + { + return RejectLowering(); + } + + if (++_loweringWindowsPassed >= WindowsBeforeKeepingLowering) + { + AcceptLowering(); + } + + return NoChange(); + } + /// /// Drops the measurements in progress because the number of tests the session runs at /// once changed for a reason other than this policy's own decision: this process's part @@ -541,11 +931,50 @@ public AdaptiveDecision OnSample(AdaptiveSample sample) /// so the next trial does not wait longer. /// /// Time since the previous sample, which this call stands in for. - public AdaptiveDecision Abandon(TimeSpan elapsed) + /// Tests that failed since the previous sample. A failure during a raise still counts against it. + public AdaptiveDecision Abandon(TimeSpan elapsed, long failedTests = 0) { - _clock += elapsed; + Advance(elapsed); + ResetMeasurements(); + + if (_trial == AdaptiveLimitChange.None) + { + return NoChange(); + } + + if (_trial == AdaptiveLimitChange.Probe + && _failuresDuringTrial + failedTests > 0 + && !_failuresBeforeTrial) + { + return RevertRaiseForFailures(); + } + + _trial = AdaptiveLimitChange.None; + return ChangeLimit(_limitBeforeTrial, AdaptiveLimitChange.TrialAbandoned); + } + /// + /// Takes over a limit that was set from outside: this process's part of a budget it + /// shares with other test processes, which shrank to make room for one that has started. + /// A trial in progress is dropped without putting its limit back, and every measurement + /// starts over. From a limit below the starting one, the policy returns to the starting + /// limit as soon as the machine has headroom, as after any lowering. + /// + /// Time since the previous sample, which this call stands in for. + /// The limit as it is now. + public void Rebase(TimeSpan elapsed, int limit) + { + Advance(elapsed); + ResetMeasurements(); + _trial = AdaptiveLimitChange.None; + ChangeLimit(Math.Min(Math.Max(limit, _limits.Minimum), _limits.Maximum), AdaptiveLimitChange.None); + } + + private void ResetMeasurements() + { ResetWindow(); + ResetWork(); + _strongGain = false; _lastThroughput = 0; _lastLimit = 0; _steadyThroughput = 0; @@ -555,15 +984,14 @@ public AdaptiveDecision Abandon(TimeSpan elapsed) _loweringWindowsPassed = 0; // The next lowering is judged against a fresh measurement. - _throughputBeforeLowering = 0; - - if (_trial == AdaptiveLimitChange.None) - { - return NoChange(); - } + EndLoweringRun(); + } - _trial = AdaptiveLimitChange.None; - return ChangeLimit(_limitBeforeTrial, AdaptiveLimitChange.TrialAbandoned); + private void EndLoweringRun() + { + _inLoweringRun = false; + _throughputBeforeLowering = 0; + _workBeforeLowering = 0; } // The wait doubles when the last kept lowering was followed by a return to a higher @@ -590,10 +1018,24 @@ private AdaptiveDecision StartTrial(int limit, AdaptiveLimitChange change, doubl { // A raise on trial leaves the run of lowerings open: if it is put back, the limit is // still below where the run began. - if (limit < _limit && _throughputBeforeLowering <= 0) + if (limit < _limit) { - _throughputBeforeLowering = throughput; - _limitBeforeLowering = _limit; + // Where the run began is set by its first step alone, whichever way that step is + // judged. A lowering judged by CPU time has no throughput to record, so a test + // on the throughput here would move the start of the run down with every step, + // and a later step that is put back would end the run and its baseline while + // the limit was still below where it began. + if (!_inLoweringRun) + { + _inLoweringRun = true; + _limitBeforeLowering = _limit; + } + + // And each kind of baseline is the one from the first step that had it. + if (_throughputBeforeLowering <= 0) + { + _throughputBeforeLowering = throughput; + } } _trial = change; @@ -601,6 +1043,9 @@ private AdaptiveDecision StartTrial(int limit, AdaptiveLimitChange change, doubl _loweringWindowsPassed = 0; _limitBeforeTrial = _limit; _throughputBeforeTrial = throughput; + _failuresBeforeTrial = _steadyHadFailures; + _failuresDuringTrial = 0; + _trialStartedAt = _clock; return ChangeLimit(limit, change); } @@ -619,7 +1064,14 @@ private AdaptiveDecision StartTrial(int limit, AdaptiveLimitChange change, doubl HeldForOutsideLoad = saturated && _limit <= _limits.Initial && sample.ProcessCpuUtilization < OwnSaturationShare; - saturated &= !HeldForOutsideLoad; + + // And when most of the running tests are inside another limit, that limit is the + // one that admits the load: lowering this one would change nothing. At the starting + // limit or below it only, like the load of other processes. A limit above it is + // there on the strength of one trial, and the tests it admits beyond the start take + // whatever slots the other limit frees, so saturation from any source sends it back. + var pressureElsewhere = sample.PressureElsewhere && _limit <= _limits.Initial; + saturated &= !HeldForOutsideLoad && !pressureElsewhere; _saturatedSamples = saturated ? _saturatedSamples + 1 : 0; @@ -633,26 +1085,41 @@ private AdaptiveDecision StartTrial(int limit, AdaptiveLimitChange change, doubl return null; } - if (sample.MemoryLoad >= MemoryPressureLoad) + if (_relievesMemoryPressure && sample.MemoryLoad >= MemoryPressureLoad) { return LowerForMemoryPressure(); } - // A lowering for CPU saturation is a trial, so it needs a steady throughput - // measurement at this limit to be judged against, and no other trial in progress. + // A lowering for CPU saturation is a trial, so it needs a measurement at this limit + // to be judged against, and no other trial in progress. A steady throughput when + // enough tests finish, and otherwise the CPU time this process and its child + // processes used. + var judgedByWork = _steadyLimit != _limit; + if (_saturatedSamples >= SaturatedSamplesBeforeDecrease && _limit > _cpuSaturationFloor && _trial == AdaptiveLimitChange.None && !_settling && !sample.TrialsBlocked - && _steadyLimit == _limit + && (!judgedByWork || (_judgesLoweringByCpuTime && _workLimit == _limit && _workCores > 0)) && _clock >= _lowerHoldUntil) { _saturatedSamples = 0; + _trialJudgedByWork = judgedByWork; + + if (judgedByWork && _workBeforeLowering <= 0) + { + _workBeforeLowering = _workCores; + } // From above the starting limit, one step goes no further down than back to it. var floor = _limit > _limits.Initial ? Math.Max(_cpuSaturationFloor, _limits.Initial) : _cpuSaturationFloor; - return StartTrial(Math.Max(floor, LowerBy(CpuDecreaseFactor)), AdaptiveLimitChange.CpuSaturation, _steadyThroughput); + // The allowance for trials that are put back does not hold this back: it bounds + // what raises cost, and a raise that was put back is no reason to leave the CPUs + // oversubscribed for minutes. A lowering that is put back still counts toward + // it, and waits for its own hold. Judged by CPU time, it has no throughput to + // be compared with: the last steady one can be from another limit. + return StartTrial(Math.Max(floor, LowerBy(CpuDecreaseFactor)), AdaptiveLimitChange.CpuSaturation, judgedByWork ? 0 : _steadyThroughput); } return null; @@ -682,6 +1149,7 @@ private AdaptiveDecision StartTrial(int limit, AdaptiveLimitChange change, doubl _trial = AdaptiveLimitChange.None; HoldRaises(); + CountRevertedRaise(); return ChangeLimit(_limitBeforeTrial, AdaptiveLimitChange.ProbeAborted); } @@ -698,7 +1166,11 @@ private AdaptiveDecision LowerForMemoryPressure() _pressureCooldownUntil = _clock + PressureCooldown; _saturatedSamples = 0; _trial = AdaptiveLimitChange.None; - _throughputBeforeLowering = 0; + + // Whatever run of lowerings was in progress is over: the next one is judged + // against a fresh measurement, of throughput or of CPU time. + EndLoweringRun(); + _strongGain = false; _keepingLowering = false; HoldRaisesUntil(_pressureCapUntil); _memoryHold = Double(_memoryHold); @@ -711,7 +1183,7 @@ private void EndLoweringRunAt(int limit) { if (limit >= _limitBeforeLowering) { - _throughputBeforeLowering = 0; + EndLoweringRun(); } } @@ -733,8 +1205,12 @@ private AdaptiveDecision ChangeLimit(int limit, AdaptiveLimitChange change) RaiseBlocker = AdaptiveRaiseBlocker.None; _lastLimit = 0; _steadyLimit = 0; + + // With the limit it was measured at: nothing may take it for this limit's. + _steadyThroughput = 0; _settling = true; _settleRemaining = TimeSpan.FromTicks(Math.Min(Math.Max(_averageSlotTime.Ticks, MinimumWindow.Ticks), MaximumSettle.Ticks)); + ResetWork(); return new AdaptiveDecision(limit, change); } @@ -746,7 +1222,6 @@ private void Accumulate(AdaptiveSample sample) _windowCompleted += sample.CompletedTests; _windowCpuSeconds += sample.CpuUtilization * sample.Elapsed.TotalSeconds; _windowMaxMemoryLoad = Math.Max(_windowMaxMemoryLoad, sample.MemoryLoad); - _windowMaxQueueDelay = sample.QueueDelay > _windowMaxQueueDelay ? sample.QueueDelay : _windowMaxQueueDelay; _windowSamples++; if (sample.LimitReached) @@ -758,6 +1233,41 @@ private void Accumulate(AdaptiveSample sample) { _windowCpuStalledSamples++; } + + if (sample.QueueDelay >= QueueDelayLimit) + { + _windowQueueDelayedSamples++; + } + } + + /// + /// Adds the sample to the CPU time measured at this limit. Returns whether that closed a + /// whole . + /// + private bool AccumulateWork(AdaptiveSample sample) + { + _workElapsed += sample.Elapsed; + _workCoreSeconds += sample.OwnCores * sample.Elapsed.TotalSeconds; + + if (_workElapsed < WorkWindow) + { + return false; + } + + _workCores = _workCoreSeconds / _workElapsed.TotalSeconds; + _workLimit = _limit; + _workElapsed = TimeSpan.Zero; + _workCoreSeconds = 0; + return true; + } + + // CPU time measured under one limit says nothing about another. + private void ResetWork() + { + _workCores = 0; + _workLimit = 0; + _workElapsed = TimeSpan.Zero; + _workCoreSeconds = 0; } // Long enough to average over at least two tests per slot, so a mix of short and long @@ -773,9 +1283,10 @@ private void ResetWindow() _windowCompleted = 0; _windowCpuSeconds = 0; _windowMaxMemoryLoad = 0; - _windowMaxQueueDelay = TimeSpan.Zero; _windowSamples = 0; _windowLimitReachedSamples = 0; _windowCpuStalledSamples = 0; + _windowQueueDelayedSamples = 0; + _windowFailed = 0; } } diff --git a/src/TUnit.Engine/Scheduling/AdaptiveParallelismSummary.cs b/src/TUnit.Engine/Scheduling/AdaptiveParallelismSummary.cs new file mode 100644 index 00000000000..da57572d23b --- /dev/null +++ b/src/TUnit.Engine/Scheduling/AdaptiveParallelismSummary.cs @@ -0,0 +1,470 @@ +#if NET +using System.Globalization; +using System.Text; + +namespace TUnit.Engine.Scheduling; + +/// +/// What kept more tests from running at once at one moment of the run. +/// +internal enum ParallelismBottleneck +{ + /// Nothing: fewer tests were ready to run than the limits allow. + None, + + /// Tests waited for a slot of the session-wide limit. + SessionLimit, + + /// Tests waited for a [ParallelLimiter] while the session-wide limit had room. + Limiter, + + /// The tests marked [NotInParallel] without a key were running, one at a time. + NotInParallel, + + /// Tests waited for a [NotInParallel] key while the session-wide limit had room. + NotInParallelKey, +} + +/// +/// Adds up what each sample measured. Not thread-safe. +/// +internal sealed class AdaptiveRunTotals +{ + private readonly TimeSpan[] _timeNotRaising = new TimeSpan[AdaptiveParallelismSummary.RaiseBlockerCount]; + private readonly TimeSpan[] _timeByBottleneck = new TimeSpan[Enum.GetValues().Length]; + private Dictionary? _timeByLimiter; + private TimeSpan _sampledTime; + private double _machineCpuSeconds; + private double _processCpuSeconds; + private double _cpuSecondsWhileWaiting; + private TimeSpan _heldForOutsideLoad; + private TimeSpan _childProcessesMeasured; + private double _childProcessCpuSeconds; + + /// How long the sample covers. + /// Share of the machine's CPU capacity in use, 0 to 1. + /// Share of the machine's CPU capacity that this process used, 0 to 1. + /// Why the limit was not being raised, if anything stood in the way. + /// Whether saturated CPUs were left alone because other processes caused the load. + /// 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. + public void Add( + TimeSpan elapsed, + double machineCpuUtilization, + double processCpuUtilization, + AdaptiveRaiseBlocker raiseBlocker, + bool heldForOutsideLoad, + double? childProcessCpuUtilization = null, + ParallelismBottleneck bottleneck = ParallelismBottleneck.SessionLimit, + string? limiter = null) + { + if (childProcessCpuUtilization is { } childProcessCpu) + { + _childProcessesMeasured += elapsed; + _childProcessCpuSeconds += childProcessCpu * elapsed.TotalSeconds; + } + + _sampledTime += elapsed; + _machineCpuSeconds += machineCpuUtilization * elapsed.TotalSeconds; + _processCpuSeconds += processCpuUtilization * elapsed.TotalSeconds; + _timeByBottleneck[(int) bottleneck] += elapsed; + + if (bottleneck == ParallelismBottleneck.SessionLimit) + { + // The reason counts only while tests wait for the limit. The rest of the time + // the limit holds nothing back, and a reason for not raising it would mislead: + // "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) + { + _timeNotRaising[(int) raiseBlocker] += elapsed; + } + + _cpuSecondsWhileWaiting += machineCpuUtilization * elapsed.TotalSeconds; + } + else if (bottleneck == ParallelismBottleneck.Limiter && limiter is not null) + { + _timeByLimiter ??= []; + _timeByLimiter[limiter] = _timeByLimiter.GetValueOrDefault(limiter) + elapsed; + } + + if (heldForOutsideLoad) + { + _heldForOutsideLoad += elapsed; + } + } + + /// + /// The averages and totals so far, or null before the first sample. + /// + public AdaptiveRunStatistics? ToStatistics() + { + if (_sampledTime <= TimeSpan.Zero) + { + return null; + } + + string? limiter = null; + + if (_timeByLimiter is not null) + { + var longest = TimeSpan.Zero; + + foreach (var entry in _timeByLimiter) + { + if (entry.Value > longest) + { + (limiter, longest) = (entry.Key, entry.Value); + } + } + } + + var waitedForLimit = _timeByBottleneck[(int) ParallelismBottleneck.SessionLimit]; + + return new AdaptiveRunStatistics( + _machineCpuSeconds / _sampledTime.TotalSeconds, + _processCpuSeconds / _sampledTime.TotalSeconds, + _heldForOutsideLoad, + AdaptiveParallelismSummary.MostCommon(_timeNotRaising), + _childProcessesMeasured, + _childProcessesMeasured > TimeSpan.Zero ? _childProcessCpuSeconds / _childProcessesMeasured.TotalSeconds : 0) + { + Sampled = _sampledTime, + WaitedForLimit = waitedForLimit, + CpuUtilizationWhileWaiting = waitedForLimit > TimeSpan.Zero ? _cpuSecondsWhileWaiting / waitedForLimit.TotalSeconds : 0, + WaitedForLimiter = _timeByBottleneck[(int) ParallelismBottleneck.Limiter], + MostWaitedLimiter = limiter, + LimitersWaitedFor = _timeByLimiter?.Count ?? 0, + NotInParallel = _timeByBottleneck[(int) ParallelismBottleneck.NotInParallel], + WaitedForKeys = _timeByBottleneck[(int) ParallelismBottleneck.NotInParallelKey], + }; + } +} + +/// +/// What the controller measured over the whole run, for its summary. +/// +/// Average share of the machine's CPU capacity in use, 0 to 1. +/// Average share of the machine's CPU capacity that this process used, 0 to 1, without its child processes. +/// How long the CPUs were saturated while this process and its child processes used too small a share of them to lower the limit. +/// The reason that kept the limit from being raised for the longest, of the time tests waited for it. +/// How long the CPU use of this process's child processes was read for. +/// Average share of the machine's CPU capacity that the child processes used over that time, 0 to 1. +internal readonly record struct AdaptiveRunStatistics( + double MachineCpuUtilization, + double ProcessCpuUtilization, + TimeSpan HeldForOutsideLoad, + AdaptiveRaiseBlocker MostCommonRaiseBlocker, + TimeSpan ChildProcessesMeasured = default, + double ChildProcessCpuUtilization = 0) +{ + /// How long the run was measured for: what the waits below are shares of. + public TimeSpan Sampled { get; init; } + + /// + /// How long the run lasted, with the time before measuring began. It is the duration + /// the reader sees next to the summary, so the summary gives waits "of" this. Whether a + /// wait is worth a sentence is still decided against , the time + /// it was measured over. when not set. + /// + public TimeSpan RunTime { get; init; } + + /// How long tests waited for a slot of the session-wide limit. + public TimeSpan WaitedForLimit { get; init; } + + /// Average share of the machine's CPU capacity in use over that time, 0 to 1. + public double CpuUtilizationWhileWaiting { get; init; } + + /// How long tests waited for a [ParallelLimiter] while the session-wide limit had room. + public TimeSpan WaitedForLimiter { get; init; } + + /// The limiter they waited for the longest. + public string? MostWaitedLimiter { get; init; } + + /// How many limiters they waited for. + public int LimitersWaitedFor { get; init; } + + /// How long the tests marked [NotInParallel] without a key ran, one at a time. + public TimeSpan NotInParallel { get; init; } + + /// How long tests waited for a [NotInParallel] key while the session-wide limit had room. + public TimeSpan WaitedForKeys { get; init; } + + /// The key they waited for the longest. + public string? MostWaitedKey { get; init; } +} + +/// +/// The text adaptive parallelism writes when the run ends. +/// +/// +/// The first line is short enough for a CI log and says what most held the run back, because +/// that is what a reader acts on: a limit that tests did not wait for is not worth tuning. +/// The figures behind it go on a second line. +/// +internal static class AdaptiveParallelismSummary +{ + // Below this share of the run, a bottleneck is not worth a sentence. + internal const double NotableShare = 0.1; + + // CPUs less busy than this have room for more tests that use them. + internal const double IdleCpuUtilization = 0.5; + + internal static int RaiseBlockerCount { get; } = Enum.GetValues().Length; + + /// + /// The line that ends the run: where the limit went, and what held the run back the most. + /// + internal static string Format( + int startLimit, + int currentLimit, + int lowestLimit, + int highestLimit, + int changes, + int changesPutBack, + AdaptiveRunStatistics? statistics = null) + { + var summary = new StringBuilder("Adaptive parallelism: the parallel test limit "); + AppendLimit(summary, startLimit, currentLimit, lowestLimit, highestLimit, changes, changesPutBack); + + if (statistics is { } run && run.Sampled > TimeSpan.Zero) + { + AppendBottleneck(summary, run); + } + + return summary.ToString(); + } + + /// + /// Where a limit went, as the end of a sentence that names it: "stayed at 8." or + /// "went from 8 to 18 (lowest 6, highest 27, 12 changes, 5 put back)." + /// + internal static void AppendLimit(StringBuilder text, int startLimit, int currentLimit, int lowestLimit, int highestLimit, int changes, int changesPutBack) + { + // The range as well as the count: a limit can move without a change of the policy's + // own, when this process's part of a shared budget shrinks. + if (changes == 0 && lowestLimit == highestLimit && currentLimit == startLimit) + { + text.Append("stayed at ").Append(currentLimit).Append('.'); + return; + } + + if (currentLimit == startLimit) + { + text.Append("moved and ended back at ").Append(currentLimit); + } + else + { + text.Append("went from ").Append(startLimit).Append(" to ").Append(currentLimit); + } + + text.Append(" (lowest ").Append(lowestLimit).Append(", highest ").Append(highestLimit); + + if (changes > 0) + { + text.Append(", ").Append(changes).Append(changes == 1 ? " change" : " changes"); + } + + if (changesPutBack > 0) + { + text.Append(", ").Append(changesPutBack).Append(" put back"); + } + + text.Append(")."); + } + + // One sentence, for whatever held tests back the longest. + private static void AppendBottleneck(StringBuilder summary, AdaptiveRunStatistics run) + { + var longest = Max(run.WaitedForLimit, run.WaitedForLimiter, run.NotInParallel, run.WaitedForKeys); + var total = FormatDuration(run.RunTime > TimeSpan.Zero ? run.RunTime : run.Sampled); + + if (longest.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) + { + summary.Append(" For ").Append(FormatDuration(longest)).Append(" of ").Append(total) + .Append(", tests marked [NotInParallel] ran one at a time, which no limit changes."); + } + else if (longest == run.WaitedForKeys) + { + summary.Append(" For ").Append(FormatDuration(longest)).Append(" of ").Append(total) + .Append(", tests waited for a [NotInParallel] key"); + + if (run.MostWaitedKey is { } key) + { + summary.Append(" (\"").Append(key).Append("\" the most)"); + } + + summary.Append(", which no limit changes."); + } + else if (longest == run.WaitedForLimiter) + { + summary.Append(" For ").Append(FormatDuration(longest)).Append(" of ").Append(total) + .Append(", tests waited for "); + + if (run.MostWaitedLimiter is not { } limiter) + { + summary.Append("a [ParallelLimiter]"); + } + else if (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(", not for this limit."); + } + 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"); + + if (run.MostCommonRaiseBlocker != AdaptiveRaiseBlocker.None) + { + summary.Append("; it was not raised mostly because ").Append(Describe(run.MostCommonRaiseBlocker)); + } + + 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."); + } + } + } + + /// + /// The figures behind the summary line: how long the run spent at each limit and how + /// busy the machine was. + /// + internal static string FormatDetails(IEnumerable> timeAtLimit, AdaptiveRunStatistics? statistics) + { + var details = new StringBuilder("Adaptive parallelism details: time at each limit: "); + + var first = true; + foreach (var entry in timeAtLimit) + { + if (!first) + { + details.Append(", "); + } + + first = false; + details.Append(entry.Key).Append(" for ").Append(FormatDuration(entry.Value)); + } + + if (statistics is not { } run) + { + return details.ToString(); + } + + var invariant = CultureInfo.InvariantCulture; + + // Both CPU figures, because the limit is read differently on a machine that other + // processes keep busy. + details.Append(invariant, $". The machine's CPUs were {run.MachineCpuUtilization * 100:0}% busy on average, and this process alone used {run.ProcessCpuUtilization * 100:0}% of them"); + + // Child processes are read only while the figure can change a decision, so there is + // no average over the whole run to give. + if (run.ChildProcessesMeasured > TimeSpan.Zero) + { + details.Append(invariant, $". Its child processes used {run.ChildProcessCpuUtilization * 100:0}% over the ") + .Append(FormatDuration(run.ChildProcessesMeasured)) + .Append(" they were measured"); + } + + if (run.HeldForOutsideLoad > TimeSpan.Zero) + { + 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"); + } + + return details.Append('.').ToString(); + } + + internal static AdaptiveRaiseBlocker MostCommon(TimeSpan[] timeNotRaising) + { + // From 1: index 0 is the time when nothing stood in the way of a raise. + var mostCommon = 0; + + for (var i = 1; i < timeNotRaising.Length; i++) + { + if (timeNotRaising[i] > (mostCommon == 0 ? TimeSpan.Zero : timeNotRaising[mostCommon])) + { + mostCommon = i; + } + } + + return (AdaptiveRaiseBlocker) mostCommon; + } + + internal static bool IsPutBack(AdaptiveLimitChange change) + => change is AdaptiveLimitChange.ProbeReverted + or AdaptiveLimitChange.ProbeAborted + or AdaptiveLimitChange.ProbeRevertedForFailures + or AdaptiveLimitChange.LowerReverted + or AdaptiveLimitChange.LowerNotJudged; + + internal static string FormatDuration(TimeSpan duration) + { + var seconds = (long) Math.Round(duration.TotalSeconds); + return seconds < 60 + ? string.Create(CultureInfo.InvariantCulture, $"{seconds}s") + : string.Create(CultureInfo.InvariantCulture, $"{seconds / 60}m {seconds % 60}s"); + } + + // Each reads as the end of "it was not raised mostly because ...". + internal static string Describe(AdaptiveRaiseBlocker blocker) => blocker switch + { + AdaptiveRaiseBlocker.LimitNotReached => "fewer tests were ready to run than it allows", + AdaptiveRaiseBlocker.TooFewTests => "too few tests finished to measure throughput", + AdaptiveRaiseBlocker.ThroughputNotSteady => "throughput kept changing between measurements", + AdaptiveRaiseBlocker.CpuBusy => "the CPUs had no headroom", + AdaptiveRaiseBlocker.MemoryBusy => "memory had no headroom", + AdaptiveRaiseBlocker.WaitingAfterFailedRaise => "an earlier raise did not help, or memory was short", + AdaptiveRaiseBlocker.KeepingLowerLimit => "a lower limit cost no throughput and the CPUs had been saturated", + AdaptiveRaiseBlocker.AtMaximum => "it was at the highest limit allowed", + AdaptiveRaiseBlocker.LimiterTrial => "another limit was being tried", + AdaptiveRaiseBlocker.PinnedAfterFailures => "tests failed after an earlier raise", + AdaptiveRaiseBlocker.ExplorationBudget => "earlier changes were put back, and more trials would cost the run time", + _ => blocker.ToString(), + }; + + internal static string Describe(AdaptiveLimitChange change) => change switch + { + AdaptiveLimitChange.Probe => "trying more tests at once", + AdaptiveLimitChange.ProbeReverted => "the last raise did not improve throughput", + AdaptiveLimitChange.ProbeAborted => "the last raise left the CPUs busy", + AdaptiveLimitChange.ProbeRevertedForFailures => "tests failed after the last raise; the limit will not go higher again in this run", + AdaptiveLimitChange.Recovery => "pressure eased", + AdaptiveLimitChange.MemoryPressure => "memory pressure", + AdaptiveLimitChange.CpuSaturation => "CPUs saturated; checking that fewer tests cost nothing", + 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", + _ => 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/ConstraintKeyScheduler.cs b/src/TUnit.Engine/Scheduling/ConstraintKeyScheduler.cs index 78158a09bf4..d3af5bcd752 100644 --- a/src/TUnit.Engine/Scheduling/ConstraintKeyScheduler.cs +++ b/src/TUnit.Engine/Scheduling/ConstraintKeyScheduler.cs @@ -152,11 +152,23 @@ private async Task WaitAndExecuteTestAsync( // directly, and a running test can release our keys between the loop queueing us and // this await. Awaiting that completed signal normally would run a synchronous test // body on the loop's thread and stall every test after it (#7075). + var activity = _maxParallelismLimiter.Activity; + var waitStartedAt = activity.BeginKeyWait(startSignal.Task); + + try + { #if NET8_0_OR_GREATER - await startSignal.Task.ConfigureAwait(ConfigureAwaitOptions.ForceYielding); + await startSignal.Task.ConfigureAwait(ConfigureAwaitOptions.ForceYielding); #else - await new ForceYieldingTaskAwaitable(startSignal.Task); + await new ForceYieldingTaskAwaitable(startSignal.Task); #endif + } + finally + { + // Also when the wait ends in an exception: a test left counted as waiting + // would have the summary blame a key for the rest of the run. + activity.EndKeyWait(waitStartedAt, constraintKeys); + } if (_logger.IsTraceEnabled) await _logger.LogTraceAsync($"Starting previously queued test {test.TestId} with constraint keys: {string.Join(", ", constraintKeys)}").ConfigureAwait(false); @@ -179,7 +191,18 @@ private async Task ExecuteTestAndReleaseKeysAsync( // are always running tests, never waiting on keys, so the two never deadlock. // Acquired before entering TestRunner so a dependency that reaches this test // first runs it inline instead of waiting behind a slot. - await _maxParallelismLimiter.WaitAsync(cancellationToken).ConfigureAwait(false); + var wait = _maxParallelismLimiter.WaitAsync(cancellationToken); + var counted = _maxParallelismLimiter.BeginWait(wait); + + try + { + await wait.ConfigureAwait(false); + } + finally + { + _maxParallelismLimiter.EndWait(counted); + } + test.HoldsParallelSlot = true; try { diff --git a/src/TUnit.Engine/Scheduling/ElasticLane.cs b/src/TUnit.Engine/Scheduling/ElasticLane.cs new file mode 100644 index 00000000000..995c4e117fd --- /dev/null +++ b/src/TUnit.Engine/Scheduling/ElasticLane.cs @@ -0,0 +1,343 @@ +using TUnit.Core; + +namespace TUnit.Engine.Scheduling; + +/// +/// Runs one with a set of workers that follows a limit which can +/// change while the tests run. +/// +/// +/// +/// The lane has as many workers as the limit admits tests right now, so a worker that asks +/// for a slot finds one free, and the wait completes without going through the thread pool. +/// A limit that never moves then costs what a fixed one costs. Workers for the highest limit +/// the budget could ever reach would instead queue for the slots that exist: every test +/// start would pass through that queue, which is slower than a fixed limit on a busy machine +/// (#7915). +/// +/// +/// When the limit is raised, workers are added at once. When it is lowered, a worker leaves +/// after the test it is running: a running test is never interrupted. +/// +/// +internal sealed class ElasticLane +{ + private readonly AbstractExecutableTest[] _tests; + private readonly int _mostWorkers; + private readonly ParallelLimitLock? _limiterLock; + private readonly MaxParallelismLimiter _limiter; + private readonly SemaphoreSlim? _turn; + private readonly Func _executeTest; + private readonly CancellationToken _cancellationToken; + private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly Action _onLimitChanged; + private readonly Func _work; + + // The execution context of whoever started the lane, for the workers that are added + // later. Null when its flow was suppressed there. + private ExecutionContext? _executionContext; + + // Guards _workers, _completed and _failure. Taken when a worker starts or leaves, and when + // a limit changes: never for a test. + private readonly Lock _workersLock = new(); + private int _workers; + private bool _completed; + private Exception? _failure; + + // Index of the last test a worker has taken. Past the end once every test is taken. + private int _next = -1; + + // Tests no worker will take any more, after a failure. Guarded by _workersLock. + private int _abandoned; + + private ElasticLane( + ParallelLane lane, + MaxParallelismLimiter limiter, + SemaphoreSlim? turn, + Func executeTest, + CancellationToken cancellationToken) + { + _tests = lane.Tests; + _mostWorkers = lane.Workers; + _limiterLock = lane.Limiter; + _limiter = limiter; + _turn = turn; + _executeTest = executeTest; + _cancellationToken = cancellationToken; + _onLimitChanged = AddWorkers; + _work = WorkAsync; + } + + public static Task RunAsync( + ParallelLane lane, + MaxParallelismLimiter limiter, + SemaphoreSlim? turn, + Func executeTest, + CancellationToken cancellationToken) + { + if (lane.Tests.Length == 0) + { + return Task.CompletedTask; + } + + return new ElasticLane(lane, limiter, turn, executeTest, cancellationToken).Start(); + } + + /// + /// The number of workers the lane should have right now: what its [ParallelLimiter] + /// admits, and no more than the session-wide budget has slots. + /// + private int WantedWorkers + { + get + { + var wanted = Math.Min(_limiter.CurrentLimit, _limiterLock?.CurrentLimit ?? _mostWorkers); + + // A worker whose test waits for another test has given its slot back. One more + // worker for each, so that slot is used while the lane has tests queued. They + // retire again as the waits end. Counted for the whole session, so a lane can + // have a worker more than it can use for a moment: it waits for a slot. + return Math.Max(1, wanted + _limiter.DependencyWaits); + } + } + + private Task Start() + { + // A raise is followed on the thread that changed the limit: adaptive parallelism's + // own, or the shared budget's. A worker started there would run its tests under that + // thread's context, without the AsyncLocals and the current Activity the scheduler + // had when it started this batch, and which tests got them would depend on timing. + _executionContext = ExecutionContext.Capture(); + + // What tells adaptive parallelism that tests are waiting for a limit. Counted for + // the lane's limiter when it has one, and for the session-wide budget otherwise. + // Which of the two holds a limiter's queued tests back is decided when it is asked: + // the limiter while it is full, the session-wide budget while the limiter has + // places free (AdaptiveLimiterTrials.HasQueuedTestsWithFreePlaces). + // Before the lane can be told of a limit change: a worker started by one takes a + // test off the count, which must not go below zero and hide another lane's queue. + AddBacklog(_tests.Length); + + // Subscribed before the first workers start, so no raise is missed in between. + _limiter.LimitChanged += _onLimitChanged; + _limiter.DependencyWaitStarted += _onLimitChanged; + + if (_limiterLock is not null) + { + _limiterLock.LimitChanged += _onLimitChanged; + } + + AddWorkers(); + return _completion.Task; + } + + private void AddBacklog(int tests) + { + if (_limiterLock is not null) + { + _limiterLock.AddBacklog(tests); + } + else + { + _limiter.AddBacklog(tests); + } + } + + /// + /// Starts workers up to , and no more than there are tests left + /// to take. Called at the start and each time a limit changes. + /// + private void AddWorkers() + { + lock (_workersLock) + { + if (_completed || _failure is not null) + { + return; + } + + var testsLeft = _tests.Length - 1 - Volatile.Read(ref _next); + + for (var toAdd = Math.Min(WantedWorkers - _workers, testsLeft); toAdd > 0; toAdd--) + { + _workers++; + StartWorker(); + } + } + } + + // Under the context the lane was started in, whichever thread adds the worker. + private void StartWorker() + { + if (_executionContext is { } context) + { + // A copy for each worker: on .NET Framework a captured context can be the + // argument of Run only once, and the second worker would throw. On .NET the + // copy is the context itself. + ExecutionContext.Run(context.CreateCopy(), static lane => _ = Task.Run(((ElasticLane) lane!)._work, CancellationToken.None), this); + } + else + { + _ = Task.Run(_work, CancellationToken.None); + } + } + + private async Task WorkAsync() + { + var left = false; + + try + { + while (true) + { + // Read without the lock for every test, and checked again under it only when + // the lane has more or fewer workers than it should. + var workers = Volatile.Read(ref _workers); + var wanted = WantedWorkers; + + if (workers > wanted && TryLeave()) + { + left = true; + return; + } + + if (workers < wanted) + { + // A raise is followed at once through LimitChanged. This covers a limit + // that went down and came back while the workers it retired were leaving. + AddWorkers(); + } + + var index = Interlocked.Increment(ref _next); + + if (index >= _tests.Length) + { + return; + } + + var test = _tests[index]; + + // Before the wait for a slot, not after it: from here the test is a waiter + // on the limiter, which counts those itself. When the wait is cancelled the + // test never runs, and the run is over. + AddBacklog(-1); + + // Counted as waiting for the session-wide limit while it queues, for its + // turn or for a slot. Awaited here, where a state machine already exists. + var wait = ParallelLimiterLanes.WaitForSlotAsync(_limiter, _turn, _cancellationToken); + var counted = _limiter.BeginWait(wait); + + try + { + await wait.ConfigureAwait(false); + } + finally + { + _limiter.EndWait(counted); + } + + test.HoldsParallelSlot = true; + + try + { + await _executeTest(test, _cancellationToken).ConfigureAwait(false); + } + finally + { + ParallelLimiterLanes.ReleaseSlot(test, _limiter); + } + } + } + catch (Exception exception) + { + Fail(exception); + } + finally + { + if (!left) + { + Leave(); + } + } + } + + /// + /// Takes this worker out of the lane when a lowered limit leaves it with too many. At + /// least one worker always stays, because the limit never goes below one. + /// + private bool TryLeave() + { + lock (_workersLock) + { + if (_workers <= WantedWorkers) + { + return false; + } + + _workers--; + return true; + } + } + + // TestRunner turns everything a test throws into its result, so only a cancelled wait for + // a slot arrives here. The workers stop taking tests, and the ones that are running finish. + private void Fail(Exception exception) + { + lock (_workersLock) + { + _failure ??= exception; + + // Every index up to the one read here was handed to a worker, and none after it + // will be: later increments start from the end of the tests. + var lastTaken = Interlocked.Exchange(ref _next, _tests.Length); + _abandoned += Math.Max(0, _tests.Length - 1 - lastTaken); + } + } + + private void Leave() + { + Exception? failure; + int abandoned; + + lock (_workersLock) + { + // The last worker leaves only once every test is taken, or after a failure: a + // lowered limit never takes the lane below one worker. + if (--_workers > 0 || _completed) + { + return; + } + + _completed = true; + failure = _failure; + abandoned = _abandoned; + } + + // Outside the lock, like everything that reaches into a limit: LimitChanged is + // raised by whoever changed a limit and takes this lock, so nothing of a limit's is + // called while holding it. + AddBacklog(-abandoned); + + _limiter.LimitChanged -= _onLimitChanged; + _limiter.DependencyWaitStarted -= _onLimitChanged; + + if (_limiterLock is not null) + { + _limiterLock.LimitChanged -= _onLimitChanged; + } + + // As Parallel.ForEachAsync ends: cancelled when the run was, whatever else happened. + if (_cancellationToken.IsCancellationRequested) + { + _completion.TrySetCanceled(_cancellationToken); + } + else if (failure is not null) + { + _completion.TrySetException(failure); + } + else + { + _completion.TrySetResult(true); + } + } +} diff --git a/src/TUnit.Engine/Scheduling/MaxParallelismLimiter.cs b/src/TUnit.Engine/Scheduling/MaxParallelismLimiter.cs index 4fa7e57e8e7..d190d29d885 100644 --- a/src/TUnit.Engine/Scheduling/MaxParallelismLimiter.cs +++ b/src/TUnit.Engine/Scheduling/MaxParallelismLimiter.cs @@ -68,7 +68,21 @@ internal sealed class MaxParallelismLimiter private int _requestedLimit; private int _ceiling = int.MaxValue; + // This process's part of a shared budget when the limit is adaptive, and whether the + // part is what last set the limit: true until adaptive parallelism sets one of its own. + // Guarded by _resizeLock. + private int _share = int.MaxValue; + private bool _limitSetByShare; + private long _slotChanges; + private int _backlog; + private int _dependencyWaits; + + /// + /// Raised after the number of slots has changed, on the thread that changed it. Each + /// set of workers follows it, so a budget that never moves has as many workers as slots. + /// + public event Action? LimitChanged; /// /// The cap used when nothing configures one, and for "unlimited" (0). A higher cap gains @@ -117,6 +131,51 @@ public MaxParallelismLimiter(Func resolveLimits) /// public int AvailableSlots => _semaphore.Value.AvailableSlots; + /// + /// The number of slots tests hold right now. + /// + public int HeldSlots => _semaphore.Value.HeldSlots; + + /// + /// The number of tests waiting for a slot right now. A fixed budget does not count. + /// + public int Waiting => _semaphore.Value.Waiting; + + /// + /// Counts the caller as waiting for a slot when has to queue. + /// The caller awaits the task itself and hands the result to . + /// + public bool BeginWait(Task wait) => _semaphore.Value.BeginWait(wait); + + /// What returned for the wait. + public void EndWait(bool counted) => _semaphore.Value.EndWait(counted); + + /// + /// The number of tests with no [ParallelLimiter] of their own that are queued behind this + /// budget's workers and have not started. Counted only under a budget that can be resized. + /// Tests queued behind a limiter are counted by its lock. + /// + public int Backlog => Volatile.Read(ref _backlog); + + public void AddBacklog(int tests) => Interlocked.Add(ref _backlog, tests); + + /// + /// Whether every slot is held while more tests could start at once: the budget, and + /// nothing else, is what holds them back. + /// + /// + /// Whether tests are queued behind a [ParallelLimiter] that has places free. Those wait + /// for a slot of this budget: their lane has no more workers than the budget has slots. + /// + public bool HasUnmetDemand(bool limiterTestsQueued = false) + => AvailableSlots == 0 && (Backlog > 0 || Waiting > 0 || limiterTestsQueued); + + /// + /// What the scheduler is doing that no parallel limit can change, for the adaptive + /// parallelism summary. + /// + public ParallelismActivity Activity { get; } = new(); + /// /// The number of slots a resizable budget has had released since the session started: one /// per finished test. A fixed budget does not count. @@ -140,21 +199,106 @@ public MaxParallelismLimiter(Func resolveLimits) /// public void ReleaseWhileWaiting() => _semaphore.Value.Release(count: false); + /// + /// The number of tests that have given their slot back to wait for another test that + /// is already running, and are still waiting. Each of them keeps a worker of its lane + /// busy without using a slot, so a lane may have that many workers more than slots. + /// + public int DependencyWaits => Volatile.Read(ref _dependencyWaits); + + /// + /// Raised when a test starts such a wait. A lane has as many workers as there are slots, + /// so without another worker the slot that was just given back would stay free while + /// the lane still has tests queued. + /// + public event Action? DependencyWaitStarted; + + /// + /// Counts a test that has given its slot back with to + /// wait for another test. Paired with . + /// + /// + /// Not for a test that waits for its [ParallelLimiter]: another worker of its lane + /// would find the same limiter full and give its slot back too. + /// + public void BeginDependencyWait() + { + Interlocked.Increment(ref _dependencyWaits); + DependencyWaitStarted?.Invoke(); + } + + public void EndDependencyWait() => Interlocked.Decrement(ref _dependencyWaits); + /// /// Resizes the budget, clamped to , and returns the new number of /// slots, which may hold below the limit asked for. Growing takes /// effect at once. Shrinking takes free slots at once and the rest as running tests /// finish: a running test is never interrupted. /// - public int SetLimit(int limit) + public int SetLimit(int limit) => SetLimit(limit, expectedSlotChanges: null, out _, out _); + + /// + /// Resizes the budget as does, and says what this call did. + /// + /// The limit asked for. + /// + /// What was when the limit was decided, or null to + /// resize whatever happened since. With another count, the number of slots has been + /// changed from elsewhere in the meantime, and the call changes nothing: a limit decided + /// before this process's part of a shared budget shrank would otherwise undo the part, + /// and the process would keep the slots it was meant to hand over. + /// + /// The number of slots just before this call. + /// + /// Whether this call changed the number of slots, which then added one to + /// . Decided under the lock every resize takes, so a change that + /// another thread made just before is never taken for this call's. + /// + public int SetLimit(int limit, long? expectedSlotChanges, out int previousSlots, out bool changed) { var limits = _limits.Value; var semaphore = _semaphore.Value; + int slots; + lock (_resizeLock) { + previousSlots = semaphore.CurrentLimit; + + if (expectedSlotChanges is { } expected && expected != _slotChanges) + { + changed = false; + return previousSlots; + } + _requestedLimit = Math.Min(Math.Max(limit, limits.Minimum), limits.Maximum); - return Apply(semaphore); + + // From here the limit is adaptive parallelism's, also when it happens to be the + // same number as the part. + _limitSetByShare = false; + slots = Apply(semaphore, out changed); + } + + if (changed) + { + LimitChanged?.Invoke(); + } + + return slots; + } + + /// + /// The number of slots and how many times it has changed, read together. A resize adds + /// to the count before it changes the slots, so two separate reads can pair a new count + /// with the number of slots from before it. + /// + public (long SlotChanges, int Slots) ReadSlots() + { + var semaphore = _semaphore.Value; + + lock (_resizeLock) + { + return (_slotChanges, semaphore.CurrentLimit); } } @@ -166,19 +310,171 @@ public int SetCeiling(int ceiling) { var semaphore = _semaphore.Value; + int slots; + bool changed; + lock (_resizeLock) { _ceiling = Math.Max(1, ceiling); - return Apply(semaphore); + slots = Apply(semaphore, out changed); } + + if (changed) + { + LimitChanged?.Invoke(); + } + + return slots; + } + + /// + /// Sets this process's part of a budget it shares with other test processes, and returns + /// the new number of slots. + /// + /// + /// + /// A fixed limit is held to its part for as long as the other processes run: nothing + /// measures what more would do. + /// + /// + /// 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 + /// 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) + { + var limits = _limits.Value; + + if (!limits.IsAdaptive) + { + return SetCeiling(share); + } + + var semaphore = _semaphore.Value; + int slots; + bool changed; + + lock (_resizeLock) + { + share = Math.Max(share, limits.Minimum); + + if (share < _share) + { + if (_requestedLimit > share) + { + _requestedLimit = share; + _limitSetByShare = true; + } + } + else if (share > _share && _limitSetByShare) + { + // Still where the part put it: nothing has moved it since, so it follows + // the part back up, as far as the limit the run starts at. That does not + // wait for adaptive parallelism, which may not be running (its warm-up, or + // after an error) or may be held back by busy CPUs that the process which + // just left was the cause of. A flag, not a comparison with the part: a + // limit that adaptive parallelism lowered to the same number is its own, + // and stays down. + _requestedLimit = Math.Max(_requestedLimit, Math.Min(share, limits.Initial)); + } + + _share = share; + slots = Apply(semaphore, out changed); + } + + if (changed) + { + LimitChanged?.Invoke(); + } + + return slots; + } + + /// + /// The limit to fall back to when adaptive parallelism stops after an error: the limit + /// the run starts at, and no more than this process's part of a budget it shares with + /// 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. + /// + public int FallbackLimit + { + get + { + var limits = _limits.Value; + + lock (_resizeLock) + { + return Math.Max(limits.Minimum, Math.Min(limits.Initial, _share)); + } + } + } + + /// + /// Has the limit follow this process's part of a shared budget again, when it has one: + /// for a limit that adaptive parallelism has stopped moving, after an error. Setting the + /// fallback limit made the limit adaptive parallelism's own, which a part that grows + /// does not raise, and the process would keep too few slots after the others had finished. + /// + public void FollowShare() + { + lock (_resizeLock) + { + _limitSetByShare = _share != int.MaxValue; + } + } + + /// + /// Gives this process its whole limit back after it has left a budget it shared with + /// other test processes, and returns the new number of slots. A fixed limit loses its + /// ceiling. An adaptive limit that had come down to its part returns to the limit the + /// run starts at: nothing else would raise it when adaptive parallelism is not running + /// yet, or has stopped. + /// + public int ClearShare() + { + var limits = _limits.Value; + + if (!limits.IsAdaptive) + { + return SetCeiling(int.MaxValue); + } + + var semaphore = _semaphore.Value; + int slots; + bool changed; + + lock (_resizeLock) + { + if (_share != int.MaxValue) + { + _requestedLimit = Math.Max(_requestedLimit, limits.Initial); + } + + _share = int.MaxValue; + _limitSetByShare = false; + slots = Apply(semaphore, out changed); + } + + if (changed) + { + LimitChanged?.Invoke(); + } + + return slots; } // Called with _resizeLock held. - private int Apply(ResizableSemaphore semaphore) + private int Apply(ResizableSemaphore semaphore, out bool changed) { var slots = Math.Min(_requestedLimit, _ceiling); + changed = slots != semaphore.CurrentLimit; - if (slots == semaphore.CurrentLimit) + if (!changed) { return slots; } diff --git a/src/TUnit.Engine/Scheduling/ParallelLimiterLanes.cs b/src/TUnit.Engine/Scheduling/ParallelLimiterLanes.cs index 292e7126e36..44238869c3d 100644 --- a/src/TUnit.Engine/Scheduling/ParallelLimiterLanes.cs +++ b/src/TUnit.Engine/Scheduling/ParallelLimiterLanes.cs @@ -4,10 +4,15 @@ namespace TUnit.Engine.Scheduling; /// -/// Tests that are started by one set of workers. is the most of them -/// that are started at once. +/// Tests that are started by one set of workers. /// -internal readonly record struct ParallelLane(AbstractExecutableTest[] Tests, int Workers); +/// The tests, in the order they should start. +/// +/// The most of them that are started at once. For a lane whose limit can change this is the +/// number it starts with, and follows the limit from there. +/// +/// The lock of the lane's [ParallelLimiter], when it has one that is known. +internal readonly record struct ParallelLane(AbstractExecutableTest[] Tests, int Workers, ParallelLimitLock? Limiter = null); /// /// Runs a batch of tests under the session-wide parallel budget, with a separate set of @@ -20,6 +25,10 @@ namespace TUnit.Engine.Scheduling; /// Tests with no limiter then cannot start until the limited ones are nearly done (#7887). /// A lane has as many workers as its limiter admits tests, so a worker that takes a slot /// finds the limiter free, and the remaining slots go to the other lanes. +/// +/// The same holds while limits change: a lane under a limit that can move runs on an +/// , which adds and retires workers as the limit does. +/// /// internal static class ParallelLimiterLanes { @@ -30,7 +39,8 @@ internal static class ParallelLimiterLanes /// /// The tests to run, in the order they should start. /// The most tests the budget ever admits at once. - public static List? Split(AbstractExecutableTest[] tests, int maxParallelism) + /// Where the lock of each [ParallelLimiter] is found, so a lane can follow a limit that changes. + public static List? Split(AbstractExecutableTest[] tests, int maxParallelism, ParallelLimitLockProvider? lockProvider = null) { var firstLimited = -1; @@ -49,7 +59,7 @@ internal static class ParallelLimiterLanes } // The limiter's lock is keyed by type (ParallelLimitLockProvider), so the lanes are too. - var workersByType = new Dictionary(); + var workersByType = new Dictionary(); var limitedByType = new Dictionary>(); var unlimited = new List(tests.Length); @@ -72,11 +82,11 @@ internal static class ParallelLimiterLanes if (!workersByType.TryGetValue(type, out var workers)) { - workers = GetWorkers(parallelLimiter, maxParallelism); + workers = GetWorkers(parallelLimiter, maxParallelism, lockProvider); workersByType.Add(type, workers); } - if (workers == 0) + if (workers.Workers == 0) { unlimited.Add(test); continue; @@ -101,7 +111,8 @@ internal static class ParallelLimiterLanes // nothing removed enumerates in insertion order). foreach (var limited in limitedByType) { - lanes.Add(new ParallelLane(limited.Value.ToArray(), workersByType[limited.Key])); + var (workers, limiterLock) = workersByType[limited.Key]; + lanes.Add(new ParallelLane(limited.Value.ToArray(), workers, limiterLock)); } if (unlimited.Count > 0) @@ -126,41 +137,44 @@ internal static class ParallelLimiterLanes } /// - /// The number of workers for a limiter's lane, or 0 when its tests belong with the tests - /// that have no limiter. + /// The number of workers a limiter's lane starts with and the limiter's lock, or 0 workers + /// when its tests belong with the tests that have no limiter. /// // Read once per type, from the first test: the limiter's lock is created the same way, so // a limit that differs between instances of one type is not supported there either. - private static int GetWorkers(IParallelLimit parallelLimiter, int maxParallelism) + private static (int Workers, ParallelLimitLock? Limiter) GetWorkers(IParallelLimit parallelLimiter, int maxParallelism, ParallelLimitLockProvider? lockProvider) { int limit; - var adaptive = false; + ParallelLimitLock? limiterLock; try { limit = parallelLimiter.Limit; -#pragma warning disable TUNITEXP001 // Adaptive parallel limits are experimental - if (limit > 0 && parallelLimiter is IAdaptiveParallelLimit adaptiveLimit) + // A limit that is not positive fails each test in TestRunner, which reads it again. + if (limit <= 0) { - // Workers for the highest limit it can reach. Those beyond its current limit - // wait for the limiter without holding a slot (#7890). - var maximum = Math.Max(adaptiveLimit.MaximumLimit, limit); - adaptive = maximum > Math.Max(1, Math.Min(adaptiveLimit.MinimumLimit, limit)); - limit = adaptive ? Math.Min(maximum, maxParallelism) : limit; + return default; } -#pragma warning restore TUNITEXP001 + + limiterLock = lockProvider?.GetLock(parallelLimiter); } catch { // User code. TestRunner reads the limit again for each test and reports the failure there. - return 0; + return default; } - // A limit that is not positive fails each test in TestRunner. A fixed limit the budget - // never reaches holds no test back, so its tests need no lane of their own. An - // adaptive one can come down below the budget later, so its tests always get a lane. - return limit <= 0 || (!adaptive && limit >= maxParallelism) ? 0 : limit; + if (limiterLock is { IsAdaptive: true }) + { + // The lane starts with workers for the limit as it is now and follows it from + // there. A limit above the budget still gets a lane: it can come down below it later. + return (Math.Min(limiterLock.CurrentLimit, maxParallelism), limiterLock); + } + + // A fixed limit the budget never reaches holds no test back, so its tests need no + // lane of their own. + return limit >= maxParallelism ? default : (limit, limiterLock); } /// @@ -171,18 +185,18 @@ public static Task RunAsync( AbstractExecutableTest[] tests, MaxParallelismLimiter limiter, Func executeTest, - CancellationToken cancellationToken) + CancellationToken cancellationToken, + ParallelLimitLockProvider? lockProvider = null) { - // With a budget that is resized this is the highest limit, and the workers beyond - // the current limit wait for a slot. + // The highest limit a budget that is resized can reach. A lane under such a budget + // has workers for the limit as it is now, never for this one. var maxParallelism = limiter.MaxParallelism; - if (Split(tests, maxParallelism) is not { } lanes) + if (Split(tests, maxParallelism, lockProvider) is not { } lanes) { - // A budget that is resized has more workers than slots, so they wait in turn. With - // a fixed budget the workers number the slots, and none of them queues for long. - var turn = limiter.Limits.IsResizable ? new SemaphoreSlim(1, 1) : null; - return RunLaneAsync(new ParallelLane(tests, maxParallelism), limiter, turn, executeTest, cancellationToken); + // The workers number the slots, whether or not the budget is resized, so none of + // them queues for long and they need not wait in turn. + return RunLaneAsync(new ParallelLane(tests, maxParallelism), limiter, turn: null, executeTest, cancellationToken); } var laneTasks = new Task[lanes.Count]; @@ -240,7 +254,6 @@ public static void ReleaseSlot(AbstractExecutableTest test, MaxParallelismLimite } } -#if NET private static Task RunLaneAsync( ParallelLane lane, MaxParallelismLimiter limiter, @@ -248,6 +261,25 @@ private static Task RunLaneAsync( Func executeTest, CancellationToken cancellationToken) { +#if NET + if (!limiter.Limits.IsResizable && lane.Limiter is not { IsAdaptive: true }) + { + return RunFixedLaneAsync(lane, limiter, turn, executeTest, cancellationToken); + } +#endif + + // A limit that can change. Also netstandard2.0, which has no Parallel.ForEachAsync. + return ElasticLane.RunAsync(lane, limiter, turn, executeTest, cancellationToken); + } + +#if NET + private static Task RunFixedLaneAsync( + ParallelLane lane, + MaxParallelismLimiter limiter, + SemaphoreSlim? turn, + Func executeTest, + CancellationToken cancellationToken) + { // MaxDegreeOfParallelism bounds this lane's workers; the shared limiter bounds the // session, because the other lanes, the keyed phase and dynamic batches run // concurrently with this one. @@ -274,41 +306,5 @@ private static Task RunLaneAsync( } ); } -#else - // Fallback for netstandard2.0: manual bounded concurrency using the shared limiter. - private static Task RunLaneAsync( - ParallelLane lane, - MaxParallelismLimiter limiter, - SemaphoreSlim? turn, - Func executeTest, - CancellationToken cancellationToken) - { - var tests = lane.Tests; - var next = -1; - var workers = new Task[Math.Min(lane.Workers, tests.Length)]; - - for (var i = 0; i < workers.Length; i++) - { - workers[i] = Task.Run(async () => - { - while (Interlocked.Increment(ref next) is var index && index < tests.Length) - { - var test = tests[index]; - await WaitForSlotAsync(limiter, turn, cancellationToken).ConfigureAwait(false); - test.HoldsParallelSlot = true; - try - { - await executeTest(test, cancellationToken).ConfigureAwait(false); - } - finally - { - ReleaseSlot(test, limiter); - } - } - }, CancellationToken.None); - } - - return Task.WhenAll(workers); - } #endif } diff --git a/src/TUnit.Engine/Scheduling/ParallelismActivity.cs b/src/TUnit.Engine/Scheduling/ParallelismActivity.cs new file mode 100644 index 00000000000..aa4269b4a1e --- /dev/null +++ b/src/TUnit.Engine/Scheduling/ParallelismActivity.cs @@ -0,0 +1,120 @@ +using System.Collections.Concurrent; +using System.Diagnostics; + +namespace TUnit.Engine.Scheduling; + +/// +/// What the scheduler is doing that no parallel limit can change: tests that must run one at +/// a time. Adaptive parallelism reads it to say what held a run back, because a limit that +/// tests are not waiting for is not worth changing (#7915). +/// +/// +/// Nothing is recorded until is set, which adaptive parallelism does +/// when it starts, so a run without it pays for one read of a field. +/// +internal sealed class ParallelismActivity +{ + private volatile bool _isObserved; + private int _sequentialPhase; + private int _waitingForKeys; + + // Total time tests have waited for each [NotInParallel] key, in Stopwatch ticks. + private ConcurrentDictionary? _keyWaitTicks; + + /// + /// Whether anything reads this, so the scheduler should record. + /// + public bool IsObserved + { + get => _isObserved; + set => _isObserved = value; + } + + /// + /// Whether the tests marked [NotInParallel] without a key are running, one at a time. + /// + public bool InSequentialPhase => Volatile.Read(ref _sequentialPhase) > 0; + + /// + /// The number of tests waiting for a [NotInParallel] key that another test holds. + /// + public int WaitingForKeys => Volatile.Read(ref _waitingForKeys); + + public void EnterSequentialPhase() => Interlocked.Increment(ref _sequentialPhase); + + public void ExitSequentialPhase() => Interlocked.Decrement(ref _sequentialPhase); + + /// + /// Records that a test starts waiting for its keys. Returns the timestamp to hand to + /// , or 0 when nothing is recorded. + /// + /// What the test waits for: completed once its keys are free. + public long BeginKeyWait(Task startSignal) + { + // A signal that has already completed is no wait: the keys were released between + // the test being queued and this call. Counted, a sample taken across the yield + // that follows would name a key that held nothing back. + if (!_isObserved || startSignal.IsCompleted) + { + return 0; + } + + Interlocked.Increment(ref _waitingForKeys); + return Stopwatch.GetTimestamp(); + } + + public void EndKeyWait(long startedAt, IReadOnlyList keys) + { + if (startedAt == 0) + { + return; + } + + Interlocked.Decrement(ref _waitingForKeys); + + var waited = Stopwatch.GetTimestamp() - startedAt; + var totals = _keyWaitTicks + ?? Interlocked.CompareExchange(ref _keyWaitTicks, new ConcurrentDictionary(), null) + ?? _keyWaitTicks!; + + // Which of its keys a test waited for is not known, so each one is charged. + for (var i = 0; i < keys.Count; i++) + { +#if NET + // The overload that takes the argument, so nothing is allocated for each key. + totals.AddOrUpdate(keys[i], static (_, wait) => wait, static (_, total, wait) => total + wait, waited); +#else + totals.AddOrUpdate(keys[i], waited, (_, total) => total + waited); +#endif + } + } + + /// + /// The [NotInParallel] key that tests waited for the longest in total, or null + /// when none waited. + /// + public (string Key, TimeSpan Waited)? MostWaitedKey + { + get + { + if (_keyWaitTicks is not { } totals) + { + return null; + } + + (string Key, long Ticks)? most = null; + + foreach (var entry in totals) + { + if (most is null || entry.Value > most.Value.Ticks) + { + most = (entry.Key, entry.Value); + } + } + + return most is { } found + ? (found.Key, TimeSpan.FromSeconds((double) found.Ticks / Stopwatch.Frequency)) + : null; + } + } +} diff --git a/src/TUnit.Engine/Scheduling/SharedParallelBudget.cs b/src/TUnit.Engine/Scheduling/SharedParallelBudget.cs index 4f89b4f840f..f63b56bbe90 100644 --- a/src/TUnit.Engine/Scheduling/SharedParallelBudget.cs +++ b/src/TUnit.Engine/Scheduling/SharedParallelBudget.cs @@ -2,6 +2,7 @@ using System.Text; using TUnit.Core.Logging; using TUnit.Engine.Configuration; +using TUnit.Engine.Logging; namespace TUnit.Engine.Scheduling; @@ -17,6 +18,15 @@ namespace TUnit.Engine.Scheduling; /// that finish. /// /// +/// A process with a fixed limit is held to its part. With adaptive parallelism the part is +/// where the process starts, and where it comes back down to when another process joins: the +/// limit moves from there as the machine allows (see ). +/// +/// +/// A test process that a member starts, from one of its tests, does not join: it runs +/// inside that test, and as a member it would take a part away from the process that started it. +/// +/// /// A process is a member of the budget while it runs tests. It shows that by holding a file /// in the budget's directory open with no sharing. The operating system closes the file when /// the process ends, however it ends, so a crashed process gives its part back without any @@ -38,6 +48,10 @@ internal sealed class SharedParallelBudget : IDisposable private readonly int _budget; private readonly SharedParallelBudgetMembership _membership; + // What the member variable held when this process started: set when it was started by a + // member of another budget. Put back when this process leaves its own. + private string? _inheritedMemberOf; + // Never disposed: the refresh thread may still be waiting on it after Dispose returns. private readonly ManualResetEventSlim _stopSignal = new(false); private Thread? _thread; @@ -95,6 +109,15 @@ internal static string GetDirectory(string name) return null; } + // Set by a member for the processes it starts, which inherit its environment. The + // processes of one test run are started side by side by a script or a CI job, which + // names the budget and does not set this. + if (string.Equals(Environment.GetEnvironmentVariable(EnvironmentConstants.SharedParallelBudgetMember), name, StringComparison.Ordinal)) + { + logger.LogDebug($"Shared parallel budget '{name}': this process was started by a test process that shares the budget, so it does not take a part of it"); + return null; + } + #if NET // No threads and no other processes there. if (OperatingSystem.IsBrowser() || OperatingSystem.IsWasi()) @@ -119,7 +142,7 @@ internal static string GetDirectory(string name) { // Nothing has been handed to the caller to dispose yet. membership.Dispose(); - limiter.SetCeiling(int.MaxValue); + limiter.ClearShare(); throw; } } @@ -129,6 +152,9 @@ internal static string GetDirectory(string name) return null; } + budget._inheritedMemberOf = Environment.GetEnvironmentVariable(EnvironmentConstants.SharedParallelBudgetMember); + Environment.SetEnvironmentVariable(EnvironmentConstants.SharedParallelBudgetMember, name); + // A dedicated thread: the part must follow the other processes while every pool // thread is busy or blocked. var thread = new Thread(budget.Run) @@ -195,11 +221,15 @@ private void Run() _logger.LogDebug($"Shared parallel budget '{_name}' stopped after an error; this process left the budget and uses its whole limit again: {ex}"); _membership.Dispose(); + // No longer a member, so a test process started from here on is not started by + // one of this budget. It may still run under a member of another. + Environment.SetEnvironmentVariable(EnvironmentConstants.SharedParallelBudgetMember, _inheritedMemberOf); + lock (_stateLock) { if (!_stopped) { - _limiter.SetCeiling(int.MaxValue); + _limiter.ClearShare(); } } } @@ -222,27 +252,35 @@ private void SetPart(int part, int members) var previous = _part; _part = part; - _limiter.SetCeiling(part); + _limiter.SetShare(part); _lowestPart = Math.Min(_lowestPart, part); _highestPart = Math.Max(_highestPart, part); _mostMembers = Math.Max(_mostMembers, members); if (part != previous && _logger.IsEnabled(LogLevel.Debug)) { - _logger.LogDebug($"Shared parallel budget '{_name}': {members} test {(members == 1 ? "process shares" : "processes share")} a budget of {_budget}, so this one runs at most {part} tests in parallel"); + _logger.LogDebug($"Shared parallel budget '{_name}': {members} test {(members == 1 ? "process shares" : "processes share")} a budget of {_budget}, so this one's part is {part} tests in parallel"); } } } - internal static string FormatSummary(string name, int budget, int lowestPart, int highestPart, int mostMembers) + /// The budget's name. + /// The number of parallel tests the members split. + /// The smallest part this process had. + /// 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) { - var parts = lowestPart == highestPart - ? $"at most {lowestPart} tests in parallel" - : $"at most {lowestPart} to {highestPart} tests in parallel"; + var range = lowestPart == highestPart ? $"{lowestPart}" : $"{lowestPart} to {highestPart}"; + + var parts = adaptive + ? $"had a part of {range} tests in parallel, which is where its adaptive limit starts" + : $"ran at most {range} tests in parallel"; return mostMembers <= 1 - ? $"Shared parallel budget '{name}': no other test process shared the budget of {budget}, so this one ran {parts}" - : $"Shared parallel budget '{name}': up to {mostMembers} test processes shared a budget of {budget}, and this one ran {parts}"; + ? $"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}"; } public void Dispose() @@ -264,15 +302,19 @@ 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); + summary = FormatSummary(_name, _budget, _lowestPart, _highestPart, _mostMembers, _limiter.Limits.IsAdaptive); } // The other processes take this one's part once its file is closed. _membership.Dispose(); + // Processes started from here on are not started by a member of this budget. The + // value this process inherited is put back: it may run under a member of another. + Environment.SetEnvironmentVariable(EnvironmentConstants.SharedParallelBudgetMember, _inheritedMemberOf); + // Information, not Debug: a failure that depends on how many tests ran at once can // only be understood from a log that says how many did. - _logger.LogInformation(summary); + _logger.LogSessionMessage(summary); } } diff --git a/src/TUnit.Engine/Scheduling/TestRunner.cs b/src/TUnit.Engine/Scheduling/TestRunner.cs index ee12bb9e997..6e34d447b19 100644 --- a/src/TUnit.Engine/Scheduling/TestRunner.cs +++ b/src/TUnit.Engine/Scheduling/TestRunner.cs @@ -140,12 +140,18 @@ private ValueTask AwaitRunningTestAsync(Task execution, AbstractExecutableTest? private async ValueTask AwaitWithoutSlotAsync(Task execution, AbstractExecutableTest slotOwner, CancellationToken cancellationToken) { + // This test's worker is busy without a slot from here. Its lane has as many workers + // as there are slots, so it is told to start another: the slot that was given back + // would otherwise stay free while the lane still has tests queued. + _maxParallelismLimiter.BeginDependencyWait(); + try { await execution.ConfigureAwait(false); } finally { + _maxParallelismLimiter.EndDependencyWait(); await TakeSlotAgainAsync(slotOwner, cancellationToken).ConfigureAwait(false); } } @@ -166,7 +172,18 @@ private bool TryGiveSlotBack(AbstractExecutableTest? slotOwner) // not return one it no longer has. private async ValueTask TakeSlotAgainAsync(AbstractExecutableTest slotOwner, CancellationToken cancellationToken) { - await _maxParallelismLimiter.WaitAsync(cancellationToken).ConfigureAwait(false); + var wait = _maxParallelismLimiter.WaitAsync(cancellationToken); + var counted = _maxParallelismLimiter.BeginWait(wait); + + try + { + await wait.ConfigureAwait(false); + } + finally + { + _maxParallelismLimiter.EndWait(counted); + } + slotOwner.HoldsParallelSlot = true; } @@ -224,7 +241,21 @@ private async ValueTask ExecuteTestInternalAsync(AbstractExecutableTest test, Ab // below: tests queued behind that lock hold their slots, so a test // must never wait for a slot while it is inside the lock. var gaveSlotBack = TryGiveSlotBack(slotOwner); - await limiter.EnterAsync(cancellationToken).ConfigureAwait(false); + + // Counted as waiting for the limiter, which is how adaptive + // parallelism knows that this limit holds tests back. + var entering = limiter.EnterAsync(cancellationToken); + var counted = limiter.BeginWait(entering); + + try + { + await entering.ConfigureAwait(false); + } + finally + { + limiter.EndWait(counted); + } + acquiredLimiter = limiter; if (gaveSlotBack) diff --git a/src/TUnit.Engine/Scheduling/TestScheduler.cs b/src/TUnit.Engine/Scheduling/TestScheduler.cs index 3d141ead80f..ab5f5d73e18 100644 --- a/src/TUnit.Engine/Scheduling/TestScheduler.cs +++ b/src/TUnit.Engine/Scheduling/TestScheduler.cs @@ -117,13 +117,20 @@ public async Task ScheduleAndExecuteAsync( // which covers an adaptive limit that has grown since. using var starvationMonitor = ThreadPoolStarvationMonitor.Start(_maxParallelismLimiter.Limits.Initial, _logger); - // Disposed before the starvation monitor, and only after the session hooks have run. - using var adaptiveParallelism = AdaptiveParallelismController.Start(_maxParallelismLimiter, _logger, _parallelLimitLockProvider); + // A [ParallelLimiter] with a fixed limit keeps it as a ceiling under adaptive + // parallelism: the limit can come down while its tests overload the machine, and + // never goes above what was declared. Set before any lock is created. + _parallelLimitLockProvider.FixedLimitsAreCeilings = _maxParallelismLimiter.Limits.IsAdaptive; // Joined only now, so a process that is still building or discovering tests takes - // no part of a budget it shares with other test processes. + // no part of a budget it shares with other test processes. Before adaptive + // parallelism starts, which takes the limit over from this process's part. using var sharedParallelBudget = SharedParallelBudget.Start(_maxParallelismLimiter, _logger); + // Disposed before the shared budget and the starvation monitor, and only after the + // session hooks have run. + using var adaptiveParallelism = AdaptiveParallelismController.Start(_maxParallelismLimiter, _logger, _parallelLimitLockProvider); + // Initialize static properties before tests run try { @@ -664,7 +671,7 @@ private Task ExecuteTestsAsync( // (ProcessorCount * 2) there rather than being a separate code path. // Tests with a [ParallelLimiter] get workers of their own, so the ones waiting for // their limiter do not keep the other tests from starting. - return ParallelLimiterLanes.RunAsync(tests, _maxParallelismLimiter, _executeScheduledTest ??= ExecuteScheduledTestAsync, cancellationToken); + return ParallelLimiterLanes.RunAsync(tests, _maxParallelismLimiter, _executeScheduledTest ??= ExecuteScheduledTestAsync, cancellationToken, _parallelLimitLockProvider); } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCode("Test execution involves reflection for hooks and initialization")] @@ -672,12 +679,23 @@ private async Task ExecuteSequentiallyAsync( AbstractExecutableTest[] tests, CancellationToken cancellationToken) { - foreach (var test in tests) + // Read by adaptive parallelism: while these run one at a time, no limit holds a test back. + var activity = _maxParallelismLimiter.Activity; + activity.EnterSequentialPhase(); + + try { - // Stop on a cancelled run instead of walking every remaining test into a cancelled - // lock wait. The tests left behind are reported once the run winds down. - cancellationToken.ThrowIfCancellationRequested(); - await ExecuteScheduledTestAsync(test, cancellationToken).ConfigureAwait(false); + foreach (var test in tests) + { + // Stop on a cancelled run instead of walking every remaining test into a cancelled + // lock wait. The tests left behind are reported once the run winds down. + cancellationToken.ThrowIfCancellationRequested(); + await ExecuteScheduledTestAsync(test, cancellationToken).ConfigureAwait(false); + } + } + finally + { + activity.ExitSequentialPhase(); } } diff --git a/src/TUnit.Engine/Scheduling/WindowsProcessTreeReader.cs b/src/TUnit.Engine/Scheduling/WindowsProcessTreeReader.cs index b98fa3a74c5..0be358fd3d7 100644 --- a/src/TUnit.Engine/Scheduling/WindowsProcessTreeReader.cs +++ b/src/TUnit.Engine/Scheduling/WindowsProcessTreeReader.cs @@ -185,6 +185,18 @@ public static bool TryReadTimes(int processId, out long created, out long cpuTic return false; } + // A process that has exited stays in the snapshot, with its times readable, + // for as long as anything holds a handle to it: its parent, antivirus, a + // debugger. It uses no CPU any more, and counted as running it would keep an + // exited child among this process's children (#7909). Asked through its exit + // code: the exit time GetProcessTimes returns is undefined while the process + // runs, and a live child skipped by mistake would have its CPU time left out. + // A process that cannot be asked counts as running, as it did before. + if (GetExitCodeProcess(handle, out var exitCode) && exitCode != StillActive) + { + return false; + } + cpuTicks = kernelTime + userTime; return true; } @@ -212,6 +224,13 @@ public static bool TryReadTimes(int processId, out long created, out long cpuTic [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GetProcessTimes(IntPtr process, out long created, out long exited, out long kernelTime, out long userTime); + // What GetExitCodeProcess reports for a process that has not exited. + private const uint StillActive = 259; + + [DllImport("kernel32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetExitCodeProcess(IntPtr process, out uint exitCode); + [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CloseHandle(IntPtr handle); diff --git a/tests/TUnit.UnitTests/AdaptiveLimiterPolicyTests.cs b/tests/TUnit.UnitTests/AdaptiveLimiterPolicyTests.cs deleted file mode 100644 index 560c9d8f7c8..00000000000 --- a/tests/TUnit.UnitTests/AdaptiveLimiterPolicyTests.cs +++ /dev/null @@ -1,264 +0,0 @@ -using TUnit.Engine.Scheduling; - -namespace TUnit.UnitTests; - -public class AdaptiveLimiterPolicyTests -{ - // 100 ms tests: each place in the limiter completes ten tests per second. - private const double TestsPerSecondPerPlace = 10; - - [Test] - public async Task Raises_To_The_Maximum_While_Throughput_Follows_The_Limit() - { - var simulation = new Simulation(initial: 4, minimum: 2, maximum: 16); - - simulation.Run(TimeSpan.FromSeconds(60)); - - await Assert.That(simulation.Policy.Limit).IsEqualTo(16); - await Assert.That(simulation.Changes.Select(x => x.Change)).IsEquivalentTo( - [ - AdaptiveLimiterChange.Raise, - AdaptiveLimiterChange.Raise, - AdaptiveLimiterChange.Raise, - AdaptiveLimiterChange.Raise, - ]); - } - - [Test] - public async Task Reverts_A_Raise_That_Brings_No_Throughput_Then_Tries_Fewer() - { - // Something behind the limiter serves 3 tests at a time, whatever the limit. - var simulation = new Simulation(initial: 4, minimum: 2, maximum: 16) - { - Throughput = limit => Math.Min(limit, 3) * TestsPerSecondPerPlace, - }; - - simulation.RunUntilChanges(3); - - await Assert.That(simulation.Changes).IsEquivalentTo( - [ - new AdaptiveLimiterDecision(6, AdaptiveLimiterChange.Raise), - new AdaptiveLimiterDecision(4, AdaptiveLimiterChange.RaiseReverted), - new AdaptiveLimiterDecision(3, AdaptiveLimiterChange.Lower), - ]); - - // Three at a time complete as many, so the lower limit is kept. Two at a time do not. - simulation.RunUntilChanges(5); - - await Assert.That(simulation.Changes.Skip(3)).IsEquivalentTo( - [ - new AdaptiveLimiterDecision(2, AdaptiveLimiterChange.Lower), - new AdaptiveLimiterDecision(3, AdaptiveLimiterChange.LowerReverted), - ]); - } - - [Test] - public async Task Steps_Down_Are_Judged_Against_Throughput_Before_The_First_Of_Them() - { - // Each step down costs a little: 100 tests per second at 12, 93 at 9, 87 at 6. The - // second step loses under 7.5% of the first one's result, but 13% of where it began. - var simulation = new Simulation(initial: 12, minimum: 2, maximum: 13) - { - Throughput = limit => limit >= 12 ? 100 : limit >= 9 ? 93 : 87, - }; - - simulation.RunUntilChanges(5); - - await Assert.That(simulation.Changes).IsEquivalentTo( - [ - new AdaptiveLimiterDecision(13, AdaptiveLimiterChange.Raise), - new AdaptiveLimiterDecision(12, AdaptiveLimiterChange.RaiseReverted), - new AdaptiveLimiterDecision(9, AdaptiveLimiterChange.Lower), - new AdaptiveLimiterDecision(6, AdaptiveLimiterChange.Lower), - new AdaptiveLimiterDecision(9, AdaptiveLimiterChange.LowerReverted), - ]); - } - - [Test] - public async Task Abandoning_A_Raise_That_Tests_Failed_During_Still_Caps_The_Limit() - { - var simulation = new Simulation(initial: 4, minimum: 2, maximum: 16); - - simulation.RunUntilChanges(1); - - var decision = simulation.Policy.Abandon(failedTests: 1); - - await Assert.That(decision).IsEqualTo(new AdaptiveLimiterDecision(4, AdaptiveLimiterChange.RaiseRevertedForFailures)); - - simulation.Run(TimeSpan.FromMinutes(10)); - - await Assert.That(simulation.Policy.Limit).IsEqualTo(4); - } - - [Test] - public async Task Abandoning_Starts_The_Next_Lowering_From_A_Fresh_Measurement() - { - // 100 tests per second at 12 and 93 at 9: the first lowering is kept. The lowest - // limit is 6, so nothing is tried below it. - var simulation = new Simulation(initial: 12, minimum: 6, maximum: 13) - { - Throughput = limit => limit >= 12 ? 100 : limit >= 9 ? 93 : 87, - }; - - simulation.RunUntilChanges(3); - await Assert.That(simulation.Policy.Limit).IsEqualTo(9); - - // Let the lowering be kept, then the session limit changes, and with it what the - // tests can do: 93 at 9 is now the measurement to beat, and 87 at 6 is within 7.5% of it. - for (var i = 0; i < 2400 && simulation.Policy.IsBusy; i++) - { - simulation.Step(); - } - - simulation.Policy.Abandon(); - simulation.RunUntilChanges(4); - - // Long enough for its verdict. Judged against the 100 from before the change, it - // would be put back. - simulation.Run(TimeSpan.FromSeconds(8)); - - await Assert.That(simulation.Changes.Skip(3)).IsEquivalentTo([new AdaptiveLimiterDecision(6, AdaptiveLimiterChange.Lower)]); - } - - [Test] - public async Task Does_Not_Lower_Before_A_Raise_Was_Rejected() - { - var simulation = new Simulation(initial: 8, minimum: 2, maximum: 8); - - simulation.Run(TimeSpan.FromSeconds(60)); - - await Assert.That(simulation.Changes).IsEmpty(); - } - - [Test] - public async Task Undoes_A_Raise_At_Once_When_Tests_Start_Failing_And_Never_Raises_Past_It_Again() - { - var simulation = new Simulation(initial: 4, minimum: 2, maximum: 16); - - // The resource behind the limiter rejects the work of more than 4 tests at once. - simulation.FailuresPerSample = limit => limit > 4 ? 1 : 0; - - simulation.Run(TimeSpan.FromMinutes(10)); - - await Assert.That(simulation.Changes).IsEquivalentTo( - [ - new AdaptiveLimiterDecision(6, AdaptiveLimiterChange.Raise), - new AdaptiveLimiterDecision(4, AdaptiveLimiterChange.RaiseRevertedForFailures), - ]); - } - - [Test] - public async Task Failures_That_Were_There_Before_A_Raise_Do_Not_Undo_It() - { - var simulation = new Simulation(initial: 4, minimum: 2, maximum: 6) - { - // The suite has tests that fail at any limit. - FailuresPerSample = _ => 1, - }; - - simulation.Run(TimeSpan.FromSeconds(30)); - - await Assert.That(simulation.Changes).IsEquivalentTo([new AdaptiveLimiterDecision(6, AdaptiveLimiterChange.Raise)]); - } - - [Test] - public async Task Does_Not_Start_A_Trial_While_Another_Limit_Is_On_Trial() - { - var simulation = new Simulation(initial: 4, minimum: 2, maximum: 16) { MayStartTrial = false }; - - simulation.Run(TimeSpan.FromSeconds(30)); - - await Assert.That(simulation.Changes).IsEmpty(); - await Assert.That(simulation.Policy.IsBusy).IsFalse(); - } - - [Test] - public async Task Does_Not_Raise_When_The_Limit_Is_Not_What_Holds_Tests_Back() - { - var simulation = new Simulation(initial: 4, minimum: 2, maximum: 16) { LimitReached = false }; - - simulation.Run(TimeSpan.FromSeconds(30)); - - await Assert.That(simulation.Changes).IsEmpty(); - } - - [Test] - public async Task Waits_Longer_Before_Each_Raise_After_A_Rejected_One() - { - // The lowest limit is the starting one, so only raises are tried. - var simulation = new Simulation(initial: 4, minimum: 4, maximum: 16) - { - Throughput = _ => 4 * TestsPerSecondPerPlace, - }; - - simulation.Run(TimeSpan.FromSeconds(60)); - - // Raises at about 2 s, 15 s (10 s hold) and 38 s (20 s hold). - await Assert.That(simulation.Changes.Count(x => x.Change == AdaptiveLimiterChange.Raise)).IsEqualTo(3); - } - - [Test] - public async Task Abandoning_A_Trial_Puts_The_Limit_Back() - { - var simulation = new Simulation(initial: 4, minimum: 2, maximum: 16); - - simulation.RunUntilChanges(1); - await Assert.That(simulation.Policy.Limit).IsEqualTo(6); - - var decision = simulation.Policy.Abandon(); - - await Assert.That(decision).IsEqualTo(new AdaptiveLimiterDecision(4, AdaptiveLimiterChange.TrialAbandoned)); - await Assert.That(simulation.Policy.Abandon().Change).IsEqualTo(AdaptiveLimiterChange.None); - } - - private sealed class Simulation(int initial, int minimum, int maximum) - { - private static readonly TimeSpan SampleInterval = TimeSpan.FromMilliseconds(250); - private double _partialTests; - - public AdaptiveLimiterPolicy Policy { get; } = new(initial, minimum, maximum); - - public List Changes { get; } = []; - - public Func Throughput { get; set; } = limit => limit * TestsPerSecondPerPlace; - - public Func FailuresPerSample { get; set; } = _ => 0; - - public bool LimitReached { get; set; } = true; - - public bool MayStartTrial { get; set; } = true; - - public void Step() - { - _partialTests += Throughput(Policy.Limit) * SampleInterval.TotalSeconds; - var finished = (long) _partialTests; - _partialTests -= finished; - - var decision = Policy.OnSample( - new AdaptiveLimiterSample(SampleInterval, finished, FailuresPerSample(Policy.Limit), LimitReached), - MayStartTrial); - - if (decision.Change != AdaptiveLimiterChange.None) - { - Changes.Add(decision); - } - } - - public void Run(TimeSpan duration) - { - for (var elapsed = TimeSpan.Zero; elapsed < duration; elapsed += SampleInterval) - { - Step(); - } - } - - // Simulated time, so the bound is on steps: ten simulated minutes. - public void RunUntilChanges(int count) - { - for (var i = 0; i < 2400 && Changes.Count < count; i++) - { - Step(); - } - } - } -} diff --git a/tests/TUnit.UnitTests/AdaptiveLimiterTrialsTests.cs b/tests/TUnit.UnitTests/AdaptiveLimiterTrialsTests.cs index 8d284b2afe1..9c64eb4802e 100644 --- a/tests/TUnit.UnitTests/AdaptiveLimiterTrialsTests.cs +++ b/tests/TUnit.UnitTests/AdaptiveLimiterTrialsTests.cs @@ -10,6 +10,16 @@ public class AdaptiveLimiterTrialsTests { private static readonly TimeSpan SampleInterval = TimeSpan.FromMilliseconds(250); + // A machine with room to spare. Each limiter adds its own tests to the reading. + private static readonly AdaptiveSample Machine = new( + SampleInterval, + CpuUtilization: 0.2, + ProcessCpuUtilization: 0.2, + MemoryLoad: 0.3, + QueueDelay: TimeSpan.Zero, + CompletedTests: 0, + LimitReached: false); + [Test] public async Task A_Fixed_Limiter_Is_Not_Adaptive_And_Counts_Nothing() { @@ -85,15 +95,17 @@ public async Task Raises_A_Limiter_Whose_Tests_Finish_Faster_With_A_Higher_Limit for (var i = 0; i < 240; i++) { await limiter.StepAsync(); - trials.Update(SampleInterval, sessionLimitBusy: false, sessionLimitChanged: false); + trials.Update(Machine, sessionLimitBusy: false, sessionLimitChanged: false); } await Assert.That(limiter.Lock.CurrentLimit).IsEqualTo(16); trials.Stop(); - await Assert.That(logger.Messages.Where(x => x.Level == LogLevel.Information).Select(x => x.Message)) - .IsEquivalentTo(["Adaptive [ParallelLimiter] FourToSixteen: the limit ranged from 4 to 16 over 4 changes and ended at 16"]); + var summary = logger.Messages.Where(x => x.Level == LogLevel.Information).Select(x => 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"); } [Test] @@ -106,7 +118,7 @@ public async Task Holds_Every_Limiter_While_The_Session_Limit_Is_On_Trial() for (var i = 0; i < 240; i++) { await limiter.StepAsync(); - trials.Update(SampleInterval, sessionLimitBusy: true, sessionLimitChanged: false); + trials.Update(Machine, sessionLimitBusy: true, sessionLimitChanged: false); } await Assert.That(limiter.Lock.CurrentLimit).IsEqualTo(4); @@ -127,7 +139,7 @@ public async Task Only_One_Limiter_Is_On_Trial_At_A_Time_And_They_Take_Turns() { await first.StepAsync(); await second.StepAsync(); - trials.Update(SampleInterval, sessionLimitBusy: false, sessionLimitChanged: false); + trials.Update(Machine, sessionLimitBusy: false, sessionLimitChanged: false); // From the start of each trial to the end of its measurement, not only the // update in which a limit changes. @@ -149,12 +161,12 @@ public async Task A_Change_Of_The_Session_Limit_Abandons_A_Trial() for (var i = 0; i < 240 && limiter.Lock.CurrentLimit == 4; i++) { await limiter.StepAsync(); - trials.Update(SampleInterval, sessionLimitBusy: false, sessionLimitChanged: false); + trials.Update(Machine, sessionLimitBusy: false, sessionLimitChanged: false); } await Assert.That(limiter.Lock.CurrentLimit).IsEqualTo(6); - trials.Update(SampleInterval, sessionLimitBusy: false, sessionLimitChanged: true); + trials.Update(Machine, sessionLimitBusy: false, sessionLimitChanged: true); await Assert.That(limiter.Lock.CurrentLimit).IsEqualTo(4); @@ -162,7 +174,7 @@ public async Task A_Change_Of_The_Session_Limit_Abandons_A_Trial() for (var i = 0; i < 240 && limiter.Lock.CurrentLimit == 4; i++) { await limiter.StepAsync(); - trials.Update(SampleInterval, sessionLimitBusy: false, sessionLimitChanged: false); + trials.Update(Machine, sessionLimitBusy: false, sessionLimitChanged: false); } await Assert.That(limiter.Lock.CurrentLimit).IsEqualTo(6); @@ -179,24 +191,26 @@ public async Task A_Test_That_Fails_During_A_Raise_Still_Caps_The_Limit_When_The for (var i = 0; i < 240 && limiter.Lock.CurrentLimit == 4; i++) { await limiter.StepAsync(); - trials.Update(SampleInterval, sessionLimitBusy: false, sessionLimitChanged: false); + trials.Update(Machine, sessionLimitBusy: false, sessionLimitChanged: false); } // A test fails during the raise, in the same update as the session limit changes. await limiter.StepAsync(failOne: true); - trials.Update(SampleInterval, sessionLimitBusy: false, sessionLimitChanged: true); + trials.Update(Machine, sessionLimitBusy: false, sessionLimitChanged: true); for (var i = 0; i < 2400; i++) { await limiter.StepAsync(); - trials.Update(SampleInterval, sessionLimitBusy: false, sessionLimitChanged: false); + trials.Update(Machine, sessionLimitBusy: false, sessionLimitChanged: false); } await Assert.That(limiter.Lock.CurrentLimit).IsEqualTo(4); trials.Stop(); - await Assert.That(logger.Messages.Where(x => x.Level == LogLevel.Information).Select(x => x.Message)) - .IsEquivalentTo(["Adaptive [ParallelLimiter] FourToSixteen: the limit ranged from 4 to 6 over 2 changes (1 put back because it did not help) and ended at 4"]); + var summary = logger.Messages.Where(x => x.Level == LogLevel.Information).Select(x => 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"); } [Test] @@ -209,7 +223,7 @@ public async Task Stop_Can_Put_Every_Limit_Back_And_Later_Updates_Change_Nothing for (var i = 0; i < 240 && limiter.Lock.CurrentLimit == 4; i++) { await limiter.StepAsync(); - trials.Update(SampleInterval, sessionLimitBusy: false, sessionLimitChanged: false); + trials.Update(Machine, sessionLimitBusy: false, sessionLimitChanged: false); } trials.Stop(resetLimits: true); @@ -218,20 +232,491 @@ public async Task Stop_Can_Put_Every_Limit_Back_And_Later_Updates_Change_Nothing for (var i = 0; i < 240; i++) { await limiter.StepAsync(); - trials.Update(SampleInterval, sessionLimitBusy: false, sessionLimitChanged: false); + trials.Update(Machine, sessionLimitBusy: false, sessionLimitChanged: false); } await Assert.That(limiter.Lock.CurrentLimit).IsEqualTo(4); } [Test] - public async Task Summary_Of_A_Limit_That_Never_Moved_And_Of_One_Put_Back() + public async Task Summary_Says_Where_The_Limit_Went_And_Why_It_Was_Not_Raised() + { + var moved = new AdaptiveLimiterSummary("Hosts", StartLimit: 4, CurrentLimit: 6, LowestLimit: 3, HighestLimit: 9, Changes: 4, ChangesPutBack: 2, + CanBeRaised: true, DeclaredAdaptive: true, Waited: TimeSpan.FromSeconds(75), AdaptiveRaiseBlocker.TooFewTests); + + await Assert.That(AdaptiveLimiterTrials.FormatSummary(moved)).IsEqualTo( + "[ParallelLimiter] Hosts: the limit went from 4 to 6 (lowest 3, highest 9, 4 changes, 2 put back). " + + "Tests waited for it for 1m 15s; it was not raised mostly because too few tests finished to measure throughput."); + + var idle = new AdaptiveLimiterSummary("Hosts", 4, 4, 4, 4, Changes: 0, ChangesPutBack: 0, CanBeRaised: true, DeclaredAdaptive: true, Waited: TimeSpan.Zero); + + await Assert.That(AdaptiveLimiterTrials.FormatSummary(idle)).IsEqualTo("[ParallelLimiter] Hosts: the limit stayed at 4."); + await Assert.That(idle.IsWorthReporting(TimeSpan.FromMinutes(5))).IsFalse(); + await Assert.That(moved.IsWorthReporting(TimeSpan.FromHours(5))).IsTrue(); + } + + [Test] + public async Task Summary_Of_A_Declared_Limit_That_Tests_Waited_For_Says_That_It_Is_Never_Raised() + { + // The ModularPipelines report in #7915: an assembly-wide limit of 2 was what bound + // the run, and the summary blamed the CPUs. + var summary = new AdaptiveLimiterSummary("PipelineTestParallelLimit", 2, 2, 2, 2, Changes: 0, ChangesPutBack: 0, + CanBeRaised: false, DeclaredAdaptive: false, Waited: TimeSpan.FromSeconds(150), CpuUtilizationWhileWaiting: 0.3); + + // An adaptive limiter whose highest limit is where it starts: the bound to change + // is its own, not the limiter as a whole. + await Assert.That(AdaptiveLimiterTrials.FormatSummary(summary with { DeclaredAdaptive = true })).IsEqualTo( + "[ParallelLimiter] PipelineTestParallelLimit: the limit stayed at 2. " + + "Tests waited for it for 2m 30s while the CPUs were 30% busy. " + + "Its MaximumLimit is not above the limit it starts at, so it could not be raised: set a higher MaximumLimit to let it."); + + // Lowered by adaptive parallelism during the run: part of the wait is its own + // doing, and the line says so before any advice about the limit as declared. + await Assert.That(AdaptiveLimiterTrials.FormatSummary(summary with { LowestLimit = 1, Changes = 2, ChangesPutBack = 1 })).IsEqualTo( + "[ParallelLimiter] PipelineTestParallelLimit: the limit moved and ended back at 2 (lowest 1, highest 2, 2 changes, 1 put back). " + + "Tests waited for it for 2m 30s while the CPUs were 30% busy. " + + "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."); + + await Assert.That(summary.IsWorthReporting(TimeSpan.FromSeconds(159))).IsTrue(); + await Assert.That(AdaptiveLimiterTrials.FormatSummary(summary)).IsEqualTo( + "[ParallelLimiter] PipelineTestParallelLimit: 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."); + } + + [Test] + public async Task A_Declared_Limit_That_Tests_Waited_For_A_Little_Does_Not_Get_A_Line_On_Every_Run() + { + // A deliberate cap, such as one database connection: its owner can do nothing with + // advice to raise it, so it is reported only when the wait is a share of the run + // worth acting on. + var cap = new AdaptiveLimiterSummary("SingleDbConnection", 1, 1, 1, 1, Changes: 0, ChangesPutBack: 0, + CanBeRaised: false, DeclaredAdaptive: false, Waited: TimeSpan.FromSeconds(20)); + + await Assert.That(cap.IsWorthReporting(TimeSpan.FromMinutes(10))).IsFalse(); + await Assert.That(cap.IsWorthReporting(TimeSpan.FromMinutes(3))).IsTrue(); + + // A limit that can be raised says why it was not, whatever the share. + await Assert.That((cap with { CanBeRaised = true }).IsWorthReporting(TimeSpan.FromMinutes(10))).IsTrue(); + } + + [Test] + public async Task A_Declared_Limit_Is_A_Ceiling_That_Is_Never_Raised() + { + var provider = new ParallelLimitLockProvider { FixedLimitsAreCeilings = true }; + var logger = new RecordingLogger(); + var trials = new AdaptiveLimiterTrials(provider, logger); + var limiter = new SimulatedLimiter(provider.GetLock(new FixedLimit())); + + await Assert.That(limiter.Lock.IsAdaptive).IsTrue(); + await Assert.That(limiter.Lock.Maximum).IsEqualTo(4); + + // Throughput follows the limit and the machine is idle: an adaptive limiter would go up. + for (var i = 0; i < 480; i++) + { + await limiter.StepAsync(); + trials.Update(Machine, sessionLimitBusy: false, sessionLimitChanged: false); + } + + 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(); + 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."); + } + + [Test] + public async Task A_Declared_Limit_Of_One_Is_Followed_So_It_Can_Be_Named_As_What_Held_Tests_Back() + { + // It cannot go lower, and is never raised, but a run can spend most of its time + // waiting for it all the same. + var provider = new ParallelLimitLockProvider { FixedLimitsAreCeilings = true }; + var logger = new RecordingLogger(); + var trials = new AdaptiveLimiterTrials(provider, logger); + var limiter = new SimulatedLimiter(provider.GetLock(new LimitOfOne())); + + await Assert.That(limiter.Lock.IsAdaptive).IsFalse(); + await Assert.That(limiter.Lock.IsObserved).IsTrue(); + + for (var i = 0; i < 40; i++) + { + await limiter.StepAsync(); + trials.Update(Machine, sessionLimitBusy: false, sessionLimitChanged: false); + + await Assert.That(trials.FindBindingLimiter()).IsSameReferenceAs(limiter.Lock); + } + + await Assert.That(limiter.Lock.CurrentLimit).IsEqualTo(1); + + trials.Stop(); + + var summary = logger.Messages.Where(x => x.Level == LogLevel.Information).Select(x => 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."); + } + + [Test] + public async Task A_Limit_Is_Not_Lowered_Without_Pressure_However_Throughput_Looks() + { + // The ModularPipelines report in #7915: a limiter went from 2 to 1 on a machine that + // was 19% busy, because a raise had been put back, and the run took a third longer. + var provider = new ParallelLimitLockProvider(); + var trials = new AdaptiveLimiterTrials(provider, new RecordingLogger()); + + // Something behind the limiter serves 3 tests at a time, so no raise brings anything + // and fewer tests at once complete as many. + var limiter = new SimulatedLimiter(provider.GetLock(new FourToSixteen())) { Throughput = limit => Math.Min(limit, 3) * 10 }; + var lowest = 4; + + for (var i = 0; i < 2400; i++) + { + await limiter.StepAsync(); + trials.Update(Machine, sessionLimitBusy: false, sessionLimitChanged: false); + lowest = Math.Min(lowest, limiter.Lock.CurrentLimit); + } + + await Assert.That(lowest).IsEqualTo(4); + } + + [Test] + public async Task Saturated_Cpus_Lower_The_Limiter_That_Most_Running_Tests_Are_Inside() + { + // The Reservoir report in #7915: tests behind a limiter each start a child process, + // those saturate the CPUs, and the session-wide limit was lowered, which changed + // nothing for tests that the limiter already held back. + var provider = new ParallelLimitLockProvider { FixedLimitsAreCeilings = true }; + var trials = new AdaptiveLimiterTrials(provider, new RecordingLogger(), processorCount: 4); + // Four processors' worth of work, whatever the limit: fewer tests at once lose nothing. + var limiter = new SimulatedLimiter(provider.GetLock(new FixedLimitOfEight())) { Throughput = _ => 40 }; + + // Saturated by this process and its child processes, which use all four processors + // however many tests run. + var saturated = Machine with { CpuUtilization = 1.0, ProcessCpuUtilization = 1.0, QueueDelay = TimeSpan.FromSeconds(1), OwnCores = 4 }; + var wasOwner = false; + + for (var i = 0; i < 480; i++) + { + await limiter.StepAsync(); + + // Every test that runs in the session is inside the limiter. + var owner = trials.FindPressureOwner(runningTests: limiter.Lock.HeldPlaces); + wasOwner |= ReferenceEquals(owner, limiter.Lock); + + trials.Update(saturated, sessionLimitBusy: false, sessionLimitChanged: false, owner); + } + + // Below one test per processor too: each test can use several processors, so four + // of them can saturate four as well as eight did. + await Assert.That(wasOwner).IsTrue(); + await Assert.That(limiter.Lock.CurrentLimit).IsLessThan(4); + } + + [Test] + public async Task A_Limiter_At_Or_Below_The_Processor_Count_Is_Lowered_For_Its_Own_Load() + { + // Eight processors and a limiter of four whose tests each use several of them, such + // as browsers. With a floor of one test per processor the limiter could never go + // lower, and the pressure went to the session-wide limit, which relieves nothing. + var provider = new ParallelLimitLockProvider { FixedLimitsAreCeilings = true }; + var trials = new AdaptiveLimiterTrials(provider, new RecordingLogger(), processorCount: 8); + var limiter = new SimulatedLimiter(provider.GetLock(new FixedLimit())) { Throughput = _ => 40 }; + var saturated = Machine with { CpuUtilization = 1.0, ProcessCpuUtilization = 1.0, QueueDelay = TimeSpan.FromSeconds(1), OwnCores = 8 }; + + for (var i = 0; i < 240 && limiter.Lock.CurrentLimit == 4; i++) + { + await limiter.StepAsync(); + trials.Update(saturated, sessionLimitBusy: false, sessionLimitChanged: false, trials.FindPressureOwner(runningTests: limiter.Lock.HeldPlaces)); + } + + await Assert.That(limiter.Lock.CurrentLimit).IsEqualTo(3); + } + + [Test] + public async Task A_Limiter_That_Would_Not_Lower_Now_Does_Not_Take_The_Pressure_From_The_Session_Limit() + { + // The run has just started: no lowering for saturated CPUs yet, for any limit. Named + // as the owner all the same, the limiter would keep the session-wide limit from + // acting while it does nothing itself. + var provider = new ParallelLimitLockProvider { FixedLimitsAreCeilings = true }; + var trials = new AdaptiveLimiterTrials(provider, new RecordingLogger(), processorCount: 4); + var limiter = new SimulatedLimiter(provider.GetLock(new FixedLimitOfEight())) { Throughput = _ => 40 }; + var saturated = Machine with { CpuUtilization = 1.0, ProcessCpuUtilization = 1.0, QueueDelay = TimeSpan.FromSeconds(1), OwnCores = 4 }; + + // Four seconds in: throughput is measured, and the startup hold of ten has not passed. + for (var i = 0; i < 16; i++) + { + await limiter.StepAsync(); + trials.Update(saturated, sessionLimitBusy: false, sessionLimitChanged: false); + } + + await Assert.That(trials.FindPressureOwner(runningTests: limiter.Lock.HeldPlaces)).IsNull(); + + // Once it could start a lowering, the pressure is its own. + for (var i = 0; i < 40; i++) + { + await limiter.StepAsync(); + trials.Update(saturated, sessionLimitBusy: false, sessionLimitChanged: false); + } + + await Assert.That(trials.FindPressureOwner(runningTests: limiter.Lock.HeldPlaces)).IsSameReferenceAs(limiter.Lock); + } + + [Test] + public async Task A_Limiter_That_Appears_Late_In_The_Run_Does_Not_Wait_Out_The_Startup_Again() + { + var provider = new ParallelLimitLockProvider { FixedLimitsAreCeilings = true }; + var trials = new AdaptiveLimiterTrials(provider, new RecordingLogger(), processorCount: 4); + var saturated = Machine with { CpuUtilization = 1.0, ProcessCpuUtilization = 1.0, QueueDelay = TimeSpan.FromSeconds(1), OwnCores = 4 }; + + // Twenty seconds of the run pass before the limiter's first test. + for (var i = 0; i < 80; i++) + { + trials.Update(saturated, sessionLimitBusy: false, sessionLimitChanged: false); + } + + var limiter = new SimulatedLimiter(provider.GetLock(new FixedLimitOfEight())) { Throughput = _ => 40 }; + + // Two windows to measure throughput, then the lowering: about two seconds, where + // the startup hold alone would be ten. + for (var i = 0; i < 16 && limiter.Lock.CurrentLimit == 8; i++) + { + await limiter.StepAsync(); + trials.Update(saturated, sessionLimitBusy: false, sessionLimitChanged: false, trials.FindPressureOwner(runningTests: limiter.Lock.HeldPlaces)); + } + + await Assert.That(limiter.Lock.CurrentLimit).IsEqualTo(6); + } + + [Test] + public async Task A_Limiters_Wait_Is_Counted_In_A_Sample_In_Which_The_Session_Limit_Changed() + { + var provider = new ParallelLimitLockProvider { FixedLimitsAreCeilings = true }; + var logger = new RecordingLogger(); + var trials = new AdaptiveLimiterTrials(provider, logger); + var limiter = new SimulatedLimiter(provider.GetLock(new FixedLimit())); + + // The session-wide limit changes in every sample, so every one is discarded as a + // measurement. The tests waited for the limiter all the same. + for (var i = 0; i < 40; i++) + { + await limiter.StepAsync(); + trials.Update(Machine, sessionLimitBusy: false, sessionLimitChanged: true); + } + + trials.Stop(); + + var summary = logger.Messages.Where(x => x.Level == LogLevel.Information).Select(x => x.Message).Single(); + await Assert.That(summary).StartsWith("[ParallelLimiter] FixedLimit: the limit stayed at 4. Tests waited for it for 10s"); + } + + [Test] + public async Task A_Limiter_That_Cannot_Go_Lower_Does_Not_Take_The_Pressure_From_The_Session_Limit() + { + // A limiter whose lowest limit is the one it is at. As the owner of the pressure it + // could not relieve the CPUs, and the session-wide limit, which could, would be + // told to leave them alone. + var provider = new ParallelLimitLockProvider(); + var trials = new AdaptiveLimiterTrials(provider, new RecordingLogger(), processorCount: 8); + var limiter = new SimulatedLimiter(provider.GetLock(new EightAtLeast())) { Throughput = _ => 40 }; + var saturated = Machine with { CpuUtilization = 1.0, ProcessCpuUtilization = 1.0, QueueDelay = TimeSpan.FromSeconds(1), OwnCores = 8 }; + + // Long enough for everything that only delays a lowering to have passed. + for (var i = 0; i < 120; i++) + { + await limiter.StepAsync(); + trials.Update(saturated, sessionLimitBusy: false, sessionLimitChanged: false); + } + + // Eight of twelve running tests are inside it: more than the share that makes an owner. + await Assert.That(limiter.Lock.HeldPlaces).IsEqualTo(8); + await Assert.That(trials.FindPressureOwner(runningTests: 12)).IsNull(); + } + + [Test] + public async Task No_Limiter_Takes_The_Pressure_While_Another_Limiter_Is_On_Trial() + { + // Limiter A holds most of the running tests and is ready to lower. Limiter B is + // being raised. Only one limit changes at a time, so A cannot start its lowering: + // named as the owner, it would take the pressure from the session-wide limit and + // nothing would lower. + var provider = new ParallelLimitLockProvider { FixedLimitsAreCeilings = true }; + var trials = new AdaptiveLimiterTrials(provider, new RecordingLogger(), processorCount: 4); + var a = new SimulatedLimiter(provider.GetLock(new FixedLimitOfEight())) { Throughput = _ => 40 }; + var b = new SimulatedLimiter(provider.GetLock(new FourToThousand())); + var checkedWhileBusy = 0; + + for (var i = 0; i < 400; i++) + { + await a.StepAsync(); + await b.StepAsync(); + trials.Update(Machine, sessionLimitBusy: false, sessionLimitChanged: false); + + // Past the startup hold, so A is ready whenever its measurements are. + if (i > 48 && trials.BusyLimiters == 1) + { + checkedWhileBusy++; + await Assert.That(trials.FindPressureOwner(runningTests: a.Lock.HeldPlaces)).IsNull(); + } + } + + // B, whose throughput follows its limit, was on trial for part of the run. + await Assert.That(checkedWhileBusy).IsGreaterThan(0); + await Assert.That(a.Lock.CurrentLimit).IsEqualTo(8); + } + + [Test] + public async Task A_Limiter_Keeps_The_Pressure_For_A_Few_Samples_In_Which_It_Is_Not_Full() + { + // Short tests: some samples find the limiter between one test ending and the next + // starting. Ownership that came and went with every sample would leave neither the + // limiter nor the session-wide limit with enough saturated samples in a row to act. + var provider = new ParallelLimitLockProvider { FixedLimitsAreCeilings = true }; + var trials = new AdaptiveLimiterTrials(provider, new RecordingLogger(), processorCount: 4); + var limiter = new SimulatedLimiter(provider.GetLock(new FixedLimitOfEight())) { Throughput = _ => 40 }; + + for (var i = 0; i < 56; i++) + { + await limiter.StepAsync(); + trials.Update(Machine, sessionLimitBusy: false, sessionLimitChanged: false); + } + + await Assert.That(trials.FindPressureOwner(runningTests: 8)).IsSameReferenceAs(limiter.Lock); + + // One place short of full still counts as full. + limiter.Lock.Exit(testFailed: false); + await Assert.That(trials.FindPressureOwner(runningTests: 7)).IsSameReferenceAs(limiter.Lock); + + // Further from full, it keeps the pressure for a few samples, and then no longer. + limiter.Lock.Exit(testFailed: false); + limiter.Lock.Exit(testFailed: false); + + for (var i = 0; i < AdaptiveLimiterTrials.PressureOwnerHoldSamples; i++) + { + await Assert.That(trials.FindPressureOwner(runningTests: 5)).IsSameReferenceAs(limiter.Lock); + } + + await Assert.That(trials.FindPressureOwner(runningTests: 5)).IsNull(); + } + + [Test] + public async Task A_Limiter_Of_Slow_Tests_Is_Not_Lowered_On_The_Cpu_Time_Of_The_Whole_Process() + { + // Slow tests behind a limiter, beside tests outside it. Lowered, the limiter frees + // session slots that the other tests take, so the process uses as much CPU time as + // before: judged by that, the lowering would be kept every time and relieve nothing. + var provider = new ParallelLimitLockProvider { FixedLimitsAreCeilings = true }; + var trials = new AdaptiveLimiterTrials(provider, new RecordingLogger(), processorCount: 4); + var limiter = new SimulatedLimiter(provider.GetLock(new FixedLimitOfEight())) { Throughput = _ => 0.2 }; + var saturated = Machine with { CpuUtilization = 1.0, ProcessCpuUtilization = 1.0, QueueDelay = TimeSpan.FromSeconds(1), OwnCores = 4 }; + + for (var i = 0; i < 480; i++) + { + await limiter.StepAsync(); + + var owner = trials.FindPressureOwner(runningTests: limiter.Lock.HeldPlaces); + + // Never its pressure: it has no measurement of its own to judge a lowering by, + // so the session-wide limit keeps the pressure. + await Assert.That(owner).IsNull(); + + trials.Update(saturated, sessionLimitBusy: false, sessionLimitChanged: false, owner); + } + + await Assert.That(limiter.Lock.CurrentLimit).IsEqualTo(8); + } + + [Test] + public async Task No_Limiter_Takes_The_Pressure_While_The_Session_Limit_Is_Being_Measured() + { + // No limiter starts a lowering while the session-wide limit is on trial. Named as + // the owner all the same, it would make the session-wide limit forget the + // saturation it has seen, and neither would act. + var provider = new ParallelLimitLockProvider { FixedLimitsAreCeilings = true }; + var trials = new AdaptiveLimiterTrials(provider, new RecordingLogger(), processorCount: 4); + var limiter = new SimulatedLimiter(provider.GetLock(new FixedLimitOfEight())) { Throughput = _ => 40 }; + var saturated = Machine with { CpuUtilization = 1.0, ProcessCpuUtilization = 1.0, QueueDelay = TimeSpan.FromSeconds(1), OwnCores = 4 }; + + // Past the startup hold, with throughput measured: ready to lower. + for (var i = 0; i < 56; i++) + { + await limiter.StepAsync(); + trials.Update(saturated, sessionLimitBusy: true, sessionLimitChanged: false); + } + + var running = limiter.Lock.HeldPlaces; + + await Assert.That(trials.FindPressureOwner(running, sessionLimitBusy: true)).IsNull(); + await Assert.That(trials.FindPressureOwner(running, sessionLimitBusy: false)).IsSameReferenceAs(limiter.Lock); + } + + [Test] + public async Task An_Adaptive_Limiter_With_No_Room_Between_Its_Bounds_Is_Followed_And_Stays_Pinned() + { + // MinimumLimit == MaximumLimit == Limit. It was not followed at all, so it had no + // line in the summary when tests waited for it. Its bounds are the user's: the + // limit is documented not to go below MinimumLimit, so it is never lowered. + var pinned = ParallelLimitLock.Create(new PinnedAtFour(), fixedLimitIsCeiling: true); + + await Assert.That(pinned.IsObserved).IsTrue(); + await Assert.That(pinned.IsDeclaredAdaptive).IsTrue(); + await Assert.That(pinned.Minimum).IsEqualTo(4); + await Assert.That(pinned.Maximum).IsEqualTo(4); + await Assert.That(pinned.SetLimit(1)).IsEqualTo(4); + + // Without adaptive parallelism it stays exactly as declared. + var plain = ParallelLimitLock.Create(new PinnedAtFour()); + + await Assert.That(plain.IsObserved).IsFalse(); + await Assert.That(plain.Minimum).IsEqualTo(4); + + // And bounds that do leave room are the user's, with or without it. + var ranged = ParallelLimitLock.Create(new FourToSixteen(), fixedLimitIsCeiling: true); + + await Assert.That(ranged.Minimum).IsEqualTo(2); + await Assert.That(ranged.Maximum).IsEqualTo(16); + } + + [Test] + public async Task A_Limiter_That_Is_Not_Full_Does_Not_Take_The_Pressure_From_The_Session_Limit() { - await Assert.That(AdaptiveLimiterTrials.FormatSummary("Hosts", 4, 4, 4, changes: 0, changesPutBack: 0)) - .IsEqualTo("Adaptive [ParallelLimiter] Hosts: the limit stayed at 4"); + // A session-wide limit of 8 and a limiter that admits 16: all eight running tests + // are inside the limiter, but only because the session-wide limit admits eight. A + // cut of the limiter to 12 would stop none of them. + var provider = new ParallelLimitLockProvider(); + var trials = new AdaptiveLimiterTrials(provider, new RecordingLogger(), processorCount: 4); + var limiterLock = provider.GetLock(new SixteenToThirtyTwo()); + + for (var i = 0; i < 8; i++) + { + await Assert.That(await limiterLock.TryEnterAsync(CancellationToken.None)).IsTrue(); + } - await Assert.That(AdaptiveLimiterTrials.FormatSummary("Hosts", 4, 3, 6, changes: 4, changesPutBack: 2)) - .IsEqualTo("Adaptive [ParallelLimiter] Hosts: the limit ranged from 3 to 6 over 4 changes (2 put back because they did not help) and ended at 4"); + await Assert.That(limiterLock.HeldPlaces).IsEqualTo(8); + await Assert.That(limiterLock.IsFull).IsFalse(); + await Assert.That(trials.FindPressureOwner(runningTests: 8)).IsNull(); + } + + [Test] + public async Task Saturated_Cpus_Do_Not_Lower_A_Limiter_That_Few_Running_Tests_Are_Inside() + { + var provider = new ParallelLimitLockProvider { FixedLimitsAreCeilings = true }; + var trials = new AdaptiveLimiterTrials(provider, new RecordingLogger(), processorCount: 4); + var limiter = new SimulatedLimiter(provider.GetLock(new FixedLimitOfEight())); + var saturated = Machine with { CpuUtilization = 1.0, ProcessCpuUtilization = 1.0, QueueDelay = TimeSpan.FromSeconds(1), OwnCores = 4 }; + + for (var i = 0; i < 240; i++) + { + await limiter.StepAsync(); + + // Eight of thirty-two: the load comes in through the session-wide limit. + var owner = trials.FindPressureOwner(runningTests: 32); + await Assert.That(owner).IsNull(); + + trials.Update(saturated, sessionLimitBusy: false, sessionLimitChanged: false, owner); + } + + await Assert.That(limiter.Lock.CurrentLimit).IsEqualTo(8); } /// @@ -242,12 +727,23 @@ private sealed class SimulatedLimiter(ParallelLimitLock parallelLimitLock) { private double _partialTests; private int _held; + private bool _queued; public ParallelLimitLock Lock { get; } = parallelLimitLock; + // Tests completed per second at a limit. + public Func Throughput { get; set; } = limit => limit * 10; + public async Task StepAsync(bool failOne = false) { - _partialTests += Lock.CurrentLimit * 10 * SampleInterval.TotalSeconds; + if (!_queued) + { + // More tests are queued behind the limiter than it admits, for the whole run. + _queued = true; + Lock.AddBacklog(1_000_000); + } + + _partialTests += Throughput(Lock.CurrentLimit) * SampleInterval.TotalSeconds; for (; _partialTests >= 1; _partialTests--) { @@ -284,6 +780,16 @@ private sealed class FixedLimit : IParallelLimit public int Limit => 4; } + private sealed class FixedLimitOfEight : IParallelLimit + { + public int Limit => 8; + } + + private sealed class LimitOfOne : IParallelLimit + { + public int Limit => 1; + } + private sealed class FourToSixteen : IAdaptiveParallelLimit { public int Limit => 4; @@ -291,6 +797,34 @@ private sealed class FourToSixteen : IAdaptiveParallelLimit public int MaximumLimit => 16; } + private sealed class FourToThousand : IAdaptiveParallelLimit + { + public int Limit => 4; + public int MinimumLimit => 2; + public int MaximumLimit => 1000; + } + + private sealed class PinnedAtFour : IAdaptiveParallelLimit + { + public int Limit => 4; + public int MinimumLimit => 4; + public int MaximumLimit => 4; + } + + private sealed class EightAtLeast : IAdaptiveParallelLimit + { + public int Limit => 8; + public int MinimumLimit => 8; + public int MaximumLimit => 16; + } + + private sealed class SixteenToThirtyTwo : IAdaptiveParallelLimit + { + public int Limit => 16; + public int MinimumLimit => 1; + public int MaximumLimit => 32; + } + private sealed class AnotherFourToSixteen : IAdaptiveParallelLimit { public int Limit => 4; diff --git a/tests/TUnit.UnitTests/AdaptiveParallelismControllerTests.cs b/tests/TUnit.UnitTests/AdaptiveParallelismControllerTests.cs index 5ba541a5881..a5eb96900c9 100644 --- a/tests/TUnit.UnitTests/AdaptiveParallelismControllerTests.cs +++ b/tests/TUnit.UnitTests/AdaptiveParallelismControllerTests.cs @@ -45,9 +45,9 @@ public async Task Reports_An_Adaptive_Limiter_When_The_Session_Limit_Is_Fixed() lockProvider.GetLock(new ThreeToNine()); } - // Only the limiter: a fixed session-wide limit has nothing to report. - var summaries = logger.Messages.Where(x => x.Level == LogLevel.Information).Select(x => x.Message).ToArray(); - await Assert.That(summaries).IsEquivalentTo(["Adaptive [ParallelLimiter] ThreeToNine: the limit stayed at 3"]); + // A fixed session-wide limit has nothing to report, and neither has a limiter that + // never moved and that no test waited for. + await Assert.That(logger.Messages.Where(x => x.Level == LogLevel.Information)).IsEmpty(); } [Test] @@ -65,63 +65,238 @@ public async Task Reports_Nothing_Without_An_Adaptive_Limiter_When_The_Session_L [Test] public async Task Summary_Of_A_Limit_That_Never_Moved_Is_One_Sentence() { - var summary = AdaptiveParallelismController.FormatSummary(36, 36, 36, changes: 0, changesPutBack: 0, []); + 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."); } [Test] - public async Task Summary_Reports_Changes_Put_Back_And_The_Time_At_Each_Limit() + public async Task Summary_Says_Where_The_Limit_Went_And_How_Many_Changes_Were_Put_Back() { - var timeAtLimit = new SortedDictionary + // The Redis client report in #7915: 8 at the start, 18 at the end. + await Assert.That(AdaptiveParallelismSummary.Format(8, 18, 6, 27, changes: 12, changesPutBack: 5)) + .IsEqualTo("Adaptive parallelism: the parallel test limit went from 8 to 18 (lowest 6, highest 27, 12 changes, 5 put back)."); + + await Assert.That(AdaptiveParallelismSummary.Format(8, 8, 6, 8, changes: 2, changesPutBack: 1)) + .IsEqualTo("Adaptive parallelism: the parallel test limit moved and ended back at 8 (lowest 6, highest 8, 2 changes, 1 put back)."); + + await Assert.That(AdaptiveParallelismSummary.Format(16, 24, 16, 24, changes: 1, changesPutBack: 0)) + .IsEqualTo("Adaptive parallelism: the parallel test limit went from 16 to 24 (lowest 16, highest 24, 1 change)."); + } + + [Test] + public async Task Summary_Of_A_Limit_That_A_Shared_Budget_Moved_Does_Not_Say_It_Stayed() + { + // 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)."); + + 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)."); + } + + [Test] + public async Task Summary_Does_Not_Give_One_Limiter_The_Time_Tests_Waited_For_Several() + { + var statistics = new AdaptiveRunStatistics(0.3, 0.16, TimeSpan.Zero, AdaptiveRaiseBlocker.None) { - [8] = TimeSpan.FromSeconds(190.4), - [4] = TimeSpan.FromSeconds(12.2), - [6] = TimeSpan.FromSeconds(30), + Sampled = TimeSpan.FromSeconds(20), + WaitedForLimiter = TimeSpan.FromSeconds(10), + MostWaitedLimiter = "Hosts", + LimitersWaitedFor = 2, + }; + + await Assert.That(AdaptiveParallelismSummary.Format(8, 8, 8, 8, changes: 0, changesPutBack: 0, statistics)).IsEqualTo( + "Adaptive parallelism: the parallel test limit stayed at 8. " + + "For 10s of 20s, tests waited for 2 [ParallelLimiter] limits (Hosts the most), not for this limit."); + } + + [Test] + public async Task Summary_Names_Tests_That_Ran_One_At_A_Time_When_They_Held_The_Run_Back() + { + // The Dekaf unit test report in #7915: 44 of 109 seconds had one test running, and + // the summary said "the CPUs have no headroom" at 38% CPU. + var statistics = new AdaptiveRunStatistics(0.38, 0.36, TimeSpan.Zero, AdaptiveRaiseBlocker.CpuBusy) + { + Sampled = TimeSpan.FromSeconds(109), + NotInParallel = TimeSpan.FromSeconds(44), + WaitedForLimit = TimeSpan.FromSeconds(30), + CpuUtilizationWhileWaiting = 0.97, }; - var summary = AdaptiveParallelismController.FormatSummary(8, 4, 8, changes: 6, changesPutBack: 1, timeAtLimit); + var summary = AdaptiveParallelismSummary.Format(8, 12, 6, 12, changes: 5, changesPutBack: 2, statistics); await Assert.That(summary).IsEqualTo( - "Adaptive parallelism: the parallel test limit ranged from 4 to 8 over 6 changes (1 put back because it did not help) and ended at 8. " - + "Time at each limit: 4 for 12s, 6 for 30s, 8 for 3m 10s"); + "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."); } [Test] - public async Task Summary_Reports_Cpu_Use_And_Why_The_Limit_Did_Not_Move() + public async Task Summary_Names_The_Key_That_Tests_Waited_For_The_Longest() { - var statistics = new AdaptiveRunStatistics( - MachineCpuUtilization: 0.984, - ProcessCpuUtilization: 0.12, - HeldForOutsideLoad: TimeSpan.FromSeconds(200), - MostCommonRaiseBlocker: AdaptiveRaiseBlocker.CpuBusy); + // The Dekaf resilience report in #7915: one keyed chain ran alone for 94% of 11 minutes. + var statistics = new AdaptiveRunStatistics(0.32, 0.03, TimeSpan.Zero, AdaptiveRaiseBlocker.LimitNotReached) + { + Sampled = TimeSpan.FromSeconds(650), + WaitedForKeys = TimeSpan.FromSeconds(611), + MostWaitedKey = "Resilience", + }; - var summary = AdaptiveParallelismController.FormatSummary(8, 8, 8, changes: 0, changesPutBack: 0, [], statistics); + 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. " - + "The machine's CPUs were 98% busy on average, and this process alone used 12% of them. " - + "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 CPU saturation. " - + "Most common reason for not raising the limit: the CPUs have no headroom"); + + "For 10m 11s of 10m 50s, tests waited for a [NotInParallel] key (\"Resilience\" the most), which no limit changes."); + } + + [Test] + public async Task Summary_Names_The_Limiter_That_Tests_Waited_For_Instead_Of_The_Session_Limit() + { + // The ModularPipelines report in #7915: an assembly-wide limiter at 2 bound the run. + var statistics = new AdaptiveRunStatistics(0.3, 0.16, TimeSpan.Zero, AdaptiveRaiseBlocker.None) + { + Sampled = TimeSpan.FromSeconds(159), + WaitedForLimiter = TimeSpan.FromSeconds(150), + MostWaitedLimiter = "PipelineTestParallelLimit", + LimitersWaitedFor = 1, + }; + + 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 2m 30s of 2m 39s, tests waited for [ParallelLimiter] PipelineTestParallelLimit, not for this limit."); + } + + [Test] + public async Task Summary_Gives_The_Cpu_Use_While_Tests_Waited_For_The_Limit_Not_The_Average() + { + // The Relayer report in #7915: containers kept the CPUs saturated for the whole run. + var statistics = new AdaptiveRunStatistics(0.6, 0.05, TimeSpan.FromSeconds(242), AdaptiveRaiseBlocker.CpuBusy) + { + Sampled = TimeSpan.FromSeconds(242), + WaitedForLimit = TimeSpan.FromSeconds(240), + CpuUtilizationWhileWaiting = 1.0, + }; + + 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."); + } + + [Test] + public async Task Summary_Points_Away_From_The_Limit_When_Raises_Bring_Nothing_On_An_Idle_Machine() + { + // The Dekaf consumer group report in #7915: a semaphore taken in a [Before(Test)] + // hook let four tests run, whatever the limit. + var statistics = new AdaptiveRunStatistics(0.34, 0.03, TimeSpan.Zero, AdaptiveRaiseBlocker.WaitingAfterFailedRaise) + { + Sampled = TimeSpan.FromSeconds(182), + WaitedForLimit = TimeSpan.FromSeconds(165), + CpuUtilizationWhileWaiting = 0.34, + }; + + var summary = AdaptiveParallelismSummary.Format(8, 8, 8, 12, changes: 2, changesPutBack: 1, statistics); + + await Assert.That(summary).IsEqualTo( + "Adaptive parallelism: the parallel test limit moved and ended back at 8 (lowest 8, highest 12, 2 changes, 1 put back). " + + "Tests waited for it for 2m 45s of 3m 2s, with the CPUs 34% busy; it was not raised mostly because an earlier raise did not help, or memory was short. " + + "The tests are probably waiting on something other than the CPUs or this limit, such as a lock, a fixture or an external service."); + } + + [Test] + public async Task Summary_Of_A_Run_Where_Tests_Seldom_Waited_Never_Blames_The_Machine() + { + // Reports in #7915 of "the CPUs have no headroom" on a machine that was 13% busy. + var statistics = new AdaptiveRunStatistics(0.13, 0.05, TimeSpan.FromSeconds(1), AdaptiveRaiseBlocker.CpuBusy) + { + Sampled = TimeSpan.FromSeconds(180), + WaitedForLimit = TimeSpan.FromSeconds(4), + CpuUtilizationWhileWaiting = 0.96, + }; + + 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 seldom waited for it: fewer were ready to run than it allows."); + } + + [Test] + public async Task Summary_Decides_Whether_A_Wait_Matters_Against_The_Time_It_Was_Measured_Over() + { + // A 6 s run: 2 s of warm-up and 4 s measured, in which tests waited 0.55 s for the + // limit. That is 14% of the time measured, though under a tenth of the whole run. + var statistics = new AdaptiveRunStatistics(0.5, 0.4, TimeSpan.Zero, AdaptiveRaiseBlocker.TooFewTests) + { + Sampled = TimeSpan.FromSeconds(4), + RunTime = TimeSpan.FromSeconds(6), + WaitedForLimit = TimeSpan.FromSeconds(0.55), + CpuUtilizationWhileWaiting = 0.5, + }; + + var summary = AdaptiveParallelismSummary.Format(8, 8, 8, 8, changes: 0, changesPutBack: 0, statistics); + + // Given "of" the whole run, which is the duration the reader sees next to it. + await Assert.That(summary).IsEqualTo( + "Adaptive parallelism: the parallel test limit stayed at 8. " + + "Tests waited for it for 1s of 6s, with the CPUs 50% busy; it was not raised mostly because too few tests finished to measure throughput."); + } + + [Test] + public async Task Summary_Is_Short_Enough_For_A_Ci_Log() + { + // The lines in #7915 ran past 600 characters, and CI log viewers cut them off. + var statistics = new AdaptiveRunStatistics(0.6, 0.05, TimeSpan.FromSeconds(242), AdaptiveRaiseBlocker.KeepingLowerLimit) + { + Sampled = TimeSpan.FromSeconds(3599), + WaitedForLimit = TimeSpan.FromSeconds(3598), + CpuUtilizationWhileWaiting = 1.0, + }; + + var summary = AdaptiveParallelismSummary.Format(128, 256, 100, 512, changes: 120, changesPutBack: 110, statistics); + + await Assert.That(summary.Length).IsLessThan(300); } [Test] - public async Task Summary_Reports_Child_Process_Cpu_Use_Over_The_Time_It_Was_Measured() + public async Task Details_Report_The_Time_At_Each_Limit_And_Cpu_Use() { + var timeAtLimit = new SortedDictionary + { + [8] = TimeSpan.FromSeconds(190.4), + [4] = TimeSpan.FromSeconds(12.2), + [6] = TimeSpan.FromSeconds(30), + }; + var statistics = new AdaptiveRunStatistics( - MachineCpuUtilization: 0.97, - ProcessCpuUtilization: 0.04, - HeldForOutsideLoad: TimeSpan.Zero, - MostCommonRaiseBlocker: AdaptiveRaiseBlocker.None, + MachineCpuUtilization: 0.984, + ProcessCpuUtilization: 0.12, + HeldForOutsideLoad: TimeSpan.FromSeconds(200), + MostCommonRaiseBlocker: AdaptiveRaiseBlocker.CpuBusy, ChildProcessesMeasured: TimeSpan.FromSeconds(130), ChildProcessCpuUtilization: 0.61); - var summary = AdaptiveParallelismController.FormatSummary(16, 16, 16, changes: 0, changesPutBack: 0, [], statistics); + await Assert.That(AdaptiveParallelismSummary.FormatDetails(timeAtLimit, statistics)).IsEqualTo( + "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."); + } - await Assert.That(summary).IsEqualTo( - "Adaptive parallelism: the parallel test limit stayed at 16. " - + "The machine's CPUs were 97% busy on average, and this process alone used 4% of them. " - + "Its child processes used 61% in the 2m 10s they were measured, which is while the CPUs were nearly saturated"); + [Test] + public async Task Details_Leave_Out_What_Did_Not_Happen() + { + var statistics = new AdaptiveRunStatistics(0.4, 0.35, TimeSpan.Zero, AdaptiveRaiseBlocker.None); + + var details = AdaptiveParallelismSummary.FormatDetails( + new SortedDictionary { [16] = TimeSpan.FromSeconds(2), [24] = TimeSpan.FromSeconds(9) }, statistics); + + await Assert.That(details).IsEqualTo( + "Adaptive parallelism details: time at each limit: 16 for 2s, 24 for 9s. " + + "The machine's CPUs were 40% busy on average, and this process alone used 35% of them."); } [Test] @@ -140,17 +315,33 @@ public async Task Totals_Average_Child_Process_Cpu_Use_Over_The_Samples_That_Rea } [Test] - public async Task Summary_Leaves_Out_What_Did_Not_Happen() + public async Task Totals_Count_A_Reason_For_Not_Raising_Only_While_Tests_Wait_For_The_Limit() { - var statistics = new AdaptiveRunStatistics(0.4, 0.35, TimeSpan.Zero, AdaptiveRaiseBlocker.None); + var totals = new AdaptiveRunTotals(); - var summary = AdaptiveParallelismController.FormatSummary( - 24, 16, 24, changes: 1, changesPutBack: 0, new SortedDictionary { [16] = TimeSpan.FromSeconds(2), [24] = TimeSpan.FromSeconds(9) }, statistics); + // Half a minute of tests running one at a time, during which the policy's latest + // reason happens to be the CPUs: nothing waited for the limit, so it does not count. + totals.Add(TimeSpan.FromSeconds(30), 0.25, 0.2, AdaptiveRaiseBlocker.CpuBusy, heldForOutsideLoad: false, bottleneck: ParallelismBottleneck.NotInParallel); + totals.Add(TimeSpan.FromSeconds(5), 0.9, 0.8, AdaptiveRaiseBlocker.TooFewTests, heldForOutsideLoad: false, bottleneck: ParallelismBottleneck.SessionLimit); - await Assert.That(summary).IsEqualTo( - "Adaptive parallelism: the parallel test limit ranged from 16 to 24 over 1 change and ended at 24. " - + "Time at each limit: 16 for 2s, 24 for 9s. " - + "The machine's CPUs were 40% busy on average, and this process alone used 35% of them"); + // Tests wait for the limit while the policy's reason, from its last whole window, is + // that fewer were ready: the wait counts, the reason cannot explain it. + totals.Add(TimeSpan.FromSeconds(9), 0.9, 0.8, AdaptiveRaiseBlocker.LimitNotReached, heldForOutsideLoad: false, bottleneck: ParallelismBottleneck.SessionLimit); + totals.Add(TimeSpan.FromSeconds(8), 0.1, 0.1, AdaptiveRaiseBlocker.None, heldForOutsideLoad: false, bottleneck: ParallelismBottleneck.Limiter, limiter: "Hosts"); + totals.Add(TimeSpan.FromSeconds(2), 0.1, 0.1, AdaptiveRaiseBlocker.None, heldForOutsideLoad: false, bottleneck: ParallelismBottleneck.Limiter, limiter: "Databases"); + totals.Add(TimeSpan.FromSeconds(3), 0.1, 0.1, AdaptiveRaiseBlocker.None, heldForOutsideLoad: false, bottleneck: ParallelismBottleneck.NotInParallelKey); + + var statistics = totals.ToStatistics()!.Value; + + await Assert.That(statistics.Sampled).IsEqualTo(TimeSpan.FromSeconds(57)); + await Assert.That(statistics.MostCommonRaiseBlocker).IsEqualTo(AdaptiveRaiseBlocker.TooFewTests); + await Assert.That(statistics.WaitedForLimit).IsEqualTo(TimeSpan.FromSeconds(14)); + await Assert.That(statistics.LimitersWaitedFor).IsEqualTo(2); + await Assert.That(statistics.CpuUtilizationWhileWaiting).IsEqualTo(0.9).Within(0.0001); + await Assert.That(statistics.NotInParallel).IsEqualTo(TimeSpan.FromSeconds(30)); + await Assert.That(statistics.WaitedForLimiter).IsEqualTo(TimeSpan.FromSeconds(10)); + await Assert.That(statistics.MostWaitedLimiter).IsEqualTo("Hosts"); + await Assert.That(statistics.WaitedForKeys).IsEqualTo(TimeSpan.FromSeconds(3)); } [Test] diff --git a/tests/TUnit.UnitTests/AdaptiveParallelismPolicyTests.cs b/tests/TUnit.UnitTests/AdaptiveParallelismPolicyTests.cs index 021417809ee..53f19ba1188 100644 --- a/tests/TUnit.UnitTests/AdaptiveParallelismPolicyTests.cs +++ b/tests/TUnit.UnitTests/AdaptiveParallelismPolicyTests.cs @@ -48,11 +48,659 @@ public async Task Waits_Longer_Before_Each_Probe_After_A_Failed_One() simulation.Run(TimeSpan.FromSeconds(60)); - // Probes at about 2 s, 9 s (5 s hold), 22 s (10 s hold) and 44 s (20 s hold). - await Assert.That(simulation.Changes.Count(x => x.Change == AdaptiveLimitChange.Probe)).IsEqualTo(4); + // Probes at about 2 s, 20 s and 40 s. Each one that is put back took 2 s, and those + // may add up to a tenth of the run so far, which outlasts the wait after a failed + // probe (5 s, then 10 s). + await Assert.That(simulation.Changes.Count(x => x.Change == AdaptiveLimitChange.Probe)).IsEqualTo(3); await Assert.That(simulation.Changes.Max(x => x.Limit)).IsEqualTo(24); } + [Test] + public async Task Doubles_The_Next_Raise_After_One_That_Brought_Most_Of_Itself() + { + // The Redis client report in #7915 took a minute and a half to get from 8 to 18. + var simulation = new Simulation(Limits); + + simulation.Run(TimeSpan.FromSeconds(60)); + + await Assert.That(simulation.Changes).IsEquivalentTo( + [ + new AdaptiveDecision(24, AdaptiveLimitChange.Probe), + new AdaptiveDecision(48, AdaptiveLimitChange.Probe), + new AdaptiveDecision(64, AdaptiveLimitChange.Probe), + ]); + } + + [Test] + public async Task A_Lowering_That_Is_Kept_Ends_The_Doubling_Of_Raises() + { + // 16 to 24 with a strong gain, so the next raise would double. Then the CPUs + // saturate and a lowering to 18 is kept. With headroom again, the next raise goes to + // 27: doubled, it would go to 36, well past where the CPUs had just saturated. + var simulation = new Simulation(new ParallelismLimits(Initial: 16, Minimum: 4, Maximum: 64)); + + simulation.RunUntilChange(); + await Assert.That(simulation.Changes[0]).IsEqualTo(new AdaptiveDecision(24, AdaptiveLimitChange.Probe)); + + simulation.TrialsBlocked = true; + simulation.Run(TimeSpan.FromSeconds(6)); + simulation.TrialsBlocked = false; + + // The CPUs are what bounds the tests now: as many finish with fewer of them at once. + simulation.CpuUtilization = 0.99; + simulation.Throughput = _ => 24 * TestsPerSecondPerSlot; + simulation.RunUntilChanges(2); + + await Assert.That(simulation.Changes[1]).IsEqualTo(new AdaptiveDecision(18, AdaptiveLimitChange.CpuSaturation)); + + // Long enough for the lowering to be kept, then headroom and a throughput that + // follows the limit again. + simulation.TrialsBlocked = true; + simulation.Run(TimeSpan.FromSeconds(8)); + simulation.TrialsBlocked = false; + + simulation.CpuUtilization = 0.2; + simulation.Throughput = limit => limit * TestsPerSecondPerSlot; + simulation.Run(TimeSpan.FromMinutes(2)); + + var nextRaise = simulation.Changes.Skip(2).First(x => x.Change == AdaptiveLimitChange.Probe); + + await Assert.That(nextRaise.Limit).IsEqualTo(27); + } + + [Test] + public async Task A_Raise_That_Brought_Only_A_Fair_Share_Is_Followed_By_One_Of_A_Half() + { + // Half of each raise arrives as throughput: enough to keep it, not enough to double. + var simulation = new Simulation(Limits) + { + Throughput = limit => (16 + (limit - 16) * 0.5) * TestsPerSecondPerSlot, + }; + + simulation.RunUntilChanges(2); + + await Assert.That(simulation.Changes).IsEquivalentTo( + [ + new AdaptiveDecision(24, AdaptiveLimitChange.Probe), + new AdaptiveDecision(36, AdaptiveLimitChange.Probe), + ]); + } + + [Test] + public async Task Gives_The_Limit_Not_The_Machine_As_The_Reason_When_No_Test_Waits_For_It() + { + // Reports in #7915 of "the CPUs have no headroom" from runs where one test ran at + // a time: busy CPUs are a reason only while tests wait for the limit. + var simulation = new Simulation(Limits) + { + CpuUtilization = 0.99, + MemoryLoad = 0.9, + LimitReached = false, + Throughput = _ => 1, + }; + + simulation.Run(TimeSpan.FromSeconds(31)); + + await Assert.That(simulation.Changes).IsEmpty(); + await Assert.That(simulation.Policy.RaiseBlocker).IsEqualTo(AdaptiveRaiseBlocker.LimitNotReached); + } + + [Test] + public async Task One_Slow_Thread_Pool_Hand_Over_In_A_Window_Does_Not_Hold_A_Raise_Back() + { + var simulation = new Simulation(Limits); + + // One sample in eight: a hiccup, where a quarter of them would be a busy machine. + for (var i = 0; i < 32 && simulation.Changes.Count == 0; i++) + { + simulation.QueueDelay = i % 8 == 0 ? TimeSpan.FromMilliseconds(400) : TimeSpan.Zero; + simulation.Step(); + } + + await Assert.That(simulation.Changes).IsEquivalentTo([new AdaptiveDecision(24, AdaptiveLimitChange.Probe)]); + } + + [Test] + public async Task Undoes_A_Raise_At_Once_When_Tests_Start_Failing_And_Never_Raises_Past_It_Again() + { + // What the limit protects rejects the work of more than 16 tests at once. + var simulation = new Simulation(Limits) { FailuresPerSample = limit => limit > 16 ? 1 : 0 }; + + simulation.Run(TimeSpan.FromMinutes(10)); + + await Assert.That(simulation.Changes).IsEquivalentTo( + [ + new AdaptiveDecision(24, AdaptiveLimitChange.Probe), + new AdaptiveDecision(16, AdaptiveLimitChange.ProbeRevertedForFailures), + ]); + await Assert.That(simulation.Policy.RaiseBlocker).IsEqualTo(AdaptiveRaiseBlocker.PinnedAfterFailures); + } + + [Test] + public async Task Failures_That_Were_There_Before_A_Raise_Do_Not_Undo_It() + { + // The suite has tests that fail at any limit. + var simulation = new Simulation(new ParallelismLimits(Initial: 16, Minimum: 4, Maximum: 24)) { FailuresPerSample = _ => 1 }; + + simulation.Run(TimeSpan.FromSeconds(30)); + + await Assert.That(simulation.Changes).IsEquivalentTo([new AdaptiveDecision(24, AdaptiveLimitChange.Probe)]); + } + + [Test] + public async Task Abandoning_A_Raise_That_Tests_Failed_During_Still_Caps_The_Limit() + { + var simulation = new Simulation(Limits); + + simulation.RunUntilChange(); + + var decision = simulation.Policy.Abandon(TimeSpan.FromMilliseconds(250), failedTests: 1); + + await Assert.That(decision).IsEqualTo(new AdaptiveDecision(16, AdaptiveLimitChange.ProbeRevertedForFailures)); + + simulation.Run(TimeSpan.FromMinutes(10)); + + await Assert.That(simulation.Policy.Limit).IsEqualTo(16); + } + + [Test] + public async Task Returns_To_The_Starting_Limit_From_A_Share_Of_A_Budget_Once_There_Is_Headroom() + { + // The limit was set from outside, to this process's part of a shared budget. + var simulation = new Simulation(Limits); + simulation.Policy.Rebase(TimeSpan.Zero, 8); + + await Assert.That(simulation.Policy.Limit).IsEqualTo(8); + + simulation.RunUntilChanges(2); + + await Assert.That(simulation.Changes).IsEquivalentTo( + [ + new AdaptiveDecision(12, AdaptiveLimitChange.Recovery), + new AdaptiveDecision(16, AdaptiveLimitChange.Recovery), + ]); + } + + [Test] + public async Task Stays_At_A_Share_Of_A_Budget_While_Other_Processes_Keep_The_Cpus_Busy() + { + // Two CPU-bound test processes on one machine: each at its part, the CPUs are full, + // and more tests in either would only take CPU time from the other. + var simulation = new Simulation(Limits) + { + CpuUtilization = 0.99, + ProcessCpuUtilization = 0.5, + Throughput = _ => 4 * TestsPerSecondPerSlot, + }; + + simulation.Policy.Rebase(TimeSpan.Zero, 8); + simulation.Run(TimeSpan.FromMinutes(2)); + + await Assert.That(simulation.Policy.Limit).IsEqualTo(8); + } + + [Test] + public async Task A_Limit_Set_From_Outside_During_A_Trial_Is_Not_Put_Back() + { + var simulation = new Simulation(Limits); + + simulation.RunUntilChange(); + await Assert.That(simulation.Policy.Limit).IsEqualTo(24); + + // Another process joined the budget, and this one's part is now 8. + simulation.Policy.Rebase(TimeSpan.FromMilliseconds(250), 8); + + await Assert.That(simulation.Policy.Limit).IsEqualTo(8); + await Assert.That(simulation.Policy.IsBusy).IsTrue(); + + simulation.RunUntilChange(); + + await Assert.That(simulation.Changes[^1]).IsEqualTo(new AdaptiveDecision(12, AdaptiveLimitChange.Recovery)); + } + + [Test] + public async Task Does_Not_Lower_For_Saturated_Cpus_While_The_Run_Starts_Up() + { + // The Kevlar report in #7915: a cut a few seconds into a run of under ten, with no + // time left to put it back. The first seconds are compilation and fixtures. + var simulation = new Simulation(Limits, startupHold: true) + { + CpuUtilization = 0.99, + QueueDelay = TimeSpan.FromMilliseconds(150), + Throughput = _ => 4 * TestsPerSecondPerSlot, + }; + + simulation.Run(AdaptiveParallelismPolicy.StartupLowerHold - TimeSpan.FromMilliseconds(250)); + await Assert.That(simulation.Changes).IsEmpty(); + + simulation.Run(TimeSpan.FromSeconds(1)); + await Assert.That(simulation.Changes).IsEquivalentTo([new AdaptiveDecision(12, AdaptiveLimitChange.CpuSaturation)]); + } + + [Test] + public async Task Memory_Pressure_Is_Not_Held_Back_While_The_Run_Starts_Up() + { + var simulation = new Simulation(Limits, startupHold: true) { MemoryLoad = 1.1 }; + + simulation.Step(); + + await Assert.That(simulation.Changes).IsEquivalentTo([new AdaptiveDecision(8, AdaptiveLimitChange.MemoryPressure)]); + } + + [Test] + public async Task A_Limit_That_Does_Not_Relieve_Memory_Pressure_Stays_Where_It_Is_Under_It() + { + // The limit of a [ParallelLimiter]: the session-wide limit is the one that comes down. + var simulation = new Simulation(Limits, relievesMemoryPressure: false) { MemoryLoad = 1.1 }; + + simulation.Run(TimeSpan.FromSeconds(30)); + + await Assert.That(simulation.Changes).IsEmpty(); + } + + [Test] + public async Task Saturated_Cpus_That_Another_Limit_Admits_The_Load_For_Do_Not_Lower_This_One() + { + // The Reservoir report in #7915: the session-wide limit went from 8 to 6 and back + // while the tests that saturated the CPUs were all behind a [ParallelLimiter]. + var simulation = new Simulation(Limits) + { + CpuUtilization = 0.99, + QueueDelay = TimeSpan.FromMilliseconds(150), + Throughput = _ => 4 * TestsPerSecondPerSlot, + PressureElsewhere = true, + }; + + simulation.Run(TimeSpan.FromSeconds(60)); + + await Assert.That(simulation.Changes).IsEmpty(); + } + + [Test] + public async Task A_Limit_Above_Where_It_Started_Comes_Back_Down_Although_Another_Limit_Admits_The_Load() + { + // The session-wide limit starts at 16, and a raise to 24 is kept. Later most of the + // running tests are inside a [ParallelLimiter] and the CPUs saturate. The limiter is + // lowered, and the slots it frees go to the extra tests the raised limit admits, so + // the CPUs stay oversubscribed unless this limit comes back as well. + var simulation = new Simulation(new ParallelismLimits(Initial: 16, Minimum: 4, Maximum: 24)); + + simulation.RunUntilChange(); + simulation.Run(TimeSpan.FromSeconds(10)); + + await Assert.That(simulation.Policy.Limit).IsEqualTo(24); + + simulation.CpuUtilization = 0.99; + simulation.PressureElsewhere = true; + simulation.Throughput = _ => 16 * TestsPerSecondPerSlot; + simulation.RunUntilChanges(2); + + // A quarter down, as for any lowering. + await Assert.That(simulation.Changes[1]).IsEqualTo(new AdaptiveDecision(18, AdaptiveLimitChange.CpuSaturation)); + + // And on down to where it started. There the pressure is the other limit's again, + // so it goes no further. + simulation.Run(TimeSpan.FromMinutes(2)); + + await Assert.That(simulation.Policy.Limit).IsEqualTo(16); + await Assert.That(simulation.Changes.Min(x => x.Limit)).IsEqualTo(16); + } + + [Test] + public async Task Slow_Tests_That_Saturate_The_Cpus_Lower_The_Limit_While_Cpu_Time_Holds() + { + // The Reservoir report in #7915: 22 tests that each run a child process for up to + // 25 seconds. Too few finish to compare throughput, so the limit never moved, and + // four at once on four processors took twice as long as two. + var simulation = new Simulation(Limits) + { + CpuUtilization = 1.0, + QueueDelay = TimeSpan.FromMilliseconds(150), + Throughput = _ => 0.2, + + // The processors are all busy, however many tests share them. + OwnCores = _ => 4, + }; + + simulation.Run(TimeSpan.FromMinutes(5)); + + await Assert.That(simulation.Changes.Select(x => x.Change)).DoesNotContain(AdaptiveLimitChange.LowerReverted); + await Assert.That(simulation.Changes.Select(x => x.Change)).Contains(AdaptiveLimitChange.CpuSaturation); + + // One test per processor: below that, fewer tests would leave processors unused. + await Assert.That(simulation.Policy.Limit).IsEqualTo(4); + } + + [Test] + public async Task Puts_Back_A_Lowering_Of_Slow_Tests_That_Leaves_Cpu_Time_Unused() + { + // Each test uses a quarter of a processor, so every test fewer is CPU time given away. + var simulation = new Simulation(Limits) + { + CpuUtilization = 1.0, + QueueDelay = TimeSpan.FromMilliseconds(150), + Throughput = _ => 0.2, + OwnCores = limit => limit * 0.25, + }; + + simulation.RunUntilChanges(2); + + await Assert.That(simulation.Changes).IsEquivalentTo( + [ + new AdaptiveDecision(12, AdaptiveLimitChange.CpuSaturation), + new AdaptiveDecision(16, AdaptiveLimitChange.LowerReverted), + ]); + } + + [Test] + public async Task Steps_Down_Judged_By_Cpu_Time_Are_All_Held_To_The_Cpu_Time_Before_The_First() + { + // Each step down gives 5% of the CPU time away: within the allowance of 7.5% alone, + // beyond it together. The baseline has to outlast a step that is put back, or every + // retry starts from a lower one and the run loses far more than the allowance. + var simulation = new Simulation(new ParallelismLimits(Initial: 32, Minimum: 1, Maximum: 64)) + { + CpuUtilization = 1.0, + QueueDelay = TimeSpan.FromMilliseconds(150), + Throughput = _ => 0.2, + OwnCores = limit => limit switch + { + >= 32 => 4.0, + >= 24 => 3.8, + >= 18 => 3.6, + _ => 3.4, + }, + }; + + simulation.Run(TimeSpan.FromMinutes(20)); + + // 32 to 24 is kept (5%). 24 to 18 is 10% against the 4.0 it began with, and is put + // back every time it is tried. + await Assert.That(simulation.Changes.Take(3)).IsEquivalentTo( + [ + new AdaptiveDecision(24, AdaptiveLimitChange.CpuSaturation), + new AdaptiveDecision(18, AdaptiveLimitChange.CpuSaturation), + new AdaptiveDecision(24, AdaptiveLimitChange.LowerReverted), + ]); + await Assert.That(simulation.Changes.Min(x => x.Limit)).IsEqualTo(18); + await Assert.That(simulation.Policy.Limit).IsGreaterThanOrEqualTo(24); + } + + [Test] + public async Task A_Raise_That_Was_Put_Back_Does_Not_Hold_A_Lowering_For_Saturated_Cpus_Back() + { + // The allowance for trials is spent on a raise that brought nothing. Then the suite + // saturates the CPUs: the limit has to come down all the same, not minutes later. + var simulation = new Simulation(Limits) { Throughput = _ => 16 * TestsPerSecondPerSlot }; + + simulation.RunUntilChanges(2); + await Assert.That(simulation.Changes[1].Change).IsEqualTo(AdaptiveLimitChange.ProbeReverted); + + simulation.CpuUtilization = 0.99; + simulation.QueueDelay = TimeSpan.FromMilliseconds(150); + simulation.Run(TimeSpan.FromSeconds(5)); + + await Assert.That(simulation.Changes[2]).IsEqualTo(new AdaptiveDecision(12, AdaptiveLimitChange.CpuSaturation)); + } + + [Test] + public async Task A_Lowering_Judged_By_Cpu_Time_Does_Not_Record_Throughput_From_Another_Limit() + { + // Steady at 32 with 320 tests a second. Memory pressure takes the limit to 16, and + // the tests that follow are slow ones that saturate the CPUs. + var simulation = new Simulation(new ParallelismLimits(Initial: 32, Minimum: 1, Maximum: 32)); + + simulation.Run(TimeSpan.FromSeconds(4)); + simulation.MemoryLoad = 1.1; + simulation.RunUntilChange(); + simulation.MemoryLoad = 0.3; + + await Assert.That(simulation.Changes[0]).IsEqualTo(new AdaptiveDecision(16, AdaptiveLimitChange.MemoryPressure)); + + simulation.CpuUtilization = 1.0; + simulation.QueueDelay = TimeSpan.FromMilliseconds(150); + simulation.Throughput = _ => 0.2; + simulation.OwnCores = _ => 4; + simulation.RunUntilChanges(2); + + await Assert.That(simulation.Changes[1]).IsEqualTo(new AdaptiveDecision(12, AdaptiveLimitChange.CpuSaturation)); + + // The suite turns to quick tests whose throughput does not depend on the limit, so + // the next step down is judged by throughput. Compared with the 320 a second from + // the limit of 32, it would be put back, and its wait would double. + simulation.Throughput = _ => 40; + simulation.Run(TimeSpan.FromMinutes(2)); + + await Assert.That(simulation.Changes.Select(x => x.Change)).DoesNotContain(AdaptiveLimitChange.LowerReverted); + await Assert.That(simulation.Policy.Limit).IsLessThan(12); + } + + [Test] + public async Task Slow_Tests_Are_Never_Raised_For_Without_A_Measured_Gain() + { + // Idle CPUs and a full limit, with tests too slow to measure: nothing says more of + // them would finish sooner, so the limit stays where a fixed one would be. + var simulation = new Simulation(Limits) { Throughput = _ => 0.2 }; + + simulation.Run(TimeSpan.FromMinutes(5)); + + await Assert.That(simulation.Changes).IsEmpty(); + await Assert.That(simulation.Policy.RaiseBlocker).IsEqualTo(AdaptiveRaiseBlocker.TooFewTests); + } + + [Test] + public async Task No_Trial_Starts_While_Trials_That_Were_Put_Back_Exceed_A_Tenth_Of_The_Run() + { + // Slow tests make a trial long: 15 s to settle and a window after it. What keeps + // adaptive parallelism from costing much against a fixed limit is that no new trial + // starts while the time spent at limits that did not help is over a tenth of the run. + // That is a rule for starting a trial, not a cap on the time: the trial that takes + // the total over the tenth runs to its end. + var simulation = new Simulation(Limits) + { + // One test a second at any limit: each slot takes 16 s, and no raise helps. + Throughput = _ => 1, + }; + + var onTrial = TimeSpan.Zero; + var total = TimeSpan.FromMinutes(30); + + for (var elapsed = TimeSpan.Zero; elapsed < total; elapsed += TimeSpan.FromMilliseconds(250)) + { + simulation.Step(); + + if (simulation.Policy.Limit != Limits.Initial) + { + onTrial += TimeSpan.FromMilliseconds(250); + } + } + + await Assert.That(simulation.Changes.Count(x => x.Change == AdaptiveLimitChange.Probe)).IsGreaterThan(1); + + // Each trial started while the total was within a tenth and added its own length, + // so the total stays within a tenth plus one trial. + await Assert.That(onTrial).IsLessThan(TimeSpan.FromTicks((long) (total.Ticks * 0.15))); + } + + [Test] + public async Task Trials_Of_Different_Limits_Share_One_Allowance() + { + // The session-wide limit and a [ParallelLimiter] each put a trial back. Counted + // apart, each would see half of what the two cost the run together. + var budget = new AdaptiveExplorationBudget(); + var sample = new AdaptiveSample(TimeSpan.FromMilliseconds(250), 0.2, 0.2, 0.3, TimeSpan.Zero, CompletedTests: 40, LimitReached: true); + + // Sixteen tests' worth of throughput whatever the limit, so its raise is put back. + var first = new AdaptiveParallelismPolicy(Limits, processorCount: 4, startupLowerHold: TimeSpan.Zero, explorationBudget: budget); + var putBack = false; + + for (var i = 0; i < 400 && !putBack; i++) + { + budget.Advance(sample.Elapsed); + putBack = first.OnSample(sample).Change == AdaptiveLimitChange.ProbeReverted; + } + + await Assert.That(putBack).IsTrue(); + await Assert.That(budget.IsSpent).IsTrue(); + + // Another limit, with a steady throughput and room to rise: its first trial has to + // wait for the allowance the other limit used. + var second = new AdaptiveParallelismPolicy(Limits, processorCount: 4, startupLowerHold: TimeSpan.Zero, explorationBudget: budget); + + for (var i = 0; i < 12; i++) + { + budget.Advance(sample.Elapsed); + await Assert.That(second.OnSample(sample).Change).IsEqualTo(AdaptiveLimitChange.None); + } + + await Assert.That(second.RaiseBlocker).IsEqualTo(AdaptiveRaiseBlocker.ExplorationBudget); + } + + [Test] + public async Task A_Lowering_Of_Slow_Tests_Is_Not_Judged_Before_The_Lower_Limit_Is_In_Effect() + { + // Tests that run for a minute: the limit goes from 16 to 12, and all 16 are still + // running. CPU time measured now is that of the limit the lowering came from, and + // would keep it without having seen what it costs. + var simulation = new Simulation(Limits) + { + CpuUtilization = 1.0, + QueueDelay = TimeSpan.FromMilliseconds(150), + Throughput = _ => 0.2, + OwnCores = _ => 4, + }; + + simulation.RunUntilChange(); + await Assert.That(simulation.Policy.Limit).IsEqualTo(12); + + simulation.OverLimit = true; + simulation.Run(TimeSpan.FromSeconds(20)); + + // Still waiting, where two windows of 5 s would have kept the lowering. + await Assert.That(simulation.Changes.Count).IsEqualTo(1); + await Assert.That(simulation.Policy.IsBusy).IsTrue(); + + // The tests outlast the trial, so nothing was learned and the limit goes back. + simulation.RunUntilChanges(2); + + await Assert.That(simulation.Changes[1]).IsEqualTo(new AdaptiveDecision(16, AdaptiveLimitChange.LowerNotJudged)); + } + + [Test] + public async Task A_Lowering_That_Could_Not_Be_Judged_Is_Not_Held_Against_Later_Trials() + { + // Nothing spoke against it: the tests only ran longer than the measurement. Charged + // as a trial that was put back, about 45 s of it would block every raise for minutes. + var budget = new AdaptiveExplorationBudget(); + var policy = new AdaptiveParallelismPolicy(Limits, processorCount: 4, startupLowerHold: TimeSpan.Zero, explorationBudget: budget); + var saturated = new AdaptiveSample(TimeSpan.FromMilliseconds(250), 1.0, 1.0, 0.3, TimeSpan.FromMilliseconds(150), CompletedTests: 0, LimitReached: true, OwnCores: 4); + var changes = new List(); + + for (var i = 0; i < 2400 && changes.Count < 2; i++) + { + budget.Advance(saturated.Elapsed); + + // Over the limit from the moment it is lowered: the tests never finish. + var decision = policy.OnSample(saturated with { OverLimit = changes.Count == 1 }); + + if (decision.Change != AdaptiveLimitChange.None) + { + changes.Add(decision); + } + } + + await Assert.That(changes.Select(x => x.Change)).IsEquivalentTo([AdaptiveLimitChange.CpuSaturation, AdaptiveLimitChange.LowerNotJudged]); + await Assert.That(budget.IsSpent).IsFalse(); + } + + [Test] + public async Task Cpu_Time_From_Before_Child_Processes_Were_Counted_Is_Not_A_Baseline_For_A_Lowering() + { + // Browser tests: the test process alone uses under one processor. Child processes + // are read only from the moment the CPUs are saturated, which is when a lowering + // can start. Judged against a window from before, any lowering would be kept: + // six processors' worth against less than one. + var simulation = new Simulation(Limits) + { + CpuUtilization = 1.0, + QueueDelay = TimeSpan.FromMilliseconds(150), + Throughput = _ => 0.2, + OwnCores = _ => 0.8, + }; + + // A whole window of this process alone, and a lowering starts on it. + simulation.RunUntilChange(); + await Assert.That(simulation.Changes[0]).IsEqualTo(new AdaptiveDecision(12, AdaptiveLimitChange.CpuSaturation)); + + // The reading of the child processes starts. Every test fewer is CPU time given up. + simulation.OwnCoresChangedBasis = true; + simulation.OwnCores = limit => limit * 0.375; + simulation.Step(); + simulation.OwnCoresChangedBasis = false; + + // The lowering in progress is given up: its baseline no longer means anything. + await Assert.That(simulation.Changes[1]).IsEqualTo(new AdaptiveDecision(16, AdaptiveLimitChange.LowerNotJudged)); + + simulation.Run(TimeSpan.FromMinutes(5)); + + // Measured alike, 4.5 processors' worth at 12 is less than the 6 at 16, so every + // later lowering is put back, where the 0.8 from before would have kept it. + await Assert.That(simulation.Changes.Skip(2).Select(x => x.Change)).Contains(AdaptiveLimitChange.LowerReverted); + await Assert.That(simulation.Changes.Min(x => x.Limit)).IsEqualTo(12); + await Assert.That(simulation.Policy.Limit).IsGreaterThanOrEqualTo(12); + } + + [Test] + public async Task A_Lowering_Of_Slow_Tests_Is_Judged_Once_The_Tests_That_Were_Running_Have_Finished() + { + var simulation = new Simulation(Limits) + { + CpuUtilization = 1.0, + QueueDelay = TimeSpan.FromMilliseconds(150), + Throughput = _ => 0.2, + OwnCores = _ => 4, + }; + + simulation.RunUntilChange(); + + simulation.OverLimit = true; + simulation.Run(TimeSpan.FromSeconds(20)); + simulation.OverLimit = false; + + // Two windows of CPU time at the lower limit, then the next step down. + simulation.RunUntilChanges(2); + + await Assert.That(simulation.Changes[1]).IsEqualTo(new AdaptiveDecision(9, AdaptiveLimitChange.CpuSaturation)); + } + + [Test] + public async Task Memory_Pressure_Ends_A_Run_Of_Lowerings_Judged_By_Cpu_Time() + { + // A lowering judged by CPU time is in progress, against four processors' worth. + var simulation = new Simulation(new ParallelismLimits(Initial: 32, Minimum: 1, Maximum: 64)) + { + CpuUtilization = 1.0, + QueueDelay = TimeSpan.FromMilliseconds(150), + Throughput = _ => 0.2, + OwnCores = _ => 4, + }; + + simulation.RunUntilChange(); + await Assert.That(simulation.Changes[0]).IsEqualTo(new AdaptiveDecision(24, AdaptiveLimitChange.CpuSaturation)); + + simulation.MemoryLoad = 1.1; + simulation.RunUntilChanges(2); + await Assert.That(simulation.Changes[1].Change).IsEqualTo(AdaptiveLimitChange.MemoryPressure); + simulation.MemoryLoad = 0.3; + + // A later phase uses two processors' worth, and keeps using them with fewer tests. + // Judged against the four from before the memory pressure, the lowering would be put back. + simulation.OwnCores = _ => 2; + simulation.Run(TimeSpan.FromMinutes(3)); + + await Assert.That(simulation.Changes.Select(x => x.Change)).DoesNotContain(AdaptiveLimitChange.LowerReverted); + } + [Test] public async Task Starts_No_Trial_While_A_Limiter_Is_On_Trial() { @@ -759,12 +1407,19 @@ public async Task Limit_Stays_Within_Its_Bounds_Under_Changing_Load() } } - private sealed class Simulation(ParallelismLimits limits, int processorCount = 4) + /// The limits to move between. + /// The number of processors the process may use. + /// Whether the limit comes down under memory pressure. + /// + /// Whether lowerings for saturated CPUs wait as long as at the start of a run. Off unless + /// asked for, so a test can saturate the CPUs from its first sample. + /// + private sealed class Simulation(ParallelismLimits limits, int processorCount = 4, bool relievesMemoryPressure = true, bool startupHold = false) { private static readonly TimeSpan SampleInterval = TimeSpan.FromMilliseconds(250); private double _partialTests; - public AdaptiveParallelismPolicy Policy { get; } = new(limits, processorCount); + public AdaptiveParallelismPolicy Policy { get; } = new(limits, processorCount, relievesMemoryPressure, startupHold ? null : TimeSpan.Zero); public List Changes { get; } = []; @@ -785,13 +1440,38 @@ private sealed class Simulation(ParallelismLimits limits, int processorCount = 4 public bool TrialsBlocked { get; set; } + public bool PressureElsewhere { get; set; } + + public bool OverLimit { get; set; } + + public bool OwnCoresChangedBasis { get; set; } + + public Func FailuresPerSample { get; set; } = _ => 0; + + // Processors' worth of CPU time the process and its child processes use at a limit. + public Func OwnCores { get; set; } = _ => 0; + public bool Step() { _partialTests += Throughput(Policy.Limit) * SampleInterval.TotalSeconds; var completed = (long) _partialTests; _partialTests -= completed; - var decision = Policy.OnSample(new AdaptiveSample(SampleInterval, CpuUtilization, ProcessCpuUtilization ?? CpuUtilization, MemoryLoad, QueueDelay, completed, LimitReached, CpuStalled, TrialsBlocked)); + var decision = Policy.OnSample(new AdaptiveSample( + SampleInterval, + CpuUtilization, + ProcessCpuUtilization ?? CpuUtilization, + MemoryLoad, + QueueDelay, + completed, + LimitReached, + CpuStalled, + TrialsBlocked, + FailuresPerSample(Policy.Limit), + OwnCores(Policy.Limit), + PressureElsewhere, + OverLimit, + OwnCoresChangedBasis)); if (decision.Change == AdaptiveLimitChange.None) { @@ -816,5 +1496,14 @@ public void RunUntilChange() { } } + + // Simulated time, so the bound is on steps: ten simulated minutes. + public void RunUntilChanges(int count) + { + for (var i = 0; i < 2400 && Changes.Count < count; i++) + { + Step(); + } + } } } diff --git a/tests/TUnit.UnitTests/MaxParallelismLimiterTests.cs b/tests/TUnit.UnitTests/MaxParallelismLimiterTests.cs index 409b2c049e4..d8f6b4f3fdf 100644 --- a/tests/TUnit.UnitTests/MaxParallelismLimiterTests.cs +++ b/tests/TUnit.UnitTests/MaxParallelismLimiterTests.cs @@ -40,6 +40,204 @@ public async Task Adaptive_Limiter_Counts_Released_Slots() await Assert.That(limiter.ReleasedSlots).IsEqualTo(2); } + [Test] + public async Task Set_Limit_Says_Whether_It_Changed_The_Slots_And_What_They_Were() + { + var limiter = new MaxParallelismLimiter(() => new ParallelismLimits(Initial: 8, Minimum: 2, Maximum: 32, SharedBudget: 8)); + + await Assert.That(limiter.SetLimit(12, expectedSlotChanges: null, out var previous, out var changed)).IsEqualTo(12); + await Assert.That(previous).IsEqualTo(8); + await Assert.That(changed).IsTrue(); + + // Another process joins the shared budget, and this one's part takes the limit to 4. + limiter.SetShare(4); + + // The policy, which has not seen that yet, asks for the 4 the limit is already at. + // The change was the budget's: counted as this call's, the controller would never + // tell the policy that its limit was set from elsewhere. + await Assert.That(limiter.SetLimit(4, expectedSlotChanges: null, out previous, out changed)).IsEqualTo(4); + await Assert.That(previous).IsEqualTo(4); + await Assert.That(changed).IsFalse(); + } + + [Test] + public async Task A_Limit_Decided_Before_A_Share_Shrank_Does_Not_Undo_The_Share() + { + // Process A decides a raise from 40 to 60 in the sample in which process B joins the + // budget and A's part drops to 20. Applied all the same, the raise would leave A at + // 60 while B runs its part too. + var limiter = new MaxParallelismLimiter(() => new ParallelismLimits(Initial: 40, Minimum: 10, Maximum: 160, SharedBudget: 40)); + var (decidedUnder, _) = limiter.ReadSlots(); + + limiter.SetShare(20); + + await Assert.That(limiter.SetLimit(60, decidedUnder, out var previous, out var changed)).IsEqualTo(20); + await Assert.That(previous).IsEqualTo(20); + await Assert.That(changed).IsFalse(); + await Assert.That(limiter.CurrentLimit).IsEqualTo(20); + + // Decided with the share known, the raise is applied. + var (known, _) = limiter.ReadSlots(); + + await Assert.That(limiter.SetLimit(30, known, out _, out changed)).IsEqualTo(30); + await Assert.That(changed).IsTrue(); + } + + [Test] + public async Task Leaving_A_Shared_Budget_Gives_An_Adaptive_Limit_Its_Starting_Limit_Back() + { + // The budget's thread failed after this process had come down to its part. Nothing + // else raises the limit when adaptive parallelism is not running yet. + var limiter = new MaxParallelismLimiter(() => new ParallelismLimits(Initial: 16, Minimum: 4, Maximum: 64, SharedBudget: 16)); + + await Assert.That(limiter.SetShare(4)).IsEqualTo(4); + await Assert.That(limiter.ClearShare()).IsEqualTo(16); + + // A limit the policy had already taken above the start stays where it is. + limiter.SetLimit(24); + limiter.SetShare(32); + await Assert.That(limiter.ClearShare()).IsEqualTo(24); + + // And a share that comes later is applied as before. + await Assert.That(limiter.SetShare(8)).IsEqualTo(8); + } + + [Test] + public async Task An_Adaptive_Limit_That_Nothing_Has_Moved_Follows_Its_Share_Back_Up() + { + // Budget 8: a second process joins, then exits. Adaptive parallelism may not be + // running, or may be held back by CPUs the other process kept busy, so the limit + // does not wait for it to return. + var limiter = new MaxParallelismLimiter(() => new ParallelismLimits(Initial: 8, Minimum: 2, Maximum: 32, SharedBudget: 8)); + + await Assert.That(limiter.SetShare(4)).IsEqualTo(4); + await Assert.That(limiter.SetShare(8)).IsEqualTo(8); + + // No further than the limit the run starts at: beyond it is the policy's to decide. + await Assert.That(limiter.SetShare(4)).IsEqualTo(4); + await Assert.That(limiter.SetShare(100)).IsEqualTo(8); + + // A limit the policy has moved away from the share is left to the policy. + limiter.SetShare(4); + limiter.SetLimit(3); + await Assert.That(limiter.SetShare(8)).IsEqualTo(3); + } + + [Test] + public async Task A_Share_That_Grows_Does_Not_Undo_A_Lowering_To_The_Same_Number() + { + // Part 6, and adaptive parallelism has the limit at 8. It lowers the limit to 6 for + // saturated CPUs, which happens to be the part. Another process leaves and the part + // becomes 8: the limit is adaptive parallelism's, and the CPUs are still saturated. + var limiter = new MaxParallelismLimiter(() => new ParallelismLimits(Initial: 16, Minimum: 2, Maximum: 64, SharedBudget: 16)); + + limiter.SetShare(6); + limiter.SetLimit(8); + limiter.SetLimit(6); + + await Assert.That(limiter.SetShare(8)).IsEqualTo(6); + } + + [Test] + public async Task The_Fallback_After_An_Error_Stays_Within_This_Process_Share() + { + // Three processes share a budget of 8, and each has a part of 2. When adaptive + // parallelism stops in one of them, it must not go back to 16 tests. + var limiter = new MaxParallelismLimiter(() => new ParallelismLimits(Initial: 16, Minimum: 1, Maximum: 64, SharedBudget: 8)); + + await Assert.That(limiter.FallbackLimit).IsEqualTo(16); + + limiter.SetShare(2); + await Assert.That(limiter.FallbackLimit).IsEqualTo(2); + + limiter.ClearShare(); + await Assert.That(limiter.FallbackLimit).IsEqualTo(16); + } + + [Test] + public async Task A_Limit_That_Fell_Back_After_An_Error_Follows_Its_Share_Up_Again() + { + // Starting limit 8, part 4. Adaptive parallelism stops after an error and sets the + // fallback of 4. When the other process finishes, the part is 8 again, and nothing + // else would give this process the slots back. + var limiter = new MaxParallelismLimiter(() => new ParallelismLimits(Initial: 8, Minimum: 2, Maximum: 32, SharedBudget: 8)); + + limiter.SetShare(4); + limiter.SetLimit(6); + limiter.SetLimit(limiter.FallbackLimit); + + // Set by adaptive parallelism, so on its own it would stay. + await Assert.That(limiter.CurrentLimit).IsEqualTo(4); + + limiter.FollowShare(); + + await Assert.That(limiter.SetShare(8)).IsEqualTo(8); + } + + [Test] + public async Task Leaving_A_Shared_Budget_Takes_The_Ceiling_Off_A_Fixed_Limit() + { + var limiter = new MaxParallelismLimiter(() => new ParallelismLimits(8, 8, 8, SharedBudget: 8)); + + await Assert.That(limiter.SetShare(4)).IsEqualTo(4); + await Assert.That(limiter.ClearShare()).IsEqualTo(8); + } + + [Test] + public async Task A_Full_Budget_That_No_Test_Waits_For_Has_No_Unmet_Demand() + { + // Every slot is held, by the last tests there are: a higher limit would start + // nothing, so the budget is not what holds tests back and no reason is charged to it. + var limiter = new MaxParallelismLimiter(() => new ParallelismLimits(Initial: 2, Minimum: 1, Maximum: 8)); + + await limiter.WaitAsync(CancellationToken.None); + await limiter.WaitAsync(CancellationToken.None); + + await Assert.That(limiter.AvailableSlots).IsEqualTo(0); + await Assert.That(limiter.HasUnmetDemand()).IsFalse(); + + // A test queued behind the budget's workers is one it holds back. + limiter.AddBacklog(1); + await Assert.That(limiter.HasUnmetDemand()).IsTrue(); + limiter.AddBacklog(-1); + + // And so is one that waits for a slot. + var waiting = limiter.WaitAsync(CancellationToken.None); + var counted = limiter.BeginWait(waiting); + + await Assert.That(counted).IsTrue(); + await Assert.That(limiter.Waiting).IsEqualTo(1); + await Assert.That(limiter.HasUnmetDemand()).IsTrue(); + + limiter.Release(); + await waiting; + limiter.EndWait(counted); + + await Assert.That(limiter.Waiting).IsEqualTo(0); + await Assert.That(limiter.HasUnmetDemand()).IsFalse(); + + // A wait that does not have to queue is not counted. + limiter.Release(); + var immediate = limiter.WaitAsync(CancellationToken.None); + + await Assert.That(limiter.BeginWait(immediate)).IsFalse(); + await Assert.That(limiter.Waiting).IsEqualTo(0); + } + + [Test] + public async Task Slots_And_Their_Change_Count_Are_Read_Together() + { + var limiter = new MaxParallelismLimiter(() => new ParallelismLimits(Initial: 8, Minimum: 2, Maximum: 32)); + + await Assert.That(limiter.ReadSlots()).IsEqualTo((0L, 8)); + + limiter.SetLimit(12); + limiter.SetLimit(12); + limiter.SetLimit(6); + + await Assert.That(limiter.ReadSlots()).IsEqualTo((2L, 6)); + } + [Test] public async Task Fixed_Limiter_Cannot_Be_Resized() { diff --git a/tests/TUnit.UnitTests/ParallelLimiterLanesTests.cs b/tests/TUnit.UnitTests/ParallelLimiterLanesTests.cs index ed8e507c6c2..37bf3363bdc 100644 --- a/tests/TUnit.UnitTests/ParallelLimiterLanesTests.cs +++ b/tests/TUnit.UnitTests/ParallelLimiterLanesTests.cs @@ -18,21 +18,500 @@ public async Task Split_WithoutLimiters_ReturnsNoLanes() } [Test] - [Arguments(32, 12)] + [Arguments(32)] // The limit can reach the budget, and can come down below it later, so it still gets a lane. - [Arguments(8, 8)] - public async Task Split_GivesAnAdaptiveLimiterWorkersForItsHighestLimit(int maxParallelism, int expectedWorkers) + [Arguments(2)] + public async Task Split_GivesAnAdaptiveLimiterWorkersForItsCurrentLimit(int maxParallelism) { + // Workers for the highest limit would queue for the places the limiter has now, and + // every test start would pass through that queue (#7915). + var lockProvider = new ParallelLimitLockProvider(); var unlimited = CreateTest("unlimited"); var adaptive1 = CreateTest("adaptive-1", new TwoToTwelve()); var adaptive2 = CreateTest("adaptive-2", new TwoToTwelve()); - var lanes = ParallelLimiterLanes.Split([unlimited, adaptive1, adaptive2], maxParallelism); + var lanes = ParallelLimiterLanes.Split([unlimited, adaptive1, adaptive2], maxParallelism, lockProvider); await Assert.That(lanes).IsNotNull(); await Assert.That(lanes!.Count).IsEqualTo(2); - await Assert.That(lanes[1].Workers).IsEqualTo(expectedWorkers); + await Assert.That(lanes[1].Workers).IsEqualTo(2); await Assert.That(lanes[1].Tests.Length).IsEqualTo(2); + await Assert.That(lanes[1].Limiter).IsSameReferenceAs(lockProvider.GetLock(new TwoToTwelve())); + } + + [Test] + public async Task RunAsync_UnderAResizableBudget_AddsWorkersWhenTheLimitIsRaised() + { + // The budget starts with two slots. Every test stays in its body until four run at + // once, which only happens once the raise has added workers: it would hang otherwise. + var limiter = new MaxParallelismLimiter(() => new ParallelismLimits(Initial: 2, Minimum: 1, Maximum: 8)); + var twoRunning = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var fourRunning = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + int running = 0, mostRunning = 0, executed = 0; + + var tests = Enumerable.Range(0, 12).Select(i => CreateTest($"test-{i}")).ToArray(); + + var run = ParallelLimiterLanes.RunAsync(tests, limiter, async (_, _) => + { + var now = Interlocked.Increment(ref running); + InterlockedMax(ref mostRunning, now); + + if (now >= 2) + { + twoRunning.TrySetResult(); + } + + if (now >= 4) + { + fourRunning.TrySetResult(); + } + + await fourRunning.Task; + Interlocked.Decrement(ref running); + Interlocked.Increment(ref executed); + }, CancellationToken.None); + + try + { + await twoRunning.Task.WaitAsync(HangTimeout); + await Assert.That(Volatile.Read(ref mostRunning)).IsEqualTo(2); + + limiter.SetLimit(4); + + await run.WaitAsync(HangTimeout); + } + finally + { + // Lets the tests go when something above failed, so none is left waiting. + fourRunning.TrySetResult(); + } + + await Assert.That(executed).IsEqualTo(12); + await Assert.That(mostRunning).IsEqualTo(4); + await Assert.That(limiter.AvailableSlots).IsEqualTo(4); + } + + [Test] + public async Task RunAsync_TestsQueuedBehindAWiderLimiter_CountAsWaitingForTheSessionLimit() + { + // A session-wide limit of 2 and a limiter that admits 8: the lane has two workers, + // and the tests behind them wait for the session-wide limit. The limiter has places + // free, so on its own count nothing would ever ask for a raise. + var limiter = new MaxParallelismLimiter(() => new ParallelismLimits(Initial: 2, Minimum: 1, Maximum: 8)); + var lockProvider = new ParallelLimitLockProvider(); + var limiterLock = lockProvider.GetLock(new EightToTwelve()); + var trials = new AdaptiveLimiterTrials(lockProvider, new TUnit.Core.Logging.NullLogger()); + var twoRunning = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var running = 0; + + var tests = Enumerable.Range(0, 10).Select(i => CreateTest($"limited-{i}", new EightToTwelve())).ToArray(); + + var run = ParallelLimiterLanes.RunAsync(tests, limiter, async (_, cancellationToken) => + { + await limiterLock.EnterAsync(cancellationToken); + + try + { + if (Interlocked.Increment(ref running) == 2) + { + twoRunning.TrySetResult(); + } + + await release.Task; + } + finally + { + limiterLock.Exit(testFailed: false); + } + }, CancellationToken.None, lockProvider); + + try + { + await twoRunning.Task.WaitAsync(HangTimeout); + + await Assert.That(limiterLock.Backlog).IsEqualTo(8); + await Assert.That(limiterLock.HasUnmetDemand).IsFalse(); + await Assert.That(trials.HasQueuedTestsWithFreePlaces()).IsTrue(); + await Assert.That(limiter.HasUnmetDemand(trials.HasQueuedTestsWithFreePlaces())).IsTrue(); + + // With the limiter as full as the session-wide limit, the queued tests wait for + // the limiter: a raise of the session-wide limit would start none of them, and + // putting it back would use up the allowance the limiter's own raise needs. + limiterLock.SetLimit(2); + + await Assert.That(limiterLock.HasUnmetDemand).IsTrue(); + await Assert.That(trials.HasQueuedTestsWithFreePlaces()).IsFalse(); + await Assert.That(limiter.HasUnmetDemand(trials.HasQueuedTestsWithFreePlaces())).IsFalse(); + } + finally + { + release.TrySetResult(); + } + + await run.WaitAsync(HangTimeout); + + await Assert.That(limiter.Backlog).IsEqualTo(0); + await Assert.That(limiterLock.Backlog).IsEqualTo(0); + } + + [Test] + public async Task RunAsync_UnderAResizableBudget_WorkersAddedByARaiseRunUnderTheContextTheLaneStartedIn() + { + // The raise comes from another thread, as adaptive parallelism's does. The tests its + // workers start must see what the scheduler had set when it started the batch. + var ambient = new AsyncLocal(); + var limiter = new MaxParallelismLimiter(() => new ParallelismLimits(Initial: 2, Minimum: 1, Maximum: 8)); + var twoRunning = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var fourRunning = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var seen = new System.Collections.Concurrent.ConcurrentBag(); + var running = 0; + + var tests = Enumerable.Range(0, 12).Select(i => CreateTest($"test-{i}")).ToArray(); + + ambient.Value = "scheduler"; + + var run = ParallelLimiterLanes.RunAsync(tests, limiter, async (_, _) => + { + seen.Add(ambient.Value); + + var now = Interlocked.Increment(ref running); + + if (now >= 2) + { + twoRunning.TrySetResult(); + } + + if (now >= 4) + { + fourRunning.TrySetResult(); + } + + await fourRunning.Task; + }, CancellationToken.None); + + ambient.Value = "test"; + + try + { + await twoRunning.Task.WaitAsync(HangTimeout); + + // A thread of its own, with a context that has nothing of the scheduler's. + var raise = new Thread(() => + { + ambient.Value = "controller"; + limiter.SetLimit(4); + }); + + using (ExecutionContext.SuppressFlow()) + { + raise.Start(); + } + + raise.Join(); + + await run.WaitAsync(HangTimeout); + } + finally + { + fourRunning.TrySetResult(); + } + + await Assert.That(seen.Count).IsEqualTo(12); + await Assert.That(seen.Distinct()).IsEquivalentTo(["scheduler"]); + } + + [Test] + public async Task RunAsync_UnderAResizableBudget_UsesASlotThatATestGaveBackToWaitForAnotherTest() + { + // Two slots, and the first two tests each wait for a test that runs elsewhere, as + // one with [DependsOn] does: they give their slots back. With two workers for two + // slots, both workers are waiting, and the lane's other tests could not start + // although both slots are free. + var limiter = new MaxParallelismLimiter(() => new ParallelismLimits(Initial: 2, Minimum: 1, Maximum: 8)); + var othersStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + int started = 0, others = 0, executed = 0; + + var tests = Enumerable.Range(0, 8).Select(i => CreateTest($"test-{i}")).ToArray(); + + var run = ParallelLimiterLanes.RunAsync(tests, limiter, async (test, cancellationToken) => + { + if (Interlocked.Increment(ref started) <= 2) + { + // What TestRunner does around a wait for a running dependency. + test.HoldsParallelSlot = false; + limiter.ReleaseWhileWaiting(); + limiter.BeginDependencyWait(); + + try + { + // The dependency finishes only once two other tests of the lane have + // started, which needs workers beyond the two that are waiting here. + await othersStarted.Task; + } + finally + { + limiter.EndDependencyWait(); + await limiter.WaitAsync(cancellationToken); + test.HoldsParallelSlot = true; + } + } + else if (Interlocked.Increment(ref others) >= 2) + { + othersStarted.TrySetResult(); + } + + Interlocked.Increment(ref executed); + }, CancellationToken.None); + + try + { + await run.WaitAsync(HangTimeout); + } + finally + { + othersStarted.TrySetResult(); + } + + await Assert.That(executed).IsEqualTo(8); + await Assert.That(limiter.DependencyWaits).IsEqualTo(0); + await Assert.That(limiter.AvailableSlots).IsEqualTo(2); + await Assert.That(limiter.Backlog).IsEqualTo(0); + } + + [Test] + public async Task RunAsync_UnderAResizableBudget_RunsNoMoreTestsThanALoweredLimit() + { + var limiter = new MaxParallelismLimiter(() => new ParallelismLimits(Initial: 4, Minimum: 1, Maximum: 8)); + var fourRunning = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var lowered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var twoRunningAfterLowering = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseAfterLowering = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + int running = 0, runningAfterLowering = 0, mostRunningAfterLowering = 0, executed = 0; + + var tests = Enumerable.Range(0, 40).Select(i => CreateTest($"test-{i}")).ToArray(); + + var run = ParallelLimiterLanes.RunAsync(tests, limiter, async (_, _) => + { + if (!lowered.Task.IsCompleted) + { + // The first four fill the budget and stay until it has been lowered. + if (Interlocked.Increment(ref running) == 4) + { + fourRunning.TrySetResult(); + } + + await lowered.Task; + Interlocked.Increment(ref executed); + return; + } + + var now = Interlocked.Increment(ref runningAfterLowering); + InterlockedMax(ref mostRunningAfterLowering, now); + + if (now >= 2) + { + twoRunningAfterLowering.TrySetResult(); + } + + // Held in the body, so a third test that was admitted would run beside these. + await releaseAfterLowering.Task; + Interlocked.Decrement(ref runningAfterLowering); + Interlocked.Increment(ref executed); + }, CancellationToken.None); + + try + { + await fourRunning.Task.WaitAsync(HangTimeout); + limiter.SetLimit(2); + lowered.SetResult(); + + // Two tests are held in their bodies, and the budget has nothing left to hand + // out: no third can be admitted beside them, however long they stay. + await twoRunningAfterLowering.Task.WaitAsync(HangTimeout); + await Assert.That(limiter.HeldSlots).IsEqualTo(2); + await Assert.That(limiter.AvailableSlots).IsEqualTo(0); + } + finally + { + lowered.TrySetResult(); + releaseAfterLowering.TrySetResult(); + } + + await run.WaitAsync(HangTimeout); + + await Assert.That(executed).IsEqualTo(40); + await Assert.That(mostRunningAfterLowering).IsEqualTo(2); + await Assert.That(limiter.AvailableSlots).IsEqualTo(2); + } + + [Test] + public async Task RunAsync_LaneOfAnAdaptiveLimiter_FollowsTheLimitersLimit() + { + var limiter = new MaxParallelismLimiter(() => 8); + var lockProvider = new ParallelLimitLockProvider(); + var limiterLock = lockProvider.GetLock(new TwoToTwelve()); + var twoRunning = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var fiveRunning = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + int running = 0, mostRunning = 0, executed = 0; + + var tests = Enumerable.Range(0, 15).Select(i => CreateTest($"adaptive-{i}", new TwoToTwelve())).ToArray(); + + // What TestRunner does for each test: the limiter's place is taken inside the slot. + var run = ParallelLimiterLanes.RunAsync(tests, limiter, async (_, cancellationToken) => + { + await limiterLock.EnterAsync(cancellationToken); + + try + { + var now = Interlocked.Increment(ref running); + InterlockedMax(ref mostRunning, now); + + if (now >= 2) + { + twoRunning.TrySetResult(); + } + + if (now >= 5) + { + fiveRunning.TrySetResult(); + } + + await fiveRunning.Task; + Interlocked.Decrement(ref running); + Interlocked.Increment(ref executed); + } + finally + { + limiterLock.Exit(testFailed: false); + } + }, CancellationToken.None, lockProvider); + + try + { + await twoRunning.Task.WaitAsync(HangTimeout); + await Assert.That(Volatile.Read(ref mostRunning)).IsEqualTo(2); + + // Five at once needs five workers: with the two it started with it would hang here. + limiterLock.SetLimit(5); + + await run.WaitAsync(HangTimeout); + } + finally + { + // Lets the tests go when something above failed, so none is left waiting. + fiveRunning.TrySetResult(); + } + + await Assert.That(executed).IsEqualTo(15); + await Assert.That(mostRunning).IsEqualTo(5); + await Assert.That(limiter.AvailableSlots).IsEqualTo(8); + } + + [Test] + public async Task RunAsync_UnderAResizableBudget_RunsAsManyTestsAsBeforeAfterALimitThatWentDownAndCameBack() + { + // A lowering and the raise that undoes it, while every worker is inside a test: the + // lane must end up with a worker for each slot again. + var limiter = new MaxParallelismLimiter(() => new ParallelismLimits(Initial: 4, Minimum: 1, Maximum: 8)); + var fourRunning = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var restored = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var fourRunningAgain = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + int running = 0, runningAfter = 0, executed = 0; + + var tests = Enumerable.Range(0, 20).Select(i => CreateTest($"test-{i}")).ToArray(); + + var run = ParallelLimiterLanes.RunAsync(tests, limiter, async (_, _) => + { + if (!restored.Task.IsCompleted) + { + if (Interlocked.Increment(ref running) == 4) + { + fourRunning.TrySetResult(); + } + + await restored.Task; + Interlocked.Increment(ref executed); + return; + } + + if (Interlocked.Increment(ref runningAfter) >= 4) + { + fourRunningAgain.TrySetResult(); + } + + // Four at once needs four workers: with fewer it would hang here. + await fourRunningAgain.Task; + Interlocked.Increment(ref executed); + }, CancellationToken.None); + + try + { + await fourRunning.Task.WaitAsync(HangTimeout); + + limiter.SetLimit(2); + limiter.SetLimit(4); + restored.SetResult(); + + await run.WaitAsync(HangTimeout); + } + finally + { + restored.TrySetResult(); + fourRunningAgain.TrySetResult(); + } + + await Assert.That(executed).IsEqualTo(20); + await Assert.That(limiter.AvailableSlots).IsEqualTo(4); + } + + [Test] + public async Task RunAsync_UnderAResizableBudget_EndsCancelledAndReturnsEverySlot() + { + var limiter = new MaxParallelismLimiter(() => new ParallelismLimits(Initial: 2, Minimum: 1, Maximum: 8)); + using var cancellation = new CancellationTokenSource(); + var twoRunning = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + int running = 0, executed = 0; + + var tests = Enumerable.Range(0, 10).Select(i => CreateTest($"test-{i}")).ToArray(); + + var run = ParallelLimiterLanes.RunAsync(tests, limiter, async (_, _) => + { + if (Interlocked.Increment(ref running) == 2) + { + twoRunning.TrySetResult(); + } + + await release.Task; + Interlocked.Increment(ref executed); + }, cancellation.Token); + + try + { + await twoRunning.Task.WaitAsync(HangTimeout); + } + finally + { + // Also when the two never got to run: no test is left waiting, and the lane + // ends. It is waited for here as well, so a failure above does not leave it + // running behind the test. The delay only bounds a hang. + cancellation.Cancel(); + release.TrySetResult(); + + using var bound = new CancellationTokenSource(); + await Task.WhenAny(run, Task.Delay(HangTimeout, bound.Token)); + bound.Cancel(); + } + + await Assert.That(async () => await run.WaitAsync(HangTimeout)).Throws(); + + // The two that were running finished, and no other test started. + await Assert.That(executed).IsEqualTo(2); + await Assert.That(limiter.AvailableSlots).IsEqualTo(2); + + // The tests that never started no longer count as waiting for the limit. + await Assert.That(limiter.Backlog).IsEqualTo(0); } [Test] @@ -307,6 +786,13 @@ private sealed class TwoToTwelve : IAdaptiveParallelLimit public int MinimumLimit => 1; public int MaximumLimit => 12; } + + private sealed class EightToTwelve : IAdaptiveParallelLimit + { + public int Limit => 8; + public int MinimumLimit => 1; + public int MaximumLimit => 12; + } #pragma warning restore TUNITEXP001 private sealed class LimitOfOne : IParallelLimit diff --git a/tests/TUnit.UnitTests/ProcessTreeCpuSamplerTests.cs b/tests/TUnit.UnitTests/ProcessTreeCpuSamplerTests.cs index 42c8c355f86..6ee36e5add5 100644 --- a/tests/TUnit.UnitTests/ProcessTreeCpuSamplerTests.cs +++ b/tests/TUnit.UnitTests/ProcessTreeCpuSamplerTests.cs @@ -484,6 +484,7 @@ public async Task Finds_A_Real_Child_Process_Until_It_Exits() })!; var childId = child.Id; + var childStartTime = 0L; var processes = new Dictionary(); try @@ -495,6 +496,8 @@ public async Task Finds_A_Real_Child_Process_Until_It_Exits() // The read's time is on the clock of the start times: no process starts after it. await Assert.That(processes[childId].StartTime).IsGreaterThan(0); await Assert.That(processes[childId].StartTime).IsLessThanOrEqualTo(now); + + childStartTime = processes[childId].StartTime; } finally { @@ -509,7 +512,13 @@ public async Task Finds_A_Real_Child_Process_Until_It_Exits() processes.Clear(); await Assert.That(reader.TryRead(processes, out _)).IsTrue(); - await Assert.That(processes.Keys).DoesNotContain(childId); + + // By ID and start time together: the operating system reuses process IDs quickly, + // and other tests start child processes at the same time, so the ID alone can be + // that of a new process (#7909). + var stillListed = processes.TryGetValue(childId, out var listed) && listed.StartTime == childStartTime; + + await Assert.That(stillListed).IsFalse(); } private static async Task AssertProcessors(double? actual, double expected) diff --git a/tests/TUnit.UnitTests/SharedParallelBudgetTests.cs b/tests/TUnit.UnitTests/SharedParallelBudgetTests.cs index 791d46c98ec..bb8a80381f7 100644 --- a/tests/TUnit.UnitTests/SharedParallelBudgetTests.cs +++ b/tests/TUnit.UnitTests/SharedParallelBudgetTests.cs @@ -216,6 +216,56 @@ public async Task A_Lowered_Ceiling_Takes_Slots_Back_As_Tests_Finish() await Assert.That(limiter.AvailableSlots).IsEqualTo(2); } + [Test] + public async Task A_Fixed_Limit_Is_Held_To_Its_Share() + { + var limiter = new MaxParallelismLimiter(() => new ParallelismLimits(8, 8, 8, SharedBudget: 8)); + + await Assert.That(limiter.SetShare(4)).IsEqualTo(4); + await Assert.That(limiter.SetLimit(8)).IsEqualTo(4); + await Assert.That(limiter.SetShare(8)).IsEqualTo(8); + } + + [Test] + public async Task An_Adaptive_Limit_Comes_Down_To_A_Share_That_Shrinks_And_Is_Free_To_Move_From_There() + { + // The report in #7915 on the shared budget: an equal part that adaptive parallelism + // could never exceed made a suite that waits on I/O slower, on a machine at half load. + var limiter = new MaxParallelismLimiter(() => new ParallelismLimits(Initial: 8, Minimum: 2, Maximum: 32, SharedBudget: 8)); + + // Another process joins: room is made for it at once. + await Assert.That(limiter.SetShare(4)).IsEqualTo(4); + + // The machine has headroom, so adaptive parallelism takes the limit back up, past the share. + await Assert.That(limiter.SetLimit(8)).IsEqualTo(8); + await Assert.That(limiter.SetLimit(12)).IsEqualTo(12); + + // The same share again changes nothing, and neither does a larger one: the policy + // decides how far the limit returns. + await Assert.That(limiter.SetShare(4)).IsEqualTo(12); + await Assert.That(limiter.SetShare(8)).IsEqualTo(12); + + // A third process joins. + await Assert.That(limiter.SetShare(3)).IsEqualTo(3); + } + + [Test] + public async Task A_Share_Never_Takes_An_Adaptive_Limit_Below_Its_Lowest() + { + var limiter = new MaxParallelismLimiter(() => new ParallelismLimits(Initial: 8, Minimum: 2, Maximum: 32, SharedBudget: 8)); + + await Assert.That(limiter.SetShare(1)).IsEqualTo(2); + } + + [Test] + public async Task Summary_With_Adaptive_Parallelism_Says_The_Part_Is_Where_The_Limit_Started() + { + // 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"); + } + [Test] public async Task A_Member_That_Has_Left_Does_Not_Join_Again() {