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
@@ -2,18 +2,36 @@
2
2
 
3
3
  require_relative "process_worker_runner"
4
4
  require_relative "execution_engine/env_scope"
5
+ require_relative "execution_engine/fork_server_scope"
5
6
 
6
7
  module Henitai
7
8
  # Runs pending mutants through the selected integration.
9
+ #
10
+ # Every run, whatever `jobs` says, goes through one {ProcessWorkerRunner}
11
+ # (ADR-20): `jobs` is only its slot count. The engine supplies what the
12
+ # scheduler cannot know: which tests a mutant runs, its timeout, the flaky
13
+ # set, control runs and the fork server.
8
14
  class ExecutionEngine
9
15
  include EnvScope
16
+ include ForkServerScope
17
+
18
+ # @param runtime [ProcessWorkerRunner::Runtime, nil] process primitives of
19
+ # the worker runner; nil uses the real ones. Replaced by the fork
20
+ # server's runtime while a server is active.
21
+ # @param wakeup [ProcessWakeup, nil] the runner's wakeup; nil installs one
22
+ def initialize(runtime: nil, wakeup: nil)
23
+ @runtime = runtime
24
+ @wakeup = wakeup
25
+ end
10
26
 
11
27
  def run(mutants, integration, config, progress_reporter: nil)
12
28
  with_reports_dir(config) do
13
29
  with_coverage_dir(config) do
14
30
  with_max_log_bytes(config) do
15
31
  with_worker_slot do
16
- execute(mutants, integration, config, progress_reporter)
32
+ with_test_order(config) do
33
+ execute(mutants, integration, config, progress_reporter)
34
+ end
17
35
  end
18
36
  end
19
37
  end
@@ -22,91 +40,91 @@ module Henitai
22
40
 
23
41
  private
24
42
 
43
+ # Verdicts pass a ControlGate before any observer sees them (ADR-19); the
44
+ # worker runner builds the gate and runs its controls as scheduler jobs.
25
45
  def execute(mutants, integration, config, progress_reporter)
26
- @flaky_retry_count = 0
27
46
  pending_mutants = Array(mutants).select(&:pending?)
28
- mutex = Mutex.new
29
- if parallel_execution?(config, pending_mutants)
30
- run_parallel(pending_mutants, integration, config, progress_reporter)
31
- else
32
- run_linear(pending_mutants, integration, config, progress_reporter, mutex)
47
+ @flaky_tests = flaky_tests_for(config)
48
+ control_run = ControlRun.new if control_runs?(config)
49
+ runner = with_fork_server(pending_mutants, integration, config) do
50
+ run_workers(pending_mutants, integration, config, progress_reporter, control_run)
33
51
  end
34
-
35
- warn_flaky_mutants(pending_mutants.size)
52
+ warn_control_failures(runner.control_stats) if control_run
53
+ warn_flaky_mutants(runner.flaky_retry_count)
36
54
  mutants
37
55
  end
38
56
 
39
- def parallel_execution?(config, mutants)
40
- worker_count(config) > 1 && mutants.size > 1
57
+ # Seeds the kill history from the reports dir and saves it back in an
58
+ # ensure, so an interrupted run keeps what it learned. Without a reports
59
+ # dir there is nowhere to keep it, so nothing is read or written.
60
+ def with_test_order(config)
61
+ path = test_order_path(config)
62
+ @kill_history = path ? KillHistory.load(path) : KillHistory.new
63
+ yield
64
+ ensure
65
+ save_test_order(path) if path
41
66
  end
42
67
 
43
- def worker_count(config)
44
- configured_jobs = config.respond_to?(:jobs) ? config.jobs : nil
45
- return configured_jobs if configured_jobs
46
-
47
- # The fallback stays conservative for now; the execution policy still
48
- # defaults to a single worker even though AvailableCpuCount exists as a
49
- # future policy hook.
50
- 1
68
+ # A learned order is a convenience: a read-only or full reports dir must
69
+ # not fail the run or hide its verdicts, so a save error only warns.
70
+ def save_test_order(path)
71
+ @kill_history&.write(path)
72
+ rescue SystemCallError => e
73
+ warn format(
74
+ "henitai: could not save the learned test order (%<class>s: %<message>s)",
75
+ class: e.class, message: e.message
76
+ )
51
77
  end
