Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 31 additions & 3 deletions docs/docs/execution/parallelism.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,8 @@ Tests not assigned to any group run separately under normal parallel execution r

`[ParallelLimiter<T>]` caps how many tests sharing the same limiter type can run concurrently. The generic type argument must implement `IParallelLimit` with a public parameterless constructor.

Tests waiting for their limiter do not hold back other tests: while two tests run under a limit of 2, the rest of the `--maximum-parallel-tests` budget goes to tests that can run. The same holds for a test waiting for a `[DependsOn]` dependency that is already running.

The limit is shared across **all** tests referencing the same `IParallelLimit` type. Tests with a different limiter type or no limiter are unaffected.

An explicit `[ParallelLimiter<T>]` always takes precedence over a limiter set programmatically through `TestRegisteredContext.SetParallelLimiter`, including one supplied by an executor. This precedence does not depend on registration callback order. Without an explicit attribute, the last programmatic limiter applies.
Expand Down Expand Up @@ -224,9 +226,29 @@ The run starts at the limit a run without adaptive parallelism uses: `--maximum-
- **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 and work is waiting for one, TUnit lowers the limit by a quarter. It keeps the lower limit only if throughput held: 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. TUnit never lowers the limit below the processor count for this reason.
- **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.** Below the starting limit, TUnit steps back up as soon as the machine has headroom, and otherwise tries the step up like any other raise.
- **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.

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

Running tests are never interrupted; a lower limit takes effect as they finish. The limit never goes above `--maximum-parallel-tests` when you set it, or 8 x the processor count when you do not. It never goes below a quarter of the default limit.
### Bounds

| | Default | Change it with |
|---|---|---|
| **Start** | `--maximum-parallel-tests` when you set it, otherwise 2 x the processor count | `--maximum-parallel-tests` |
| **Highest** | `--maximum-parallel-tests` when you set it, otherwise 8 x the processor count | `--adaptive-max-parallel-tests`, `TUNIT_ADAPTIVE_MAX_PARALLEL_TESTS` or `context.Settings.Parallelism.AdaptiveMaximumParallelTests` |
| **Lowest** | A quarter of the start (at most a quarter of 2 x the processor count) | `--adaptive-min-parallel-tests`, `TUNIT_ADAPTIVE_MIN_PARALLEL_TESTS` or `context.Settings.Parallelism.AdaptiveMinimumParallelTests` |

```bash
# Start at 8, let the run go as high as 64
dotnet run --project MyTests -- --adaptive-parallelism --maximum-parallel-tests 8 --adaptive-max-parallel-tests 64

# Tests that each use a lot of memory: let memory pressure take the limit down to 1
dotnet run --project MyTests -- --adaptive-parallelism --adaptive-min-parallel-tests 1
```

The highest bound wins when the two cross, and the start moves inside them. The lowest bound is how far memory pressure can take the limit. Lowering for CPU still stops at the processor count, or at the lowest bound when that is higher. The bounds have no effect without adaptive parallelism.

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<T>]`.

### What TUnit measures

Expand All @@ -242,7 +264,13 @@ 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. Because TUnit keeps a change only when the measurement supports it, such suites stay at the starting limit. `[ParallelLimiter<T>]` 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, for example `Adaptive parallelism: the parallel test limit ranged from 16 to 64 over 4 changes and ended at 64`. Run with `--log-level Debug` to see each change and its reason. 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.
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:

```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
```

Run with `--log-level Debug` 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.

Adaptive parallelism requires .NET 8 or later and runs on Windows, Linux and macOS. Elsewhere the limit stays fixed.

