← Back to index

lib/BDD/Behave/Parallel.rakumod

523 / 559 lines covered (93.6%)

1unit module BDD::Behave::Parallel;23use BDD::Behave::Parallel::Distribution;4use BDD::Behave::Parallel::WorkerPool;5use BDD::Behave::Parallel::Queue;6use BDD::Behave::Parallel::Manifest;7use BDD::Behave::Parallel::EventStream;8use BDD::Behave::SpecRegistry;9use BDD::Behave::SpecLoader;10use BDD::Behave::Runner;11use BDD::Behave::Formatter;12use BDD::Behave::Failures;13use BDD::Behave::Failure;14use BDD::Behave::Colors;15use BDD::Behave::Coverage;16use BDD::Behave::Configuration;1718need BDD::Behave::SpecTree;1920constant Suite        = BDD::Behave::SpecTree::Suite;21constant ExampleGroup = BDD::Behave::SpecTree::ExampleGroup;22constant Example      = BDD::Behave::SpecTree::Example;23constant RunResult    = BDD::Behave::Runner::RunResult;2425class ParallelRunOptions is export {26  has Int      $.worker-count is required;27  has @.spec-files;28  has @.worker-argv;29  has @.discovery-argv;30  has %.base-env;31  has BDD::Behave::Formatter $.formatter is required;32  has Bool     $.verbose = False;33  has Int      $.seed;34  has Str      $.order = 'random';35  has Str      $.seed-mode = 'xor';36  has Bool     $.progress-total = False;37  has @.include-tags;38  has @.exclude-tags;39  has @.example-patterns;40  has @.only-locations;41  has Bool     $.fail-fast-any = False;42  has Bool     $.discovery-in-process = False;43  has Bool     $.precompile-pass = True;44  has Str      $.parallel-mode = BDD::Behave::Configuration::DEFAULT-PARALLEL-MODE;45  has Int      $.parallel-retry = 0;46  has IO::Path $.coverage-log-dir = IO::Path;47  has Bool     $.coverage-counts = False;48}4950sub discover-suites(@spec-files --> List) is export {51  my $registry = BDD::Behave::SpecRegistry::registry();52  my @suites;53  my @load-errors;54  for @spec-files -> $file {55    try {56      BDD::Behave::SpecLoader::load-spec-file($file);57      CATCH {58        default {59          @load-errors.push: %( :$file, :message(.message) );60        }61      }62    }63    my $suite = $registry.suite-for-file($file.IO);64    @suites.push($suite) if $suite.defined;65  }66  (@suites.List, @load-errors.List).List;67}6869sub current-include-flags(--> List) is export {70  (gather for $*REPO.repo-chain.reverse {71      take '-I' ~ .prefix.absolute if $_ ~~ CompUnit::Repository::FileSystem;72  }).List;73}7475sub default-discovery-argv(--> List) is export {76  ('raku', |current-include-flags(), $*PROGRAM-NAME).List;77}7879# Reaching the parallel runner costs a precompile subprocess, a discovery80# subprocess, and at least one worker subprocess, each paying the Raku81# startup and the module load again. For a selection that resolves to a82# single spec file that is more than the file itself costs, so an omitted83# --parallel resolves to zero workers there and the run stays in this84# process. An explicit --parallel N is always honored.85our sub resolve-worker-count(86  Int :$requested,87  Int :$file-count!,88  Int :$cpu-cores!,89  --> Int90) is export {91  return $requested if $requested.defined;92  return 0 if $file-count <= 1;93  $cpu-cores;94}9596# The pass exists to stop several processes writing the same precomp units from97# different load states, so it only pays for its extra Raku process when more98# than one process will load the spec files concurrently. A selection of one99# spec file is loaded by discovery and then by its single worker, one after the100# other, so the second process reads what the first wrote and there is nothing101# to protect against. Discovery in-process loads everything in this process for102# the same reason.103our sub should-precompile(104  Int  :$file-count!,105  Bool :$requested = True,106  Bool :$discovery-in-process = False,107  --> Bool108) is export {109  return False unless $requested;110  return False if $discovery-in-process;111  $file-count > 1;112}113114# Build the module precompilation for every spec file in ONE --compile-only115# subprocess before discovery and the workers load anything, so the whole116# dependency graph is written by a single process in a single pass and every117# later process only reads it. Precomp units written by processes with118# different load states carry conflicting repossession records; loading such119# a mix segfaults MoarVM's deserializer, or surfaces as a deferred compile120# exception that crashes the exception printer at process teardown.121#122# An already-inconsistent cache (left by earlier mixed-writer runs) kills the123# pass itself the same way. The subprocess reports each project lib dir it124# loads through (via BEHAVE_COMPILE_REPORT); when the pass dies by signal,125# those dirs' .precomp caches are cleared and the pass runs once more to126# rebuild them consistently. Nonzero exits are ignored: discovery reports127# real load errors with their messages.128sub precompile-specs-serially(129  @spec-files,130  :@discovery-argv,131  :%base-env,132  --> Nil133) is export {134  return unless @spec-files.elems;135136  my @base = (@discovery-argv.elems ?? @discovery-argv.list !! default-discovery-argv()).list;137138  my $report = $*TMPDIR.add("behave-compile-report-{$*PID}-{(now * 1e6).Int}");139  LEAVE { try $report.unlink }140141  my %env = %base-env.elems ?? %base-env.Hash !! %*ENV.Hash;142  %env<BEHAVE_DISABLE_CONFIG> = '1';143  %env<BEHAVE_WORKER_INDEX> //= '0';144  %env<BEHAVE_WORKER_COUNT> //= '1';145  %env<BEHAVE_COMPILE_REPORT> = $report.absolute;146  %env<MVM_COVERAGE_LOG>:delete;147  %env<MVM_COVERAGE_CONTROL>:delete;148  %env<BEHAVE_COVERAGE_LOG>:delete;149150  my $timeout-secs = (%*ENV<BEHAVE_DISCOVERY_TIMEOUT> // 300).Numeric;151152  sub run-pass(@files --> Bool) {153    my @argv = |@base, '--no-config', '--compile-only', |@files.map(*.Str);154    my $proc = Proc::Async.new(|@argv);155    $proc.stdout.tap(-> $ { });156    $proc.stderr.tap(-> $ { });157158    my $died-by-signal = False;159    try {160      my $promise = $proc.start(:ENV(%env));161      await Promise.anyof($promise, Promise.in($timeout-secs));162      if $promise.status ~~ Kept {163        $died-by-signal = $promise.result.signal != 0;164      } else {165        $proc.kill(SIGKILL);166        try await $promise;167        $died-by-signal = True;168      }169      CATCH { default { $died-by-signal = True } }170    }171    $died-by-signal;172  }173174  return unless run-pass(@spec-files);175176  # The union pass crashed on an inconsistent cache. Loading one file per177  # process still works in that state, so run each file alone purely to learn178  # the project lib dirs the specs pull in (each process appends its repo179  # chain to the report), then clear those dirs' caches and rebuild the whole180  # graph in one pass.181  run-pass(($_,)) for @spec-files;182183  my @prefixes = $report.e ?? $report.slurp.lines.unique.grep(*.chars) !! ();184  return unless @prefixes.elems;185186  for @prefixes -> $prefix {187    my $precomp = $prefix.IO.add('.precomp');188    next unless $precomp.d;189    remove-tree($precomp);190  }191192  run-pass(@spec-files);193}194195# Recursive directory removal for the .precomp caches cleared above.196sub remove-tree(IO::Path:D $dir --> Nil) {197  for $dir.dir -> $entry {198    $entry.d ?? remove-tree($entry) !! (try $entry.unlink);199  }200  try $dir.rmdir;201}202203sub discover-suites-subprocess(204  @spec-files,205  :@discovery-argv,206  :%base-env,207  :$timeout,208  --> List209) is export {210  my @suites;211  my @load-errors;212213  return (@suites.List, @load-errors.List).List unless @spec-files.elems;214215  my @argv = (@discovery-argv.elems ?? @discovery-argv.list !! default-discovery-argv()).list;216  @argv.push: '--no-config';217  @argv.push: '--list-examples';218  @argv.push: '--list-examples-format=json';219  @argv.append: @spec-files.map(*.Str);220221  my %env = %base-env.elems ?? %base-env.Hash !! %*ENV.Hash;222  %env<BEHAVE_DISABLE_CONFIG> = '1';223  %env<BEHAVE_WORKER_INDEX> //= '0';224  %env<BEHAVE_WORKER_COUNT> //= '1';225  %env<MVM_COVERAGE_LOG>:delete;226  %env<MVM_COVERAGE_CONTROL>:delete;227  %env<BEHAVE_COVERAGE_LOG>:delete;228229  my $proc = Proc::Async.new(|@argv);230  my @stdout-chunks;231  my @stderr-chunks;232  $proc.stdout.tap(-> $chunk { @stdout-chunks.push($chunk) });233  $proc.stderr.tap(-> $chunk { @stderr-chunks.push($chunk) });234235  my $timeout-secs = $timeout.defined236    ?? $timeout.Numeric237    !! (%*ENV<BEHAVE_DISCOVERY_TIMEOUT> // 300).Numeric;238239  my $result;240  try {241    my $promise = $proc.start(:ENV(%env));242    await Promise.anyof($promise, Promise.in($timeout-secs));243244    unless $promise.status ~~ Kept {245      $proc.kill(SIGKILL);246      my $reaped = try await $promise;247      my $msg = "discovery subprocess timed out after {$timeout-secs}s "248              ~ "(a spec may hang while loading, e.g. a stale precompilation)";249      for @spec-files -> $f {250        @load-errors.push: %( file => $f.Str, :message($msg) );251      }252      return (@suites.List, @load-errors.List).List;253    }254255    $result = $promise.result;256    CATCH {257      default {258        for @spec-files -> $f {259          @load-errors.push: %( file => $f.Str, message => "discovery subprocess failed: {.message}" );260        }261        return (@suites.List, @load-errors.List).List;262      }263    }264  }265266  my $stdout = @stdout-chunks.join;267  my $stderr = @stderr-chunks.join;268269  if $result.signal || $result.exitcode > 1 {270    my $msg = $result.signal271      ?? "discovery subprocess died with signal {$result.signal}"272         ~ " (a corrupt precompilation cache can segfault the loader;"273         ~ " clearing the project's .precomp directories usually clears it)"274      !! "discovery subprocess exited with code {$result.exitcode}";275    $msg ~= ": $stderr" if $stderr.chars;276    for @spec-files -> $f {277      @load-errors.push: %( file => $f.Str, :message($msg) );278    }279    return (@suites.List, @load-errors.List).List;280  }281282  my %doc;283  try {284    %doc = BDD::Behave::Coverage::parse-baseline-json($stdout);285    CATCH {286      default {287        for @spec-files -> $f {288          @load-errors.push: %( file => $f.Str, message => "discovery subprocess returned invalid JSON: {.message}" );289        }290        return (@suites.List, @load-errors.List).List;291      }292    }293  }294295  for ((%doc<suites> // ()).list) -> %node {296    my $suite = rebuild-suite(%node);297    @suites.push: $suite if $suite.defined;298  }299300  for ((%doc<load-errors> // ()).list) -> %err {301    @load-errors.push: %(302      file    => (%err<file>    // '').Str,303      message => (%err<message> // '').Str,304    );305  }306307  (@suites.List, @load-errors.List).List;308}309310sub rebuild-suite(%node) {311  my %meta = json-metadata-to-raku(%node<metadata> // %());312  my $suite = Suite.new(313    :description((%node<description> // '').Str),314    :file((%node<file> // '').IO),315    :line((%node<line> // 0).Int),316    :metadata(%meta),317  );318  for ((%node<children> // ()).list) -> %child {319    rebuild-child-into($suite, %child);320  }321  $suite;322}323324sub rebuild-child-into($parent, %node) {325  my $type = (%node<type> // '').Str;326  my %meta = json-metadata-to-raku(%node<metadata> // %());327  given $type {328    when 'group' {329      my $group = ExampleGroup.new(330        :description((%node<description> // '').Str),331        :file((%node<file> // '').IO),332        :line((%node<line> // 0).Int),333        :occurrence((%node<occurrence> // 1).Int),334        :shares-line(?%node<shares-line>),335        :metadata(%meta),336      );337      $parent.add-child($group);338      for ((%node<children> // ()).list) -> %child {339        rebuild-child-into($group, %child);340      }341    }342    when 'example' {343      my $example = Example.new(344        :description((%node<description> // '').Str),345        :file((%node<file> // '').IO),346        :line((%node<line> // 0).Int),347        :occurrence((%node<occurrence> // 1).Int),348        :shares-line(?%node<shares-line>),349        :metadata(%meta),350        :block(sub { }),351      );352      $example.pending = ?(%node<pending>);353      $parent.add-child($example);354    }355  }356}357358sub json-metadata-to-raku(%raw --> Hash) {359  my %m;360  for %raw.kv -> $k, $v {361    %m{$k} = $v;362  }363  %m;364}365366sub locations-for-buckets(@buckets --> List) is export {367  my @all;368  for @buckets -> $b {369    @all.append: $b.locations.list;370  }371  @all.List;372}373374sub collect-filtered-buckets(375  @suites,376  :@include-tags,377  :@exclude-tags,378  :@example-patterns,379  :@only-locations,380  --> List381) is export {382  my @all-buckets;383  for @suites -> $suite {384    @all-buckets.append: collect-buckets($suite).list;385  }386387  my @filtered = @all-buckets.map(-> $b {388      my @kept = $b.examples.grep({389          example-passes-filters($_, :@include-tags, :@exclude-tags, :@example-patterns, :@only-locations);390      });391      if @kept.elems == $b.examples.elems {392        $b;393      } elsif @kept.elems == 0 {394        Nil;395      } else {396        my $new = BDD::Behave::Parallel::Distribution::Bucket.new(397          :id($b.id),398          :file($b.file),399        );400        $new.add($_) for @kept;401        $new.serial = $b.serial;402        $new;403      }404  }).grep(*.defined);405406  @filtered.List;407}408409sub build-worker-manifests(410  @suites,411  Int $worker-count,412  :@include-tags,413  :@exclude-tags,414  :@example-patterns,415  :@only-locations,416  Str :$seed-mode = 'xor',417  Int :$seed,418  --> Hash419) is export {420  my @filtered = collect-filtered-buckets(421    @suites,422    :@include-tags,423    :@exclude-tags,424    :@example-patterns,425    :@only-locations,426  );427428  my ($parallel-buckets, $serial-buckets) = split-parallel-and-serial(@filtered);429430  my @parallel-assignments = $seed-mode eq 'stable'431  ?? distribute-stable($parallel-buckets, $worker-count, $seed // 0)432  !! distribute-lpt($parallel-buckets, $worker-count);433434  my @parallel-manifests;435  for ^$worker-count -> $i {436    my @locs;437    for @parallel-assignments[$i].list -> $b {438      @locs.append: $b.locations.list;439    }440    @parallel-manifests.push: @locs;441  }442443  my @serial-locations;444  for $serial-buckets.list -> $b {445    @serial-locations.append: $b.locations.list;446  }447448  %(449    parallel-manifests => @parallel-manifests.List,450    serial-locations   => @serial-locations.List,451    parallel-count     => $parallel-buckets.list.map(*.cost).sum,452    serial-count       => $serial-buckets.list.map(*.cost).sum,453  );454}455456sub example-passes-filters(Example $example, :@include-tags, :@exclude-tags, :@example-patterns, :@only-locations --> Bool) {457  my @tags = $example.effective-tags;458  if @exclude-tags.elems && @tags.first({ $_ ∈ @exclude-tags }).defined {459    return False;460  }461  if @include-tags.elems && !@tags.first({ $_ ∈ @include-tags }).defined {462    return False;463  }464  if @example-patterns.elems {465    my $desc = nested-description($example);466    my $matched = False;467    for @example-patterns -> $pat {468      if pattern-matches($desc, $pat) {469        $matched = True;470        last;471      }472    }473    return False unless $matched;474  }475  if @only-locations.elems {476    my $matched = False;477    for @only-locations -> $loc {478      if location-matches($example, $loc) {479        $matched = True;480        last;481      }482      for $example.ancestry -> $node {483        next unless $node ~~ ExampleGroup;484        if location-matches($node, $loc) {485          $matched = True;486          last;487        }488      }489      last if $matched;490    }491    return False unless $matched;492  }493  True;494}495496sub nested-description(Example $example --> Str) {497  my @parts = $example.ancestry.grep(ExampleGroup).map(*.description);498  @parts.push($example.description);499  @parts.join(' ');500}501502sub pattern-matches(Str $description, Str $pattern --> Bool) {503  if $pattern.chars > 2 && $pattern.starts-with('/') && $pattern.ends-with('/') {504    my $body = $pattern.substr(1, $pattern.chars - 2);505    my $rx = / <{ $body }> /;506    return so $description.match($rx);507  }508  $description.contains($pattern);509}510511sub location-matches($node, Str $pattern --> Bool) {512  return False unless $pattern.contains(':');513  my $idx = $pattern.rindex(':');514  my $pat-path = $pattern.substr(0, $idx);515  my $pat-line = $pattern.substr($idx + 1);516  return False unless $node.matches-line($pat-line);517518  my $ex-path = $node.file.absolute;519  return True if $ex-path eq $pat-path;520  return True if $ex-path.IO.absolute eq $pat-path.IO.absolute;521  return True if $ex-path.ends-with('/' ~ $pat-path);522  False;523}524525class ShardRetryRecord is export {526  has Int $.worker      is required;527  has Int $.attempts    is required;528  has Int $.final-exit  is required;529  has Str $.outcome     is required;530  has @.crash-codes;531}532533class ParallelRunResult is export {534  has Int $.total   is rw = 0;535  has Int $.passed  is rw = 0;536  has Int $.failed  is rw = 0;537  has Int $.pending is rw = 0;538  has Int $.skipped is rw = 0;539  has @.failures;540  has @.load-errors;541  has @.retry-records;542  has @.shard-retry-records;543  has @.executed-locations;544  has @.failed-locations;545  has @.timed-examples;546  has @.benchmark-summaries;547  has Int $.exit-code is rw = 0;548549  method success(--> Bool) { $!failed == 0 && @!load-errors.elems == 0 && $!exit-code == 0 }550}551552sub run-parallel-isolated-impl(553  ParallelRunOptions $opts,554  ParallelRunResult $result,555  @suites,556  --> ParallelRunResult557) {558  my @filtered = collect-filtered-buckets(559    @suites,560    :include-tags($opts.include-tags),561    :exclude-tags($opts.exclude-tags),562    :example-patterns($opts.example-patterns),563    :only-locations($opts.only-locations),564  );565566  my @file-buckets = coalesce-by-file(@filtered);567568  if $opts.progress-total {569    my $total = @file-buckets.map(*.cost).sum;570    $opts.formatter.set-total($total);571  }572573  return $result unless @file-buckets.elems;574575  my $manifest-dir = $*TMPDIR.add("behave-parallel-isolated-{$*PID}-{(now * 1e6).Int}");576  $manifest-dir.mkdir;577578  LEAVE {579    if $manifest-dir.defined && $manifest-dir.e && $manifest-dir.d {580      for $manifest-dir.dir -> $f { $f.unlink if $f.f }581      $manifest-dir.rmdir;582    }583  }584585  my Lock $event-lock .= new;586  my $event-buffer = WorkerEventBuffer.new(:pass-through(!$opts.formatter.needs-whole-files));587588  # Build one job per spec file (manifest + argv + env), then feed them through589  # a closed Channel to a fixed pool of exactly worker-count threads. Each590  # thread owns a stable slot (0 .. N-1) that it exports as BEHAVE_WORKER_INDEX591  # and pulls one job at a time, so concurrently-running files always hold592  # distinct indices — user code can key a per-worker resource (e.g. a database593  # `myapp_test_{Worker.id}`) off the index with only N to provision. Using a594  # fixed N-thread pool (not one `start` per file) is essential: one start per595  # file would pile up worker-count-blocked threads and starve the thread pool596  # that Proc::Async needs to drain worker stdout, deadlocking the run.597  my $queue = Channel.new;598  my $file-index = 0;599600  for @file-buckets -> $bucket {601    my $idx          = $file-index++;602    my $file         = $bucket.file;603    my @locations    = $bucket.locations.list;604    my $manifest-path = $manifest-dir.add("file-$idx.manifest");605    write-manifest($manifest-path, @locations);606607    my @argv = $opts.worker-argv.Slip;608    @argv.push: '--worker-manifest', $manifest-path.absolute;609    @argv.push: $file;610611    my %env = |$opts.base-env;612    %env<BEHAVE_WORKER_COUNT> = $opts.worker-count.Str;613614    if $opts.coverage-log-dir.defined {615      %env<MVM_COVERAGE_LOG>616      = $opts.coverage-log-dir.add("isolated-$idx.raw").absolute;617      %env<MVM_COVERAGE_CONTROL> = $opts.coverage-counts ?? '2' !! '0';618    }619620    $queue.send({ :$idx, :$file, :@argv, :%env });621  }622  $queue.close;623624  my @promises;625  for ^$opts.worker-count -> $slot {626    @promises.push: start {627      loop {628        my %job = $queue.receive;629        CATCH { when X::Channel::ReceiveOnClosed { last } }630631        my @argv = %job<argv>.list;632        my %env  = %job<env>.hash;633        my $idx  = %job<idx>;634        my $file = %job<file>;635636        %env<BEHAVE_WORKER_INDEX> = $slot.Str;637638        my $proc   = Proc::Async.new(|@argv);639        my $parser = JsonLineParser.new;640641        $proc.stdout.tap(-> $chunk {642            for $parser.feed($chunk) -> $event {643              $event-lock.protect: {644                for $event-buffer.hold($idx, $event) -> $ready {645                  handle-event($opts.formatter, $result, $idx, $ready, @suites);646                }647              }648            }649        });650        $proc.stderr.tap(-> $chunk {651            $event-lock.protect: { $*ERR.print($chunk) }652        });653654        my $proc-result = await $proc.start(:ENV(%env));655656        $event-lock.protect: {657          my @ready = $parser.flush.map({ |$event-buffer.hold($idx, $_) });658          @ready.append: $event-buffer.release($idx);659660          for @ready -> $ready {661            handle-event($opts.formatter, $result, $idx, $ready, @suites);662          }663        }664665        my $effective = $proc-result.signal666          ?? 128 + $proc-result.signal667          !! $proc-result.exitcode;668        if $effective > 1 {669          $event-lock.protect: {670            $result.exit-code = 1;671            note red($proc-result.signal672              ?? "Isolated worker for $file died with signal {$proc-result.signal}"673              !! "Isolated worker for $file exited with code {$proc-result.exitcode}");674          }675        }676      }677    };678  }679680  await Promise.allof(@promises);681  $result;682}683684sub run-parallel-queue-impl(685  ParallelRunOptions $opts,686  ParallelRunResult $result,687  @suites,688  --> ParallelRunResult689) {690  my @filtered = collect-filtered-buckets(691    @suites,692    :include-tags($opts.include-tags),693    :exclude-tags($opts.exclude-tags),694    :example-patterns($opts.example-patterns),695    :only-locations($opts.only-locations),696  );697698  my ($parallel-buckets, $serial-buckets) = split-parallel-and-serial(@filtered);699  my @parallel = $parallel-buckets.list;700  my @serial   = $serial-buckets.list;701702  if $opts.progress-total {703    my $total = @parallel.map(*.cost).sum + @serial.map(*.cost).sum;704    $opts.formatter.set-total($total);705  }706707  if @parallel.elems {708    my $worker-count = $opts.worker-count min @parallel.elems;709    my $scheduler = BDD::Behave::Parallel::Queue::QueueScheduler.new;710    $scheduler.enqueue-sorted(@parallel);711712    my Lock $dispatch-lock .= new;713    my Lock $event-lock    .= new;714    my $event-buffer = WorkerEventBuffer.new(:pass-through(!$opts.formatter.needs-whole-files));715    my $pool;716717    my &dispatch-events = sub (Int $wi, @events --> Nil) {718      for @events -> $event {719        handle-event($opts.formatter, $result, $wi, $event, @suites);720      }721    }722723    my &dispatch-or-shutdown = sub (Int $wi --> Nil) {724      my $next;725      $dispatch-lock.protect: {726        $next = $scheduler.next-bucket;727      }728      if $next.defined {729        $pool.send-bucket($wi, $next);730      } else {731        $pool.send-shutdown($wi);732      }733    }734735    $pool = BDD::Behave::Parallel::Queue::QueueWorkerPool.new(736      :$worker-count,737      :worker-argv($opts.worker-argv),738      :spec-files($opts.spec-files.map(*.Str).List),739      :base-env(%(|$opts.base-env)),740      :coverage-log-dir($opts.coverage-log-dir),741      :coverage-counts($opts.coverage-counts),742      # Tap callbacks for every worker fire on the thread pool, so743      # several can be processing events concurrently. handle-event744      # mutates $result.total / $result.passed / ... and writes to the745      # parent formatter; both are unsynchronized state, so we serialize746      # all per-event work behind a single lock.747      :on-event(sub ($wi, $event) {748          $event-lock.protect: {749            dispatch-events($wi, $event-buffer.hold($wi, $event));750          }751      }),752      :on-ready(&dispatch-or-shutdown),753      :on-done(sub ($wi, $id) {754          $event-lock.protect: {755            dispatch-events($wi, $event-buffer.release($wi));756          }757          $dispatch-lock.protect: { $scheduler.mark-complete }758          dispatch-or-shutdown($wi);759      }),760    );761762    $pool.launch;763    $pool.wait-all;764    for $event-buffer.release-all -> $held {765      dispatch-events($held.key, $held.value);766    }767    for $pool.workers -> $w {768      if $w.exit-code > 1 {769        $result.exit-code = 1;770        note red("Queue worker {$w.index} exited with code {$w.exit-code}");771      }772    }773  }774775  if @serial.elems {776    my $serial-dir = $*TMPDIR.add("behave-parallel-queue-serial-{$*PID}-{(now * 1e6).Int}");777    $serial-dir.mkdir;778    LEAVE {779      if $serial-dir.defined && $serial-dir.e && $serial-dir.d {780        for $serial-dir.dir -> $f { $f.unlink if $f.f }781        $serial-dir.rmdir;782      }783    }784785    my @serial-locations;786    for @serial -> $b { @serial-locations.append: $b.locations.list }787788    my $serial-manifest-path = $serial-dir.add('serial.manifest');789    write-manifest($serial-manifest-path, @serial-locations);790    my @files = files-from-manifest(@serial-locations);791    my @argv = $opts.worker-argv.Slip;792    @argv.push: '--worker-manifest', $serial-manifest-path.absolute;793    @argv.append: @files;794795    my %env = |$opts.base-env;796    %env<BEHAVE_WORKER_INDEX> = '0';797    %env<BEHAVE_WORKER_COUNT> = '1';798799    if $opts.coverage-log-dir.defined {800      %env<MVM_COVERAGE_LOG>801      = $opts.coverage-log-dir.add('serial.raw').absolute;802      %env<MVM_COVERAGE_CONTROL> = $opts.coverage-counts ?? '2' !! '0';803    }804805    my $proc = Proc::Async.new(|@argv);806    my $parser = JsonLineParser.new;807808    $proc.stdout.tap(-> $chunk {809        for $parser.feed($chunk) -> $event {810          handle-event($opts.formatter, $result, -1, $event, @suites);811        }812    });813    $proc.stderr.tap(-> $chunk {814        $*ERR.print($chunk);815    });816817    my $start = $proc.start(:ENV(%env));818    my $proc-result = await $start;819    for $parser.flush -> $event {820      handle-event($opts.formatter, $result, -1, $event, @suites);821    }822    my $effective = $proc-result.signal823      ?? 128 + $proc-result.signal824      !! $proc-result.exitcode;825    if $effective > 1 {826      $result.exit-code = 1;827      note red($proc-result.signal828        ?? "Serial worker died with signal {$proc-result.signal}"829        !! "Serial worker exited with code {$proc-result.exitcode}");830    }831  }832833  $result;834}835836sub run-parallel(837  ParallelRunOptions $opts,838  --> ParallelRunResult839) is export {840  my $result = ParallelRunResult.new;841842  precompile-specs-serially(843    $opts.spec-files,844    :discovery-argv($opts.discovery-argv),845    :base-env(%(|$opts.base-env)),846  ) if should-precompile(847    :file-count($opts.spec-files.elems),848    :requested($opts.precompile-pass),849    :discovery-in-process($opts.discovery-in-process),850  );851852  my $disco = $opts.discovery-in-process853  ?? discover-suites($opts.spec-files)854  !! discover-suites-subprocess(855    $opts.spec-files,856    :discovery-argv($opts.discovery-argv),857    :base-env(%(|$opts.base-env)),858  );859  my @suites      = $disco[0].list;860  my @load-errors = $disco[1].list;861  $result.load-errors.append: @load-errors;862863  my $mode = BDD::Behave::Configuration::resolve-parallel-mode($opts.parallel-mode);864865  if $mode eq 'queue' {866    return run-parallel-queue-impl($opts, $result, @suites);867  }868869  if $mode eq 'isolated' {870    return run-parallel-isolated-impl($opts, $result, @suites);871  }872873  my %plan = build-worker-manifests(874    @suites,875    $opts.worker-count,876    :include-tags($opts.include-tags),877    :exclude-tags($opts.exclude-tags),878    :example-patterns($opts.example-patterns),879    :only-locations($opts.only-locations),880    :seed-mode($opts.seed-mode),881    :seed($opts.seed),882  );883884  my @parallel-manifests = %plan<parallel-manifests>.list;885  my @serial-locations   = %plan<serial-locations>.list;886887  if $opts.progress-total {888    my $total = (%plan<parallel-count> // 0).Int + (%plan<serial-count> // 0).Int;889    $opts.formatter.set-total($total);890  }891892  my $manifest-dir = $*TMPDIR.add("behave-parallel-{$*PID}-{(now * 1e6).Int}");893  $manifest-dir.mkdir;894895  LEAVE {896    if $manifest-dir.defined && $manifest-dir.e && $manifest-dir.d {897      for $manifest-dir.dir -> $f { $f.unlink if $f.f }898      $manifest-dir.rmdir;899    }900  }901902  if @parallel-manifests.grep({ .elems }).elems {903    my Lock $event-lock .= new;904    my $event-buffer = WorkerEventBuffer.new(:pass-through(!$opts.formatter.needs-whole-files));905    my $pool = WorkerPool.new(906      :worker-count($opts.worker-count),907      :worker-argv($opts.worker-argv),908      :base-env(%(|$opts.base-env)),909      :manifest-dir($manifest-dir),910      :coverage-log-dir($opts.coverage-log-dir),911      :coverage-counts($opts.coverage-counts),912      :retry-count($opts.parallel-retry),913      # Tap callbacks fire on the thread pool — N workers can dispatch914      # concurrently into handle-event, which mutates $result.* and915      # writes to the parent formatter. Serialize both.916      :on-event(sub ($wi, $event) {917          $event-lock.protect: {918            for $event-buffer.hold($wi, $event) -> $ready {919              handle-event($opts.formatter, $result, $wi, $ready, @suites);920            }921          }922      }),923      :on-shard-retry(sub ($wi, $attempt, $exit-code) {924          $event-lock.protect: {925            note yellow("Worker $wi crashed with exit $exit-code; retrying (attempt $attempt of {$opts.parallel-retry + 1})");926          }927      }),928    );929    $pool.launch(@parallel-manifests);930    $pool.wait-all;931    for $event-buffer.release-all -> $held {932      for $held.value.list -> $ready {933        handle-event($opts.formatter, $result, $held.key, $ready, @suites);934      }935    }936    for $pool.workers -> $w {937      if $w.attempt > 1 {938        my $outcome = $w.exit-code > 1 ?? 'crashed' !! 'recovered';939        $result.shard-retry-records.push: ShardRetryRecord.new(940          :worker($w.index),941          :attempts($w.attempt),942          :final-exit($w.exit-code),943          :$outcome,944          :crash-codes($w.crash-codes.list),945        );946      }947      if $w.exit-code > 1 {948        $result.exit-code = 1;949        note red("Worker {$w.index} exited with code {$w.exit-code} (after {$w.attempt} attempt{$w.attempt == 1 ?? '' !! 's'})");950      }951    }952  }953954  if @serial-locations.elems {955    my $serial-manifest-path = $manifest-dir.add('serial.manifest');956    write-manifest($serial-manifest-path, @serial-locations);957    my @files = files-from-manifest(@serial-locations);958    my @argv = $opts.worker-argv.Slip;959    @argv.push: '--worker-manifest', $serial-manifest-path.absolute;960    @argv.append: @files;961962    my %env = |$opts.base-env;963    %env<BEHAVE_WORKER_INDEX> = '0';964    %env<BEHAVE_WORKER_COUNT> = '1';965966    if $opts.coverage-log-dir.defined {967      %env<MVM_COVERAGE_LOG>968      = $opts.coverage-log-dir.add('serial.raw').absolute;969      %env<MVM_COVERAGE_CONTROL> = $opts.coverage-counts ?? '2' !! '0';970    }971972    my $proc = Proc::Async.new(|@argv);973    my $parser = JsonLineParser.new;974975    $proc.stdout.tap(-> $chunk {976        for $parser.feed($chunk) -> $event {977          handle-event($opts.formatter, $result, -1, $event, @suites);978        }979    });980    $proc.stderr.tap(-> $chunk {981        $*ERR.print($chunk);982    });983984    my $start = $proc.start(:ENV(%env));985    my $proc-result = await $start;986    for $parser.flush -> $event {987      handle-event($opts.formatter, $result, -1, $event, @suites);988    }989    my $effective = $proc-result.signal990      ?? 128 + $proc-result.signal991      !! $proc-result.exitcode;992    if $effective > 1 {993      $result.exit-code = 1;994      note red($proc-result.signal995        ?? "Serial worker died with signal {$proc-result.signal}"996        !! "Serial worker exited with code {$proc-result.exitcode}");997    }998    $serial-manifest-path.unlink if $serial-manifest-path.e;999  }10001001  $result;1002}10031004sub handle-event($formatter, ParallelRunResult $result, Int $worker, %event, @suites) {1005  my $type = %event<type> // 'unknown';1006  given $type {1007    when 'suite-start' {1008      my $suite = lookup-suite(@suites, %event<id>);1009      $formatter.suite-start($suite, :multi-file(@suites.elems > 1)) if $suite.defined;1010    }1011    when 'suite-end' {1012      my $suite = lookup-suite(@suites, %event<id>);1013      $formatter.suite-end($suite) if $suite.defined;1014    }1015    when 'group-start' {1016      my $group = lookup-group(@suites, %event<id>);1017      $formatter.group-start($group) if $group.defined;1018    }1019    when 'group-end' {1020      my $group = lookup-group(@suites, %event<id>);1021      $formatter.group-end($group) if $group.defined;1022    }1023    when 'group-around-skipped' {1024      my $group = lookup-group(@suites, %event<id>);1025      $formatter.group-around-skipped($group) if $group.defined;1026    }1027    when 'example-start' {1028      my $example = resolve-example(@suites, %event);1029      if $example.defined {1030        $example.started-at = now;1031        $formatter.example-start($example, :auto(?%event<auto>));1032      }1033    }1034    when 'example-auto-description' {1035      my $example = resolve-example(@suites, %event);1036      $formatter.example-auto-description($example, :description(%event<description> // ''))1037      if $example.defined;1038    }1039    when 'example-pass' {1040      my $example = resolve-example(@suites, %event);1041      if $example.defined {1042        $example.duration = (%event<duration> // 0).Real;1043        $formatter.example-pass($example);1044        $result.executed-locations.push($example.node-id);1045      }1046      $result.total++;1047      $result.passed++;1048    }1049    when 'example-fail' {1050      my $example = resolve-example(@suites, %event);1051      my %failure-info = (1052        description => (%event<failure-description> // ($example.defined ?? $example.description !! '')),1053        file        => (%event<failure-file> // ($example.defined ?? $example.file.absolute !! '')),1054        line        => (%event<failure-line> // ($example.defined ?? $example.line !! 0)),1055      );1056      with %event<exception-message> {1057        %failure-info<exception-message> = $_;1058      }1059      with %event<exception-backtrace> {1060        %failure-info<exception-backtrace> = $_;1061      }10621063      my @expectations = (%event<failures> // ()).list.map(-> %f {1064        my %rec = (1065          file     => (%f<file> // '').Str,1066          line     => (%f<line> // 0).Int,1067          negated  => (%f<negated> // False),1068          given    => (%f<given>    // '').Str,1069          expected => (%f<expected> // '').Str,1070        );1071        %rec<message> = %f<message>.Str if (%f<message> // '').Str.chars;1072        %rec;1073      });1074      %failure-info<expectations> = @expectations if @expectations.elems;10751076      $result.total++;1077      $result.failed++;1078      $result.failures.push: %failure-info;10791080      # Record this example's failures on the global list before emitting the1081      # event. A streaming formatter derives an example's failures from the list1082      # since the previous event, so recording after emitting would attribute1083      # them to the next example instead of this one.1084      my $desc = %failure-info<description>;1085      my @event-failures = (%event<failures> // ()).list;1086      for @event-failures -> %f {1087        my $given    = (%f<given>    // '').Str;1088        my $expected = (%f<expected> // '').Str;1089        my $negated  = ?(%f<negated> // False);1090        my $msg      = (%f<message> // '').Str;1091        $msg = compose-failure-message($given, $expected, $negated) unless $msg.chars;10921093        Failures.list.push: Failure.new(1094          :file((%f<file> // '').Str),1095          :line((%f<line> // 0).Int),1096          :given($given.chars ?? $given !! Nil),1097          :expected($expected.chars ?? $expected !! Nil),1098          :$negated,1099          :message($msg.chars ?? $msg !! Str),1100          :aggregation-label(1101            ((%f<aggregation-label> // '').Str.chars1102              ?? %f<aggregation-label>.Str !! Str)),1103          :description($desc),1104        );1105      }1106      unless @event-failures.elems {1107        with %event<exception-message> -> $msg {1108          my $prefixed = $desc.chars1109          ?? "exception in $desc: " ~ $msg.Str1110          !! $msg.Str;11111112          Failures.list.push: Failure.new(1113            :file(%failure-info<file>.Str),1114            :line(%failure-info<line>.Int),1115            :message($prefixed),1116            :description($desc),1117            :from-runner-exception,1118          );1119        }1120      }11211122      if $example.defined {1123        $example.duration = (%event<duration> // 0).Real;1124        $formatter.example-fail($example, :%failure-info);1125        my $loc = $example.node-id;1126        $result.executed-locations.push($loc);1127        $result.failed-locations.push($loc);1128      } else {1129        my $f = %failure-info<file>.Str;1130        my $l = %failure-info<line>.Int;1131        $result.failed-locations.push("$f:$l") if $f.chars && $l;1132      }1133    }1134    when 'example-retry' {1135      my $example = resolve-example(@suites, %event);1136      $formatter.example-retry(1137        $example,1138        :attempt((%event<attempt> // 1).Int),1139        :max-attempts((%event<max-attempts> // 1).Int),1140      ) if $example.defined;1141    }1142    when 'example-pending' {1143      my $example = resolve-example(@suites, %event);1144      $formatter.example-pending($example) if $example.defined;1145      $result.total++;1146      $result.pending++;1147    }1148    when 'example-skipped' {1149      my $example = resolve-example(@suites, %event);1150      $formatter.example-skipped($example) if $example.defined;1151      $result.total++;1152      $result.skipped++;1153    }1154    when 'example-around-skipped' {1155      my $example = resolve-example(@suites, %event);1156      $formatter.example-around-skipped($example) if $example.defined;1157      $result.total++;1158      $result.skipped++;1159    }1160    when 'example-slow' {1161      my $example = resolve-example(@suites, %event);1162      $formatter.example-slow($example, :threshold((%event<threshold> // 0).Real))1163      if $example.defined;1164    }1165    when 'profile-record' {1166      my $example = resolve-example(@suites, %event);1167      $result.timed-examples.push: %(1168        example     => $example,1169        description => (%event<description> // '').Str,1170        duration    => (%event<duration> // 0).Real,1171      );1172    }1173    when 'benchmark-record' {1174      my $example = resolve-example(@suites, %event);1175      my @timings = (%event<timings> // ()).list.map(*.Real).List;1176      $result.benchmark-summaries.push: %(1177        example     => $example,1178        description => (%event<description> // '').Str,1179        key         => (%event<key>         // '').Str,1180        label       => (%event<label>.defined && (%event<label>).Str.chars1181          ?? %event<label>.Str !! Str),1182        position    => (%event<position>    // 0).Int,1183        runs        => (%event<runs>        // 0).Int,1184        iterations  => (%event<iterations>  // 0).Int,1185        timings     => @timings,1186        min         => (%event<min>    // 0).Real,1187        max         => (%event<max>    // 0).Real,1188        mean        => (%event<mean>   // 0).Real,1189        median      => (%event<median> // 0).Real,1190        total       => (%event<total>  // 0).Real,1191      );1192    }1193    when 'retry-record' {1194      my $rec = BDD::Behave::Runner::RetryRecord.new(1195        :description((%event<description> // '').Str),1196        :location((%event<location> // '').Str),1197        :attempts((%event<attempts> // 1).Int),1198        :max-attempts((%event<max-attempts> // 1).Int),1199        :outcome((%event<outcome> // 'pass').Str),1200      );1201      $result.retry-records.push($rec);1202    }1203    when 'load-error' {1204      $result.load-errors.push: %( file => %event<file>, message => %event<message> );1205    }1206    when 'parse-error' {1207      note red("Worker $worker emitted unparseable event: " ~ (%event<raw> // ''));1208    }1209    when 'run-summary' { }1210    default { }1211  }1212}12131214sub lookup-suite(@suites, Str $id) {1215  return Nil unless $id.defined;1216  for @suites -> $suite {1217    return $suite if $suite.node-id eq $id;1218  }1219  Nil;1220}12211222sub lookup-group(@suites, Str $id) {1223  return Nil unless $id.defined;1224  for @suites -> $suite {1225    my $hit = walk-find-group($suite, $id);1226    return $hit if $hit.defined;1227  }1228  Nil;1229}12301231sub walk-find-group($container, Str $id) {1232  for $container.children -> $child {1233    given $child {1234      when ExampleGroup {1235        return $child if $child.node-id eq $id;1236        my $deeper = walk-find-group($child, $id);1237        return $deeper if $deeper.defined;1238      }1239    }1240  }1241  Nil;1242}12431244sub lookup-example(@suites, Str $id) {1245  return Nil unless $id.defined;1246  for @suites -> $suite {1247    my $hit = walk-find-example($suite, $id);1248    return $hit if $hit.defined;1249  }1250  Nil;1251}12521253our sub resolve-example(@suites, %event) {1254  my $hit = lookup-example(@suites, %event<id>);1255  return $hit if $hit.defined;1256  my $desc = (%event<description> // %event<failure-description> // '').Str;1257  my $file = (%event<file>        // %event<failure-file>        // '').Str;1258  my $line = (%event<line>        // %event<failure-line>        // 0).Int;1259  return Nil unless $desc.chars || $file.chars;1260  Example.new(1261    :description($desc),1262    :file($file.IO),1263    :line($line),1264    :block(sub { }),1265  );1266}12671268sub walk-find-example($container, Str $id) {1269  for $container.children -> $child {1270    given $child {1271      when Example {1272        return $child if $child.node-id eq $id;1273      }1274      when ExampleGroup {1275        my $deeper = walk-find-example($child, $id);1276        return $deeper if $deeper.defined;1277      }1278    }1279  }1280  Nil;1281}