52
78
 
53
- def run_linear(mutants, integration, config, progress_reporter, mutex)
54
- mutants.each do |mutant|
55
- process_mutant(mutant, integration, config, progress_reporter, mutex)
56
- end
79
+ def test_order_path(config)
80
+ dir = config.reports_dir if config.respond_to?(:reports_dir)
81
+ File.join(dir, KillHistory::FILE_NAME) unless dir.nil? || dir.empty?
57
82
  end
58
83
 
59
- def run_parallel(mutants, integration, config, progress_reporter)
60
- runner = ProcessWorkerRunner.new(worker_count: worker_count(config))
61
- results = runner.run(
62
- mutants,
63
- integration,
64
- config,
65
- progress_reporter,
66
- test_file_resolver: ->(mutant) { prioritized_tests_for(mutant, integration, config) },
67
- timeout_resolver: ->(_mutant, test_files) { resolved_timeout(test_files, config) }
68
- )
69
- @flaky_retry_count = runner.flaky_retry_count
70
- results
71
- end
84
+ def control_runs?(config) = config.respond_to?(:control_runs) && config.control_runs
72
85
 
73
- def process_mutant(mutant, integration, config, progress_reporter, mutex)
74
- test_files = prioritized_tests_for(mutant, integration, config)
75
- record_test_files(mutant, test_files)
76
- return record_no_coverage(mutant, progress_reporter, mutex) if test_files.empty?
86
+ def warn_control_failures(stats)
87
+ return if stats[:failed].zero?
77
88
 
78
- scenario_result = run_with_flaky_retry(mutant, integration, config, test_files, mutex)
79
- mutant.status = scenario_status(scenario_result)
89
+ warn format("henitai: control runs failed for %<failed>d of %<verified>d subjects; " \
90
+ "%<reclassified>d detected verdicts reclassified as CompileError", **stats)
91
+ end
80
92
 
81
- report_progress(mutant, scenario_result, progress_reporter, mutex)
93
+ # `jobs` is a slot count; unset or zero means one slot. The default stays
94
+ # conservative: AvailableCpuCount exists as a future policy hook.
95
+ def worker_count(config)
96
+ [config.jobs.to_i, 1].max
82
97
  end
83
98
 
84
- def record_test_files(mutant, test_files)
85
- mutant.covered_by = test_files if mutant.respond_to?(:covered_by=)
86
- mutant.tests_completed = test_files.size if mutant.respond_to?(:tests_completed=)
99
+ def run_workers(mutants, integration, config, progress_reporter, control_run)
100
+ runner = ProcessWorkerRunner.new(worker_count: worker_count(config), flaky_tests: @flaky_tests,
101
+ **runner_primitives)
102
+ observers = CompositeProgressReporter.new([@kill_history, progress_reporter])
103
+ runner.run(mutants, @fork_server_runner || integration, config, observers,
104
+ **run_options(integration, config, control_run))
105
+ runner
87
106
  end
88
107
 
89
- def record_no_coverage(mutant, progress_reporter, mutex)
90
- mutant.status = :no_coverage
91
- report_progress(mutant, nil, progress_reporter, mutex)
108
+ def runner_primitives
109
+ { runtime: @runtime, wakeup: @wakeup }.compact.merge(fork_server_runtime_options)
92
110
  end
93
111
 
94
- def report_progress(mutant, scenario_result, progress_reporter, mutex)
95
- if mutex
96
- mutex.synchronize { progress_reporter&.progress(mutant, scenario_result:) }
97
- else
98
- progress_reporter&.progress(mutant, scenario_result:)
99
- end
112
+ def run_options(integration, config, control_run)
113
+ {
114
+ test_file_resolver: ->(mutant) { prioritized_tests_for(mutant, integration, config) },
115
+ timeout_resolver: ->(_mutant, test_files) { resolved_timeout(test_files, config) },
116
+ control_run:
117
+ }
100
118
  end
