Commit 71fee78d authored by catch's avatar catch
Browse files

task: #3630648 Improve balancing of CI test jobs

By: longwave
By: mondrake
(cherry picked from commit 6842d98b)
parent 9c4baed6
Loading
Loading
Loading
Loading
Loading
+1 −1
Changes for .gitlab-ci.yml: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -327,7 +327,7 @@ default:

'⚙️️ PHPUnit Kernel':
  <<: [ *with-composer, *test-setup ]
  parallel: 4
  parallel: 3
  variables:
    TESTSUITE: kernel
    KUBERNETES_CPU_REQUEST: "12"
+11 −9
Changes for core/scripts/run-tests.sh: 11 added lines, 9 removed lines.
Original line number Diff line number Diff line
@@ -761,19 +761,20 @@ function dump_tests_sequence(array $tests): void {
  }
  echo "Test execution sequence\n";
  echo "-----------------------\n\n";
  echo " Seq Slow? Group            Cnt Class\n";
  echo "-----------------------------------------\n";
  echo " Seq Slow? Group            Cnt Weight Class\n";
  echo "------------------------------------------------\n";
  foreach ($tests as $testInfo) {
    echo sprintf(
      "%4d %5s %15s %4d %s\n",
      "%4d %5s %15s %4d %6d %s\n",
      $testInfo['worker_sequence'],
      in_array('#slow', $testInfo['groups']) ? '#slow' : '',
      trim_with_ellipsis($testInfo['group'], 15, \STR_PAD_RIGHT),
      $testInfo['tests_count'],
      $testInfo['weight'],
      trim_with_ellipsis($testInfo['name'], 60, \STR_PAD_LEFT),
    );
  }
  echo "-----------------------------------------\n\n";
  echo "------------------------------------------------\n\n";
}

/**
@@ -789,25 +790,26 @@ function dump_tests_sequence(array $tests): void {
function dump_bin_tests_sequence(int $bin, array $allTests, array $tests): void {
  echo "Test execution sequence. ";
  echo "Tests marked *** will be executed in this PARALLEL BIN #{$bin}.\n";
  echo "-------------------------------------------------------------------------------------\n\n";
  echo "--------------------------------------------------------------------------------------------\n\n";
  echo "    Sort  Bin                                 \n";
  echo "Bin  Seq  Seq Slow? Group            Cnt Class\n";
  echo "-------------------------------------------------------------------------------------\n";
  echo "Bin  Seq  Seq Slow? Group            Cnt Weight Class\n";
  echo "--------------------------------------------------------------------------------------------\n";
  foreach ($allTests as $testInfo) {
    $inBin = isset($tests[$testInfo['name']]);
    $message = sprintf(
      "%s %4d %s %5s %15s %4d %s\n",
      "%s %4d %s %5s %15s %4d %6d %s\n",
      $inBin ? "***" : "   ",
      $testInfo['sorted_sequence'],
      $inBin ? sprintf('%4d', $tests[$testInfo['name']]['worker_sequence']) : "    ",
      in_array('#slow', $testInfo['groups']) ? '#slow' : '',
      trim_with_ellipsis($testInfo['group'], 15, \STR_PAD_RIGHT),
      $testInfo['tests_count'],
      $testInfo['weight'],
      trim_with_ellipsis($testInfo['name'], 60, \STR_PAD_LEFT),
    );
    simpletest_script_print($message, $inBin ? SIMPLETEST_SCRIPT_COLOR_BRIGHT_WHITE : SIMPLETEST_SCRIPT_COLOR_GRAY);
  }
  echo "-------------------------------------------------------------------------------------\n\n";
  echo "--------------------------------------------------------------------------------------------\n\n";
}

/**
+39 −37
Changes for core/tests/Drupal/TestTools/TestRunner/WorkAllocator.php: 39 added lines, 37 removed lines.
Original line number Diff line number Diff line
@@ -15,6 +15,15 @@
 */
class WorkAllocator {

  /**
   * The weight multiplier for tests in the '#slow' group.
   *
   * A test class weighs its number of test cases. Tests in the '#slow' group
   * take several times longer per test case than other tests, so their weight
   * is multiplied by this value.
   */
  const SLOW_TEST_WEIGHT = 8;

