henitai 0.5.3 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +332 -1
  3. data/README.md +123 -19
  4. data/assets/schema/henitai.schema.json +26 -0
  5. data/lib/henitai/arid_node_filter.rb +4 -19
  6. data/lib/henitai/bootstrap_error_message.rb +38 -0
  7. data/lib/henitai/canonical_report_merger.rb +23 -2
  8. data/lib/henitai/checkpoint_reporter.rb +5 -0
  9. data/lib/henitai/cli/operator_command.rb +10 -3
  10. data/lib/henitai/cli/run_command.rb +25 -7
  11. data/lib/henitai/cli/run_options.rb +1 -1
  12. data/lib/henitai/cli.rb +6 -2
  13. data/lib/henitai/composite_progress_reporter.rb +15 -2
  14. data/lib/henitai/configuration.rb +9 -1
  15. data/lib/henitai/configuration_validator/rules.rb +9 -0
  16. data/lib/henitai/configuration_validator/scalars.rb +22 -0
  17. data/lib/henitai/configuration_validator.rb +4 -2
  18. data/lib/henitai/constant_path.rb +48 -0
  19. data/lib/henitai/control_gate.rb +78 -0
  20. data/lib/henitai/control_run.rb +67 -0
  21. data/lib/henitai/coverage_bootstrapper.rb +46 -11
  22. data/lib/henitai/coverage_formatter.rb +26 -3
  23. data/lib/henitai/coverage_report_reader.rb +21 -0
  24. data/lib/henitai/equivalence_detector/operand_predicates.rb +16 -0
  25. data/lib/henitai/equivalence_detector.rb +46 -38
  26. data/lib/henitai/example_summary.rb +24 -0
  27. data/lib/henitai/execution_engine/env_scope.rb +3 -3
  28. data/lib/henitai/execution_engine/fork_server_scope.rb +57 -0
  29. data/lib/henitai/execution_engine.rb +109 -119
  30. data/lib/henitai/execution_provenance.rb +67 -0
  31. data/lib/henitai/fidelity_check.rb +173 -0
  32. data/lib/henitai/flaky_detection_baseline.rb +63 -0
  33. data/lib/henitai/flaky_retry_decision.rb +23 -0
  34. data/lib/henitai/flaky_test_registry.rb +63 -0
  35. data/lib/henitai/fork_server/client.rb +222 -0
  36. data/lib/henitai/fork_server/group_killer.rb +48 -0
  37. data/lib/henitai/fork_server/launcher.rb +38 -0
  38. data/lib/henitai/fork_server/mutant_runner.rb +110 -0
  39. data/lib/henitai/fork_server/protocol.rb +73 -0
  40. data/lib/henitai/fork_server/reaper.rb +24 -0
  41. data/lib/henitai/fork_server/runtime.rb +109 -0
  42. data/lib/henitai/fork_server/server.rb +108 -0
  43. data/lib/henitai/fork_server/server_process.rb +73 -0
  44. data/lib/henitai/fork_server/status.rb +52 -0
  45. data/lib/henitai/fork_server.rb +42 -0
  46. data/lib/henitai/generated_artifacts.rb +3 -0
  47. data/lib/henitai/git_diff_analyzer.rb +28 -11
  48. data/lib/henitai/history_checkpointer.rb +72 -0
  49. data/lib/henitai/incremental_filter.rb +20 -10
  50. data/lib/henitai/integration/base.rb +78 -19
  51. data/lib/henitai/integration/capped_log_sink.rb +34 -0
  52. data/lib/henitai/integration/child_bootstrap.rb +7 -0
  53. data/lib/henitai/integration/child_report_store.rb +65 -0
  54. data/lib/henitai/integration/minitest.rb +8 -13
  55. data/lib/henitai/integration/minitest_autorun.rb +20 -0
  56. data/lib/henitai/integration/minitest_fail_fast.rb +43 -0
  57. data/lib/henitai/integration/minitest_outcome_reporter.rb +44 -0
  58. data/lib/henitai/integration/minitest_preload.rb +30 -0
  59. data/lib/henitai/integration/minitest_runnable_filter.rb +61 -0
  60. data/lib/henitai/integration/minitest_test_runner.rb +47 -18
  61. data/lib/henitai/integration/mutant_run_support.rb +80 -17
  62. data/lib/henitai/integration/rspec_child_runner.rb +49 -9
  63. data/lib/henitai/integration/rspec_file_order.rb +37 -0
  64. data/lib/henitai/integration/rspec_preload.rb +35 -0
  65. data/lib/henitai/integration/rspec_process_runner.rb +4 -20
  66. data/lib/henitai/integration/scenario_log_support.rb +31 -18
  67. data/lib/henitai/integration.rb +18 -6
  68. data/lib/henitai/kill_history/store.rb +67 -0
  69. data/lib/henitai/kill_history.rb +85 -0
  70. data/lib/henitai/minitest_coverage_reporter.rb +22 -6
  71. data/lib/henitai/minitest_result_file.rb +62 -0
  72. data/lib/henitai/mutant/activation.rb +32 -0
  73. data/lib/henitai/mutant/activator.rb +75 -55
  74. data/lib/henitai/mutant/def_injection.rb +136 -0
  75. data/lib/henitai/mutant/lexical_scope_check.rb +120 -0
  76. data/lib/henitai/mutant/lexical_target.rb +105 -0
  77. data/lib/henitai/mutant/replacement.rb +52 -0
  78. data/lib/henitai/mutant.rb +32 -8
  79. data/lib/henitai/mutant_generator.rb +62 -18
  80. data/lib/henitai/mutant_history_store/database.rb +61 -0
  81. data/lib/henitai/mutant_history_store/sql.rb +9 -3
  82. data/lib/henitai/mutant_history_store/subject_scans.rb +101 -0
  83. data/lib/henitai/mutant_history_store/verdict_cache.rb +48 -18
  84. data/lib/henitai/mutant_history_store.rb +77 -51
  85. data/lib/henitai/mutant_identity.rb +5 -1
  86. data/lib/henitai/mutant_verdict.rb +71 -0
  87. data/lib/henitai/operator.rb +6 -2
  88. data/lib/henitai/operators/array_declaration.rb +4 -0
  89. data/lib/henitai/operators/assignment_expression.rb +2 -0
  90. data/lib/henitai/operators/conditional_expression.rb +21 -1
  91. data/lib/henitai/operators/equality_identity_operator.rb +2 -2
  92. data/lib/henitai/operators/hash_key_type.rb +11 -1
  93. data/lib/henitai/operators/hash_literal.rb +37 -9
  94. data/lib/henitai/operators/method_expression.rb +14 -3
  95. data/lib/henitai/operators/regex_metacharacters.rb +89 -0
  96. data/lib/henitai/operators/regex_mutator.rb +23 -28
  97. data/lib/henitai/operators/return_value.rb +1 -1
  98. data/lib/henitai/operators/string_literal.rb +17 -4
  99. data/lib/henitai/operators.rb +1 -0
  100. data/lib/henitai/per_test_coverage.rb +11 -7
  101. data/lib/henitai/per_test_coverage_collector.rb +30 -31
  102. data/lib/henitai/per_test_coverage_delta.rb +60 -0
  103. data/lib/henitai/per_test_coverage_selector.rb +26 -13
  104. data/lib/henitai/process_wakeup.rb +8 -3
  105. data/lib/henitai/process_worker_runner.rb +41 -7
  106. data/lib/henitai/reporter.rb +15 -8
  107. data/lib/henitai/result.rb +32 -16
  108. data/lib/henitai/reuse_context.rb +52 -0
  109. data/lib/henitai/rspec_coverage_formatter.rb +4 -0
  110. data/lib/henitai/rspec_outcomes.rb +74 -0
  111. data/lib/henitai/runner.rb +112 -21
  112. data/lib/henitai/runner_dependencies.rb +44 -3
  113. data/lib/henitai/sampling_strategy.rb +36 -6
  114. data/lib/henitai/scenario_execution_result.rb +51 -5
  115. data/lib/henitai/signal_deferral.rb +25 -0
  116. data/lib/henitai/signature_line.rb +21 -0
  117. data/lib/henitai/slot_scheduler/control_slots.rb +58 -0
  118. data/lib/henitai/slot_scheduler/draining.rb +35 -6
  119. data/lib/henitai/slot_scheduler/process_control.rb +33 -0
  120. data/lib/henitai/slot_scheduler/retry_policy.rb +20 -6
  121. data/lib/henitai/slot_scheduler.rb +64 -21
  122. data/lib/henitai/source_file_selection.rb +1 -1
  123. data/lib/henitai/source_parser.rb +29 -9
  124. data/lib/henitai/static_filter.rb +45 -14
  125. data/lib/henitai/stillborn_filter.rb +70 -2
  126. data/lib/henitai/subject.rb +8 -3
  127. data/lib/henitai/subject_resolver.rb +65 -31
  128. data/lib/henitai/suite_boot_clock.rb +48 -0
  129. data/lib/henitai/survivor_activation_cache.rb +18 -11
  130. data/lib/henitai/survivor_rerun_strategy.rb +47 -43
  131. data/lib/henitai/test_file_outcomes.rb +93 -0
  132. data/lib/henitai/test_prioritizer.rb +10 -2
  133. data/lib/henitai/timeout_calibrator.rb +31 -9
  134. data/lib/henitai/timeout_ceiling.rb +37 -0
  135. data/lib/henitai/verdict_fingerprint.rb +29 -30
  136. data/lib/henitai/version.rb +1 -1
  137. data/lib/henitai.rb +21 -1
  138. data/sig/configuration_validator.rbs +1 -0
  139. data/sig/henitai.rbs +254 -56
  140. metadata +63 -5
  141. data/lib/henitai/survivor_test_filter.rb +0 -72
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Henitai
6
+ # The set of test files whose outcome differed between two baseline runs.
7
+ #
8
+ # Produced by comparing per-file pass/fail maps from two runs of the same
9
+ # suite, and persisted as `henitai_flaky_tests.json` so that later runs can
10
+ # tell a kill caused by a flaky test from one caused by a stable test.
11
+ class FlakyTestRegistry
12
+ FILE_NAME = "henitai_flaky_tests.json"
13
+
14
+ # A file is flaky only when both runs ran it and disagreed. A file seen in
15
+ # one run only has no second observation, so it is never called flaky;
16
+ # FlakyDetectionBaseline rejects a failing run that such a file leaves
17
+ # unexplained.
18
+ def self.from_outcomes(first, second)
19
+ shared = first.keys & second.keys
20
+ flaky = shared.reject { |file| first[file] == second[file] }
21
+ new(flaky)
22
+ end
23
+
24
+ def self.load(path)
25
+ return new([]) unless File.file?(path)
26
+
27
+ new(Array(JSON.parse(File.read(path))["flaky_tests"]))
28
+ end
29
+
30
+ def self.for_config(config)
31
+ return new([]) unless config.respond_to?(:flaky_detection) && config.flaky_detection
32
+
33
+ for_reports_dir(config.respond_to?(:reports_dir) ? config.reports_dir : nil)
34
+ end
35
+
36
+ def self.for_reports_dir(dir)
37
+ return new([]) if dir.nil?
38
+
39
+ load(File.join(dir, FILE_NAME))
40
+ end
41
+
42
+ def initialize(files)
43
+ @files = files.map { |file| File.expand_path(file) }.uniq.sort.freeze
44
+ @lookup = @files.to_set.freeze
45
+ end
46
+
47
+ def all
48
+ @files
49
+ end
50
+
51
+ def flaky?(path)
52
+ @lookup.include?(File.expand_path(path))
53
+ end
54
+
55
+ def empty?
56
+ @files.empty?
57
+ end
58
+
59
+ def write(path)
60
+ File.write(path, JSON.pretty_generate("flaky_tests" => @files))
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,222 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Henitai
4
+ module ForkServer
5
+ # The parent's end of the connection to the fork server. It sends `run`
6
+ # requests and collects the server's events; the parent cannot wait on the
7
+ # mutant processes (they are the server's children), so their ends arrive
8
+ # as `exited` events.
9
+ class Client
10
+ class ServerLost < StandardError; end
11
+
12
+ class BootFailed < StandardError; end
13
+
14
+ class SpawnFailed < StandardError; end
15
+
16
+ SHUTDOWN_GRACE = 5.0
17
+ SPAWN_TIMEOUT = 30.0
18
+ REAP_POLL_SECONDS = 0.05
19
+
20
+ # @param socket [IO] the parent end of the connection
21
+ # @param pid [Integer, nil] the server process, reaped on #shutdown
22
+ # @param shutdown_grace [Float] seconds the server may take to exit before it is killed
23
+ def initialize(socket:, pid:, shutdown_grace: SHUTDOWN_GRACE)
24
+ @socket = socket
25
+ @pid = pid
26
+ @shutdown_grace = shutdown_grace
27
+ @reader = Protocol::Reader.new(socket)
28
+ @next_request_id = 0
29
+ @boot = nil
30
+ @spawned = {}
31
+ @exits = {}
32
+ @outstanding = []
33
+ end
34
+
35
+ def lost?
36
+ @lost == true
37
+ end
38
+
39
+ # The connection the parent can select on to learn of relayed events.
40
+ def io
41
+ @socket
42
+ end
43
+
44
+ # @raise [BootFailed] when the server reports failure or stays silent
45
+ # @raise [ServerLost] when the server dies while booting
46
+ def wait_until_ready(timeout)
47
+ outcome = await(timeout) { @boot }
48
+ raise BootFailed, "the fork server did not become ready within #{timeout}s" unless outcome
49
+ raise BootFailed, outcome.last if outcome.first == :failed
50
+
51
+ nil
52
+ end
53
+
54
+ # @return [Integer] pid of the forked mutant process
55
+ # @raise [SpawnFailed] when the server could not fork this mutant
56
+ # @raise [ServerLost]
57
+ def spawn_mutant(mutant_id:, test_files:, log_paths:, env: {})
58
+ request_id = (@next_request_id += 1)
59
+ send_message("type" => "run", "request_id" => request_id, "mutant_id" => mutant_id,
60
+ "test_files" => test_files, "log_paths" => log_paths, "env" => env)
61
+ outcome = await(SPAWN_TIMEOUT) { @spawned.delete(request_id) }
62
+ lose_server("the fork server did not answer a run request") unless outcome
63
+ raise SpawnFailed, outcome.last if outcome.first == :failed
64
+
65
+ @outstanding << outcome.last
66
+ outcome.last
67
+ end
68
+
69
+ # @return [Status, nil] how the process ended; nil when it is still
70
+ # running after +timeout+ seconds
71
+ def wait_exit(pid, timeout)
72
+ await(timeout) { @exits.delete(pid) }
73
+ end
74
+
75
+ # Non-blocking variants for the parallel scheduler, which reaps
76
+ # completions from relayed events. A lost server completes every
77
+ # outstanding process with a {Status.lost} instead of raising, so no
78
+ # slot waits for an event that cannot arrive and no verdict is invented.
79
+ #
80
+ # @return [Status, nil]
81
+ def poll_exit(pid)
82
+ drain_available
83
+ @exits.delete(pid)
84
+ end
85
+
86
+ # @return [Array(Integer, Status), nil]
87
+ def poll_any_exit
88
+ drain_available
89
+ pid, status = @exits.first
90
+ return nil unless pid
91
+
92
+ @exits.delete(pid)
93
+ [pid, status]
94
+ end
95
+
96
+ # Whether an event is already in user space (read off the socket but not
97
+ # yet handed out), which the socket's readability no longer signals.
98
+ def pending_events?
99
+ !@exits.empty? || @reader.buffered_message?
100
+ end
101
+
102
+ # Gives up on a server that is lost or stalled: it must not fork another
103
+ # mutant that a local run is about to repeat.
104
+ def abandon
105
+ @lost = true
106
+ kill_outstanding
107
+ close_socket
108
+ reap_server
109
+ @pid = nil
110
+ end
111
+
112
+ def shutdown
113
+ send_message("type" => "shutdown")
114
+ rescue ServerLost
115
+ nil
116
+ ensure
117
+ close_socket
118
+ reap_server
119
+ end
120
+
121
+ private
122
+
123
+ # The registry keeps fallback children from inheriting this connection.
124
+ def close_socket
125
+ InheritedFdRegistry.unregister(@socket)
126
+ @socket.close unless @socket.closed?
127
+ end
128
+
129
+ # Without its server a mutant process has no one to reap it, and a local
130
+ # rerun of the same mutant must not race it.
131
+ def kill_outstanding
132
+ @outstanding.each { |pid| GroupKiller.kill(pid) }
133
+ end
134
+
135
+ def await(timeout)
136
+ deadline = now + timeout
137
+ until (result = yield)
138
+ remaining = deadline - now
139
+ return nil unless remaining.positive?
140
+
141
+ pump(remaining)
142
+ end
143
+ result
144
+ end
145
+
146
+ def pump(timeout)
147
+ message = @reader.next_message(timeout)
148
+ return if message == Protocol::Reader::TIMEOUT
149
+ return lose_server if message.nil?
150
+
151
+ record(message)
152
+ end
153
+
154
+ def drain_available
155
+ loop do
156
+ message = @reader.next_message(0)
157
+ break if message == Protocol::Reader::TIMEOUT
158
+
159
+ message.nil? ? lose_server : record(message)
160
+ end
161
+ rescue ServerLost
162
+ nil
163
+ end
164
+
165
+ def lose_server(reason = "the fork server closed the connection")
166
+ @lost = true
167
+ kill_outstanding
168
+ @outstanding.each { |pid| @exits[pid] ||= Status.lost }
169
+ @outstanding.clear
170
+ raise ServerLost, reason
171
+ end
172
+
173
+ def record(message)
174
+ case message["type"]
175
+ when "ready" then @boot = [:ready]
176
+ when "boot_failed" then @boot = [:failed, message["reason"]]
177
+ when "spawned" then @spawned[message["request_id"]] = [:ok, message["pid"]]
178
+ when "spawn_failed" then @spawned[message["request_id"]] = [:failed, message["reason"]]
179
+ when "exited" then record_exit(message)
180
+ end
181
+ end
182
+
183
+ def record_exit(message)
184
+ pid = message["pid"]
185
+ return unless @outstanding.delete(pid)
186
+
187
+ @exits[pid] = Status.from_event(message)
188
+ end
189
+
190
+ def send_message(message)
191
+ @socket.write(Protocol.encode(message))
192
+ rescue IOError, SystemCallError => e
193
+ raise ServerLost, "the fork server connection is gone: #{e.message}"
194
+ end
195
+
196
+ def reap_server
197
+ return if @pid.nil? || exited_within?(@shutdown_grace)
198
+
199
+ Process.kill(:SIGKILL, @pid)
200
+ Process.wait(@pid)
201
+ rescue Errno::ECHILD, Errno::ESRCH
202
+ nil
203
+ end
204
+
205
+ def exited_within?(grace)
206
+ deadline = now + grace
207
+ loop do
208
+ return true if Process.wait(@pid, Process::WNOHANG)
209
+ return false if now > deadline
210
+
211
+ sleep(REAP_POLL_SECONDS)
212
+ end
213
+ rescue Errno::ECHILD
214
+ true
215
+ end
216
+
217
+ def now
218
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
219
+ end
220
+ end
221
+ end
222
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Henitai
4
+ module ForkServer
5
+ # Signals a mutant process the fork server forked. Such a process leads
6
+ # its own process group only once its bootstrap ran +setpgid+, so until
7
+ # then the group does not exist and the process itself is signalled.
8
+ # Its parent is the server, so it is never ours to wait on.
9
+ module GroupKiller
10
+ # @param leader [Boolean] whether the pid itself may still be alive;
11
+ # false once it was reaped, when only stragglers in its group remain
12
+ def self.kill(pid, signal = :SIGKILL, leader: true)
13
+ Process.kill(signal, -pid)
14
+ rescue Errno::ESRCH
15
+ kill_leader(pid, signal) if leader
16
+ rescue Errno::EPERM
17
+ nil
18
+ end
19
+
20
+ def self.kill_leader(pid, signal)
21
+ Process.kill(signal, pid)
22
+ rescue Errno::ESRCH, Errno::EPERM
23
+ nil
24
+ end
25
+ private_class_method :kill_leader
26
+
27
+ # Signal 0 probes existence only; a missing process or group is not alive.
28
+ def self.alive?(pid, leader: true)
29
+ Process.kill(0, -pid)
30
+ true
31
+ rescue Errno::ESRCH
32
+ leader && probe(pid)
33
+ rescue Errno::EPERM
34
+ true
35
+ end
36
+
37
+ def self.probe(pid)
38
+ Process.kill(0, pid)
39
+ true
40
+ rescue Errno::ESRCH
41
+ false
42
+ rescue Errno::EPERM
43
+ true
44
+ end
45
+ private_class_method :probe
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Henitai
4
+ module ForkServer
5
+ # Forks one mutant process from the booted server. The process then does
6
+ # what a per-mutant child does after its own boot: process-group and trap
7
+ # setup, output capture, activation, the tests, the child report.
8
+ class Launcher
9
+ # @param mutants [Hash{String => Mutant}] the run's mutants by id
10
+ def initialize(integration:, mutants:, socket:, server_pid: Process.pid)
11
+ @integration = integration
12
+ @mutants = mutants
13
+ @socket = socket
14
+ @server_pid = server_pid
15
+ end
16
+
17
+ # @param request [Hash] a `run` request
18
+ # @return [Integer] pid of the forked process
19
+ def call(request)
20
+ mutant = @mutants.fetch(request["mutant_id"]) { raise KeyError, "unknown mutant #{request['mutant_id']}" }
21
+ test_files = Array(request["test_files"])
22
+ log_paths = request.fetch("log_paths").transform_keys(&:to_sym)
23
+ env = request["env"] || {}
24
+ Process.fork { run_forked(mutant, test_files, log_paths, env) }
25
+ end
26
+
27
+ private
28
+
29
+ def run_forked(mutant, test_files, log_paths, env)
30
+ @socket.close
31
+ Integration::ChildBootstrap.after_fork!(parent_pid: @server_pid)
32
+ env.each { |key, value| ENV[key] = value }
33
+ ENV["HENITAI_MUTANT_ID"] = mutant.id
34
+ Process.exit(@integration.run_in_child(mutant:, test_files:, log_paths:))
35
+ end
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,110 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "forwardable"
4
+
5
+ module Henitai
6
+ module ForkServer
7
+ # Runs mutants through the fork server instead of booting the test
8
+ # environment in every mutant process. Stands in for the integration of
9
+ # the scheduler (ADR-20): #spawn_mutant hands it a handle for a process the
10
+ # server forked, and #runtime lets it learn of that process's exit from
11
+ # the server's events.
12
+ #
13
+ # Falls back to the integration's own per-mutant boot when the server is
14
+ # lost, or when it cannot fork one particular mutant (for example the
15
+ # control run's mutant, which the server never saw).
16
+ class MutantRunner
17
+ extend Forwardable
18
+
19
+ def_delegators :@integration, :build_result, :select_tests, :test_files
20
+
21
+ # @param fallback_timeout [#call, nil] test files -> timeout for a mutant
22
+ # the parent boots itself; the scheduler's timeout excludes boot while
23
+ # the server is active and would be far too short for it.
24
+ # rubocop:disable Metrics/ParameterLists
25
+ def initialize(integration:, client:, env: {}, warner: nil, fallback_timeout: nil,
26
+ report_store: Integration::ChildReportStore.new)
27
+ # rubocop:enable Metrics/ParameterLists
28
+ @integration = integration
29
+ @client = client
30
+ @env = env
31
+ @warner = warner || ->(message) { Kernel.warn(message) }
32
+ @fallback_timeout = fallback_timeout
33
+ @report_store = report_store
34
+ @active = true
35
+ end
36
+
37
+ # False once the server is gone; a lost connection is noticed here even
38
+ # when no request is pending.
39
+ def active?
40
+ deactivate("the fork server closed the connection") if @active && @client.lost?
41
+ @active
42
+ end
43
+
44
+ def runtime
45
+ @runtime ||= Runtime.new(client: @client)
46
+ end
47
+
48
+ # @return [Integration::ChildHandle]
49
+ def spawn_mutant(mutant:, test_files:)
50
+ return spawn_locally(mutant, test_files) unless active?
51
+
52
+ spawn_through_server(mutant, test_files)
53
+ rescue Client::SpawnFailed
54
+ spawn_locally(mutant, test_files)
55
+ rescue Client::ServerLost => e
56
+ deactivate(e.message)
57
+ spawn_locally(mutant, test_files)
58
+ end
59
+
60
+ # Forks on the per-mutant path without asking the server, for a process
61
+ # the server never saw (a control run, ADR-19). The pid is registered
62
+ # with the runtime so the scheduler reaps it, and the timeout includes
63
+ # booting the suite.
64
+ # @return [Integration::ChildHandle]
65
+ def spawn_local(mutant:, test_files:)
66
+ spawn_locally(mutant, test_files)
67
+ end
68
+
69
+ def stop
70
+ @active = false
71
+ @client.shutdown
72
+ end
73
+
74
+ private
75
+
76
+ def spawn_through_server(mutant, test_files)
77
+ log_paths = @integration.mutant_log_paths(mutant)
78
+ @report_store.clear(log_paths[:report_path])
79
+ pid = @client.spawn_mutant(mutant_id: mutant.id, test_files:, log_paths:, env: spawn_env)
80
+ runtime.served(pid)
81
+ Integration::ChildHandle.new(pid:, log_paths:)
82
+ end
83
+
84
+ def spawn_locally(mutant, test_files)
85
+ handle = @integration.spawn_mutant(mutant:, test_files:)
86
+ runtime.local(handle.pid)
87
+ Integration::ChildHandle.new(pid: handle.pid, log_paths: handle.log_paths,
88
+ timeout: fallback_timeout(test_files))
89
+ end
90
+
91
+ # The scheduler exports the slot of the process it is about to spawn.
92
+ def spawn_env
93
+ slot = ENV.fetch(SlotScheduler::WORKER_SLOT_ENV, nil)
94
+ slot ? @env.merge(SlotScheduler::WORKER_SLOT_ENV => slot) : @env
95
+ end
96
+
97
+ def fallback_timeout(test_files)
98
+ @fallback_timeout&.call(test_files)
99
+ end
100
+
101
+ def deactivate(reason)
102
+ return unless @active
103
+
104
+ @active = false
105
+ @client.abandon
106
+ @warner.call("henitai: the fork server stopped (#{reason}); falling back to per-mutant boot")
107
+ end
108
+ end
109
+ end
110
+ end
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Henitai
6
+ module ForkServer
7
+ # Line-delimited JSON messages between the henitai parent and its fork
8
+ # server. One message per line keeps both ends independent of how the
9
+ # socket chunks the stream.
10
+ #
11
+ # Requests (parent -> server):
12
+ # run: request_id, mutant_id, test_files, log_paths, env
13
+ # shutdown
14
+ # Events (server -> parent):
15
+ # ready | boot_failed(reason)
16
+ # spawned(request_id, pid) | spawn_failed(request_id, reason)
17
+ # exited(pid, exitstatus | termsig)
18
+ module Protocol
19
+ MAX_READ_BYTES = 65_536
20
+
21
+ def self.encode(message)
22
+ "#{JSON.generate(message)}\n"
23
+ end
24
+
25
+ # Buffers a stream and yields whole messages. Returns nil at end of
26
+ # stream, so a dead peer is distinguishable from a quiet one.
27
+ class Reader
28
+ TIMEOUT = :timeout
29
+
30
+ def initialize(io)
31
+ @io = io
32
+ @buffer = +""
33
+ @eof = false
34
+ end
35
+
36
+ # @param timeout [Float, nil] seconds to wait for a complete message
37
+ # @return [Hash, Symbol, nil] the message, TIMEOUT, or nil at end of stream
38
+ def next_message(timeout)
39
+ deadline = timeout && (Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout)
40
+ loop do
41
+ line = @buffer.slice!(/\A.*\n/)
42
+ return JSON.parse(line) if line
43
+ return nil if @eof
44
+
45
+ fill(deadline) or return TIMEOUT
46
+ end
47
+ end
48
+
49
+ # True when a whole message is already read off the socket, so the
50
+ # socket itself will not signal it as readable.
51
+ def buffered_message?
52
+ @buffer.include?("\n")
53
+ end
54
+
55
+ private
56
+
57
+ def fill(deadline)
58
+ remaining = deadline && [deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC), 0].max
59
+ return false unless @io.wait_readable(remaining)
60
+
61
+ chunk = @io.read_nonblock(MAX_READ_BYTES, exception: false)
62
+ return true if chunk == :wait_readable
63
+
64
+ @eof = true if chunk.nil?
65
+ @buffer << chunk unless chunk.nil?
66
+ true
67
+ rescue EOFError, Errno::ECONNRESET
68
+ @eof = true
69
+ end
70
+ end
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Henitai
4
+ module ForkServer
5
+ # Collects the processes that have ended since the last call, without
6
+ # blocking. The fork server is the only process that can wait on its
7
+ # mutant processes.
8
+ module Reaper
9
+ # @return [Array<Array(Integer, Status)>] pid and status per ended child
10
+ def self.reap
11
+ exits = [] # : Array[[Integer, Status]]
12
+ loop do
13
+ pid, status = Process.wait2(-1, Process::WNOHANG)
14
+ break unless pid
15
+
16
+ exits << [pid, Status.from_process_status(status)]
17
+ end
18
+ exits
19
+ rescue Errno::ECHILD
20
+ exits
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,109 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Henitai
4
+ module ForkServer
5
+ # The process primitives {SlotScheduler} drives, for a parallel run whose
6
+ # mutant processes belong to the fork server (ADR-15).
7
+ #
8
+ # The parent cannot wait on a grandchild, so a served pid completes when
9
+ # the server relays its +exited+ event. A pid forked locally (the per-mutant
10
+ # fallback) is waited on as usual. Signals go straight to the OS: every
11
+ # mutant process leads its own process group.
12
+ class Runtime
13
+ WAIT_SECONDS = 5.0
14
+ ANY_PID = -1
15
+
16
+ # @param client [Client]
17
+ # @param base [#clock_gettime, #wait2, #kill, #wait, #pause, #trap]
18
+ def initialize(client:, base: ProcessWorkerRunner::Runtime.new)
19
+ @client = client
20
+ @base = base
21
+ @served = []
22
+ @local = []
23
+ end
24
+
25
+ def served(pid)
26
+ @served << pid
27
+ end
28
+
29
+ def local(pid)
30
+ @local << pid
31
+ end
32
+
33
+ # Sockets the event loop must wake on besides its signal pipe.
34
+ def wakeup_ios
35
+ @client.lost? ? [] : [@client.io]
36
+ end
37
+
38
+ # An event already read off the socket does not wake a select on it.
39
+ def pending_events?
40
+ @client.pending_events?
41
+ end
42
+
43
+ def wait2(pid, flags = nil)
44
+ return any_exit(flags) if pid == ANY_PID
45
+ return served_exit(pid) if @served.include?(pid)
46
+
47
+ local_exit(pid, flags)
48
+ end
49
+
50
+ def wait(pid)
51
+ return @base.wait(pid) unless @served.include?(pid)
52
+
53
+ status = await_exit(pid)
54
+ @served.delete(pid) if status
55
+ status
56
+ end
57
+
58
+ # A served process leads no group until its bootstrap ran +setpgid+;
59
+ # until then the signal goes to the process itself.
60
+ def kill(signal, pid)
61
+ @base.kill(signal, pid)
62
+ rescue Errno::ESRCH
63
+ raise unless pid.negative? && @served.include?(-pid)
64
+
65
+ @base.kill(signal, -pid)
66
+ end
67
+
68
+ def clock_gettime(clock_id) = @base.clock_gettime(clock_id)
69
+ def pause(seconds) = @base.pause(seconds)
70
+ def trap(signal, handler = nil, &) = @base.trap(signal, handler, &)
71
+
72
+ private
73
+
74
+ def any_exit(flags)
75
+ finished = @client.poll_any_exit
76
+ if finished
77
+ @served.delete(finished.first)
78
+ return finished
79
+ end
80
+
81
+ @local.each do |pid|
82
+ result = local_exit(pid, flags)
83
+ return result if result
84
+ end
85
+ nil
86
+ end
87
+
88
+ def served_exit(pid)
89
+ status = @client.poll_exit(pid)
90
+ return nil unless status
91
+
92
+ @served.delete(pid)
93
+ [pid, status]
94
+ end
95
+
96
+ def local_exit(pid, flags)
97
+ result = @base.wait2(pid, flags)
98
+ @local.delete(pid) if result
99
+ result
100
+ end
101
+
102
+ def await_exit(pid)
103
+ @client.wait_exit(pid, WAIT_SECONDS)
104
+ rescue Client::ServerLost
105
+ @client.poll_exit(pid)
106
+ end
107
+ end
108
+ end
109
+ end