Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to main content

Controlling Parallelism

TUnit runs all tests in parallel by default. This page covers three attributes that give you fine-grained control when you need it.

Performance

Parallel execution is a major contributor to TUnit's speed advantage. See the performance benchmarks for real-world data.

Default Behavior​

With no attributes, every test is eligible to run concurrently. At most 2 x the processor count run at once. Change this limit with --maximum-parallel-tests, the TUNIT_MAX_PARALLEL_TESTS environment variable or context.Settings.Parallelism.MaximumParallelTests. For most test suites the default is the fastest option and requires no configuration. If your tests share a resource with limited capacity, such as a database connection pool, lower the limit for those tests with [ParallelLimiter<T>]: extra concurrent tests add no throughput and only wait inside their test bodies, which counts toward [Timeout].

Async tests and the thread pool

TUnit uses the standard .NET thread pool and, like most .NET applications, is susceptible to thread pool starvation. Blocking calls or heavy CPU-bound Task.Run work can delay async continuations in other tests and cause timed waits to expire.

By default, the pool adds threads beyond its minimum only about once or twice per second, so a burst of blocking tests can delay timers and [Timeout] handling in unrelated tests. To reduce this, TUnit watches the thread pool while tests run. If queued work waits for a thread while most CPUs are idle, TUnit raises the pool's minimum worker thread count to the maximum number of parallel tests plus one per processor. If the pool is still starved once it has grown that far (for example because keyed [NotInParallel] tests run alongside the parallel limit), TUnit doubles the minimum, up to 64 threads per processor. The raised minimum lasts for the rest of the run. Suites that do not block never trigger this, so they keep the default thread count. TUnit never lowers a minimum that you configured yourself. To turn this off, set context.Settings.Execution.ThreadPoolTuningEnabled = false in a [Before(HookType.TestDiscovery)] hook (see Programmatic Configuration), or set the TUNIT_DISABLE_THREADPOOL_TUNING=1 environment variable.

When a test times out, the error message includes a thread pool snapshot. If the pool looked saturated, the message says the timeout may come from blocking calls in other tests.

Use proper async throughout your tests: await asynchronous APIs instead of blocking with .Wait(), .Result, or .GetAwaiter().GetResult(). Await asynchronous I/O directly rather than wrapping it in Task.Run; Task.Run still uses the same thread pool.

For heavy CPU-bound tests, use a shared ParallelLimiter<T> to reduce concurrency for those tests. The limiter caps concurrent tests that share it, not the number of tasks each test creates.

[NotInParallel] — Disabling Parallelism​

Add [NotInParallel] to prevent a test from running at the same time as other constrained tests.

It accepts an optional array of constraint keys. Tests that share any key will never overlap. Tests with no common key may still run concurrently.

If no keys are supplied, the test runs completely alone — no other test executes at the same time.

using TUnit.Core;

namespace MyTestProject;

public class MyTestClass
{
private const string DatabaseTest = "DatabaseTest";
private const string RegistrationTest = "RegistrationTest";
private const string ParallelTest = "ParallelTest";

[Test]
[NotInParallel(DatabaseTest)]
public async Task MyTest()
{
var count = await Database.GetUserCountAsync();
await Assert.That(count).IsGreaterThanOrEqualTo(0);
}

[Test]
[NotInParallel(new[] { DatabaseTest, RegistrationTest })]
public async Task MyTest2()
{
var user = await Database.CreateUserAsync("alice");
await Assert.That(user.Name).IsEqualTo("alice");
}

[Test]
[NotInParallel(ParallelTest)]
public async Task MyTest3()
{
var result = await Api.PingAsync();
await Assert.That(result.IsSuccess).IsTrue();
}
}

MyTest and MyTest2 share the DatabaseTest key, so they never overlap. MyTest3 has a different key and may run alongside either of them.

Global [NotInParallel]​

Disable parallelism for every test in an assembly (run all tests sequentially):

[assembly: NotInParallel]

[ParallelGroup] — Grouping Tests into Phases​

[ParallelGroup("key")] batches classes into groups. Tests within the same group run in parallel with each other, but no tests from other groups run at the same time. The engine finishes one group entirely before starting the next.

using TUnit.Core;

namespace MyTestProject;

[ParallelGroup("Database")]
public class UserRepositoryTests
{
[Test]
public async Task Create_User()
{
var user = await UserRepository.CreateAsync("alice");
await Assert.That(user.Name).IsEqualTo("alice");
}

[Test]
public async Task Delete_User()
{
await UserRepository.DeleteAsync("bob");
var exists = await UserRepository.ExistsAsync("bob");
await Assert.That(exists).IsFalse();
}
}

[ParallelGroup("Database")]
public class OrderRepositoryTests
{
[Test]
public async Task Create_Order()
{
var order = await OrderRepository.CreateAsync("item-1");
await Assert.That(order.Id).IsNotEmptyGuid();
}
}

[ParallelGroup("ExternalApi")]
public class PaymentApiTests
{
[Test]
public async Task Charge_Succeeds()
{
var result = await PaymentApi.ChargeAsync(100);
await Assert.That(result.Success).IsTrue();
}
}