  /**
   * The sorted tests list, prior to allocation.
   *
@@ -69,25 +78,18 @@ public function getAllocatedList(): array {
   * Allocates tests to workers.
   */
  private function process(): void {

    // Separate tests in the '#slow' group from the rest.
    // Merge the tests from all groups into a unique list, since tests may
    // appear in more than one group, and weigh them.
    $tests = array_merge(...array_values($this->groupedTestClassInfoList));
    $slowTests = $this->groupedTestClassInfoList['#slow'] ?? [];
    $notSlowTests = [];
    foreach ($this->groupedTestClassInfoList as $group => $tests) {
      if ($group === '#slow') {
        continue;
      }
      $notSlowTests = array_merge($notSlowTests, $tests);
    foreach ($tests as $class => &$test) {
      $test['weight'] = $test['tests_count'] * (isset($slowTests[$class]) ? self::SLOW_TEST_WEIGHT : 1);
    }

    // Filter slow tests out of the not slow tests and ensure a unique list
    // since tests may appear in more than one group.
    $notSlowTests = array_diff_key($notSlowTests, $slowTests);
    unset($test);

    // Sort all tests.
    $this->sortTestsByTypeAndCount($slowTests);
    $this->sortTestsByTypeAndCount($notSlowTests);
    $this->sortedList = array_merge($slowTests, $notSlowTests);
    $this->sortTestsByTypeAndWeight($tests);
    $this->sortedList = $tests;
    $this->assignTestsSequence($this->sortedList, 'sorted_sequence');

    // If the tests are not being run in parallel, the sorted list is enough.
@@ -97,35 +99,30 @@ private function process(): void {
      return;
    }

    // Set up a bin per test runner. Loop over the slow tests and add them to
    // a bin one by one, this distributes the tests evenly across the bins.
    $binnedSlowTests = $this->placeTestsIntoBins($slowTests);
    $slowTestsForJob = $binnedSlowTests[$this->binIndex - 1];

    // And the same for the rest of the tests.
    $binnedOtherTests = $this->placeTestsIntoBins($notSlowTests);
    $otherTestsForJob = $binnedOtherTests[$this->binIndex - 1];

    $this->allocatedList = array_merge($slowTestsForJob, $otherTestsForJob);
    $binnedTests = $this->placeTestsIntoBins($this->sortedList);
    $this->allocatedList = $binnedTests[$this->binIndex - 1];
    $this->assignTestsSequence($this->allocatedList, 'worker_sequence');
  }

  /**
   * Sort tests by test type and count of tests to be executed.
   * Sort tests by test type and weight.
   *
   * Tests with several methods take longer to run than tests with a single
   * method all else being equal, so this allows tests runs to be sorted by
   * approximately the slowest to fastest tests. Tests that are exceptionally
   * slow can be added to the '#slow' group so they are placed first in each
   * test run regardless of the number of methods.
   * Tests with several test cases take longer to run than tests with a single
   * test case, all else being equal, so this sorts tests approximately from
   * the slowest to the fastest. Tests that are exceptionally slow can be added
   * to the '#slow' group to increase their weight.
   *
   * Every worker computes the same sort, so ties are broken by class name.
   *
   * @param TestClassInfoList $tests
   *   The tests to sort.
   */
  private function sortTestsByTypeAndCount(array &$tests): void {
  private function sortTestsByTypeAndWeight(array &$tests): void {
    uasort(
      $tests,
      fn (array $a, array $b): int => $this->getTestTypeWeight($b) <=> $this->getTestTypeWeight($a) ?: $b['tests_count'] <=> $a['tests_count'],
      fn(array $a, array $b): int => $this->getTestTypeWeight($b) <=> $this->getTestTypeWeight($a)
        ?: $b['weight'] <=> $a['weight']
          ?: strcmp($a['name'], $b['name']),
    );
  }

@@ -161,19 +158,24 @@ private function assignTestsSequence(array &$tests, string $sequenceKey): void {
  }

  /**
   * Distribute tests into roughly equal sized bins.
   * Distribute tests into bins of roughly equal total weight.
   *
   * Each test, in sorted order, goes into the bin with the lowest total weight
   * so far. When several bins have the lowest weight, the first one is used.
   *
   * @param TestClassInfoList $tests
   *   An array of test class names.
   *   The sorted tests.
   *
   * @return array<int,TestClassInfoList>
   *   An associative array of bins and the test class names in each bin.
   */
  private function placeTestsIntoBins(array $tests): array {
    $bins = array_fill(0, $this->totalBins, []);
    $i = 0;
    $binWeights = array_fill(0, $this->totalBins, 0);
    foreach ($tests as $key => $test) {
      $bins[($i++ % $this->totalBins)][$key] = $test;
      $bin = array_search(min($binWeights), $binWeights, TRUE);
      $bins[$bin][$key] = $test;
      $binWeights[$bin] += $test['weight'];
    }
    return $bins;
  }
+72 −37
Changes for core/tests/Drupal/Tests/Core/Test/WorkAllocatorTest.php: 72 added lines, 37 removed lines.
Original line number Diff line number Diff line
@@ -7,63 +7,98 @@
use Drupal\Tests\UnitTestCase;
use Drupal\TestTools\TestRunner\WorkAllocator;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;

/**
 * Unit tests for WorkAllocator.
 *
 * @phpstan-import-type TestClassInfo from \Drupal\Core\Test\PhpUnitTestDiscovery
 */
#[CoversClass(WorkAllocator::class)]
#[Group('Test')]
class WorkAllocatorTest extends UnitTestCase {

  /**
   * Tests sorting and allocation of tests.
   * Tests sorting tests into a single bin.
   */
  #[DataProvider('allocatorProvider')]
  public function testAllocator(int $totalBins, int $binIndex, array $groupedTestClassInfoList, array $expected): void {
    $allocator = new WorkAllocator($groupedTestClassInfoList, $totalBins, $binIndex);
    $this->assertEquals($expected, $allocator->getAllocatedList());
  public function testSingleBin(): void {
    $path = __DIR__ . '/../../../../fixtures/test_runner/work_allocator';
    $allocator = new WorkAllocator(json_decode(file_get_contents($path . '/simple_in.json'), TRUE));
    $this->assertEquals(json_decode(file_get_contents($path . '/simple_out.json'), TRUE), $allocator->getAllocatedList());
  }

  /**
   * Data for ::testAllocator.
   * Tests that each test goes into the bin with the lowest total weight.
   *
   * The test classes only need to be existing classes, as the allocator uses
   * their names but never loads them.
   */
  public static function allocatorProvider(): \Generator {
    $path = __DIR__ . '/../../../../fixtures/test_runner/work_allocator';

    yield 'with slow test, single bin' => [
      1,
      1,
      json_decode(file_get_contents($path . '/simple_in.json'), TRUE),
      json_decode(file_get_contents($path . '/simple_out.json'), TRUE),
  public function testLeastWeightedBin(): void {
    $a = \ArrayObject::class;
    $b = \DateTime::class;
    $c = \Exception::class;
    $d = \SplQueue::class;
    $e = \SplStack::class;
    $tests = [
      $a => static::testClassInfo($a, 3),
      $b => static::testClassInfo($b, 3),
      $c => static::testClassInfo($c, 2),
      $d => static::testClassInfo($d, 1),
      $e => static::testClassInfo($e, 1, TRUE),
    ];
    $grouped = ['group' => $tests, '#slow' => [$e => $tests[$e]]];

    yield 'with slow test, 2 bins, bin #1' => [
      2,
      1,
      json_decode(file_get_contents($path . '/simple_in.json'), TRUE),
      json_decode(file_get_contents($path . '/simple_one_of_two_out.json'), TRUE),
    ];
    // The #slow test weighs 1 × 8, so the order is e (8), a (3), b (3), c (2),
    // d (1), with ties broken by class name. e goes to bin 1, a to bin 2, b
    // to bin 2 (3 < 8), c to bin 2 (6 < 8), then d to bin 1 (8 = 8, the first
    // bin wins).
    $bin1 = new WorkAllocator($grouped, 2, 1);
    $this->assertSame([$e, $d], array_keys($bin1->getAllocatedList()));
    $this->assertSame([1, 2], array_column($bin1->getAllocatedList(), 'worker_sequence'));
    $bin2 = new WorkAllocator($grouped, 2, 2);
    $this->assertSame([$a, $b, $c], array_keys($bin2->getAllocatedList()));
    $this->assertSame([$e, $a, $b, $c, $d], array_keys($bin1->getSortedList()));
  }

    // This is an edge case. Since we have 1 #slow test class and one other
    // test class not #slow, both classes get allocated to bin #1, and bin #2
    // remains empty, because the current algorithm allocates first all #slow
    // then all normal starting again. Does not happen in practice.
    yield 'with slow test, 2 bins, bin #2' => [
      2,
      2,
      json_decode(file_get_contents($path . '/simple_in.json'), TRUE),
      [],
    ];
  /**
   * Tests that every test is allocated to exactly one bin.
   */
  public function testEveryTestAllocatedOnce(): void {
    $grouped = json_decode(file_get_contents(__DIR__ . '/../../../../fixtures/test_runner/work_allocator/complex_in.json'), TRUE);
    $expected = array_keys(array_merge(...array_values($grouped)));

    yield 'with slow test, 8 bins, bin #2' => [
      8,
      2,
      json_decode(file_get_contents($path . '/complex_in.json'), TRUE),
      json_decode(file_get_contents($path . '/complex_two_of_eight_out.json'), TRUE),
    ];
    $allocated = [];
    for ($bin = 1; $bin <= 8; $bin++) {
      $allocated = array_merge($allocated, array_keys((new WorkAllocator($grouped, 8, $bin))->getAllocatedList()));
    }
    sort($expected);
    sort($allocated);
    $this->assertSame($expected, $allocated);
  }

  /**
   * Builds test class information for a kernel test.
   *
   * @param class-string $class
   *   The test class.
   * @param positive-int $testsCount
   *   The number of test cases.
   * @param bool $slow
   *   Whether the test is in the '#slow' group.
   *
   * @return TestClassInfo
   *   The test class information.
   */
  protected static function testClassInfo(string $class, int $testsCount, bool $slow = FALSE): array {
    return [
      'name' => $class,
      'group' => 'group',
      'groups' => $slow ? ['group', '#slow'] : ['group'],
      'type' => 'kernel',
      'description' => '',
      'file' => '',
      'tests_count' => $testsCount,
    ];
  }

}
−135

File deleted.

Loading