Skip to content
31 changes: 21 additions & 10 deletions docs/docs/execution/parallelism.md
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ Nothing is measured in the first 2 seconds of a run, so a test project that fini
- **The limit that admits the load.** When most of the running tests are inside one `[ParallelLimiter<T>]`, saturated CPUs lower that limiter's limit and leave the session-wide limit alone: a lower session-wide limit changes nothing for tests that a limiter already holds back. A limiter's limit can go below the processor count for this, down to its lowest limit, because its tests can each use several processors. A limiter that would not lower now (it is at its lowest limit, or is waiting after a lowering that was put back) is left out, and the session-wide limit is lowered as usual.
- **Holding under other processes' load.** At the starting limit or below it, when the CPUs are saturated but the test process and the processes it started use less than half of the machine's CPU capacity, the limit stays where it is. Running fewer tests could not relieve the CPUs, and throughput measured while other processes move the load says little. This is the usual case on a CI runner that runs several test processes at once. Browsers and other programs the tests start count as the test process's own load, and so does whatever those start. Containers do not, because they are children of the container runtime, and neither does a process whose parent has exited. Suites that spend most of their CPU time in containers are therefore not lowered for CPU. When a container CPU quota is what throttles the test process, the share is measured against the quota instead of the machine, so a process at its quota always counts as the cause.
- **Lowering for memory.** When the machine or container is nearly out of memory, TUnit halves the limit at once, without a trial, because swapping or an out-of-memory kill costs more than a slower run.
- **Returning.** After memory pressure, TUnit steps back up as soon as the machine has headroom. After a lowering for CPU that was kept, it steps back up once the CPUs have gone 15 seconds without being saturated, and otherwise tries the step up like any other raise after the same wait. The wait doubles, up to 2 minutes, each time the way back fails: the limit came back and was lowered again, or the trial was put back. Tests that alternate between CPU-bound work and waiting therefore settle at the lower limit and do not move back and forth.
- **Returning.** After memory pressure, TUnit steps back up as soon as the machine has headroom. After a lowering for CPU that was kept, it steps back up once the CPUs have gone 15 seconds without being saturated, and otherwise tries the step up like any other raise after the same wait. The wait doubles, up to 2 minutes, each time the way back fails: the limit came back and was lowered again, or the trial was put back. Tests that alternate between CPU-bound work and waiting therefore settle at the lower limit and do not move back and forth. There is one shortcut: when throughput falls below what the lowering was kept on, while tests wait for the limit and the CPUs are less than 50% busy, the limit steps back up after a quarter of the wait. The tests have changed, and the lower limit now holds back tests that would not load the CPUs.

Running tests are never interrupted; a lower limit takes effect as they finish.

Expand Down Expand Up @@ -295,9 +295,11 @@ A `[ParallelLimiter<T>]` whose type implements only `IParallelLimit` keeps its d
When tests waited for such a limiter for a tenth of the run or more, the summary says so. A shorter wait is written at `--log-level Debug` only, so a deliberate cap does not add a line to every run:

```text
[ParallelLimiter] DatabaseLimit: the limit stayed at 2. Tests waited for it for 2m 30s while the CPUs were 30% busy. Adaptive parallelism never raises a declared limit. If it is not a hard cap, a higher limit, or no limiter, may shorten the run.
[ParallelLimiter] DatabaseLimit (MyTests, net10.0): the limit stayed at 2. Tests waited for it for 2m 30s while the CPUs were 30% busy. Adaptive parallelism never raises a declared limit. If it is not a hard cap, a higher limit, or no limiter, may shorten the run.
```

The last two sentences are advice that holds for every declared limit, so only the first such line of a run carries them.

If a limiter is there only to keep the load on the machine down, remove it and let adaptive parallelism manage the load. Keep limiters for hard caps.

### What TUnit measures
Expand All @@ -306,7 +308,7 @@ The readings cover the whole machine, not only the test process, because other t

