Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
8c5b5ea
perf(engine): size each lane's workers to the current parallel limit
thomhurst Nov 30, 2026
47b9495
feat(engine): one adaptive policy for every parallel limit, driven by…
thomhurst Nov 30, 2026
37f90ee
feat(engine): a shared parallel budget is where an adaptive limit sta…
thomhurst Nov 30, 2026
293b7cd
feat(engine): show the adaptive parallelism summary under dotnet test…
thomhurst Nov 30, 2026
3a820c8
feat(engine): follow a declared [ParallelLimiter] limit of 1 under ad…
thomhurst Nov 30, 2026
d472d66
fix(engine): address review of the adaptive parallelism rework
thomhurst Nov 30, 2026
b0e8ded
fix(engine): count a limiter's queued tests as session demand only wh…
thomhurst Nov 30, 2026
ed25988
fix(engine): hand CPU pressure only to a limiter that is full, and wo…
thomhurst Nov 30, 2026
b90ccd4
fix(engine): never miss a slot change from a shared budget, and tidy …
thomhurst Nov 30, 2026
eadf006
fix(engine): read the slots and their change count as one snapshot, a…
thomhurst Nov 30, 2026
8721ce0
fix(engine): include a limit that moved during warm-up in the summary…
thomhurst Nov 30, 2026
d10ad18
fix(engine): address maintainer review of the adaptive parallelism re…
thomhurst Nov 30, 2026
f1bf9e0
fix(engine): address second maintainer review of the adaptive paralle…
thomhurst Nov 30, 2026
c124796
fix(engine): keep the declared MinimumLimit of a pinned adaptive limiter
thomhurst Nov 30, 2026
cffe38e
fix(engine): address third maintainer review of the adaptive parallel…
thomhurst Nov 30, 2026
5a8f94f
fix(engine): address fourth maintainer review of the adaptive paralle…
thomhurst Nov 30, 2026
17e55de
fix(engine): address fifth review round of the adaptive parallelism r…
thomhurst Nov 30, 2026
609fc3b
fix(engine): address sixth review round of the adaptive parallelism r…
thomhurst Nov 30, 2026
06c7b9d
fix(engine): start added lane workers under the scheduler's context, …
thomhurst Nov 30, 2026
ecb82f7
fix(engine): copy the execution context for each lane worker, and set…
thomhurst Nov 30, 2026
be405ea
fix(engine): use a slot that a test gave back to wait for another test
thomhurst Nov 30, 2026
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
68 changes: 51 additions & 17 deletions docs/docs/execution/parallelism.md

Large diffs are not rendered by default.

24 changes: 18 additions & 6 deletions src/TUnit.Core/Interfaces/IAdaptiveParallelLimit.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,24 @@ namespace TUnit.Core.Interfaces;
/// </summary>
/// <remarks>
/// <para>
/// The run starts at <see cref="IParallelLimit.Limit"/>. 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 <see cref="IParallelLimit.Limit"/>. 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.
/// </para>
/// <para>
/// The limit is lowered only while the CPUs are saturated and most of the running tests are
Comment thread
thomhurst marked this conversation as resolved.
Resolved
/// 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 <see cref="IParallelLimit.Limit"/>
/// comes back down toward it for saturated CPUs whatever causes them.
/// </para>
/// <para>
/// A limiter that implements only <see cref="IParallelLimit"/> is never raised: under
/// adaptive parallelism its limit is a ceiling.
/// </para>
/// <para>
/// This needs .NET 8 or later. Elsewhere the limit stays at <see cref="IParallelLimit.Limit"/>.
Expand Down
124 changes: 106 additions & 18 deletions src/TUnit.Core/ParallelLimitLockProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@ public class ParallelLimitLockProvider
private readonly Lock _adaptiveLocksLock = new();
private volatile ParallelLimitLock[] _adaptiveLocks = [];

/// <summary>
/// Whether the limit of a [ParallelLimiter] that is not an <see cref="IAdaptiveParallelLimit"/>
/// 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.
/// </summary>
internal bool FixedLimitsAreCeilings { get; set; }

