diff --git a/docs/docs/execution/parallelism.md b/docs/docs/execution/parallelism.md
index 394192ccdc..0a4045021d 100644
--- a/docs/docs/execution/parallelism.md
+++ b/docs/docs/execution/parallelism.md
@@ -219,10 +219,10 @@ TUNIT_ADAPTIVE_PARALLELISM=1 dotnet run --project MyTests
You can also set `context.Settings.Parallelism.Adaptive = true` in a `[Before(HookType.TestDiscovery)]` hook.
-The run starts at the limit a run without adaptive parallelism uses: `--maximum-parallel-tests` when you set it, or 2 x the processor count. A move away from that limit has to pay for itself in completed tests per second. TUnit measures throughput, changes the limit, measures again, and puts the limit back if the change did not help. After a change that did not help, it waits before trying another: 15 seconds at first, doubling up to 2 minutes.
+The run starts at the limit a run without adaptive parallelism uses: `--maximum-parallel-tests` when you set it, or 2 x the processor count. A move away from that limit has to pay for itself in completed tests per second. TUnit measures throughput, changes the limit, measures again, and puts the limit back if the change did not help. It starts only once two measurements in a row agree, so a suite whose throughput is still changing (a shared fixture starting, for example) is left alone until it settles. After a change that did not help, it waits before trying another. For a raise the wait is 5 seconds at first, doubling up to 30 seconds. For a lowering it is 15 seconds at first, doubling up to 2 minutes.
-- **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.
-- **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. TUnit never lowers the limit below the processor count for this reason.
+- **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.
diff --git a/src/TUnit.Engine/Scheduling/AdaptiveParallelismController.cs b/src/TUnit.Engine/Scheduling/AdaptiveParallelismController.cs
index fb0a218208..0fe0dbdf39 100644
--- a/src/TUnit.Engine/Scheduling/AdaptiveParallelismController.cs
+++ b/src/TUnit.Engine/Scheduling/AdaptiveParallelismController.cs
@@ -198,7 +198,7 @@ private void Sample(ParallelismLimits limits)
&& TrySetLimit(decision.Limit, out var previousLimit, out var limit)
&& _logger.IsEnabled(LogLevel.Debug))
{
- _logger.LogDebug($"Adaptive parallelism: limit {previousLimit} -> {limit} ({Describe(decision.Change)}); CPU {cpuUtilization * 100:0}%, memory load {memoryLoad * 100:0}%");
+ _logger.LogDebug($"Adaptive parallelism: limit {previousLimit} -> {limit} ({Describe(decision.Change)}); CPU {cpuUtilization * 100:0}% in the latest sample, memory load {memoryLoad * 100:0}%");
}
previousCpuTime = cpuTime;
@@ -239,9 +239,10 @@ private bool TrySetLimit(int requestedLimit, out int previousLimit, out int limi
{
AdaptiveLimitChange.Probe => "probing for more throughput",
AdaptiveLimitChange.ProbeReverted => "the last raise did not improve throughput",
+ AdaptiveLimitChange.ProbeAborted => "the last raise left the CPUs busy",
AdaptiveLimitChange.Recovery => "pressure eased",
AdaptiveLimitChange.MemoryPressure => "memory pressure",
- AdaptiveLimitChange.CpuSaturation => "CPUs saturated and work is queuing for a thread; checking that fewer tests cost no throughput",
+ AdaptiveLimitChange.CpuSaturation => "CPUs saturated; checking that fewer tests cost no throughput",
AdaptiveLimitChange.LowerReverted => "the lower limit cost throughput",
_ => change.ToString(),
};
diff --git a/src/TUnit.Engine/Scheduling/AdaptiveParallelismPolicy.cs b/src/TUnit.Engine/Scheduling/AdaptiveParallelismPolicy.cs
index ae51bf0244..7f3ed5fa30 100644
--- a/src/TUnit.Engine/Scheduling/AdaptiveParallelismPolicy.cs
+++ b/src/TUnit.Engine/Scheduling/AdaptiveParallelismPolicy.cs
@@ -29,6 +29,9 @@ internal enum AdaptiveLimitChange
/// The last probe did not raise throughput enough, so its raise was undone.
ProbeReverted,
+ /// The last probe left the CPUs busy, so its raise was undone without waiting for a verdict.
+ ProbeAborted,
+
/// Raised back toward the starting limit after pressure eased.
Recovery,
@@ -65,6 +68,13 @@ internal enum AdaptiveLimitChange
/// limit back and makes the next one wait longer.
///
///
+/// A trial compares two windows, so it means something only while the tests themselves are not
+/// changing. Tests that all wait on one shared fixture and then finish together look like a
+/// gain to whichever trial is running. So a trial starts only after two windows in a row agree
+/// on throughput, and a raise above the starting limit is also held to what it does to the
+/// CPUs: it is undone as soon as they are busy, without waiting for the verdict.
+///
+///
/// There are two exceptions. Memory pressure lowers the limit at once, because swapping or an
/// out-of-memory kill costs far more than a trial. And the starting limit needs no proof: the
/// policy returns to it once the machine has headroom again.
@@ -79,6 +89,10 @@ internal sealed class AdaptiveParallelismPolicy
internal const double CpuHeadroomUtilization = 0.8;
internal const double MemoryHeadroomLoad = 0.85;
+ // A raise above the starting limit started with headroom. CPUs this busy mean the extra
+ // tests used it up, and from here they only take CPU time from each other.
+ internal const double ProbeCpuCeiling = 0.9;
+
internal const double MemoryPressureLoad = 1.0;
// Longer than OS scheduling jitter, shorter than a delay a timing-sensitive test would notice.
@@ -101,6 +115,11 @@ internal sealed class AdaptiveParallelismPolicy
// sends an undecided trial back to the limit it started from.
internal const double MinimumGainShare = 0.3;
+ // Two windows in a row at one limit must agree this closely before a trial starts: the
+ // gain a raise has to show. Windows further apart mean the tests are changing (a shared
+ // fixture starting, a different kind of test coming up), and a verdict would be noise.
+ internal const double SteadyThroughputTolerance = (IncreaseFactor - 1) * MinimumGainShare;
+
internal static readonly TimeSpan MinimumWindow = TimeSpan.FromSeconds(1);
internal static readonly TimeSpan MaximumWindow = TimeSpan.FromSeconds(30);
@@ -111,9 +130,18 @@ internal sealed class AdaptiveParallelismPolicy
internal static readonly TimeSpan PressureCooldown = TimeSpan.FromSeconds(3);
// After a failed trial or memory pressure, how long before the next trial. Doubles each time.
- internal static readonly TimeSpan InitialHold = TimeSpan.FromSeconds(15);
+ // A raise that fails is undone within a sample or two when it overloads the CPUs, so
+ // another may follow soon. A lowering that fails costs throughput until its verdict, and
+ // memory pressure risks the run, so those wait longer.
+ internal static readonly TimeSpan InitialRaiseHold = TimeSpan.FromSeconds(5);
+ internal static readonly TimeSpan InitialLowerHold = TimeSpan.FromSeconds(15);
+ internal static readonly TimeSpan MemoryPressureHold = TimeSpan.FromSeconds(15);
internal static readonly TimeSpan MaximumHold = TimeSpan.FromMinutes(2);
+ // Failed raises stop doubling here, so a long run still notices within half a minute when
+ // later tests can use more concurrency than earlier ones could.
+ internal static readonly TimeSpan MaximumRaiseHold = TimeSpan.FromSeconds(30);
+
// After a change, tests admitted under the old limit are still running. Throughput reflects
// the new limit only once about one test duration has passed.
internal static readonly TimeSpan MaximumSettle = TimeSpan.FromSeconds(15);
@@ -137,10 +165,17 @@ internal sealed class AdaptiveParallelismPolicy
private double _throughputBeforeTrial;
// Throughput of the latest window, and the limit it was measured at: 0 when that window
- // could not be compared with another. A trial starts only from a measurement at the
- // current limit.
- private double _measuredThroughput;
- private int _measuredLimit;
+ // could not be compared with another.
+ private double _lastThroughput;
+ private int _lastLimit;
+
+ // The mean of the latest two windows when they agree, and the limit both were measured
+ // at: 0 when they do not. A trial starts only from a steady measurement at the current limit.
+ private double _steadyThroughput;
+ private int _steadyLimit;
+
+ // Samples in a row that a raise above the starting limit has left the CPUs busy.
+ private int _probeBusySamples;
// Throughput before the first of a run of lowerings, and the limit it was measured at.
// Every lowering is judged against it for as long as the limit stays below that one, so
@@ -153,9 +188,12 @@ internal sealed class AdaptiveParallelismPolicy
private TimeSpan _averageSlotTime = MinimumWindow;
// Raises and lowerings wait separately: a failed raise says nothing against lowering.
- private TimeSpan _raiseHold = InitialHold;
+ private TimeSpan _raiseHold = InitialRaiseHold;
private TimeSpan _raiseHoldUntil;
- private TimeSpan _lowerHold = InitialHold;
+ private TimeSpan _lowerHold = InitialLowerHold;
+
+ // Memory pressure has its own wait, so failed raises neither lengthen nor shorten it.
+ private TimeSpan _memoryHold = MemoryPressureHold;
private TimeSpan _lowerHoldUntil;
// While pressure is recent, the limit stays below the one that caused it.
@@ -191,6 +229,13 @@ public AdaptiveDecision OnSample(AdaptiveSample sample)
return relieved;
}
+ // Before the settling check on purpose: the samples right after a raise, while the
+ // extra tests start, are the ones that show what it does to the CPUs.
+ if (TryAbortProbe(sample) is { } aborted)
+ {
+ return aborted;
+ }
+
if (_settling)
{
_settleRemaining -= sample.Elapsed;
@@ -217,10 +262,13 @@ public AdaptiveDecision OnSample(AdaptiveSample sample)
var measurable = _windowCompleted >= MinimumWindowCompletions
&& _windowLimitReachedSamples * 2 >= _windowSamples;
+ var cpuUtilization = _windowCpuSeconds / _windowElapsed.TotalSeconds;
+ var cpuStalled = _windowCpuStalledSamples * 4 >= _windowSamples;
+
var hasMemoryHeadroom = _windowMaxMemoryLoad < MemoryHeadroomLoad;
- var hasCpuHeadroom = _windowCpuSeconds / _windowElapsed.TotalSeconds < CpuHeadroomUtilization
+ var hasCpuHeadroom = cpuUtilization < CpuHeadroomUtilization
&& _windowMaxQueueDelay < QueueDelayLimit
- && _windowCpuStalledSamples * 4 < _windowSamples;
+ && !cpuStalled;
ResetWindow();
@@ -240,7 +288,14 @@ public AdaptiveDecision OnSample(AdaptiveSample sample)
? _throughputBeforeTrial * (1 + change * MinimumGainShare)
: _throughputBeforeLowering * (1 - (1 - CpuDecreaseFactor) * MinimumGainShare);
- if (!measurable || throughput < requiredThroughput)
+ // More completed tests do not justify a raise above the starting limit that
+ // leaves the CPUs busy: the tests may have changed between the two windows, and
+ // the busy CPUs are the cost that is certain.
+ var overloaded = raised
+ && _limit > _limits.Initial
+ && (cpuUtilization >= ProbeCpuCeiling || cpuStalled);
+
+ if (!measurable || throughput < requiredThroughput || overloaded)
{
if (raised)
{
@@ -256,20 +311,34 @@ public AdaptiveDecision OnSample(AdaptiveSample sample)
if (raised)
{
- _raiseHold = InitialHold;
+ _raiseHold = InitialRaiseHold;
+ _memoryHold = MemoryPressureHold;
EndLoweringRunAt(_limit);
}
+ else if (_limitBeforeTrial > _limits.Initial)
+ {
+ // Fewer tests did as well above the starting limit, so the raise that led
+ // there was a mistake, and the next one waits like any failed raise.
+ _lowerHold = InitialLowerHold;
+ HoldRaises();
+ }
else
{
// Fewer tests did as well, so trying more again straight away would only
// undo it. The wait does not grow: nothing failed.
- _lowerHold = InitialHold;
- _raiseHoldUntil = _clock + _raiseHold;
+ _lowerHold = InitialLowerHold;
+ HoldRaisesUntil(_clock + _raiseHold);
}
}
- _measuredThroughput = throughput;
- _measuredLimit = measurable ? _limit : 0;
+ var steady = measurable
+ && _lastLimit == _limit
+ && Math.Abs(throughput - _lastThroughput) <= Math.Max(throughput, _lastThroughput) * SteadyThroughputTolerance;
+
+ _steadyThroughput = steady ? (throughput + _lastThroughput) / 2 : 0;
+ _steadyLimit = steady ? _limit : 0;
+ _lastThroughput = throughput;
+ _lastLimit = measurable ? _limit : 0;
if (!hasMemoryHeadroom)
{
@@ -306,12 +375,12 @@ public AdaptiveDecision OnSample(AdaptiveSample sample)
return NoChange();
}
- if (!measurable || _clock < _raiseHoldUntil)
+ if (_steadyLimit != _limit || _clock < _raiseHoldUntil)
{
return NoChange();
}
- return StartTrial(higher, AdaptiveLimitChange.Probe, throughput);
+ return StartTrial(higher, AdaptiveLimitChange.Probe, _steadyThroughput);
}
private AdaptiveDecision StartTrial(int limit, AdaptiveLimitChange change, double throughput)
@@ -325,6 +394,7 @@ private AdaptiveDecision StartTrial(int limit, AdaptiveLimitChange change, doubl
}
_trial = change;
+ _probeBusySamples = 0;
_limitBeforeTrial = _limit;
_throughputBeforeTrial = throughput;
return ChangeLimit(limit, change);
@@ -333,9 +403,12 @@ private AdaptiveDecision StartTrial(int limit, AdaptiveLimitChange change, doubl
private AdaptiveDecision? TryRelievePressure(AdaptiveSample sample)
{
// Either the CPUs are all busy while work queues for a thread, or the operating
- // system says outright that tasks are waiting for a CPU.
+ // system says outright that tasks are waiting for a CPU. Above the starting limit busy
+ // CPUs are enough: the limit is there on the strength of one trial, the thread pool
+ // grows to keep its queue short, and only Linux reports waiting tasks.
var saturated = sample.CpuStalled
- || (sample.CpuUtilization >= SaturatedCpuUtilization && sample.QueueDelay >= QueueDelayLimit);
+ || (sample.CpuUtilization >= SaturatedCpuUtilization
+ && (sample.QueueDelay >= QueueDelayLimit || _limit > _limits.Initial));
_saturatedSamples = saturated ? _saturatedSamples + 1 : 0;
if (_limit <= _limits.Minimum || _clock < _pressureCooldownUntil)
@@ -348,22 +421,52 @@ private AdaptiveDecision StartTrial(int limit, AdaptiveLimitChange change, doubl
return LowerForMemoryPressure();
}
- // A lowering for CPU saturation is a trial, so it needs a throughput measurement at
- // this limit to be judged against, and no other trial in progress.
+ // A lowering for CPU saturation is a trial, so it needs a steady throughput
+ // measurement at this limit to be judged against, and no other trial in progress.
if (_saturatedSamples >= SaturatedSamplesBeforeDecrease
&& _limit > _cpuSaturationFloor
&& _trial == AdaptiveLimitChange.None
&& !_settling
- && _measuredLimit == _limit
+ && _steadyLimit == _limit
&& _clock >= _lowerHoldUntil)
{
_saturatedSamples = 0;
- return StartTrial(Math.Max(_cpuSaturationFloor, LowerBy(CpuDecreaseFactor)), AdaptiveLimitChange.CpuSaturation, _measuredThroughput);
+
+ // From above the starting limit, one step goes no further down than back to it.
+ var floor = _limit > _limits.Initial ? Math.Max(_cpuSaturationFloor, _limits.Initial) : _cpuSaturationFloor;
+ return StartTrial(Math.Max(floor, LowerBy(CpuDecreaseFactor)), AdaptiveLimitChange.CpuSaturation, _steadyThroughput);
}
return null;
}
+ ///
+ /// Undoes a raise above the starting limit once the CPUs have been busy for two samples in
+ /// a row. Its verdict is a test duration and a window away, and until then every running
+ /// test pays for the extra ones.
+ ///
+ private AdaptiveDecision? TryAbortProbe(AdaptiveSample sample)
+ {
+ // A raise from below the starting limit stops at it, so a limit above it here was
+ // raised from the starting limit or higher, and undoing it never goes below.
+ if (_trial != AdaptiveLimitChange.Probe || _limit <= _limits.Initial)
+ {
+ return null;
+ }
+
+ var busy = sample.CpuStalled || sample.CpuUtilization >= ProbeCpuCeiling;
+ _probeBusySamples = busy ? _probeBusySamples + 1 : 0;
+
+ if (_probeBusySamples < SaturatedSamplesBeforeDecrease)
+ {
+ return null;
+ }
+
+ _trial = AdaptiveLimitChange.None;
+ HoldRaises();
+ return ChangeLimit(_limitBeforeTrial, AdaptiveLimitChange.ProbeAborted);
+ }
+
private int LowerBy(double factor) => Math.Max(_limits.Minimum, Math.Min(_limit - 1, (int) (_limit * factor)));
private AdaptiveDecision LowerForMemoryPressure()
@@ -373,12 +476,13 @@ private AdaptiveDecision LowerForMemoryPressure()
// Halfway back is the highest the limit may return to while the pressure is recent, so
// repeated pressure closes in on a limit the machine can hold.
_pressureCap = Math.Max(lowered, (_limit + lowered) / 2);
- _pressureCapUntil = _clock + _raiseHold;
+ _pressureCapUntil = _clock + _memoryHold;
_pressureCooldownUntil = _clock + PressureCooldown;
_saturatedSamples = 0;
_trial = AdaptiveLimitChange.None;
_throughputBeforeLowering = 0;
- HoldRaises();
+ HoldRaisesUntil(_pressureCapUntil);
+ _memoryHold = Double(_memoryHold);
return ChangeLimit(lowered, AdaptiveLimitChange.MemoryPressure);
}
@@ -392,10 +496,14 @@ private void EndLoweringRunAt(int limit)
}
}
+ // Failed raises, kept lowerings and memory pressure each make raises wait. A shorter wait
+ // never cuts a longer one short.
+ private void HoldRaisesUntil(TimeSpan until) => _raiseHoldUntil = until > _raiseHoldUntil ? until : _raiseHoldUntil;
+
private void HoldRaises()
{
- _raiseHoldUntil = _clock + _raiseHold;
- _raiseHold = Double(_raiseHold);
+ HoldRaisesUntil(_clock + _raiseHold);
+ _raiseHold = TimeSpan.FromTicks(Math.Min(_raiseHold.Ticks * 2, MaximumRaiseHold.Ticks));
}
private static TimeSpan Double(TimeSpan hold) => TimeSpan.FromTicks(Math.Min(hold.Ticks * 2, MaximumHold.Ticks));
@@ -403,7 +511,8 @@ private void HoldRaises()
private AdaptiveDecision ChangeLimit(int limit, AdaptiveLimitChange change)
{
_limit = limit;
- _measuredLimit = 0;
+ _lastLimit = 0;
+ _steadyLimit = 0;
_settling = true;
_settleRemaining = TimeSpan.FromTicks(Math.Min(Math.Max(_averageSlotTime.Ticks, MinimumWindow.Ticks), MaximumSettle.Ticks));
return new AdaptiveDecision(limit, change);
diff --git a/tests/TUnit.UnitTests/AdaptiveParallelismPolicyTests.cs b/tests/TUnit.UnitTests/AdaptiveParallelismPolicyTests.cs
index b06fb78079..ec92c1f66e 100644
--- a/tests/TUnit.UnitTests/AdaptiveParallelismPolicyTests.cs
+++ b/tests/TUnit.UnitTests/AdaptiveParallelismPolicyTests.cs
@@ -29,7 +29,7 @@ public async Task Reverts_A_Raise_That_Brings_No_Throughput()
Throughput = limit => Math.Min(limit, 16) * TestsPerSecondPerSlot,
};
- simulation.Run(TimeSpan.FromSeconds(10));
+ simulation.Run(TimeSpan.FromSeconds(8));
await Assert.That(simulation.Changes).IsEquivalentTo(
[
@@ -48,11 +48,152 @@ public async Task Waits_Longer_Before_Each_Probe_After_A_Failed_One()
simulation.Run(TimeSpan.FromSeconds(60));
- // Probes at about 1 s, 18 s (15 s hold) and 51 s (30 s hold).
- await Assert.That(simulation.Changes.Count(x => x.Change == AdaptiveLimitChange.Probe)).IsEqualTo(3);
+ // Probes at about 2 s, 9 s (5 s hold), 22 s (10 s hold) and 44 s (20 s hold).
+ await Assert.That(simulation.Changes.Count(x => x.Change == AdaptiveLimitChange.Probe)).IsEqualTo(4);
await Assert.That(simulation.Changes.Max(x => x.Limit)).IsEqualTo(24);
}
+ [Test]
+ public async Task Does_Not_Raise_Before_Two_Windows_Agree()
+ {
+ var simulation = new Simulation(Limits);
+
+ // One window is not enough: the first raise waits for a second that agrees with it.
+ simulation.Run(TimeSpan.FromSeconds(1.75));
+ await Assert.That(simulation.Changes).IsEmpty();
+
+ simulation.Step();
+ await Assert.That(simulation.Changes).IsEquivalentTo([new AdaptiveDecision(24, AdaptiveLimitChange.Probe)]);
+ }
+
+ [Test]
+ public async Task Does_Not_Raise_While_Tests_Wait_On_A_Shared_Fixture_Then_Finish_Together()
+ {
+ // Quick tests first. Then every slot holds a test waiting for one fixture, and nothing
+ // completes. Then the fixture is ready and they all finish at once. The CPUs are idle
+ // throughout, and every slot is in use.
+ var simulation = new Simulation(Limits);
+ simulation.Run(TimeSpan.FromSeconds(1));
+
+ simulation.Throughput = _ => 2;
+ simulation.Run(TimeSpan.FromSeconds(6));
+
+ simulation.Throughput = _ => 400;
+ simulation.Run(TimeSpan.FromSeconds(1));
+
+ await Assert.That(simulation.Changes).IsEmpty();
+
+ // Once throughput settles, the limit is probed as usual.
+ simulation.Throughput = limit => limit * TestsPerSecondPerSlot;
+ simulation.Run(TimeSpan.FromSeconds(4));
+
+ await Assert.That(simulation.Changes.Select(x => x.Change)).Contains(AdaptiveLimitChange.Probe);
+ }
+
+ [Test]
+ [Arguments(120, false)]
+ [Arguments(150, true)]
+ public async Task Raises_Only_When_Consecutive_Windows_Are_Within_The_Gain_A_Raise_Must_Show(int otherWindowThroughput, bool raises)
+ {
+ // One-second windows that alternate between 160 tests per second and the other figure:
+ // 25% apart, or 6%. A raise has to show 15%.
+ var simulation = new Simulation(Limits);
+
+ for (var second = 0; second < 20 && simulation.Changes.Count == 0; second++)
+ {
+ var throughput = second % 2 == 0 ? 160 : otherWindowThroughput;
+ simulation.Throughput = _ => throughput;
+ simulation.Run(TimeSpan.FromSeconds(1));
+ }
+
+ await Assert.That(simulation.Changes.Any(x => x.Change == AdaptiveLimitChange.Probe)).IsEqualTo(raises);
+ }
+
+ [Test]
+ public async Task Undoes_A_Raise_As_Soon_As_It_Leaves_The_Cpus_Busy()
+ {
+ var simulation = new Simulation(Limits);
+ simulation.RunUntilChange();
+ await Assert.That(simulation.Changes[0]).IsEqualTo(new AdaptiveDecision(24, AdaptiveLimitChange.Probe));
+
+ // The extra tests are CPU-bound. One busy sample can be a burst; the second undoes it.
+ simulation.CpuUtilization = 0.97;
+ simulation.Step();
+ await Assert.That(simulation.Changes.Count).IsEqualTo(1);
+
+ simulation.Step();
+ await Assert.That(simulation.Changes[1]).IsEqualTo(new AdaptiveDecision(16, AdaptiveLimitChange.ProbeAborted));
+ }
+
+ [Test]
+ public async Task Does_Not_Keep_A_Raise_That_Leaves_The_Cpus_Busy_On_Average()
+ {
+ var simulation = new Simulation(Limits);
+ simulation.RunUntilChange();
+
+ // Never busy two samples in a row, so the raise reaches its verdict, and throughput
+ // followed the limit. The window still averages 92% CPU.
+ for (var i = 0; simulation.Changes.Count == 1 && i < 100; i++)
+ {
+ simulation.CpuUtilization = i % 2 == 0 ? 0.99 : 0.85;
+ simulation.Step();
+ }
+
+ await Assert.That(simulation.Changes[1]).IsEqualTo(new AdaptiveDecision(16, AdaptiveLimitChange.ProbeReverted));
+ }
+
+ [Test]
+ public async Task Busy_Cpus_Do_Not_Undo_A_Raise_Back_Toward_The_Starting_Limit()
+ {
+ var simulation = new Simulation(Limits) { MemoryLoad = 1.05 };
+ simulation.Run(TimeSpan.FromSeconds(1));
+
+ // Other processes keep the CPUs busy. Below the starting limit that is no evidence
+ // against this process, so the way back is judged on throughput alone.
+ simulation.MemoryLoad = 0.3;
+ simulation.CpuUtilization = 0.97;
+ simulation.Run(TimeSpan.FromSeconds(60));
+
+ await Assert.That(simulation.Changes.Select(x => x.Change)).DoesNotContain(AdaptiveLimitChange.ProbeAborted);
+ await Assert.That(simulation.Policy.Limit).IsEqualTo(Limits.Initial);
+ }
+
+ [Test]
+ public async Task Busy_Cpus_Alone_Lower_A_Limit_Above_The_Starting_One()
+ {
+ var simulation = new Simulation(Limits);
+ simulation.Run(TimeSpan.FromSeconds(8));
+ await Assert.That(simulation.Policy.Limit).IsGreaterThan(Limits.Initial);
+
+ // The tests turn CPU-bound: sixteen at once now do as much as any higher number. No
+ // work queues for a thread and the system reports no waiting tasks.
+ simulation.Throughput = _ => 16 * TestsPerSecondPerSlot;
+ simulation.CpuUtilization = 0.99;
+ simulation.Run(TimeSpan.FromSeconds(60));
+
+ // Back down to the starting limit, and no further: there, busy CPUs alone prove nothing.
+ await Assert.That(simulation.Policy.Limit).IsEqualTo(Limits.Initial);
+ await Assert.That(simulation.Changes.Select(x => x.Change)).DoesNotContain(AdaptiveLimitChange.LowerReverted);
+ }
+
+ [Test]
+ public async Task Failed_Raises_Are_Never_More_Than_Half_A_Minute_Apart()
+ {
+ var simulation = new Simulation(Limits)
+ {
+ Throughput = limit => Math.Min(limit, 16) * TestsPerSecondPerSlot,
+ };
+
+ simulation.Run(TimeSpan.FromMinutes(10));
+ var probesBefore = simulation.Changes.Count(x => x.Change == AdaptiveLimitChange.Probe);
+
+ // Each failed raise is followed by a 30 s hold, the raise itself and its verdict.
+ simulation.Run(TimeSpan.FromMinutes(5));
+ var probes = simulation.Changes.Count(x => x.Change == AdaptiveLimitChange.Probe) - probesBefore;
+
+ await Assert.That(probes).IsBetween(7, 10);
+ }
+
[Test]
public async Task Does_Not_Raise_Without_Cpu_Headroom()
{
@@ -114,6 +255,34 @@ public async Task Memory_Pressure_Halves_The_Limit_Then_Waits_For_It_To_Take_Eff
await Assert.That(simulation.Changes).IsEquivalentTo([new AdaptiveDecision(8, AdaptiveLimitChange.MemoryPressure)]);
}
+ [Test]
+ public async Task Failed_Raises_Do_Not_Lengthen_The_Wait_After_Memory_Pressure()
+ {
+ // A minute of failed raises: the next one would wait 30 s.
+ var simulation = new Simulation(Limits)
+ {
+ Throughput = limit => Math.Min(limit, 16) * TestsPerSecondPerSlot,
+ };
+ simulation.Run(TimeSpan.FromSeconds(60));
+
+ // Let a raise that is on trial be put back first.
+ for (var i = 0; i < 100 && simulation.Policy.Limit != Limits.Initial; i++)
+ {
+ simulation.Step();
+ }
+
+ simulation.MemoryLoad = 1.05;
+ simulation.Step();
+ await Assert.That(simulation.Policy.Limit).IsEqualTo(8);
+
+ // The limit that caused the pressure is off limits for 15 s, as after any first pressure.
+ simulation.MemoryLoad = 0.3;
+ simulation.Run(TimeSpan.FromSeconds(19));
+
+ // Back at the starting limit, or already trying a raise from it.
+ await Assert.That(simulation.Policy.Limit).IsGreaterThanOrEqualTo(Limits.Initial);
+ }
+
[Test]
public async Task Sustained_Memory_Pressure_Stops_At_The_Minimum()
{
@@ -158,8 +327,8 @@ public async Task Cpu_Saturation_Lowers_The_Limit_Once_Throughput_Has_Been_Measu
QueueDelay = TimeSpan.FromMilliseconds(150),
};
- // The first window measures what the lowering will be judged against.
- simulation.Run(TimeSpan.FromSeconds(1));
+ // Two windows that agree measure what the lowering will be judged against.
+ simulation.Run(TimeSpan.FromSeconds(2));
await Assert.That(simulation.Changes).IsEmpty();
simulation.Step();
@@ -231,7 +400,7 @@ public async Task Waits_Longer_Before_Each_Lowering_After_A_Failed_One()
simulation.Run(TimeSpan.FromSeconds(60));
- // Lowered at about 1 s, 19 s (15 s hold) and 52 s (30 s hold), and put back each time.
+ // Lowered at about 2 s, 21 s (15 s hold) and 55 s (30 s hold), and put back each time.
await Assert.That(simulation.Changes.Count(x => x.Change == AdaptiveLimitChange.CpuSaturation)).IsEqualTo(3);
await Assert.That(simulation.Changes.Min(x => x.Limit)).IsEqualTo(12);
}
@@ -280,7 +449,7 @@ public async Task Several_Lowerings_Cannot_Each_Give_A_Little_Throughput_Away()
},
};
- simulation.Run(TimeSpan.FromSeconds(12));
+ simulation.Run(TimeSpan.FromSeconds(9));
await Assert.That(simulation.Changes).IsEquivalentTo(
[
@@ -371,7 +540,7 @@ private sealed class Simulation(ParallelismLimits limits, int processorCount = 4
public List Changes { get; } = [];
- public Func Throughput { get; init; } = limit => limit * TestsPerSecondPerSlot;
+ public Func Throughput { get; set; } = limit => limit * TestsPerSecondPerSlot;
public double CpuUtilization { get; set; } = 0.2;