Module: Mutineer::ExternalBackend

Defined in:
lib/mutineer/external_backend.rb

Overview

External execution backend. Runs the user's --test-command as a subprocess in the app's own runtime (whatever Ruby its bundle resolves to), so mutineer (Ruby ≥ 3.4) can mutation-test apps pinned to an older Ruby.

This is deliberately NOT a TestRunners framework adapter: those return an Integer 0/1 from inside a fork and are dispatched by framework name. This is a whole backend — it spawns a process, enforces a wall-clock timeout, and maps the exit status to a Result. The mapping follows Isolation.decode: exit 0 is survived, exit 1 is killed, and any other exit is error (#292). When the clean smoke run printed a Minitest or RSpec summary line, exit 1 is a kill only when the output also shows a failing test, so a suite that crashed before its tests ran is not a kill. The smoke check (below) guards a persistently broken environment, and the score is disclosed as an upper bound.

Child environment: bundler/gem env injected by Mutineer's Ruby is stripped, and version-manager concrete version bins (e.g. ~/.rbenv/versions/3.4.9/bin) are removed from PATH so shims / .ruby-version can select the app's Ruby (#32). PARALLEL_WORKERS and DISABLE_SPRING are set to 1 (RailsRunEnv), and so is DISABLE_BOOTSNAP_COMPILE_CACHE (ExternalBackend.child_env).

Constant Summary collapse

SMOKE_TIMEOUT =

Generous ceiling for the one-off smoke/calibration run (a cold app boot plus the full suite). The per-mutant timeout is derived from how long this took.

900
POLL =

Poll interval for the deadline wait loop. Independent of Isolation's loop — this backend waits on an external process TREE, not an in-process fork.

0.02
CANNOT_RUN_CODES =

Exit codes a shell or wrapper uses when the command could not run at all (126: not executable, 127: not found). Scored error, never killed.

[126, 127].freeze
FAILURE_CODE =

The exit code Minitest, bin/rails test and RSpec use for a failing test. Any other non-zero code is scored error, the same rule as Isolation.decode.

1
MINITEST_SUMMARY =

The end-of-run summary line of Minitest 5 and 6 ("N runs") and of minitest-reporters ("N tests"). Captures the failure and error counts.

/\d+ (?:runs|tests), \d+ assertions, (\d+) failures, (\d+) errors/
RSPEC_SUMMARY =

The end-of-run summary line of RSpec ("N examples, N failures"). Captures the failure count.

/\d+ examples?, (\d+) failures?/
MINITEST_RUNNING =

The line Minitest prints once every test file has loaded, before the first test runs. Exit 1 after it with no summary line means code under test called exit 1 or abort, which the in-process backend also scores killed.

"# Running:"
SIMPLECOV_GATE =

The line SimpleCov prints when its minimum_coverage gate fails the run.

/SimpleCov failed with exit \d+ due to a coverage related error/
RSPEC_OUTSIDE_ERROR =

RSpec's note that a file raised outside any example, such as at load.

/errors? occurred outside of examples/
ANSI_CODE =

ANSI colour codes, removed before matching so a coloured summary still counts.

/\e\[[\d;]*m/
MINITEST_SEED =

The seed line Minitest prints before every run. Captures the seed.

/^Run options:.*--seed (\d+)/
RSPEC_SEED =

The seed line RSpec prints when it shuffles the tests. Captures the seed.

/^Randomized with seed (\d+)/
MINITEST_SEED_GIVEN =

A Minitest seed given on the command or in TESTOPTS (SEED=N, --seed N -s N or -sN). Minitest prints its seed line for a fixed seed too, so the line alone cannot tell.

/\bSEED=|--seed\b|(?:\A|\s)-s(?![A-Za-z_])/
RSPEC_SEED_GIVEN =

An RSpec seed given on the command or in SPEC_OPTS (--seed N or --order rand:N). RSpec ignores SEED.

/--seed\b|\brand(?:om)?:\d/
VERSION_BIN_PATH =

PATH entries that pin a concrete Ruby under a version manager (ahead of shims). Optional trailing slash; normal bins are left alone.

%r{
  (?:
    /\.rbenv/versions/[^/]+/bin
    |/\.asdf/installs/ruby/[^/]+/bin
    |/\.rubies/[^/]+/bin
    |/rubies/[^/]+/bin
  )/?\z
}x
CLEAR_ENV_KEYS =

Env keys Process.spawn must unset (nil value) so Mutineer's Ruby/bundler context does not leak. Spawn merges env onto the parent; omitting a key does NOT clear it.

%w[
  BUNDLER_VERSION RBENV_VERSION ASDF_RUBY_VERSION RBENV_DIR
].freeze
{}

Class Method Summary collapse

Class Method Details

.build_argv(command, files) ⇒ Array<String>

Turn a command template into an argv array (no shell → no eval, no injection). The %{files} token expands IN PLACE to N separate argv elements — one per path, unescaped — so a path containing a space stays a single argument. It is not a space-joined string.

Parameters:

  • command (String) —

    the --test-command template (contains %{files}).

  • files (Array<String>) —

    test file paths to substitute.

Returns:

  • (Array<String>) —

    argv.



104
105
106
# File 'lib/mutineer/external_backend.rb', line 104

def self.build_argv(command, files)
  Shellwords.split(command).flat_map { |tok| tok == "%{files}" ? files : [tok] }
end

.child_env ⇒ Hash{String => String, nil}

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Environment delta for the test-command child. Process.spawn merges this onto the parent env: set a key to nil to unset it. Scrubs Mutineer/bundler injection and version-manager PATH pins so shims / .ruby-version can win. Keeps other vars (e.g. RAILS_ENV) so setting them on the Mutineer command still reaches the suite. Also sets PARALLEL_WORKERS, DISABLE_SPRING and DISABLE_BOOTSNAP_COMPILE_CACHE to 1. A wrapper can change them again. Bootsnap checks only that its variable is set, so only unsetting it turns the cache back on. The Bootsnap pin is here, not in RailsRunEnv.pin_child!: this backend rewrites each source file in place, and Bootsnap keys its compile cache on path, size and whole-second mtime, so a same-size mutant written in the same second can load the previous mutant's cached code (#285). The daemon loads each mutant from a new file and keeps the cache.

Returns:

  • (Hash{String => String, nil}) —

    env for Process.spawn.



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/mutineer/external_backend.rb', line 124

def self.child_env
  env = {}
  cleared_pin = false
  ENV.each_key do |k|
    next unless clear_env_key?(k)

    env[k] = nil
    cleared_pin = true
  end
  path = ENV["PATH"].to_s.split(File::PATH_SEPARATOR)
  kept = path.reject { |p| p.match?(VERSION_BIN_PATH) }
  scrubbed_bin = kept.size != path.size
  # Only reorder PATH when we scrubbed a pin; otherwise leave the user's PATH alone.
  path = if cleared_pin || scrubbed_bin
           (version_manager_shim_dirs + kept).uniq
         else
           kept
         end
  env["PATH"] = path.join(File::PATH_SEPARATOR)
  RailsRunEnv.pin_child!(env, spring: true)
  env["DISABLE_BOOTSNAP_COMPILE_CACHE"] = "1"
  env
end

.clear_env_key?(key) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

True when the key must be unset in the child (bundler/gem/version-manager).

Parameters:

  • key (String) —

    environment variable name.

Returns:

  • (Boolean)


153
154
155
# File 'lib/mutineer/external_backend.rb', line 153

def self.clear_env_key?(key)
  key.start_with?("BUNDLE_", "RUBY", "GEM_") || CLEAR_ENV_KEYS.include?(key)
end

.command_redact_file(dir) ⇒ String?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Path of command_redact.rb that RUBYOPT can carry. Ruby splits RUBYOPT at whitespace and has no quoting or escape, so a path with a space (a home directory named "Jane Doe") makes every Ruby child stop with "invalid switch in RUBYOPT". Such a path is reached through a symlink in a temporary directory, removed when this process exits. require_relative in the file resolves the real path, so the rest of the copier loads.

Parameters:

  • dir (String) —

    the directory that holds command_redact.rb.

Returns:

  • (String, nil) —

    nil when the temporary directory name has whitespace too.



414
415
416
417
418
419
420
421
422
423
424
425
426
427
# File 'lib/mutineer/external_backend.rb', line 414

def self.command_redact_file(dir)
  path = File.expand_path("command_redact.rb", dir)
  return path unless path.match?(/\s/)

  COMMAND_REDACT_LINKS[dir] ||= begin
    tmp = Dir.mktmpdir("mutineer-redact")
    at_exit { FileUtils.remove_entry(tmp, true) }
    link = File.join(tmp, "command_redact.rb")
    File.symlink(path, link)
    link
  end
  link = COMMAND_REDACT_LINKS[dir]
  link.match?(/\s/) ? nil : link
end

.command_rubyopt(dir = __dir__) ⇒ String

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

RUBYOPT for a --test-command child: the copier file alone. The tool's own RUBYOPT (-rbundler/setup under bundle exec) stays out, as child_env clears every RUBY* key so the suite picks its own Ruby and gems. Empty when the copier file cannot be named without whitespace.

Parameters:

  • dir (String) (defaults to: __dir__) —

    the directory that holds command_redact.rb.

Returns:

  • (String)


399
400
401
402
# File 'lib/mutineer/external_backend.rb', line 399

def self.command_rubyopt(dir = __dir__)
  path = command_redact_file(dir)
  path ? "-r#{path}" : ""
end

.exited_during_tests?(text) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

True when Minitest started its tests and the process then ended with no summary line after that start: code under test called exit 1 or abort mid-run. Only the last start counts, so a wrapper whose earlier suite printed a summary still kills. A load crash ends before Minitest prints MINITEST_RUNNING, so it stays false. Only the default Minitest reporter prints that line: under RSpec or minitest-reporters, such an exit scores error, not killed. Ceiling: an exception that escapes Minitest.run itself (a reporter plugin bug) also reads as a kill here, where the in-process backend scores error.

Parameters:

Returns:

  • (Boolean)


271
272
273
274
275
276
277
# File 'lib/mutineer/external_backend.rb', line 271

def self.exited_during_tests?(text)
  running_at = text.rindex(MINITEST_RUNNING)
  return false unless running_at

  summary_at = [text.rindex(MINITEST_SUMMARY), text.rindex(RSPEC_SUMMARY)].compact.max
  summary_at.nil? || summary_at < running_at
end

.failure_reported?(text) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

True when a summary line reports a failing test: a Minitest failure or error, or an RSpec failure. An RSpec error outside examples alone (a spec file that raised while loading) is not one, as in TestRunners::RSpec. Any matching line counts, so a wrapper that runs two suites still kills. A test that prints a fake summary line to stdout fools this check.

Parameters:

Returns:

  • (Boolean)


253
254
255
256
# File 'lib/mutineer/external_backend.rb', line 253

def self.failure_reported?(text)
  text.scan(MINITEST_SUMMARY).any? { |failures, errors| (failures.to_i + errors.to_i).positive? } ||
    text.scan(RSPEC_SUMMARY).any? { |(failures)| failures.to_i.positive? }
end

.generic_env_hint ⇒ String

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Generic smoke-failure framing when no Ruby-version mismatch is detected.

Returns:

  • (String)


363
364
365
366
# File 'lib/mutineer/external_backend.rb', line 363

def self.generic_env_hint
  "the unmutated suite is not green (failing tests, or a broken environment: " \
    "DB, RAILS_ENV, migrations) — fix that before scoring"
end

.random_order(command, text) ⇒ Array(Symbol, String)?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The runner and seed of a random test order the output shows, or nil. Nil also when Mutineer sees a fixed seed: for Minitest, SEED, TESTOPTS or the command sets one; for RSpec, SPEC_OPTS or the command does. RSpec --order defined prints no seed line. Each runner is checked on its own, so a seeded Minitest suite does not hide an unseeded RSpec suite that the same command runs. Ceiling: a seed set in a wrapper script or .rspec, or Minitest's test_order, is not seen, so the warning still prints; a seed-like argument meant for a wrapper hides it (#338, limits tracked in #368).

Parameters:

  • command (String) —

    the --test-command template.

  • text (String) —

    output from summary_text.

Returns:

  • (Array(Symbol, String), nil) —

    [:minitest | :rspec, seed].



316
317
318
319
320
321
322
323
324
325
# File 'lib/mutineer/external_backend.rb', line 316

def self.random_order(command, text)
  minitest = text[MINITEST_SEED, 1]
  if minitest && ENV["SEED"].to_s.empty? &&
     [command, ENV["TESTOPTS"]].none? { |s| s.to_s.match?(MINITEST_SEED_GIVEN) }
    return [:minitest, minitest]
  end

  rspec = text[RSPEC_SEED, 1]
  [:rspec, rspec] if rspec && [command, ENV["SPEC_OPTS"]].none? { |s| s.to_s.match?(RSPEC_SEED_GIVEN) }
end

.ruby_version_mismatch_hint(output) ⇒ String?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Targeted hint when Bundler reports a RubyVersionMismatch (common under rbenv/asdf/chruby when Mutineer's version bin sits ahead of shims on PATH).

Parameters:

  • output (String) —

    captured child stdout+stderr.

Returns:

  • (String, nil) —

    hint text, or nil when not a version mismatch.



374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# File 'lib/mutineer/external_backend.rb', line 374

def self.ruby_version_mismatch_hint(output)
  return nil if output.nil? || output.empty?
  return nil unless output.match?(/RubyVersionMismatch|Your Ruby version is .* but your Gemfile specified/i)

  ran = output[/Your Ruby version is ([0-9.]+)/i, 1]
  want = output[/Gemfile specified ([0-9.]+)/i, 1]
  parts = +"Detected a Ruby version mismatch"
  parts << ": the test command ran under #{ran}" if ran
  parts << " but the app expects #{want}" if want
  parts << ". Mutineer already scrubbed version-manager bins and RBENV_VERSION/" \
           "ASDF_RUBY_VERSION from the child env; the suite still picked the wrong " \
           "Ruby. Use a wrapper that re-selects the app Ruby and ensure " \
           ".ruby-version / .tool-versions is present " \
           "(see https://github.com/davidteren/mutineer/blob/main/docs/rails-setup.md#apps-on-ruby--34, section Under a version manager)"
  parts
end

.run(command, files, timeout:, verbose: false, check_summary: false) ⇒ Mutineer::Result

Runs the command for ONE mutant against whatever is currently on disk (the caller has already swapped the mutant in via FileSwap). Maps the outcome to a Result. Uses child_env so version-manager PATH pins from Mutineer's Ruby do not force the suite onto the wrong interpreter.

Parameters:

  • command (String) —

    the --test-command template.

  • files (Array<String>) —

    test file paths.

  • timeout (Numeric) —

    per-mutant wall-clock timeout in seconds.

  • verbose (Boolean) (defaults to: false) —

    print the child's captured output on a non-pass.

  • check_summary (Boolean) (defaults to: false) —

    score exit 1 as killed only when the output has a summary line that reports a failing test (see failure_reported?). The runner turns this on when the clean smoke run printed a summary line.

Returns:



184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/mutineer/external_backend.rb', line 184

def self.run(command, files, timeout:, verbose: false, check_summary: false)
  kind, code, output, = spawn_capture(command, files, timeout)
  case kind
  when :timeout
    # A timeout is the one non-pass we flag by default — a normal kill is also
    # a non-zero exit, so notifying on every non-zero would spam every kill.
    warn "[mutineer] test-command exceeded #{timeout}s and was killed (scored timeout)."
    warn Redaction.text(output) if verbose && !output.empty?
    Result.timeout
  else # :exited
    return Result.survived if code&.zero?
    # Signal death (nil exitstatus) is infrastructure, not a suite assertion
    # failure — match Isolation/daemon (error), do not inflate kill rate.
    if code.nil?
      warn Redaction.text(output) if verbose && !output.empty?
      return Result.error("test-command terminated by signal")
    end

    warn Redaction.text(output) if verbose && !output.empty?
    # 126 (cannot execute) and 127 (command not found) come from a wrapper
    # such as `bundle exec` that could not start the suite: no test ran.
    return Result.error("test-command could not start (exit #{code})") if CANNOT_RUN_CODES.include?(code)

    text = summary_text(output)
    # SimpleCov's minimum_coverage gate replaced the exit code. Under
    # Minitest it runs in Minitest.after_run even after a failing test, so a
    # failing summary plus its message is still a kill. A passing summary
    # plus its message means no test caught the mutant: in process, the
    # fork exits before that hook, and the mutant survives. Keyed on
    # SimpleCov's own message, so code under test that calls `exit 2`
    # still scores error. Ceiling: with `SimpleCov.print_error_status =
    # false` the gate prints nothing, and its exit scores error too.
    if text.match?(SIMPLECOV_GATE)
      return Result.killed if failure_reported?(text)
      return Result.survived if tests_passed?(text)
    end

    unless code == FAILURE_CODE
      return Result.error("test-command exited #{code} (only exit 1 counts as a kill; " \
                          "check RSpec --failure-exit-code, a coverage gate, or your wrapper)")
    end

    if check_summary && !failure_reported?(text) && !exited_during_tests?(text)
      return Result.error("test-command exited 1 but its output shows no failing test " \
                          "(the suite or the mutant crashed before tests ran; --verbose shows the output)")
    end

    Result.killed
  end
end

.smoke_check!(command, files, timeout: SMOKE_TIMEOUT) ⇒ Array(Float, Boolean, Array(Symbol, String), nil)

Pre-flight: run the command once against the UNMUTATED tree. Green (exit 0) returns the elapsed seconds (used to calibrate the per-mutant timeout), whether the output has a Minitest or RSpec summary line (used to turn on the summary check in run), and the runner and seed of a random test order (see random_order); anything else raises SmokeCheckError so the run aborts before scoring.

Parameters:

  • command (String) —

    the --test-command template.

  • files (Array<String>) —

    test file paths.

  • timeout (Numeric) (defaults to: SMOKE_TIMEOUT) —

    ceiling for the calibration run.

Returns:

  • (Array(Float, Boolean, Array(Symbol, String), nil)) —

    [elapsed_seconds, summary_seen, random_order].

Raises:



340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/mutineer/external_backend.rb', line 340

def self.smoke_check!(command, files, timeout: SMOKE_TIMEOUT)
  kind, code, output, elapsed = spawn_capture(command, files, timeout)
  if kind == :exited && code&.zero?
    text = summary_text(output)
    return [elapsed, summary_line?(text), random_order(command, text)]
  end

  reason =
    if kind == :timeout then "did not finish within #{timeout}s"
    elsif code.nil?      then "was terminated by a signal"
    else                      "exited #{code}"
    end
  detail = output.empty? ? "" : "\n--- last output ---\n#{tail(output)}"
  hint = ruby_version_mismatch_hint(output)
  raise SmokeCheckError,
        "the test command #{reason} against the UNMUTATED source — " \
        "#{hint || generic_env_hint}.#{detail}"
end

.spawn_capture(command, files, timeout) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Spawns the command to a captured combined-output tempfile, enforces a wall-clock timeout (SIGKILL past the deadline), and returns [kind, exit_code, output, elapsed]. Mirrors Isolation's single-waiter loop: we are the only caller of waitpid on this pid, so the kill can never hit a reaped/recycled pid.



439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# File 'lib/mutineer/external_backend.rb', line 439

def self.spawn_capture(command, files, timeout)
  argv = build_argv(command, files)
  # Unreachable in practice (validate_test_command! guarantees a non-empty
  # command with %{files}); a neutral ArgumentError, not the smoke-specific
  # SmokeCheckError, since this is not a smoke-check failure.
  raise ArgumentError, "--test-command produced an empty command" if argv.empty?

  out = Tempfile.create("mutineer_ext")
  start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  # `pgroup: true` puts the child in its OWN process group so a timeout can
  # kill the whole tree (`bundle exec rails test` forks parallel workers;
  # spring/bundler add more) — killing only the leader would orphan workers
  # that keep holding the shared DB, corrupting later serial mutants. The
  # explicit [program, argv0] form guarantees the no-shell exec path even for a
  # degenerate single-element argv (Process.spawn(*argv) would route a lone
  # metachar-bearing string through /bin/sh, breaking the argv-only invariant).
  # RUBYOPT loads the copier in each Ruby process this command starts, so a
  # password that process assigns is hidden before the bytes are captured
  # (#457). A program that is not Ruby ignores RUBYOPT.
  pid = Process.spawn(child_env.merge("RUBYOPT" => command_rubyopt), [argv.first, argv.first], *argv[1..],
                      out: out, err: %i[child out], pgroup: true)
  kind, code = wait_with_timeout(pid, timeout)
  elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start
  out.rewind
  # Test output is arbitrary bytes. Read it as UTF-8 whatever the locale (#303).
  # Each invalid byte becomes `\xNN`, as in Reporter#printable, so the
  # smoke-failure checks can match on the text and nothing is lost.
  output = out.read.force_encoding(Encoding::UTF_8)
              .scrub { |bytes| bytes.unpack("C*").map { |b| format("\\x%02X", b) }.join }
  [kind, code, output, elapsed]
ensure
  if out
    out.close
    File.unlink(out.path) rescue nil # rubocop:disable Style/RescueModifier
  end
end

.summary_line?(text) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

True when the text has a Minitest or RSpec summary line.

Parameters:

Returns:

  • (Boolean)


240
241
242
# File 'lib/mutineer/external_backend.rb', line 240

def self.summary_line?(text)
  text.match?(MINITEST_SUMMARY) || text.match?(RSPEC_SUMMARY)
end

.summary_text(output) ⇒ String

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The output as binary with ANSI colour codes removed. Binary, so bytes that are invalid in the default encoding (an unset locale) cannot raise. Computed once per run and passed to the predicates above.

Parameters:

  • output (String) —

    captured child stdout+stderr.

Returns:

  • (String)


298
299
300
# File 'lib/mutineer/external_backend.rb', line 298

def self.summary_text(output)
  output.b.gsub(ANSI_CODE, "")
end

.tail(output, lines = 40) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Last ~40 lines of captured output, for a smoke-failure message.



515
516
517
# File 'lib/mutineer/external_backend.rb', line 515

def self.tail(output, lines = 40)
  output.lines.last(lines).join
end

.tests_passed?(text) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

True when a recognized summary line is present and none shows a failing test or an RSpec error outside examples. With no recognized summary line (a JUnit or custom reporter), it is false, so a SimpleCov gate exit there scores error rather than a survivor the output cannot prove.

Parameters:

Returns:

  • (Boolean)


287
288
289
# File 'lib/mutineer/external_backend.rb', line 287

def self.tests_passed?(text)
  summary_line?(text) && !failure_reported?(text) && !text.match?(RSPEC_OUTSIDE_ERROR)
end

.version_manager_shim_dirs ⇒ Array<String>

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Existing shim directories for rbenv / asdf (chruby uses PATH without shims).

Returns:

  • (Array<String>) —

    absolute shim paths that exist.



161
162
163
164
165
166
167
168
169
# File 'lib/mutineer/external_backend.rb', line 161

def self.version_manager_shim_dirs
  home = ENV["HOME"]
  return [] if home.nil? || home.empty?

  [
    File.join(home, ".rbenv", "shims"),
    File.join(home, ".asdf", "shims")
  ].select { |d| File.directory?(d) }
end

.wait_with_timeout(pid, timeout) ⇒ Array(Symbol, Integer, nil)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Waits for the spawned pid, SIGKILLing its process group past the deadline. Single-waiter deadline loop (mirrors Isolation), so the kill can never hit a reaped/recycled pid.

Parameters:

  • pid (Integer) —

    the spawned child pid.

  • timeout (Numeric) —

    wall-clock deadline in seconds.

Returns:

  • (Array(Symbol, Integer, nil)) —

    [:exited, code] or [:timeout, nil].



484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
# File 'lib/mutineer/external_backend.rb', line 484

def self.wait_with_timeout(pid, timeout)
  deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
  loop do
    reaped, status = Process.waitpid2(pid, Process::WNOHANG)
    return [:exited, status.exitstatus] if reaped

    if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline
      # Kill the whole process GROUP (negative pid) so forked test workers die
      # with the leader; fall back to the leader alone if the group is already
      # gone. The child led its group (pgroup: true at spawn).
      begin
        Process.kill(:KILL, -pid)
      rescue Errno::ESRCH, Errno::EPERM
        Process.kill(:KILL, pid) rescue nil # rubocop:disable Style/RescueModifier
      end
      begin
        _reaped, status = Process.waitpid2(pid)
        # Finished cleanly between poll and kill — honor real exit code.
        return [:exited, status.exitstatus] if status && status.exited? && !status.signaled?
      rescue Errno::ECHILD
        # already reaped
      end
      return [:timeout, nil]
    end
    sleep POLL
  end
end