internal ParallelLimitLock GetLock(IParallelLimit parallelLimit)
{
if (parallelLimit.Limit <= 0)
Expand All @@ -22,20 +29,21 @@ internal ParallelLimitLock GetLock(IParallelLimit parallelLimit)
}

/// <summary>
/// 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.
/// </summary>
internal ParallelLimitLock[] AdaptiveLocks => _adaptiveLocks;

/// <summary>
/// Called each time a lock whose limit can be adjusted is created.
/// Called each time a lock that adaptive parallelism follows is created.
/// </summary>
internal Action? AdaptiveLockCreated { get; set; }

private ParallelLimitLock CreateLock(IParallelLimit parallelLimit)
{
var parallelLimitLock = ParallelLimitLock.Create(parallelLimit);
var parallelLimitLock = ParallelLimitLock.Create(parallelLimit, FixedLimitsAreCeilings);
Comment thread
thomhurst marked this conversation as resolved.
Resolved

if (parallelLimitLock.IsAdaptive)
if (parallelLimitLock.IsObserved)
{
lock (_adaptiveLocksLock)
{
Expand All @@ -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)
/// <param name="parallelLimit">The limiter the lock is for.</param>
/// <param name="fixedLimitIsCeiling">
/// Whether a limit that is not an <see cref="IAdaptiveParallelLimit"/> 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.
/// </param>
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);
Comment thread
thomhurst marked this conversation as resolved.
Resolved
}

public Type LimitType { get; }
Expand All @@ -102,6 +129,20 @@ public static ParallelLimitLock Create(IParallelLimit parallelLimit)
/// </summary>
public bool IsAdaptive => Minimum < Maximum;

/// <summary>
/// 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.
/// </summary>
public bool IsObserved { get; }

/// <summary>
/// Whether the limiter is an <see cref="IAdaptiveParallelLimit"/>, whose own bounds
/// decide how far the limit can move.
/// </summary>
public bool IsDeclaredAdaptive { get; private init; }

public int CurrentLimit => _semaphore.CurrentLimit;

/// <summary>
Expand All @@ -111,8 +152,38 @@ public static ParallelLimitLock Create(IParallelLimit parallelLimit)
public bool IsFull => _semaphore.AvailableSlots == 0;

/// <summary>
/// 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.
/// </summary>
public int HeldPlaces => _semaphore.HeldSlots;

/// <summary>
/// The number of tests waiting to enter the lock right now. Counted only when <see cref="IsObserved"/>.
/// </summary>
public int Waiting => _semaphore.Waiting;

/// <inheritdoc cref="ResizableSemaphore.BeginWait"/>
public bool BeginWait(Task wait) => _semaphore.BeginWait(wait);

/// <inheritdoc cref="ResizableSemaphore.EndWait"/>
public void EndWait(bool counted) => _semaphore.EndWait(counted);

/// <summary>
/// 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.
/// </summary>
public int Backlog => Volatile.Read(ref _backlog);

public void AddBacklog(int tests) => Interlocked.Add(ref _backlog, tests);

/// <summary>
/// Whether the lock is full while more of its tests could start at once: this limit, and
/// nothing else, is what holds them back.
/// </summary>
public bool HasUnmetDemand => IsFull && (Backlog > 0 || Waiting > 0);

