Module: Mutineer::DaemonServer

Defined in:
lib/mutineer/daemon_server.rb

Overview

App-side daemon (persistent worker).

Runs UNDER THE APP'S OWN BUNDLE/RUBY (the tool's DaemonClient spawns it via bundle exec ruby). It boots the app ONCE, then serves per-mutant test-run requests over stdin/stdout as newline-delimited JSON (the protocol keeps a private copy of the original stdout; the app's own stdout goes to stderr). For each request it FORKS a child that loads the mutated source text the tool sent, runs the covering tests, and exits with a status the parent decodes into a verdict.

HARD CONSTRAINT: this file must be loadable WITHOUT Prism or the rest of mutineer. The app's Ruby may be < 3.4 (no stdlib Prism) and its bundle has no mutineer. So it requires ONLY stdlib + the app's own boot file; it re-implements the fork/timeout/decode loop rather than requiring isolation.rb (which pulls in Prism). All parsing/mutation happened tool-side; the daemon only loads text.

Protocol (one JSON object per line, both directions):

boot in  : {"cmd":"boot","project_root":"...","boot":"config/environment","require_paths":[...],
          "load_paths":["test"],"framework":"minitest","rails":true}
ready out: {"ready":true,"ruby":"3.3.6","databases":{"names":["primary"],"primary":"primary"}}
         ("databases" is null with no worker-DB adapter, {"error":"...","primary":"primary"|null} when the lookup fails)
         (or {"ready":false,"error":"..."} then exit)
provision: {"cmd":"provision","slots":N} -> {"ok":true} or {"ok":false,"error":"..."}
run  in  : {"id":N,"worker":I,"payload":{"code":"<ruby>","source_file":"app/models/order.rb"},
          "tests":["test/models/order_test.rb"],"timeout":30}
         (a :maybe mutant also sends "reach_path" and "reach_key" inside
          "payload". The child clears that file, and the fiber-local
          named by reach_key, after load and before tests, so a
          load-time call is not a test reaching the expression, #345)
         (a mutant of a def in a concern's hook block adds to the payload
          "hook_def":{"line":12,"name":"total","singleton":false}, #297)
verdict  : {"id":N,"verdict":"survived"|"killed"|"error"|"timeout"}
         (an "error" adds "details" when the child sent a cause line:
          a raise → "Class: message" (#388); an in-test database error →
          "a test failed with a database error: Class: message" (#417))
quit in  : {"cmd":"quit"}

Worker isolation: when the app is Rails, each fork is routed to its own database via RailsWorkerDb BEFORE any test loads, so concurrent workers cannot clobber each other's transactional fixtures. worker defaults to 0 (serial). SQLite copies a file per slot. Postgres and MySQL use <base>-mutineer-<w>, created once before the worker daemons start.

Verdict mapping: child exit 0=survived (suite passed), 1=killed (suite failed), 2=error (child raised AROUND the test: load, boot, or worker-DB routing failure); parent-detected timeout. Exit 2 also covers a run whose first failing test failed with an Active Record connection or lock error inside the test (#296): MinitestIntegration::InTestDatabaseError decides.

Defined Under Namespace

Modules: DaemonTempIgnore

Constant Summary collapse

POLL =

Poll interval (seconds) for the per-fork deadline wait loop.

0.02

Class Method Summary collapse

Class Method Details

.apply_payload(payload) ⇒ Object (private)

Write the tool-built mutated text beside the real source and load it, reopening the mutated class/method in THIS child only. It goes in the source file's directory (like Isolation.apply_whole_file) so a require_relative in the mutated source resolves against its real neighbours. Writing it to the tmpdir would LoadError on such files and score a spurious error that diverges from the in-process path. The leading dot keeps the file away from Zeitwerk, which skips hidden files: loading it can be the first time Zeitwerk scans a namespace directory, and a parallel worker's file may sit there too (#253). sweep_temps only removes orphans and never touches a live file. Same path for reload (whole file) and redefine (wrapped snippet). The backend sends the whole file, so the concern blocks it stores replace the forgotten ones (#256). With a "hook_def", the load places the mutated hook-block def into each class that has the method, before the rest of the file runs; it raises when none was stored, so the mutant scores error (#297, #348).



549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
# File 'lib/mutineer/daemon_server.rb', line 549

def apply_payload(payload)
  hook = payload["hook_def"]
  hook &&= { line: hook.fetch("line"), name: hook.fetch("name").to_sym, singleton: hook.fetch("singleton") }
  dir = File.dirname(File.expand_path(payload.fetch("source_file")))
  Tempfile.create([".mutineer_daemon", ".rb"], dir) do |f|
    # Held until this block ends, including SIGKILL (the kernel drops it).
    # Another run's sweep sees the lock and does not delete the file.
    f.flock(File::LOCK_EX) rescue nil # rubocop:disable Style/RescueModifier
    # JSON delivered Unicode. Write the encoding the comment names (#346).
    f.binmode
    f.write(SourceBytes.for_file(payload.fetch("code")))
    f.flush
    ConcernBlocks.load_mutant(payload.fetch("source_file"), f.path, hook_def: hook)
  end
end

.boot!(cfg) ⇒ Object (private)

BOOT ONCE. chdir + require the app's boot file so the whole app is loaded and inherited by every fork. Never requires mutineer.



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
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
# File 'lib/mutineer/daemon_server.rb', line 164

def boot!(cfg)
  @cfg = cfg
  @framework = cfg.fetch("framework", "minitest")
  @source_dirs = Array(cfg["source_dirs"]).map { |d| File.expand_path(d) }
  Dir.chdir(cfg["project_root"]) if cfg["project_root"]
  # The parent's drain knows the tool's DATABASE_URL. A URL the app
  # loads from a dotenv file, or assigns before it prints, is hidden
  # here, where this process can see it (#341). Stderr only: stdout is
  # the protocol channel reserved above. Point fd 1 at the filtered
  # stderr so `puts` from the app takes the same path.
  Redaction.extra_urls = DatabaseUrls.from_files(Dir.pwd)
  unless OutputFilter.install(streams: [:stderr]) == :started
    raise "cannot redirect stderr, so a database password would be printed"
  end
  if @protocol
    STDOUT.reopen(STDERR)
    $stdout = STDOUT
  end
  ENV["RAILS_ENV"] ||= "test" if cfg["rails"]
  Array(cfg["load_paths"]).each { |d| $LOAD_PATH.unshift(File.expand_path(d)) }
  # Start Coverage BEFORE the app loads, so booted source lines are
  # instrumented. The map build (build_via_fork) forks this booted parent.
  if cfg["coverage"]
    require "coverage"
    Coverage.start(lines: true, methods: true)
  end
  # Clear a mutant tempfile a prior SIGKILLed child orphaned in a source
  # dir BEFORE the app boots. Zeitwerk skips a hidden one, but it would
  # choke on the non-constant name of one an older version wrote without
  # the dot (#253). A file another
  # live process still owns stays: this runs before the database lock,
  # so a refused boot must not delete that run's mutant. The kept file
  # is hidden from Zeitwerk instead.
  sweep_temps
  install_zeitwerk_ignore! if cfg["rails"]
  require File.expand_path(cfg["boot"]) if cfg["boot"]
  @zeitwerk_trace&.disable
  # The --require files, after the boot as in-process (Runner.execute), so
  # the coverage peek sees what they ran at load.
  Array(cfg["require_paths"]).each { |f| require File.expand_path(f) }
  setup_worker_db(cfg) if cfg["rails"]
rescue Exception => e # rubocop:disable Lint/RescueException
  # Boot failed (bad boot path, app error). Tell the client and exit so it
  # can surface a clean error rather than hang on the handshake.
  @output.puts(JSON.generate("ready" => false, "error" => describe_error(e)))
  @output.flush
  # exit! skips at_exit, so flush the stderr pipe before it.
  OutputFilter.uninstall
  exit!(1)
end

.build_coverage_map ⇒ Object (private)

Build the coverage map app-side (Coverage was started at boot) and return it as {map, failed_test_files, load_lines, load_methods} for the tool to select covering tests. Capture forks route to worker 0's DB (isolated, serial). On any failure return an empty map + an error string. The tool then falls back to the full test set rather than mis-scoring everything as no_coverage.



307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/mutineer/daemon_server.rb', line 307

def build_coverage_map
  require_relative "coverage_map"
  root = @cfg["project_root"] || Dir.pwd
  cmap = CoverageMap.new(
    source_paths: Array(@cfg["sources"]), test_paths: Array(@cfg["tests"]),
    load_paths: Array(@cfg["load_paths"]), project_root: root,
    boot_path: @cfg["boot"], require_paths: Array(@cfg["require_paths"]),
    framework: @framework, cache_dir: @cfg["cache_dir"] || File.join(root, ".mutineer"),
    capture_timeout: @cfg["capture_timeout"] || CoverageMap::DEFAULT_CAPTURE_TIMEOUT
  ).build_via_fork(after_fork: coverage_after_fork)
  # Nothing reads Coverage after the map, so a mutant forked from this
  # daemon does not pay for it (#228).
  Coverage.suspend if Coverage.running?
  { "map" => cmap.map, "failed_test_files" => cmap.failed_test_files,
    "failed_clean_tests" => cmap.failed_clean_tests,
    "failed_clean_details" => cmap.failed_clean_details,
    "clean_timeouts" => cmap.clean_timeouts,
    "load_lines" => cmap.load_lines.to_a,
    "load_methods" => cmap.load_methods.to_a }
rescue Exception => e # rubocop:disable Lint/RescueException
  error = describe_error(e)
  @errio.puts("[daemon] coverage build failed: #{error}")
  { "map" => {}, "failed_test_files" => [], "error" => error }
end

.check_shared_databases! ⇒ void (private)

This method returns an undefined value.

Raise when a test in this fork used a database that parallel workers share (shared_databases). Its verdict may rest on another worker's rows, so the mutant is scored error. A serial run sends no names.

Raises:

  • (RuntimeError) —

    when a shared database holds a connection.



280
281
282
283
284
285
286
287
288
# File 'lib/mutineer/daemon_server.rb', line 280

def check_shared_databases!
  return if @worker_db.nil? || @shared_databases.nil? || @shared_databases.empty?

  used = @worker_db.touched_shared_databases(@shared_databases)
  return if used.empty?

  raise "shared database used during a parallel run: #{used.join(", ")}. " \
        "Remove it from shared_databases, or see https://github.com/davidteren/mutineer/blob/main/docs/rails-setup.md#more-than-one-database"
end

.close_protocol ⇒ Object (private)

A forked child never answers on the protocol channel. Closing its inherited copy lets a daemon crash read as EOF on the client at once, not only after a slow or hung child exits. A caller-supplied output (for example STDOUT) is left open.



368
369
370
# File 'lib/mutineer/daemon_server.rb', line 368

def close_protocol
  @protocol&.close rescue nil # rubocop:disable Style/RescueModifier
end

.coverage_after_fork ⇒ Object (private)

Fork-safety hook for coverage capture. Each capture fork drops its copy of the protocol channel (see close_protocol) and, when the app has a worker-DB adapter, routes to a fresh copy of the base DB in worker 0's slot (captures run serially, so one worker is enough).



355
356
357
358
359
360
361
362
# File 'lib/mutineer/daemon_server.rb', line 355

def coverage_after_fork
  worker_db = @worker_db
  schema = @schema_path
  lambda do
    close_protocol
    worker_db&.after_fork(0, schema, seed: true)
  end
end

.databases ⇒ Hash? (private)

The booted test environment's database config names and the one each worker copies, for the tool's worker count. nil when the app has no worker-DB adapter. A failed lookup is reported, not hidden: the tool then keeps one worker. That report still names the primary when it resolves, so the tool still rejects a shared_databases that lists it.

Returns:

  • (Hash, nil)


257
258
259
260
261
262
263
# File 'lib/mutineer/daemon_server.rb', line 257

def databases
  return nil unless @worker_db

  @worker_db.database_names
rescue StandardError => e
  { "error" => describe_error(e), "primary" => primary_database_name }
end

.describe_error(error) ⇒ String (private)

Class: message for an error the daemon reports, with credentials hidden. Rails parses DATABASE_URL itself, so its URI error can carry the password. Redaction.describe never raises, so a rescue that calls this cannot make the raw error the cause of a new one.

Parameters:

  • error (Exception)

Returns:

  • (String)


339
340
341
# File 'lib/mutineer/daemon_server.rb', line 339

def describe_error(error)
  Redaction.describe(error)
end

.forget_load_reach(path, key) ⇒ void (private)

This method returns an undefined value.

Empties the reach sentinel after the mutant file has loaded. Same rule as ReachProbe.forget_load. Written here because this file cannot require Prism.

Parameters:

  • path (String, nil) —

    sentinel path, inside the run payload.

  • key (String, nil) —

    fiber-local key, mutineer_r plus 16 hex digits, the same pattern as ReachProbe::KEY_FORMAT.



527
528
529
530
531
532
# File 'lib/mutineer/daemon_server.rb', line 527

def forget_load_reach(path, key)
  return unless path.is_a?(String) && !path.empty?

  Thread.current[key.to_sym] = nil if key.is_a?(String) && key.match?(/\Amutineer_r[0-9a-f]{16}\z/)
  File.write(path, "")
end

.install_zeitwerk_ignore! ⇒ void (private)

This method returns an undefined value.

Hide kept mutant files from Zeitwerk before the app builds its loaders. The loader class may not exist yet. Watch for it, then stop watching.



447
448
449
450
451
452
453
454
455
456
457
458
459
460
# File 'lib/mutineer/daemon_server.rb', line 447

def install_zeitwerk_ignore!
  if defined?(Zeitwerk::Loader)
    prepend_daemon_temp_ignore
    return
  end

  @zeitwerk_trace = TracePoint.new(:end) do |event|
    next unless event.self.is_a?(Class) && event.self.name == "Zeitwerk::Loader"

    @zeitwerk_trace.disable
    prepend_daemon_temp_ignore
  end
  @zeitwerk_trace.enable
end

.prepend_daemon_temp_ignore ⇒ void (private)

This method returns an undefined value.



463
464
465
466
467
# File 'lib/mutineer/daemon_server.rb', line 463

def prepend_daemon_temp_ignore
  return if Zeitwerk::Loader.ancestors.include?(DaemonTempIgnore)

  Zeitwerk::Loader.prepend(DaemonTempIgnore)
end

.primary_database_name ⇒ String? (private)

The primary config name alone, or nil when it does not resolve either.

Returns:

  • (String, nil)


268
269
270
271
272
# File 'lib/mutineer/daemon_server.rb', line 268

def primary_database_name
  @worker_db.primary_database_name
rescue StandardError
  nil
end

.provision_slots(slots) ⇒ Hash (private)

Run RailsWorkerDb.provision and report success or the cause. A failure stays on this reply. It does not become a mutant verdict.

Parameters:

  • slots (Integer, String)

Returns:

  • (Hash)


295
296
297
298
299
300
# File 'lib/mutineer/daemon_server.rb', line 295

def provision_slots(slots)
  @worker_db.provision(Integer(slots)) if @worker_db
  { "ok" => true }
rescue Exception => e # rubocop:disable Lint/RescueException
  { "ok" => false, "error" => describe_error(e) }
end

.redact(text) ⇒ String (private)

Hide database credentials in text bound for the client or stderr.

Parameters:

  • text (String)

Returns:

  • (String)


347
348
349
# File 'lib/mutineer/daemon_server.rb', line 347

def redact(text)
  Redaction.text(text)
end

.reserve_protocol_output ⇒ IO (private)

Move the protocol channel off fd 1 before the app boots. The app may print through puts, STDOUT, or a raw fd 1 write (a logger, a subprocess). A line like that ahead of the ready message would break the client's JSON read. The protocol keeps a private dup of the original stdout. Fd 1 then points at stderr, so app output stays visible in the tool's diagnostics.

Returns:

  • (IO) —

    the reserved protocol stream.



155
156
157
158
159
160
# File 'lib/mutineer/daemon_server.rb', line 155

def reserve_protocol_output
  protocol = STDOUT.dup
  STDOUT.reopen(STDERR)
  $stdout = STDOUT
  protocol
end

.run(input: $stdin, output: nil, errio: $stderr) ⇒ void

This method returns an undefined value.

Serve the protocol on the given IO pair (defaults to stdio). Returns on quit.

Parameters:

  • input (IO) (defaults to: $stdin) —

    request stream.

  • output (IO, nil) (defaults to: nil) —

    verdict stream. nil (the default) reserves the process's original stdout for the protocol and points fd 1 at stderr.

  • errio (IO) (defaults to: $stderr) —

    diagnostics stream (never the IPC channel).



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/mutineer/daemon_server.rb', line 92

def run(input: $stdin, output: nil, errio: $stderr)
  # Only a stream `run` reserved itself is the daemon's to close in a fork.
  @protocol = output ? nil : reserve_protocol_output
  output ||= @protocol
  @errio = errio
  @output = output
  # The client sends UTF-8 JSON; with LANG unset the pipe would read as US-ASCII (#303).
  # Replies are UTF-8 too, including a non-ASCII path (#346).
  input.set_encoding(Encoding::UTF_8)
  output.set_encoding(Encoding::UTF_8)
  boot_line = input.gets
  return if boot_line.nil? # client vanished before boot

  boot!(JSON.parse(boot_line.strip))
  output.puts(JSON.generate("ready" => true, "ruby" => RUBY_VERSION, "databases" => databases))
  output.flush

  input.each_line do |line|
    line = line.strip
    next if line.empty?

    begin
      req = JSON.parse(line)
    rescue JSON::ParserError => e
      # A corrupt line has no id to address a reply to (and the client only
      # ever sends valid JSON, so it cannot be a pending request). Log and
      # read on rather than write an unaddressable verdict onto the channel.
      @errio.puts("[daemon] dropped unparseable line: #{e.message}")
      next
    end
    break if req["cmd"] == "quit"

    # Create worker databases before coverage forks or mutant forks.
    # The first daemon does this. A restarted worker daemon does not.
    if req["cmd"] == "provision"
      output.puts(JSON.generate(provision_slots(req["slots"])))
      output.flush
      next
    end

    # Build the coverage map app-side and ship it to the tool, which then
    # selects covering tests per mutant. One-shot control message.
    if req["cmd"] == "coverage"
      output.puts(JSON.generate(build_coverage_map))
      output.flush
      next
    end

    output.puts(JSON.generate(run_mutant(req)))
    output.flush
  end
end

.run_mutant(req) ⇒ Object (private)

Fork a child to run one mutant in isolation; decode its exit into a verdict.



373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
# File 'lib/mutineer/daemon_server.rb', line 373

def run_mutant(req)
  timeout = req.fetch("timeout", 30)
  worker  = req.fetch("worker", 0)
  # Seed the slot's DB until the first killed/survived fork for this worker slot.
  first_use = @worker_db && !@slot_ready[worker]
  daemon = Process.pid
  cause_rd, cause_wr = IO.pipe
  cause_wr.sync = true
  pid = fork do
    child = Process.pid
    cause_rd.close
    ChildCause.arm!(cause_wr, child)
    # New process group so a per-fork timeout can SIGKILL the whole subtree,
    # and silence the child's stdout so test output stays out of the diagnostics.
    Process.setpgid(0, 0) rescue nil # rubocop:disable Style/RescueModifier
    OrphanGuard.start(daemon)
    code =
      begin
        ChildStdout.silence
        ChildCoverage.allow_start
        close_protocol
        # Route THIS fork at its own worker database before any test loads.
        # A routing failure raises here and is scored `error`, never a false verdict.
        @worker_db&.after_fork(worker, first_use ? @schema_path : nil, seed: first_use)
        apply_payload(req["payload"])
        # A reload can run the probed expression while the file loads.
        # Drop that write before tests, matching the in-process child (#345).
        # A request with no payload (a test stub) has nothing to clear.
        loaded = req["payload"] || {}
        forget_load_reach(loaded["reach_path"], loaded["reach_key"])
        # A parallel worker records each pool that runs SQL, so a test
        # that closes its shared connection is still caught below.
        if @worker_db && @shared_databases&.any?
          @worker_db.skip_schema_check!
          @worker_db.watch_sql
        end
        result = run_tests(Array(req["tests"]))
        check_shared_databases!
        result
      rescue Exception => e # rubocop:disable Lint/RescueException
        @errio.puts("[daemon-child] #{describe_error(e)}")
        ChildCause.write(cause_wr, e, child)
        2
      ensure
        ChildCause.disarm!
      end
    exit!(code)
  end
  cause_wr.close
  verdict = wait_verdict(pid, timeout)
  # Mark ready only when the child finished cleanly after seeding
  # (killed/survived). Timeout can interrupt mid-copy; error can be a
  # routing failure or a database error inside a test (#296). Both leave
  # the slot unready so the next fork seeds again. A shared-database
  # error (check_shared_databases!) also exits 2, so it seeds again too:
  # the exit code cannot tell it from a routing failure. That costs only
  # time, in a run where that check then fails every mutant.
  @slot_ready[worker] = true if first_use && %w[killed survived].include?(verdict)
  # A SIGKILLed timeout child skipped its Tempfile unlink. Sweep the orphan
  # so it cannot outlive the run.
  sweep_temps if verdict == "timeout"
  reply = { "id" => req["id"], "verdict" => verdict }
  cause = verdict == "error" && ChildCause.read(cause_rd)
  reply["details"] = cause if cause
  reply
ensure
  cause_rd&.close
  cause_wr.close if cause_wr && !cause_wr.closed?
end

.run_tests(tests) ⇒ Object (private)

Load the covering test files and run them; 0 = all passed (survived), 1 = a failure/error (killed), 2 = the first failure was an in-test database error (error, #296). Minitest only; rspec is not yet on this path. MinitestIntegration.run is the method the daemon's clean check uses, so each mutant fork gets the same seed and, within each file, the same class order as the clean check (#282). It loads only stdlib, so the daemon still needs no Prism. The fork requires nothing else first: the test files' require "test_helper" loads rails/test_help after the class list is reset, as in the clean check.



574
575
576
577
578
579
# File 'lib/mutineer/daemon_server.rb', line 574

def run_tests(tests)
  raise "unsupported framework #{@framework.inspect}" unless @framework == "minitest"

  require_relative "minitest_integration"
  MinitestIntegration.run(tests.map { |t| File.expand_path(t) })
end

.setup_worker_db(cfg) ⇒ Object (private)

Load the per-worker DB adapter app-side (sibling gem file, by relative path so it bypasses the app bundle, like this daemon itself). No-op unless the app has ActiveRecord. Records the adapter + schema path so each fork can route to its own database.

db_role "prepare" waits for a provision command (the first daemon). "worker" only takes the shared lock (a worker daemon, including a respawn). Anything else provisions now, which is what a direct client that never sends the command needs. SQLite takes the run lock and copies files on first use.



225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/mutineer/daemon_server.rb', line 225

def setup_worker_db(cfg)
  require_relative "rails_worker_db"
  @worker_db = RailsWorkerDb.available? ? RailsWorkerDb : nil
  # Only the booted app knows its schema file (`schema_dump:` can rename it).
  @schema_path = @worker_db&.ruby_schema_path
  # Only a parallel worker daemon gets these names (DaemonBackend.boot_config).
  @shared_databases = Array(cfg["shared_databases"]).map(&:to_s)
  # Each SQLite slot is seeded once, on first use (not every mutant fork).
  # Postgres and MySQL slots are copied at provision time, so this flag is unused there.
  @slot_ready = {}
  return unless @worker_db

  case cfg["db_role"]
  when "prepare"
    nil
  when "worker"
    @worker_db.prepare_worker!
  else
    @worker_db.provision(cfg.fetch("slots", 2).to_i)
  end
rescue LoadError => e
  @errio.puts("[daemon] worker-DB routing unavailable: #{redact(e.message)}")
  @worker_db = nil
end

.sweep_temps ⇒ Object (private)

Remove orphaned mutant tempfiles of both modes from the source dirs (parent-side; the SIGKILL path cannot run the child's ensure). Mirrors JobPlan.sweep_orphans. Skips a file another process still owns (OrphanGuard.mutant_file_in_use?).



473
474
475
476
477
478
479
480
481
# File 'lib/mutineer/daemon_server.rb', line 473

def sweep_temps
  @source_dirs.to_a.each do |dir|
    Dir.glob(File.join(dir, OrphanGuard::TEMP_BASENAME)).each do |path|
      next if OrphanGuard.mutant_file_in_use?(path)

      File.unlink(path) rescue nil # rubocop:disable Style/RescueModifier
    end
  end
end

.wait_verdict(pid, timeout) ⇒ Object (private)

Single-waiter deadline loop (mirrors Isolation.run and ExternalBackend.wait_with_timeout, re-implemented here because Isolation pulls in Prism which is forbidden app-side). NOTE: this is the 3rd copy of the waitpid2(WNOHANG)+deadline+pgroup-SIGKILL+decode discipline. A fix to the kill/reap/decode logic must be applied to all three in lockstep. CoverageMap#await_child applies the same deadline and group kill to coverage capture. SIGKILL the child's process group past the deadline; a signalled child (nil exitstatus) is error.



492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
# File 'lib/mutineer/daemon_server.rb', line 492

def wait_verdict(pid, timeout)
  deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
  loop do
    reaped, status = Process.waitpid2(pid, Process::WNOHANG)
    if reaped
      return { 0 => "survived", 1 => "killed" }.fetch(status.exitstatus, "error")
    end
    if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline
      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)
        if status && status.exited? && !status.signaled?
          return { 0 => "survived", 1 => "killed" }.fetch(status.exitstatus, "error")
        end
      rescue Errno::ECHILD
        # already reaped
      end
      return "timeout"
    end
    sleep POLL
  end
end