UserRepositoryTests and OrderRepositoryTests share the "Database" group, so all their tests run together. PaymentApiTests is in "ExternalApi" and runs in a separate phase.

Tests not assigned to any group run separately under normal parallel execution rules.

[ParallelLimiter<T>] — Limiting Concurrent Test Count​

[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.

using TUnit.Core;

namespace MyTestProject;

[ParallelLimiter<MyParallelLimit>]
public class MyTestClass
{
[Test, Repeat(10)]
public async Task MyTest()
{
await Assert.That(true).IsTrue();
}

[Test, Repeat(10)]
public async Task MyTest2()
{
await Assert.That(1 + 1).IsEqualTo(2);
}
}

public record MyParallelLimit : IParallelLimit
{
public int Limit => 2;
}

With a limit of 2, at most two of these 20 test invocations execute at the same time.

Assembly-Level Limiter​

[assembly: ParallelLimiter<MyAssemblyParallelLimit>]

public record MyAssemblyParallelLimit : IParallelLimit
{
public int Limit => 2;
}

More specific attributes override less specific ones. Precedence: Method > Class > Assembly.

Adaptive Limiter​

Experimental

Adaptive limiters are experimental. Their behavior may change, or they may be removed, in a future release. Implementing IAdaptiveParallelLimit reports diagnostic TUNITEXP001; suppress it to opt in, for example with #pragma warning disable TUNITEXP001.

A limiter's limit is often a guess. It usually protects something TUnit cannot observe, such as a database server's connections: too low and tests queue for no reason, too high and they time out. To let TUnit find the limit during the run, implement IAdaptiveParallelLimit in place of IParallelLimit. It adds two properties:

PropertyMeaning
LimitThe limit the run starts at.
MinimumLimitThe lowest limit TUnit goes to. Never less than 1, and never more than Limit.
MaximumLimitThe highest limit TUnit goes to. Never less than Limit.

Use the type with [ParallelLimiter<T>] as you would any other limiter. No command-line flag is needed, and adaptive parallelism does not have to be on.

TUnit decides the limit of an adaptive limiter the same way it decides the session-wide limit under 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, 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 pooled throughput fell by no more than 7.5%. After a measured loss on a multi-slot reduction, TUnit retries with one fewer slot while the workload stays comparable and CPU saturation persists. Five seconds of relief or a sustained workload change allows a fresh quarter-step reduction. 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 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), the measurement in progress is dropped, the limit goes back, and the trial starts again later.

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:

[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.

Setting Maximum Parallel Tests​

You can cap the total number of concurrent tests globally using the command line or an environment variable:

# Command-line flag
dotnet run --project MyTests -- --maximum-parallel-tests 4

# Environment variable
TUNIT_MAX_PARALLEL_TESTS=4 dotnet run --project MyTests

You can also set this programmatically via context.Settings.Parallelism.MaximumParallelTests in a [Before(HookType.TestDiscovery)] hook. See the Programmatic Configuration reference for details.

Finding expensive parallel constraints​

Experimental

The --parallel-constraint-report flag and its output are experimental and may change between releases.

Run a representative selection with --parallel-constraint-report. It works with fixed and adaptive limits. Each project prints one row per observed key or limiter, and a separate row for tests that run alone under bare [NotInParallel]. Rows with the most sampled time while session slots were free appear first.

  • Tests observed counts distinct tests held back by that constraint. For bare [NotInParallel], it counts the tests that ran alone.
  • Elapsed measures wall time with at least one waiting test, or time spent running alone. Ten tests waiting together for one second contribute one second. A test waiting for several keys is charged to one held key at a time. Rows can overlap, so adding them does not predict a speed-up.
  • Sampled with free slots and CPU describe the periods when the constraint held tests back. Short waits can fall between samples. CPU is marked unmeasured when the sampler has no reading.
  • Holder waiting for a session slot with tests behind it measures the part of a keyed wait that earlier slot admission could shorten. A key can be busy for minutes while its holder spends only milliseconds waiting for a slot.

Adaptive Parallelism​

Experimental

Adaptive parallelism is experimental. Its behavior may change, or it may be removed, in a future release. Using context.Settings.Parallelism.Adaptive in code reports diagnostic TUNITEXP001; suppress it to opt in, for example with #pragma warning disable TUNITEXP001.

A fixed limit suits some suites better than others. Tests that mostly await I/O leave the machine idle at 2 x the processor count, while tests that use a lot of memory can exhaust it at the same number. With adaptive parallelism, TUnit changes the limit while the run is in progress. It is off by default.

# Command-line flag
dotnet run --project MyTests -- --adaptive-parallelism

# Environment variable
TUNIT_ADAPTIVE_PARALLELISM=1 dotnet run --project MyTests

You can also set context.Settings.Parallelism.Adaptive = true in a [Before(HookType.TestDiscovery)] hook.

Adaptive parallelism also gives earlier session slots to tests holding busy keys, even when the minimum and maximum are equal. Among queued tests with equal execution priority and order, TUnit alternates between the oldest request and the holder of the key needed by the most remaining tests in its batch. For a test holding several keys, TUnit uses the largest backlog. It counts the tests selected in the current process, including dynamic batches, so this works on a fresh CI runner.

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. TUnit measures throughput, changes the limit, measures again, and puts the limit back if the change did not help. Ordinarily a trial starts 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.

At the session's starting limit there is one exception for noisy I/O workloads. After at least three measurable windows spanning six seconds with queued demand, CPU below 50%, and memory headroom, TUnit can try one raise despite unstable throughput. It pools the baseline completions and measures the trial over at least the baseline duration, up to 30 seconds. The end-of-run details identify this trial and explain why TUnit raised the limit despite variable throughput. The usual gain, pressure, rollback, and exploration-budget rules still apply.

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.

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. A CPU reduction requires at least five continuous seconds of saturation across multiple samples. 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 compares completions per second across two queued measurement windows at each limit, weighting each window by its duration. Across consecutive reductions, throughput may fall at most 7.5% from the rate before the first throughput-measured step. CPU-time trials use a separate baseline from the first step measured by CPU time. After a measured loss, TUnit restores the limit. While the workload stays comparable and CPU saturation persists, the retry after a rejected multi-slot reduction removes just one slot. Five seconds of relief or a sustained workload change allows a fresh quarter-step reduction. If a one-slot reduction costs throughput, TUnit holds the restored limit until saturation eases or three consecutive comparable windows show a sustained change in the same direction. 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 and the same one-slot retry rule applies. If quick tests follow, three consecutive windows with frequent completions and queued tests allow a new throughput trial even if CPU use stays the same. 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<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. 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.

Bounds​

DefaultChange 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
LowestA 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
# 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>].

Limiters With a Declared Limit​

A [ParallelLimiter<T>] 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:

[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​

The readings cover the whole machine, not only the test process, because other test processes, child processes and containers share it.

CPUMemory
LinuxBusy 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.
WindowsBusy time across all processor groups.Physical memory in use; 95% counts as nearly out.
macOSBusy time across all processors.The kernel's own memory pressure level: a warning stops the limit being raised, and critical counts as nearly out.

On every system, thread pool work that waits 100 ms or more for a thread while the CPUs are at least 95% busy also counts as work waiting for a CPU. A container's CPU quota and memory limit are read under cgroup v2 only.

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<T>] is still the right tool when you know a group of tests shares limited capacity.

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:

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 saysWhat 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 containersThe 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 raiseA 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 measureThe 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 timeTests 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 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 limitThat limiter held tests back while the session-wide limit had room. The limiter has a line of its own.
Tests seldom waited for itFewer 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 limitTests 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.

If memory pressure or CPU saturation made the final reduction, the headline names it. Details include peak sampled OS memory use when available. The last CPU reduction includes saturation duration, CPU utilization and the stall signal used. The last memory reduction includes the reading at the decision and any reclaim stalls.

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.

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:

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

Sharing the Limit Between Test Processes​

Experimental

Sharing the limit between test processes is experimental. Its behavior may change, or it may be removed, in a future release.

Each test process sizes its limit as if it had the whole machine. A CI job that runs several test projects at once therefore starts far more tests than the machine has processors: three projects on a 4-processor runner start 3 x 8 = 24 tests between them.

Set TUNIT_SHARED_PARALLEL_BUDGET to the same name in every one of those processes, and they split one limit between them:

export TUNIT_SHARED_PARALLEL_BUDGET=ci-tests
dotnet run --project Api.Tests &
dotnet run --project Services.Tests &
dotnet run --project Web.Tests &
wait
  • The budget is the limit a process would have alone without adaptive parallelism: --maximum-parallel-tests when you set it, or 2 x the processor count. Give every process the same value.
  • Each process that is running tests takes an equal part: 3, 3 and 2 of a budget of 8. A process always runs at least one test at a time, so more processes than the budget has slots still all make progress.
  • When a process finishes, the others take over its part within about half a second. The same holds for a process that crashes or is killed, except in the first five seconds after it joined, when the others can take up to five seconds to notice. A process joins only once it starts running tests, so time spent building or discovering tests takes no part.
  • Running tests are never interrupted. A smaller part takes effect as they finish.

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, 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.

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:

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 (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​

ScenarioAttribute
Tests must never overlap (e.g., shared database state)[NotInParallel("key")]
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<T>]
Same, but the right cap is a guess[ParallelLimiter<T>] with an adaptive limiter
Tests are heavy on CPU or memory and you only want to keep the load downNo attribute: adaptive parallelism
Several test processes run at once on one machineTUNIT_SHARED_PARALLEL_BUDGET
Disable all parallelism for an assembly[assembly: NotInParallel]

Caveats​

  • If a test uses [DependsOn(nameof(OtherTest))] and the dependency has a different parallel limiter or group, ordering is not guaranteed.
  • [NotInParallel] without keys is the most restrictive — the test runs completely alone. Use constraint keys when possible to allow unrelated tests to proceed.