/// <summary>
/// The number of tests that have left the lock, and how many of them failed, read
/// together. Counted only when <see cref="IsObserved"/>.
/// </summary>
public (long Finished, long Failed) ReadCounts()
{
Expand All @@ -128,10 +199,10 @@ public static ParallelLimitLock Create(IParallelLimit parallelLimit)

public Task EnterAsync(CancellationToken cancellationToken) => _semaphore.WaitAsync(cancellationToken);

/// <param name="testFailed">Whether the test that leaves failed. Counted for an adaptive lock only.</param>
/// <param name="testFailed">Whether the test that leaves failed. Counted only when <see cref="IsObserved"/>.</param>
public void Exit(bool testFailed)
{
if (IsAdaptive)
if (IsObserved)
{
Interlocked.Add(ref _counts, testFailed ? (1L << 32) + 1 : 1);
}
Expand All @@ -142,5 +213,22 @@ public void Exit(bool testFailed)
/// <summary>
/// Changes the limit, kept within <see cref="Minimum"/> and <see cref="Maximum"/>, and returns it.
/// </summary>
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;
}

/// <summary>
/// Raised after the limit has changed, on the thread that changed it. The workers that
/// start this limiter's tests follow it.
/// </summary>
public event Action? LimitChanged;
}
51 changes: 51 additions & 0 deletions src/TUnit.Core/ResizableSemaphore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/// <param name="initial">The number of slots to start with.</param>
/// <param name="maximum">The most slots <see cref="SetLimit"/> can ever grow to.</param>
/// <param name="resizable">Whether <see cref="SetLimit"/> may be called.</param>
Expand All @@ -47,11 +50,59 @@ public ResizableSemaphore(int initial, int maximum, bool resizable)
/// </summary>
public long CountedReleases => Volatile.Read(ref _countedReleases);

/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
public int HeldSlots => Math.Max(0, Volatile.Read(ref _currentLimit) + Volatile.Read(ref _slotsToRetire) - _semaphore.CurrentCount);

/// <summary>
/// The number of callers waiting for a slot right now. Always 0 unless resizable.
/// </summary>
public int Waiting => Volatile.Read(ref _waiting);

/// <summary>
/// Waits for a slot. An uncontended wait completes synchronously without allocating.
/// </summary>
public Task WaitAsync(CancellationToken cancellationToken) => _semaphore.WaitAsync(cancellationToken);

/// <summary>
/// Counts the caller as waiting for a slot, when <paramref name="wait"/> has to queue
/// and the semaphore is resizable. Returns whether it was counted, which the caller
/// hands to <see cref="EndWait"/> once the wait is over, however it ended.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
public bool BeginWait(Task wait)
{
if (!_resizable || wait.IsCompleted)
{
return false;
}

Interlocked.Increment(ref _waiting);
return true;
}

/// <param name="counted">What <see cref="BeginWait"/> returned for the wait.</param>
public void EndWait(bool counted)
{
if (counted)
{
Interlocked.Decrement(ref _waiting);
}
}

/// <summary>
/// Waits for a slot for at most <paramref name="millisecondsTimeout"/>. With 0 it never
/// waits: the task is already complete, with <c>false</c> when no slot is free.
Expand Down
4 changes: 4 additions & 0 deletions src/TUnit.Engine/Configuration/EnvironmentConstants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
39 changes: 39 additions & 0 deletions src/TUnit.Engine/Logging/ISessionMessageLogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using TUnit.Core.Logging;

namespace TUnit.Engine.Logging;

/// <summary>
/// A logger that can write a line which stays in the output of the whole test run.
/// </summary>
/// <remarks>
/// When <c>dotnet test</c> 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).
/// </remarks>
internal interface ISessionMessageLogger
{
/// <summary>
/// Writes <paramref name="message"/> at <see cref="LogLevel.Information"/> as a message
/// that belongs to the test session.
/// </summary>
void LogSessionMessage(string message);
}

internal static class SessionMessageLoggerExtensions
{
/// <summary>
/// Writes a line that ends the run: as a session message where the logger has them, and
/// as an ordinary <see cref="LogLevel.Information"/> line otherwise.
/// </summary>
public static void LogSessionMessage(this ILogger logger, string message)
{
if (logger is ISessionMessageLogger sessionMessageLogger)
{
sessionMessageLogger.LogSessionMessage(message);
}
else
{
logger.LogInformation(message);
}
}
}
15 changes: 14 additions & 1 deletion src/TUnit.Engine/Logging/TUnitFrameworkLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -64,6 +64,19 @@ public void Log<TState>(LogLevel logLevel, TState state, Exception? exception, F
_adapter.Log(logLevel, state, exception, formatter);
}

/// <inheritdoc />
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)
Expand Down
Loading
Loading