| | CPU | Memory |
|---|---|---|
| **Linux** | Busy time from `/proc/stat`. Work is waiting for a CPU when the kernel's pressure stall information reports tasks stalled, or a container's CPU quota throttled the process, for a tenth of the time or more. | Available memory from `/proc/meminfo`, or the container's limit and usage under cgroup v2. Nearly out of memory means 95% in use, or tasks repeatedly stalled waiting for memory to be reclaimed. |
| **Linux** | Busy time from `/proc/stat`. Work is waiting for a CPU when a container's CPU quota throttled the process for a tenth of the time or more, or when the kernel's pressure stall information reports tasks stalled for that long while the CPUs are at least 80% busy. Tasks that wait for a moment on a machine that is mostly idle do not count. | Available memory from `/proc/meminfo`, or the container's limit and usage under cgroup v2. Nearly out of memory means 95% in use, or tasks repeatedly stalled waiting for memory to be reclaimed. |
| **Windows** | Busy time across all processor groups. | Physical memory in use; 95% counts as nearly out. |
| **macOS** | Busy time across all processors. | The kernel's own memory pressure level: a warning stops the limit being raised, and critical counts as nearly out. |

Expand All @@ -319,24 +321,33 @@ Machine load alone does not move the limit. Tests that wait on a shared resource
The run ends with one line that says where the limit went and what held the run back the most. A limit that tests did not wait for is not worth tuning, so the line names what they did wait for:

```text
Adaptive parallelism: the parallel test limit went from 8 to 18 (lowest 6, highest 27, 12 changes, 5 put back). Tests waited for it for 9m 40s of 13m 10s, with the CPUs 24% busy; it was not raised mostly because throughput kept changing between measurements.
Adaptive parallelism (MyTests, net10.0): the parallel test limit went from 8 to 18 (lowest 6, highest 27, 12 changes, 5 put back). Tests waited for it for 9m 40s of 13m 10s, with the CPUs 64% busy; it was not raised further mostly because the CPUs had no headroom (93% busy at those times).
```

Every line names the test project and target framework it is from, because `dotnet test` prints the lines of several test processes between each other's results.

| The line says | What it means |
|---|---|
| `Tests waited for it for ...` | The session-wide limit held tests back, with the CPU use over that time and the reason it was most often not raised. |
| `(93% busy at those times)` | The CPU use while that reason applied, when it differs from the figure for the whole wait. A suite that saturates the CPUs for part of the wait and idles for the rest has a low average and still had no headroom. |
| `most of their load came from other processes or containers` | The CPUs had no headroom, and the test process and the processes it started used less than half of what was in use. |
| `too few measurements completed to try a raise` | A raise is tried only on throughput that was measured twice. A short run, or one of slow tests, does not get that far. |
| `The run was too short to measure` | The run ended within the first 2 seconds, before anything is measured. |
| `Also, for ...` | What held tests back second-longest, when that was a fifth of the run or more. |
| `tests marked [NotInParallel] ran one at a time` | Tests marked `[NotInParallel]` without a key ran alone for that long. No limit changes that. Give them constraint keys, or remove the attribute where it is not needed. |
| `tests waited for a [NotInParallel] key` | Tests that share a key ran one after another while the limit had room. The key that tests waited for the longest is named. |
| `tests waited for the [NotInParallel] key "X"` | Tests that share a key ran one after another while the limit had room. With several keys, the one that tests waited for the longest is named. |
| `tests waited for [ParallelLimiter] X, not for this limit` | That limiter held tests back while the session-wide limit had room. The limiter has a line of its own. |
| `Tests seldom waited for it` | Fewer tests were ready to run than the limit allows for most of the run. |
| `The tests are probably waiting on something other than the CPUs or this limit` | Raises brought nothing while the CPUs were mostly idle. The tests wait on something TUnit cannot see, such as a lock or a semaphore taken in a hook, a shared fixture, or an external service. |
| `The tests are probably waiting on something other than the CPUs or this limit` | Tests waited for the limit while the CPUs were mostly idle, and raises brought nothing or throughput never settled enough to try one. The tests wait on something TUnit cannot see, such as a lock or a semaphore taken in a hook, a shared fixture, or an external service. If it is a cap of your own, declare it with `[ParallelLimiter<T>]` so the summary can name it. |