101
119
 
102
120
  def prioritized_tests_for(mutant, integration, config)
103
- tests = reject_excluded_tests(integration.select_tests(mutant.subject), config)
104
- tests = per_test_coverage_selector.filter(
105
- tests,
121
+ tests = per_test_coverage_selector.select(
106
122
  mutant,
107
- reports_dir: config.reports_dir
123
+ reports_dir: config.reports_dir,
124
+ test_files: -> { reject_excluded_tests(integration.test_files, config) },
125
+ fallback: -> { reject_excluded_tests(integration.select_tests(mutant.subject), config) }
108
126
  )
109
- test_prioritizer(config).sort(tests, mutant, test_history(config))
127
+ test_prioritizer(config).sort(tests, mutant, @kill_history)
110
128
  end
111
129
 
112
130
  def reject_excluded_tests(tests, config)
@@ -133,11 +151,21 @@ module Henitai
133
151
  def resolved_timeout(test_files, config)
134
152
  return config.timeout unless calibration_enabled?(config)
135
153
 
136
- calibrated = timeout_calibrator(config).timeout_for(test_files)
137
- return [calibrated, max_timeout(config)].min if calibrated
154
+ calibrator = timeout_calibrator(config)
155
+ calibrated = calibrator.timeout_for(test_files)
156
+ unless calibrated
157
+ warn_timeout_fallback_once
158
+ return Configuration::DEFAULT_TIMEOUT
159
+ end
160
+
161
+ timeout_ceiling(config).cap(calibrated, calibrator.baseline_for(test_files))
162
+ end
138
163
 
139
- warn_timeout_fallback_once
140
- Configuration::DEFAULT_TIMEOUT
164
+ def timeout_ceiling(config)
165
+ @timeout_ceiling ||= TimeoutCeiling.new(
166
+ ceiling: max_timeout(config),
167
+ warner: ->(message) { warn(message) }
168
+ )
141
169
  end
142
170
 
143
171
  # Ceiling on the auto-calibrated timeout so a runaway mutant is killed in
@@ -153,13 +181,21 @@ module Henitai
153
181
  config.respond_to?(:timeout_configured?) && !config.timeout_configured?
154
182
  end
155
183
 
184
+ # Boot stays in the timeout even with a fork server: served mutants still
185
+ # run the suite's before(:suite) hooks, which the boot measurement includes.
156
186
  def timeout_calibrator(config)
157
187
  @timeout_calibrator ||= TimeoutCalibrator.new(
158
188
  timing_source: timing_source(config),
159
- multiplier: config.timeout_multiplier
189
+ multiplier: config.timeout_multiplier,
190
+ boot_seconds: -> { boot_seconds(config) }
160
191
  )
161
192
  end
162
193
 
194
+ def boot_seconds(config)
195
+ path = File.join(config.reports_dir, PerTestCoverageCollector::BOOT_FILE_NAME)
196
+ CoverageReportReader.new.boot_seconds(path)
197
+ end
198
+
163
199
  def warn_timeout_fallback_once
164
200
  return if @warned_timeout_fallback
165
201
 
@@ -172,65 +208,19 @@ module Henitai
172
208
 
173
209
  def per_test_coverage_selector = @per_test_coverage_selector ||= PerTestCoverageSelector.new
174
210
 
175
- def test_history(config)
176
- return {} unless config.respond_to?(:history)
177
-
178
- config.history || {}
211
+ def flaky_tests_for(config)
212
+ FlakyTestRegistry.for_config(config)
179
213
  end
180
214
 
181
- # Retry logic is kept in one place to preserve the status transition flow.
182
- # The retry budget is configurable because repeated survivors can multiply
183
- # runtime on real CI workloads.
184
- # rubocop:disable Metrics/MethodLength
185
- def run_with_flaky_retry(mutant, integration, config, test_files, mutex)
186
- timeout = resolved_timeout(test_files, config)
187
- scenario_result = integration.run_mutant(
188
- mutant:,
189
- test_files:,
190
- timeout: timeout
191
- )
192
- return scenario_result unless scenario_status(scenario_result) == :survived
193
-
194
- retries = 0
195
- max_flaky_retries(config).times do
196
- retries += 1
197
- scenario_result = integration.run_mutant(
198
- mutant:,
199
- test_files:,
200
- timeout: timeout
201
- )
202
- break unless scenario_status(scenario_result) == :survived
203
- end
204
-
205
- mutex.synchronize { @flaky_retry_count += 1 } if retries.positive?
206
- scenario_result
207
- end
208
- # rubocop:enable Metrics/MethodLength
209
-
210
- def scenario_status(result)
211
- return result if result.is_a?(Symbol)
212
-
213
- result.status
214
- end
215
-
216
- def warn_flaky_mutants(total_mutants)
217
- return if total_mutants.zero?
218
-
219
- flaky_ratio = @flaky_retry_count.to_f / total_mutants
220
- return unless flaky_ratio > 0.05
215
+ def warn_flaky_mutants(count)
216
+ return if count.zero?
221
217
 
222
218
  warn format(
223
- "Flaky-test mitigation: %<flaky>d/%<total>d mutants required retries (%<ratio>.2f%%)",
224
- flaky: @flaky_retry_count,
225
- total: total_mutants,
226
- ratio: flaky_ratio * 100.0
219
+ "Flaky-test mitigation: %<count>d killed mutant(s) were re-checked because their killing tests " \
220
+ "are flaky (%<files>s)",
221
+ count:,
222
+ files: @flaky_tests.all.join(", ")
227
223
  )
228
224
  end
229
-
230
- def max_flaky_retries(config)
231
- return 3 unless config.respond_to?(:max_flaky_retries)
232
-
233
- config.max_flaky_retries || 3
234
- end
235
225
  end
236
226
  end
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "verdict_fingerprint"
4
+
5
+ module Henitai
6
+ # Binds cached verdicts to the inputs that were executed (ADR-19 §4).
7
+ #
8
+ # Before Gate 1 parses anything, the run records size and mtime of every
9
+ # source and test file it may parse, load or execute, and of every test
10
+ # dependency file ({VerdictFingerprint.dependency_files}). A verdict may be
11
+ # fingerprinted only while its files still match that record: hashing them
12
+ # then hashes the content that was parsed, loaded and executed.
13
+ #
14
+ # Any change counts, including an edit that was later undone: editors and
15
+ # git move the mtime forward, so a restored file still differs from the
16
+ # record. A dependency file changing, appearing or disappearing invalidates
17
+ # every verdict of the run for good, since a helper loaded once (for
18
+ # example by the fork server) affects every mutant. A tool that rewrites a
19
+ # file and also restores its mtime is not detected; ADR-19 accepts that.
20
+ class ExecutionProvenance
21
+ # Stands in until a run has captured its inputs: nothing is intact, so a
22
+ # verdict recorded without a capture is never cached.
23
+ UNCAPTURED = Class.new { def intact?(_paths) = false }.new.freeze
24
+
25
+ def self.capture(paths, root: Dir.pwd)
26
+ dependencies = VerdictFingerprint.dependency_files(root)
27
+ stats = (Array(paths) + dependencies).to_h { |path| [File.expand_path(path), stat_of(path)] }
28
+ new(stats:, dependencies:, root:)
29
+ end
30
+
31
+ def self.stat_of(path)
32
+ stat = File.stat(path)
33
+ [stat.size, stat.mtime.to_i, stat.mtime.nsec]
34
+ rescue SystemCallError
35
+ nil
36
+ end
37
+
38
+ def initialize(stats:, dependencies:, root:)
39
+ @stats = stats
40
+ @dependencies = dependencies
41
+ @root = root
42
+ @dependencies_drifted = false
43
+ end
44
+
45
+ # True when every path was captured and is unchanged, and no test
46
+ # dependency changed since the capture.
47
+ def intact?(paths)
48
+ dependencies_intact? && Array(paths).all? { |path| unchanged?(File.expand_path(path.to_s)) }
49
+ end
50
+
51
+ private
52
+
53
+ def dependencies_intact?
54
+ return false if @dependencies_drifted
55
+
56
+ intact = VerdictFingerprint.dependency_files(@root) == @dependencies &&
57
+ @dependencies.all? { |path| unchanged?(File.expand_path(path)) }
58
+ @dependencies_drifted = true unless intact
59
+ intact
60
+ end
61
+
62
+ def unchanged?(path)
63
+ recorded = @stats[path]
64
+ !recorded.nil? && self.class.stat_of(path) == recorded
65
+ end
66
+ end
67
+ end
@@ -0,0 +1,173 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "prism"
4
+ require_relative "parser_current"
5
+ require_relative "source_parser"
6
+
7
+ module Henitai
8
+ # Verifies, before a mutant runs, that its activation source differs from
9
+ # the original method by exactly the reported mutation and nothing else.
10
+ #
11
+ # The checks run in order:
12
+ #
13
+ # 1. Site: the mutated node must lie inside the method body that the
14
+ # activation replaces.
15
+ # 2. Syntax: the activation source must be valid Ruby in context. Prism's
16
+ # error list is used because the parser translation layer recovers from
17
+ # errors silently.
18
+ # 3. Structure: the activated method body, re-parsed, must equal the
19
+ # original body with the original node replaced by the mutated node.
20
+ # Both sides are normalised first: parentheses around one expression
21
+ # are dropped, an interpolation-free +dstr+ is the same value as one
22
+ # +str+, nested statement sequences flatten, an empty kwargs node is no
23
+ # argument, and +__FILE__+ compares as an absolute path.
24
+ #
25
+ # A violation is a harness defect, not a test verdict: the mutant must not
26
+ # run, and the reason must be reported.
27
+ class FidelityCheck
28
+ # @return [String, nil] the reason the mutant is unfaithful, or nil
29
+ def violation(mutant)
30
+ return unless checkable?(mutant)
31
+
32
+ activation = Mutant::Activator.activation_for(mutant)
33
+ return "activation source could not be built" unless activation
34
+
35
+ whole_def = activation.mode == :toplevel
36
+ expected = expected_tree(mutant, whole_def)
37
+ return "mutation site is outside the executed method body" unless expected
38
+
39
+ syntax_violation(activation.source) || structure_violation(mutant, expected, activation, whole_def)
40
+ rescue StandardError => e
41
+ "fidelity could not be verified (#{e.class}: #{e.message})"
42
+ end
43
+
44
+ private
45
+
46
+ def checkable?(mutant)
47
+ return false unless mutant.original_node
48
+
49
+ subject = mutant.subject
50
+ !subject.method_name.nil? && !subject.ast_node.nil?
51
+ end
52
+
53
+ def syntax_violation(source)
54
+ error = Prism.parse(source).errors.first
55
+ "activation source is not valid Ruby: #{error.message}" if error
56
+ end
57
+
58
+ def structure_violation(mutant, expected, activation, whole_def)
59
+ source = activation.source
60
+ tree = SourceParser.parse(source, path: activation.file || Mutant::Activator::EVAL_FILE,
61
+ line: activation.line || 1)
62
+ actual = normalize(activated_tree(tree, mutant.subject.method_name, whole_def))
63
+ expected = normalize(expected)
64
+ "activated code differs from the reported mutation" unless actual == expected
65
+ end
66
+
67
+ # A re-evaluated def (ADR-13) is compared as a whole, parameters
68
+ # included; the define_method fallback only by body.
69
+ def expected_tree(mutant, whole_def)
70
+ definition = mutant.subject.ast_node
71
+ scope = whole_def ? definition : method_body(definition)
72
+ replaced, found = substitute(scope, mutant.original_node, mutant.mutated_node)
73
+ replaced if found
74
+ end
75
+
76
+ def method_body(node)
77
+ case node.type
78
+ when :defs then node.children[3]
79
+ when :def, :block then node.children[2]
80
+ end
81
+ end
82
+
83
+ def substitute(node, target, replacement)
84
+ return [replacement, true] if node.equal?(target)
85
+ return [node, false] unless node.is_a?(Parser::AST::Node)
86
+
87
+ found = false
88
+ children = node.children.map do |child|
89
+ child, child_found = substitute(child, target, replacement)
90
+ found ||= child_found
91
+ child
92
+ end
93
+ [found ? node.updated(nil, children) : node, found]
94
+ end
95
+
96
+ # The method as activated: a re-evaluated +def+ (ADR-13) or the
97
+ # +define_method+ block of the fallback.
98
+ def activated_tree(tree, method_name, whole_def)
99
+ name = method_name.to_sym
100
+ definition = find_node(tree) do |node|
101
+ activated_def?(node, name) || (node.type == :block && define_method_call?(node.children[0], name))
102
+ end
103
+ whole_def ? definition : definition && method_body(definition)
104
+ end
105
+
106
+ def activated_def?(node, name)
107
+ (node.type == :def && node.children[0] == name) || (node.type == :defs && node.children[1] == name)
108
+ end
109
+
110
+ def define_method_call?(call, method_name)
111
+ call.type == :send && call.children[0].nil? && call.children[1] == :define_method &&
112
+ call.children[2]&.type == :sym && call.children[2].children[0] == method_name
113
+ end
114
+
115
+ def find_node(node, &)
116
+ return unless node.is_a?(Parser::AST::Node)
117
+ return node if yield(node)
118
+
119
+ node.children.each do |child|
120
+ found = find_node(child, &)
121
+ return found if found
122
+ end
123
+ nil
124
+ end
125
+
126
+ def normalize(node)
127
+ return node unless node.is_a?(Parser::AST::Node)
128
+ return normalize(node.children[0]) if parenthesised?(node)
129
+ return node.updated(:str, [literal_text(node)]) if literal_dstr?(node)
130
+ return node.updated(nil, [File.expand_path(node.children[0])]) if file_keyword?(node)
131
+
132
+ node.updated(nil, normalized_children(node))
133
+ end
134
+
135
+ # `foo(a, )` -- left behind when all keyword arguments are removed --
136
+ # calls `foo(a)`, so an empty kwargs node is no argument at all.
137
+ def normalized_children(node)
138
+ children = node.children.map { |child| normalize(child) }.reject { |child| empty_kwargs?(child) }
139
+ node.type == :begin ? children.flat_map { |child| statements(child) } : children
140
+ end
141
+
142
+ # Parentheses around one expression carry no meaning once the tree
143
+ # encodes precedence; Mutant::Replacement adds them around operators.
144
+ def parenthesised?(node)
145
+ node.type == :begin && node.children.size == 1
146
+ end
147
+
148
+ def empty_kwargs?(node)
149
+ node.is_a?(Parser::AST::Node) && node.type == :kwargs && node.children.empty?
150
+ end
151
+
152
+ # A statement sequence spliced into another one parses as one flat
153
+ # sequence.
154
+ def statements(node)
155
+ node.is_a?(Parser::AST::Node) && node.type == :begin ? node.children : [node]
156
+ end
157
+
158
+ def file_keyword?(node)
159
+ node.type == :str && node.location&.expression&.source == "__FILE__"
160
+ end
161
+
162
+ # An interpolation-free heredoc parses into a +dstr+ of line segments.
163
+ def literal_dstr?(node)
164
+ node.type == :dstr && node.children.all? { |child| child.type == :str || literal_dstr?(child) }
165
+ end
166
+
167
+ def literal_text(node)
168
+ return node.children[0] if node.type == :str
169
+
170
+ node.children.map { |child| literal_text(child) }.join
171
+ end
172
+ end
173
+ end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+
5
+ module Henitai
6
+ # Runs the suite twice and persists the test files whose outcome differed.
7
+ #
8
+ # Only used when `mutation.flaky_detection` is enabled. Each run records
9
+ # per-file outcomes via the integration's coverage hooks; the files that
10
+ # disagree between the two runs are written to `henitai_flaky_tests.json`.
11
+ class FlakyDetectionBaseline
12
+ # @param timeout [Numeric] seconds each baseline run may take
13
+ def initialize(reports_dir:, timeout: Configuration::DEFAULT_SUITE_TIMEOUT)
14
+ @reports_dir = reports_dir
15
+ @timeout = timeout
16
+ end
17
+
18
+ def run(integration:, test_files:)
19
+ FileUtils.mkdir_p(@reports_dir)
20
+ first, first_result = run_once(integration, test_files)
21
+ second, second_result = run_once(integration, test_files)
22
+ registry = FlakyTestRegistry.from_outcomes(first.outcomes, second.outcomes)
23
+ ensure_usable_suite(registry, [[first, first_result], [second, second_result]])
24
+ registry.write(File.join(@reports_dir, FlakyTestRegistry::FILE_NAME))
25
+ warn_flaky(registry)
26
+ registry
27
+ end
28
+
29
+ private
30
+
31
+ def run_once(integration, test_files)
32
+ outcome_path = TestFileOutcomes.report_path(@reports_dir)
33
+ FileUtils.rm_f(outcome_path)
34
+ result = integration.run_suite(test_files, timeout: @timeout)
35
+ raise CoverageError, "could not record suite outcomes" unless File.exist?(outcome_path)
36
+
37
+ [TestFileOutcomes.load(outcome_path), result]
38
+ end
39
+
40
+ # A failing run is only acceptable as evidence of flakiness: the suite
41
+ # must pass at least once and every file that failed in a failing run must
42
+ # be a flaky file. A run that failed without a file to blame (a load error,
43
+ # a suite-level hook) is never explained.
44
+ def ensure_usable_suite(registry, runs)
45
+ failing = runs.reject { |_outcomes, result| result.survived? }
46
+ return if failing.empty?
47
+ return if failing.size < runs.size && failing.all? { |outcomes, _result| explained?(registry, outcomes) }
48
+
49
+ raise CoverageError, BootstrapErrorMessage.build(failing.first.last, timeout: @timeout)
50
+ end
51
+
52
+ def explained?(registry, outcomes)
53
+ failed = outcomes.failed_files
54
+ !outcomes.unattributed_failures? && !failed.empty? && failed.all? { |file| registry.flaky?(file) }
55
+ end
56
+
57
+ def warn_flaky(registry)
58
+ return if registry.empty?
59
+
60
+ warn("Flaky tests detected (#{registry.all.size}): #{registry.all.join(', ')}")
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Henitai
4
+ # Decides whether a mutant verdict earns another attempt.
5
+ #
6
+ # Survivors are never retried: flakiness can only turn a survivor into a
7
+ # kill, which would inflate the score. A kill is retried only when every test
8
+ # that killed the mutant is a known flaky test, because flakiness can fake a
9
+ # kill but not a survivor. Without a flaky set nothing is retried.
10
+ class FlakyRetryDecision
11
+ def initialize(flaky_tests:, max_retries:)
12
+ @flaky_tests = flaky_tests
13
+ @max_retries = max_retries.to_i
14
+ end
15
+
16
+ def retry?(status:, killing_tests:, attempts:)
17
+ status == :killed &&
18
+ attempts < @max_retries &&
19
+ killing_tests.any? &&
20
+ killing_tests.all? { |file| @flaky_tests.flaky?(file) }
21
+ end
22
+ end
23
+ end