Expand Down
8 changes: 8 additions & 0 deletions docs/docs/reference/command-line-flags.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,14 @@ Please note that for the coverage and trx report, you need to install [additiona
Experimental. Adjust the number of parallel tests while running, based on machine load and throughput
Programmatic equivalent: context.Settings.Parallelism.Adaptive

--adaptive-min-parallel-tests
Experimental. The lowest number of parallel tests --adaptive-parallelism goes to (defaults to a quarter of the starting limit)
Comment thread
thomhurst marked this conversation as resolved.
Resolved
Programmatic equivalent: context.Settings.Parallelism.AdaptiveMinimumParallelTests

--adaptive-max-parallel-tests
Experimental. The highest number of parallel tests --adaptive-parallelism goes to (defaults to --maximum-parallel-tests, or 8 per processor)
Programmatic equivalent: context.Settings.Parallelism.AdaptiveMaximumParallelTests

--coverage
Collect the code coverage using dotnet-coverage tool

Expand Down
17 changes: 17 additions & 0 deletions docs/docs/reference/environment-variables.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,21 @@ export TUNIT_ADAPTIVE_PARALLELISM=1

**Note:** Any one of the flag, the environment variable and the programmatic setting enables it.

### TUNIT_ADAPTIVE_MIN_PARALLEL_TESTS and TUNIT_ADAPTIVE_MAX_PARALLEL_TESTS

**Experimental.** The lowest and the highest number of parallel tests adaptive parallelism goes to. Each takes a positive integer and has no effect unless adaptive parallelism is enabled. See [Bounds](../execution/parallelism.md#bounds).

```bash
export TUNIT_ADAPTIVE_MIN_PARALLEL_TESTS=1 # Memory pressure may take the limit down to 1
export TUNIT_ADAPTIVE_MAX_PARALLEL_TESTS=64 # The limit may go as high as 64
```

**Equivalent to:** `--adaptive-min-parallel-tests` and `--adaptive-max-parallel-tests`

**Programmatic equivalent:** `context.Settings.Parallelism.AdaptiveMinimumParallelTests` and `AdaptiveMaximumParallelTests` (see [Programmatic Configuration](./programmatic-configuration.md))

**Note:** Command-line arguments take precedence over environment variables.

### TUNIT_DISABLE_THREADPOOL_TUNING

By default, TUnit watches the thread pool while tests run. If queued work waits for a thread while most CPUs are idle (a sign that tests are blocking), TUnit raises the pool's minimum worker thread count to the maximum number of parallel tests plus one per processor, and doubles it while starvation continues, up to 64 per processor. This stops blocking tests from delaying timers and timeouts in other tests while the pool slowly adds threads. TUnit never lowers a minimum that you configured yourself. Set this variable to `1`, `true` or `yes` to turn the behavior off.
Expand Down Expand Up @@ -340,6 +355,8 @@ When the same setting is configured in multiple places, TUnit follows this prior
| `JUNIT_XML_OUTPUT_PATH` | - | JUnit output path |
| `TUNIT_MAX_PARALLEL_TESTS` | `--maximum-parallel-tests` | Max parallel tests |
| `TUNIT_ADAPTIVE_PARALLELISM` | `--adaptive-parallelism` | Adjusts the parallel test limit while running (`1` to enable). Experimental |
| `TUNIT_ADAPTIVE_MIN_PARALLEL_TESTS` | `--adaptive-min-parallel-tests` | Lowest limit adaptive parallelism goes to. Experimental |
| `TUNIT_ADAPTIVE_MAX_PARALLEL_TESTS` | `--adaptive-max-parallel-tests` | Highest limit adaptive parallelism goes to. Experimental |
| `TUNIT_DISABLE_THREADPOOL_TUNING` | - | Disables the thread pool starvation monitor (`1` to disable) |
| `TUNIT_DISABLE_JIT_WARMUP` | - | Disables background compilation of the engine's startup code (`1` to disable) |
| `TUNIT_EXECUTION_MODE` | `--reflection` | Selects source-generation (`sourcegeneration`/`aot`) or `reflection` execution mode |
Expand Down
2 changes: 2 additions & 0 deletions docs/docs/reference/programmatic-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ On Linux and macOS with .NET 10 or later, SIGTERM (sent by `docker stop`, Kubern
|---|---|---|---|
| `MaximumParallelTests` | `int?` | `null` (2 x CPU cores) | Maximum number of tests that can execute concurrently. Set to `null` to use the default heuristic. |
| `Adaptive` | `bool` | `false` | **Experimental** (diagnostic `TUNITEXP001`). Changes the number of concurrent tests while the run is in progress, based on machine load and throughput. `MaximumParallelTests`, when set, is the highest the limit goes. See [Adaptive Parallelism](../execution/parallelism.md#adaptive-parallelism). |
| `AdaptiveMinimumParallelTests` | `int?` | `null` (a quarter of the starting limit) | **Experimental** (diagnostic `TUNITEXP001`). The lowest limit adaptive parallelism goes to. No effect unless `Adaptive` is enabled. |
| `AdaptiveMaximumParallelTests` | `int?` | `null` (`MaximumParallelTests`, or 8 x CPU cores) | **Experimental** (diagnostic `TUNITEXP001`). The highest limit adaptive parallelism goes to. Set it above `MaximumParallelTests` to start there and let the run go higher. No effect unless `Adaptive` is enabled. |

### `context.Settings.Display`

Expand Down
6 changes: 6 additions & 0 deletions src/TUnit.Core/AbstractExecutableTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ public abstract class AbstractExecutableTest
// dependency recursion, so TestRunner must keep using its execution dedup ledger.
internal bool RequiresExecutionDedup { get; set; }

// Whether the scheduler worker that started this test holds a slot of the parallel test
// budget for it right now. TestRunner gives the slot back while the test, or a dependency
// it runs inline, waits for a [ParallelLimiter] or for a test that is already running,
// and takes one again afterwards. Only the flow that runs the test reads or writes this.
internal bool HoldsParallelSlot { get; set; }

// Set by TestRunner once the test has every lock and slot it needs and is handed to
// TestCoordinator, which always publishes its result. A cancelled run uses this to find
// tests that failed before execution (data source or registration errors) and were never
Expand Down
47 changes: 46 additions & 1 deletion src/TUnit.Core/Settings/ParallelismSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,55 @@ public int? MaximumParallelTests
/// are saturated, and keeps either change only if it completes more tests per second (or, for
/// a lowering, no fewer). Memory pressure lowers the limit at once.
/// <see cref="MaximumParallelTests"/>, when set, is where the limit starts and the highest it
/// goes; otherwise it starts at 2× CPU cores and may reach 8×. Default: <c>false</c>.
/// goes; otherwise it starts at 2× CPU cores and may reach 8×. <see cref="AdaptiveMinimumParallelTests"/>
/// and <see cref="AdaptiveMaximumParallelTests"/> change the lowest and the highest. Default: <c>false</c>.
/// Enabled by any of <c>--adaptive-parallelism</c>, <c>TUNIT_ADAPTIVE_PARALLELISM</c> or TUnitSettings.
/// This setting is experimental: its behavior may change, or it may be removed, in a future release.
/// </summary>
[Experimental("TUNITEXP001")]
public bool Adaptive { get; set; }

/// <summary>
/// The lowest number of parallel tests adaptive parallelism goes to. Default: <c>null</c>
/// (a quarter of the limit it starts at, with 2× CPU cores as the most that start counts for).
/// Set it to 1 or 2 for tests that each use a lot of memory, so memory pressure can take the limit that low.
/// Has no effect unless <see cref="Adaptive"/> is enabled.
/// Precedence: <c>--adaptive-min-parallel-tests</c> → <c>TUNIT_ADAPTIVE_MIN_PARALLEL_TESTS</c> → TUnitSettings → built-in default.
/// This setting is experimental: its behavior may change, or it may be removed, in a future release.
/// </summary>
[Experimental("TUNITEXP001")]
public int? AdaptiveMinimumParallelTests
{
get => _adaptiveMinimumParallelTests;
set => _adaptiveMinimumParallelTests = ValidateAdaptiveBound(value);
}

/// <summary>
/// The highest number of parallel tests adaptive parallelism goes to. Default: <c>null</c>
/// (<see cref="MaximumParallelTests"/> when set, otherwise 8× CPU cores).
/// Set it above <see cref="MaximumParallelTests"/> to start at that limit and let the run go higher.
/// Has no effect unless <see cref="Adaptive"/> is enabled.
/// Precedence: <c>--adaptive-max-parallel-tests</c> → <c>TUNIT_ADAPTIVE_MAX_PARALLEL_TESTS</c> → TUnitSettings → built-in default.
/// This setting is experimental: its behavior may change, or it may be removed, in a future release.
/// </summary>
[Experimental("TUNITEXP001")]
public int? AdaptiveMaximumParallelTests
{
get => _adaptiveMaximumParallelTests;
set => _adaptiveMaximumParallelTests = ValidateAdaptiveBound(value);
}

private int? _adaptiveMinimumParallelTests;
private int? _adaptiveMaximumParallelTests;

private static int? ValidateAdaptiveBound(int? value)
{
if (value < 1)
{
throw new ArgumentOutOfRangeException(nameof(value), value,
"An adaptive parallelism bound must be null or a positive number.");
}

return value;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ namespace TUnit.Engine.CommandLineProviders;
internal class AdaptiveParallelismCommandProvider(IExtension extension) : ICommandLineOptionsProvider
{
public const string AdaptiveParallelism = "adaptive-parallelism";
public const string AdaptiveMinParallelTests = "adaptive-min-parallel-tests";
public const string AdaptiveMaxParallelTests = "adaptive-max-parallel-tests";

public Task<bool> IsEnabledAsync()
{
Expand All @@ -25,17 +27,36 @@ public IReadOnlyCollection<CommandLineOption> GetCommandLineOptions()
{
return
[
new CommandLineOption(AdaptiveParallelism, "Experimental. Adjust the number of parallel tests while running, based on machine load and throughput", ArgumentArity.Zero, false)
new CommandLineOption(AdaptiveParallelism, "Experimental. Adjust the number of parallel tests while running, based on machine load and throughput", ArgumentArity.Zero, false),
new CommandLineOption(AdaptiveMinParallelTests, "Experimental. The lowest number of parallel tests --adaptive-parallelism goes to (defaults to a quarter of the starting limit)", ArgumentArity.ExactlyOne, false),
new CommandLineOption(AdaptiveMaxParallelTests, "Experimental. The highest number of parallel tests --adaptive-parallelism goes to (defaults to --maximum-parallel-tests, or 8 per processor)", ArgumentArity.ExactlyOne, false)
];
}

public Task<ValidationResult> ValidateOptionArgumentsAsync(CommandLineOption commandOption, string[] arguments)
{
if (commandOption.Name is AdaptiveMinParallelTests or AdaptiveMaxParallelTests
&& (arguments.Length != 1 || !int.TryParse(arguments[0], out var bound) || bound < 1))
{
return ValidationResult.InvalidTask($"--{commandOption.Name} takes a single positive integer");
}

return ValidationResult.ValidTask;
}

public Task<ValidationResult> ValidateCommandLineOptionsAsync(ICommandLineOptions commandLineOptions)
{
if (commandLineOptions.TryGetOptionArgumentList(AdaptiveMinParallelTests, out var minimum)
&& commandLineOptions.TryGetOptionArgumentList(AdaptiveMaxParallelTests, out var maximum)
&& minimum.Length == 1
&& maximum.Length == 1
&& int.TryParse(minimum[0], out var lowest)
&& int.TryParse(maximum[0], out var highest)
&& lowest > highest)
{
return ValidationResult.InvalidTask($"--{AdaptiveMinParallelTests} ({lowest}) must not be higher than --{AdaptiveMaxParallelTests} ({highest})");
}

return ValidationResult.ValidTask;
}
}
3 changes: 3 additions & 0 deletions src/TUnit.Engine/Configuration/EnvironmentConstants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ internal static class EnvironmentConstants
public const string MaxParallelTests = "TUNIT_MAX_PARALLEL_TESTS";
// Opts in to resizing the parallel test limit from machine load and throughput while tests run.
public const string AdaptiveParallelism = "TUNIT_ADAPTIVE_PARALLELISM";
// The lowest and highest limits adaptive parallelism moves between.
public const string AdaptiveMinParallelTests = "TUNIT_ADAPTIVE_MIN_PARALLEL_TESTS";
public const string AdaptiveMaxParallelTests = "TUNIT_ADAPTIVE_MAX_PARALLEL_TESTS";
// 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";
Expand Down
Loading
Loading