When the limit moved, a second line gives the figures: how long the run spent at each limit, the average CPU use of the machine and of the test process, and how long saturated CPUs were left alone because other processes caused the load. When the limit did not move, that line is written at `--log-level Debug`.
When the limit moved, a second line gives the figures: how long the run spent at each limit, how many changes of each kind were made, the average CPU use of the machine and of the test process, and how long saturated CPUs were left alone because other processes caused the load. When the limit did not move, that line is written at `--log-level Debug`.

```text
Adaptive parallelism details: time at each limit: 6 for 2s, 8 for 28s, 12 for 59s, 18 for 11m 18s, 27 for 19s. The machine's CPUs were 24% busy on average, and this process alone used 21% of them.
Adaptive parallelism details (MyTests, net10.0): time at each limit: 6 for 2s, 8 for 28s, 12 for 59s, 18 for 11m 18s, 27 for 19s. Changes: 7x raised to try more tests, 4x raise put back for no gain in throughput, 1x raise put back because it left the CPUs busy, 2x lowered for saturated CPUs, 2x raised back after pressure eased. The machine's CPUs were 64% busy on average, and this process alone used 58% of them.
```

A limit that changed as the last tests finished reads `6 as the run ended`: that change never took effect.

Both lines are also shown when `dotnet test` runs several test projects at once.

The test process's figure does not include the processes the tests start, such as browsers. TUnit reads those from the moment the CPUs are nearly saturated while the test process alone uses less than half of them, and for a minute after that. When it has read them, the details line adds their share over that time:
Expand Down Expand Up @@ -376,7 +387,7 @@ wait

The parts are equal whatever each process has left to run: a process whose remaining tests are few, or held by a `[NotInParallel]` constraint, keeps its part until it finishes.

With [adaptive parallelism](#adaptive-parallelism), a process's part is where its limit starts, not the most it runs. When another process joins, the limit comes down to the smaller part at once. From there it moves as the machine allows: while the CPUs are busy it stays at the part, and once they have room it returns to the limit the process would have alone, and goes beyond that on a measured gain. So test processes that use the CPUs keep to their parts, and test processes that mostly wait on I/O do not lose slots that nothing else can use.
With [adaptive parallelism](#adaptive-parallelism), a process's part is where its limit starts, not the most it runs. When another process joins, the limit comes down to the smaller part at once. From there it moves as the machine allows. Once the CPUs have room it returns to the limit the process would have alone, and goes beyond that on a measured gain. While the CPUs are busy it stays at the part when the processes that share the budget are what keeps them busy. TUnit takes that to be the case when this process's share of the machine's CPU capacity, times the number of processes in the budget, is half or more. The share includes the processes the tests start, such as browsers, and the limit does not leave its part before those have been read. Below that, the load comes from elsewhere, such as containers the tests start, and staying at the part would relieve nothing: when tests wait for the limit, it returns to the limit the process would have alone, as a process without a budget is not lowered for such load either. So test processes that use the CPUs keep to their parts, and test processes that mostly wait on I/O do not lose slots that nothing else can use.

A test process that one of the tests starts does not join the budget, although it inherits the variable. It runs inside that test, and as a member it would take a part away from the process that started it.

Expand All @@ -386,7 +397,7 @@ The processes find each other through files in the temporary directory that each
Shared parallel budget 'ci-tests': up to 3 test processes shared a budget of 8, and this one ran at most 2 to 8 tests in parallel
```

With adaptive parallelism it reads `this one had a part of 2 to 8 tests in parallel, which is where its adaptive limit starts`, and the adaptive parallelism summary says where the limit went.
With adaptive parallelism it reads `this one had a part of 2 to 8 tests in parallel (the part grows as other processes finish), which is where its adaptive limit starts`, and the adaptive parallelism summary says where the limit went.

## When to Use Which

Expand Down
41 changes: 32 additions & 9 deletions src/TUnit.Engine/Scheduling/AdaptiveLimiterTrials.cs
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,10 @@ public void Stop(bool resetLimits = false)
// A limiter whose first test arrived after the last update is reported too.
AddNewLimiters();

// What to do about a declared limit is said once, on the first line that needs
// it: on every line it was half of each of them (#7915).
var adviceGiven = false;

foreach (var limiter in _limiters)
{
if (resetLimits)
Expand All @@ -392,21 +396,28 @@ public void Stop(bool resetLimits = false)
// tests ran at once can only be understood from a log that says how many did.
if (summary.IsWorthReporting(_elapsed))
{
_logger.LogSessionMessage(FormatSummary(summary));
_logger.LogSessionMessage(FormatSummary(summary, TestProcessName.Current, includeAdvice: !adviceGiven));
adviceGiven |= summary.HasAdvice;
Comment thread
thomhurst marked this conversation as resolved.
Resolved
}
else if (summary.Waited > TimeSpan.Zero && _logger.IsEnabled(LogLevel.Debug))
{
// A deliberate cap that tests waited for a little: there for whoever asks.
_logger.LogDebug(FormatSummary(summary));
// It neither carries the advice nor counts as having given it: the
// advice belongs on a line every run shows, and those say it once.
_logger.LogDebug(FormatSummary(summary, TestProcessName.Current, includeAdvice: false));
}
}
}
}

internal static string FormatSummary(AdaptiveLimiterSummary summary)
/// <param name="summary">Where the limiter's limit went.</param>
/// <param name="processName">The test process the line is from.</param>
/// <param name="includeAdvice">Whether to say what to do about a declared limit that tests waited for. False once another limiter's line has said it.</param>
internal static string FormatSummary(AdaptiveLimiterSummary summary, string? processName = null, bool includeAdvice = true)
{
var text = new System.Text.StringBuilder();
text.Append("[ParallelLimiter] ").Append(summary.Name).Append(": the limit ");
text.Append("[ParallelLimiter] ").Append(summary.Name);
TestProcessName.AppendTo(text, processName).Append(": the limit ");
AdaptiveParallelismSummary.AppendLimit(text, summary.StartLimit, summary.CurrentLimit, summary.LowestLimit, summary.HighestLimit, summary.Changes, summary.ChangesPutBack);

if (summary.Waited <= TimeSpan.Zero)
Expand All @@ -429,18 +440,24 @@ internal static string FormatSummary(AdaptiveLimiterSummary summary)
{
// The limit is the user's to change, so say what the wait cost and what the
// machine was doing meanwhile.
text.Append(System.Globalization.CultureInfo.InvariantCulture, $" while the CPUs were {summary.CpuUtilizationWhileWaiting * 100:0}% busy. ");
text.Append(System.Globalization.CultureInfo.InvariantCulture, $" while the CPUs were {summary.CpuUtilizationWhileWaiting * 100:0}% busy.");

// Part of the wait is adaptive parallelism's own doing when it took the limit
// down: say so before any advice about the limit as declared.
if (summary.LowestLimit < summary.StartLimit)
{
text.Append("Adaptive parallelism lowered it while its tests saturated the CPUs, which is part of that wait. ");
text.Append(" Adaptive parallelism lowered it while its tests saturated the CPUs, which is part of that wait.");
}

text.Append(summary.DeclaredAdaptive
? "Its MaximumLimit is not above the limit it starts at, so it could not be raised: set a higher MaximumLimit to let it."
: "Adaptive parallelism never raises a declared limit. If it is not a hard cap, a higher limit, or no limiter, may shorten the run.");
if (summary.DeclaredAdaptive)
{
// About this limiter's own bounds, so it is said for each.
text.Append(" Its MaximumLimit is not above the limit it starts at, so it could not be raised: set a higher MaximumLimit to let it.");
}
else if (includeAdvice && summary.HasAdvice)
{
text.Append(" Adaptive parallelism never raises a declared limit. If it is not a hard cap, a higher limit, or no limiter, may shorten the run.");
}
}

return text.ToString();
Expand Down Expand Up @@ -599,6 +616,12 @@ internal readonly record struct AdaptiveLimiterSummary(
AdaptiveRaiseBlocker MostCommonRaiseBlocker = AdaptiveRaiseBlocker.None,
double CpuUtilizationWhileWaiting = 0)
{
/// <summary>
/// Whether the line ends with advice that is the same for every declared limit, so one
/// line of a run is enough to carry it.
/// </summary>
public bool HasAdvice => Waited > TimeSpan.Zero && !CanBeRaised && !DeclaredAdaptive;

/// <summary>
/// Whether the limiter gets a line in the output of every run.
/// </summary>
Expand Down
Loading
Loading