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,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "henitai/test_file_outcomes"
4
+
5
+ module Henitai
6
+ # Records the outcome of each finished RSpec example per spec file.
7
+ #
8
+ # Failures outside an example produce no failed example. A hook error in
9
+ # `before(:context)` fails the group's examples, so it is attributed
10
+ # already; an `after(:context)` error is announced as a message while its
11
+ # group is open and is attributed to that group's file. Everything else
12
+ # counted by `errors_outside_of_examples_count` (a spec file that fails to
13
+ # load, `before(:suite)`) has no file and is recorded as unattributed.
14
+ module RspecOutcomes
15
+ EVENTS = %i[example_finished example_group_started example_group_finished message dump_summary].freeze
16
+ HOOK_ERROR = "An error occurred in "
17
+
18
+ # RSpec drops finished examples from its groups after a run, so
19
+ # outcomes are collected as the reporter announces them.
20
+ class Listener
21
+ def initialize(outcomes)
22
+ @outcomes = outcomes
23
+ @open_group_files = []
24
+ @attributed_errors = 0
25
+ end
26
+
27
+ def example_finished(notification)
28
+ RspecOutcomes.record(@outcomes, notification.example)
29
+ end
30
+
31
+ def example_group_started(notification)
32
+ file = RspecOutcomes.group_file(notification.group)
33
+ @open_group_files.push(file)
34
+ @outcomes.started(file) if file
35
+ end
36
+
37
+ def example_group_finished(_notification)
38
+ @open_group_files.pop
39
+ end
40
+
41
+ def message(notification)
42
+ file = @open_group_files.last
43
+ return unless file && notification.message.strip.start_with?(HOOK_ERROR)
44
+
45
+ @outcomes.record(file, failed: true)
46
+ @attributed_errors += 1
47
+ end
48
+
49
+ def dump_summary(summary)
50
+ return unless summary.errors_outside_of_examples_count > @attributed_errors
51
+
52
+ @outcomes.record_unattributed_failure
53
+ end
54
+ end
55
+
56
+ module_function
57
+
58
+ def register(outcomes, reporter)
59
+ reporter.register_listener(Listener.new(outcomes), *EVENTS)
60
+ end
61
+
62
+ def group_file(group)
63
+ metadata = group.metadata
64
+ metadata[:absolute_file_path] || metadata[:file_path]
65
+ end
66
+
67
+ def record(outcomes, example)
68
+ status = example.execution_result.status
69
+ return if status.nil?
70
+
71
+ outcomes.record(example.metadata[:file_path], failed: status == :failed)
72
+ end
73
+ end
74
+ end
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "securerandom"
4
+
3
5
  module Henitai
4
6
  # Orchestrates the full mutation testing pipeline.
5
7
  #
@@ -11,16 +13,20 @@ module Henitai
11
13
  #
12
14
  # Gate 2 — Mutant generation
13
15
  # Apply operators to each Subject's AST. Filter arid (non-productive)
14
- # nodes via ignore_patterns. Produces the initial mutant list.
16
+ # nodes from the built-in catalog. Produces the initial mutant list.
15
17
  #
16
18
  # Gate 3 — Static filtering
17
- # Remove ignored mutants (pattern matches), compile-time errors.
19
+ # Mark mutants whose original start line matches an ignore_patterns
20
+ # entry as :ignored, and remove compile-time errors.
18
21
  # Apply per-test coverage data: mark :no_coverage for uncovered mutants.
19
22
  #
20
23
  # Gate 4 — Mutant execution
21
24
  # Run surviving mutants in isolated child processes (fork isolation).
22
- # Each child process loads the test suite with the mutated method
23
- # injected via Module#define_method. Collect kill/survive/timeout results.
25
+ # Each child process loads the test suite, then re-evaluates the
26
+ # subject's own `def` with the mutation spliced in, inside its original
27
+ # module/class openers (ADR-13). Module#define_method is only the fallback
28
+ # for subjects that cannot be reopened by name. Collect kill/survive/
29
+ # timeout results.
24
30
  #
25
31
  # Gate 5 — Reporting
26
32
  # Write results to configured reporters (terminal, html, json, dashboard).
@@ -29,7 +35,8 @@ module Henitai
29
35
  attr_reader :config, :result
30
36
 
31
37
  # @param mode [Hash] execution-mode flags: +dry_run:+ stops before Gate 4,
32
- # +incremental:+ reuses still-valid Killed verdicts from history.
38
+ # +incremental:+ reuses still-valid Killed verdicts from history,
39
+ # +force:+ disables the verdict reuse that survivor reruns apply.
33
40
  # +deps+ is assigned in the body, not defaulted in the signature: the
34
41
  # default needs @config, and `config:` itself defaults to a load.
35
42
  #
@@ -45,6 +52,7 @@ module Henitai
45
52
  @survivors_from = survivors_from
46
53
  @dry_run = mode.fetch(:dry_run, false)
47
54
  @incremental = mode.fetch(:incremental, false)
55
+ @force = mode.fetch(:force, false)
48
56
  end
49
57
 
50
58
  # Entry point — runs the full pipeline and returns a Result.
@@ -76,9 +84,14 @@ module Henitai
76
84
  # static/skip/arid/stillborn filtering — everything short of execution.
77
85
  def pipeline_mutants
78
86
  if survivor_rerun? && (fast_mutants = survivor_strategy.try_recipe_run)
87
+ @recipe_run = true
88
+ # Gate 0 still runs: test selection reads the per-test map, which must
89
+ # include new or edited tests.
90
+ bootstrap_coverage(fast_mutants.filter_map { |mutant| mutant.subject.source_file }.uniq)
79
91
  return fast_mutants
80
92
  end
81
93
 
94
+ capture_provenance unless @dry_run
82
95
  source_files = self.source_files
83
96
  subjects = resolve_subjects(source_files)
84
97
  mutants_for(subjects, source_files)
@@ -104,8 +117,9 @@ module Henitai
104
117
  )
105
118
  end
106
119
 
120
+ # A survivor rerun must see every prior survivor, so it never samples.
107
121
  def generate_mutants(subjects)
108
- mutant_generator.generate(subjects, operators, config:)
122
+ mutant_generator.generate(subjects, operators, config:, sample: !survivor_rerun?)
109
123
  end
110
124
 
111
125
  def filter_mutants(mutants)
@@ -116,23 +130,31 @@ module Henitai
116
130
  bootstrap_thread = bootstrap_mutants(source_files)
117
131
  mutants = generate_mutants(subjects)
118
132
  bootstrap_thread.value
119
- filtered = apply_incremental_filter(filter_mutants(mutants))
120
- return filtered unless survivor_rerun?
133
+ filtered = filter_mutants(mutants)
134
+ return apply_incremental_filter(filtered) unless survivor_rerun?
121
135
 
122
- survivor_strategy.apply_selection(filtered)
136
+ survivor_strategy.apply_selection(filtered, reuse_filter: @force ? nil : reuse_filter)
123
137
  end
124
138
 
125
- # Opt-in verdict reuse (`--incremental`): still-valid Killed and Survived
126
- # verdicts from the history store are marked with their stored status +
127
- # from_cache before execution. The filter is only ever constructed when
128
- # the flag is set; it runs after the coverage bootstrap join in
129
- # mutants_for, so the live per-test map it reads is never mid-write.
139
+ # Verdict reuse (opt-in `--incremental`; always for `--survivors-from`
140
+ # reruns, where it runs on the selected survivors): still-valid Killed and
141
+ # Survived verdicts from the history store are marked with their stored
142
+ # status + from_cache before execution. It runs after the coverage
143
+ # bootstrap join in mutants_for, so the live per-test map it reads is never
144
+ # mid-write.
130
145
  def apply_incremental_filter(mutants)
131
146
  return mutants unless @incremental
132
147
 
133
- IncrementalFilter.new(history_store:, per_test_coverage:,
134
- dependency_fingerprint: VerdictFingerprint.dependency_fingerprint)
135
- .apply(mutants)
148
+ reuse_filter.apply(mutants)
149
+ end
150
+
151
+ def reuse_filter = deps.reuse_filter
152
+
153
+ # Before Gate 1 parses anything: what the run may parse, load or execute
154
+ # (ADR-19). Dry runs record nothing, and the recipe fast path's stubs are
155
+ # never cacheable, so neither captures.
156
+ def capture_provenance
157
+ deps.capture_provenance(source_files + Array(integration.test_files))
136
158
  end
137
159
 
138
160
  def bootstrap_mutants(source_files) = Thread.new { bootstrap_coverage(source_files) }
@@ -144,20 +166,50 @@ module Henitai
144
166
  config,
145
167
  progress_reporter: progress_reporter
146
168
  )
169
+ rescue SignalException
170
+ save_interrupted_progress
171
+ raise
172
+ end
173
+
174
+ # The engine has torn its children down by now. Whatever the observers
175
+ # still buffer is written, so `--incremental` can resume (ADR-19); the
176
+ # aborted run itself gets no history record.
177
+ def save_interrupted_progress
178
+ flush_progress
179
+ saved = history_checkpointer&.committed || 0
180
+ warn "henitai: interrupted; #{saved} verdicts saved, resume with --incremental"
181
+ end
182
+
183
+ def flush_progress
184
+ reporter = progress_reporter
185
+ reporter.flush if reporter.respond_to?(:flush)
186
+ rescue StandardError => e
187
+ warn "henitai: could not flush progress (#{e.class}: #{e.message})"
147
188
  end
148
189
 
149
190
  def report(result)
150
191
  Reporter.run_all(names: config.reporters, result:, config:, history_store:)
151
192
  end
152
193
 
194
+ # History is an auxiliary trend artifact: a corrupt or locked database
195
+ # must not discard the run's verdicts, so the reports are still written.
153
196
  def persist_history(result, recorded_at)
154
197
  history_store.record(
155
198
  result,
156
199
  version: Henitai::VERSION,
157
- recorded_at:
200
+ recorded_at:,
201
+ operators: config.operators,
202
+ full_scan: full_mutant_set?,
203
+ run_id:
158
204
  )
205
+ rescue StandardError => e
206
+ warn "henitai: could not record mutation history (#{e.class}: #{e.message}); reports are still written"
159
207
  end
160
208
 
209
+ # A sampled run generates a fraction of each subject's mutants, so it
210
+ # cannot stand as evidence that the ones it omitted no longer exist.
211
+ def full_mutant_set? = config.respond_to?(:sampling) && config.sampling.to_h[:ratio].nil?
212
+
161
213
  def build_result(mutants, started_at, finished_at)
162
214
  @result = build_result_object(mutants, started_at, finished_at)
163
215
  persist_history(@result, finished_at)
@@ -177,10 +229,33 @@ module Henitai
177
229
  git_sha: safe_head_sha,
178
230
  source_provider: source_provider,
179
231
  authoritative: full_run?,
180
- since: @since
232
+ since: @since,
233
+ complete_files: complete_files,
234
+ sampling: result_sampling
181
235
  )
182
236
  end
183
237
 
238
+ # Files whose every subject this run mutated: no subject patterns and no
239
+ # survivor rerun (a --since run still selects whole changed files).
240
+ def complete_files
241
+ return [] if Array(@subjects).any? || survivor_rerun?
242
+
243
+ source_files
244
+ end
245
+
246
+ # Records the sampling that actually shaped the mutant set, with the
247
+ # default seed filled in so the report is reproducible on its own.
248
+ def result_sampling
249
+ sampling = optional_config(:sampling)
250
+ return nil if survivor_rerun? || !(sampling && sampling[:ratio])
251
+
252
+ {
253
+ strategy: (sampling[:strategy] || "stratified").to_s,
254
+ ratio: sampling[:ratio],
255
+ seed: sampling[:seed] || SamplingStrategy::DEFAULT_SEED
256
+ }
257
+ end
258
+
184
259
  def safe_head_sha
185
260
  git_diff_analyzer.head_sha
186
261
  rescue StandardError
@@ -205,9 +280,25 @@ module Henitai
205
280
  def operators = deps.operators
206
281
  def history_store = deps.history_store
207
282
  def per_test_coverage = deps.per_test_coverage
283
+ def source_selection_coverage = deps.source_selection_coverage
208
284
  def source_provider = deps.source_provider
209
285
 
210
- def progress_reporter = deps.progress_reporter(full_run: full_run?)
286
+ # Built once per run, so an interrupt flushes the observers the engine
287
+ # was given.
288
+ def progress_reporter
289
+ return @progress_reporter if defined?(@progress_reporter)
290
+
291
+ @progress_reporter = deps.progress_reporter(full_run: full_run?, history_checkpointer:)
292
+ end
293
+
294
+ # Recipe stubs are never cacheable, so the fast path checkpoints nothing.
295
+ def history_checkpointer
296
+ return @history_checkpointer if defined?(@history_checkpointer)
297
+
298
+ @history_checkpointer = @recipe_run ? nil : deps.history_checkpointer(run_id:)
299
+ end
300
+
301
+ def run_id = @run_id ||= SecureRandom.uuid
211
302
 
212
303
  def source_files
213
304
  @source_files ||= source_file_selection.call
@@ -216,7 +307,7 @@ module Henitai
216
307
  def source_file_selection
217
308
  @source_file_selection ||= SourceFileSelection.new(
218
309
  config: config, since: @since,
219
- git_diff_analyzer: git_diff_analyzer, per_test_coverage: per_test_coverage
310
+ git_diff_analyzer: git_diff_analyzer, per_test_coverage: source_selection_coverage
220
311
  )
221
312
  end
222
313
 
@@ -12,6 +12,10 @@ module Henitai
12
12
  # {#per_test_coverage} and {#history_store}: the incremental filter proves
13
13
  # survivor reuse against the same live coverage map the history store records
14
14
  # its intersection set from. Two instances would be two snapshots.
15
+ #
16
+ # {#source_selection_coverage} is deliberately a *different* instance: Gate 1
17
+ # reads the map as it was before this run's coverage bootstrap rewrote it, and
18
+ # a shared instance would memoize that stale snapshot for the reuse decisions.
15
19
  class RunnerDependencies
16
20
  def initialize(config:)
17
21
  @config = config
@@ -36,10 +40,38 @@ module Henitai
36
40
  @per_test_coverage ||= PerTestCoverage.new(reports_dir: @config.reports_dir)
37
41
  end
38
42
 
43
+ def source_selection_coverage
44
+ @source_selection_coverage ||= PerTestCoverage.new(reports_dir: @config.reports_dir)
45
+ end
46
+
39
47
  def history_store
40
48
  @history_store ||= MutantHistoryStore.new(
41
49
  path: File.join(@config.reports_dir, Henitai::HISTORY_STORE_FILENAME),
42
- per_test_coverage: per_test_coverage
50
+ per_test_coverage: per_test_coverage,
51
+ reuse_context: reuse_context,
52
+ provenance: execution_provenance
53
+ )
54
+ end
55
+
56
+ # Records the run's inputs; {Runner} calls it before Gate 1 parses
57
+ # anything (ADR-19). @return [ExecutionProvenance]
58
+ def capture_provenance(paths)
59
+ @execution_provenance = ExecutionProvenance.capture(paths)
60
+ end
61
+
62
+ # Until the capture, nothing counts as intact: a store built too early
63
+ # caches nothing rather than vouch for unrecorded inputs.
64
+ def execution_provenance = @execution_provenance || ExecutionProvenance::UNCAPTURED
65
+
66
+ # Shared by the incremental filter and the history store: verdicts are
67
+ # recorded under exactly the context they are later checked against.
68
+ def reuse_context
69
+ @reuse_context ||= ReuseContext.new(config: @config)
70
+ end
71
+
72
+ def reuse_filter
73
+ IncrementalFilter.new(
74
+ history_store: history_store, per_test_coverage: per_test_coverage, reuse_context: reuse_context
43
75
  )
44
76
  end
45
77
 
@@ -50,8 +82,17 @@ module Henitai
50
82
  # Deliberately *not* memoized: `full_run?` is a property of the invocation,
51
83
  # not of the dependency set, and a cached reporter would silently keep the
52
84
  # first answer.
53
- def progress_reporter(full_run:)
54
- CompositeProgressReporter.for(config: @config, source_provider: source_provider, full_run: full_run)
85
+ def progress_reporter(full_run:, history_checkpointer: nil)
86
+ CompositeProgressReporter.for(config: @config, source_provider: source_provider, full_run: full_run,
87
+ history_checkpointer:)
88
+ end
89
+
90
+ # Checkpoints verdicts into the history store during the run (ADR-19);
91
+ # nil when `reports.checkpoint` is off.
92
+ def history_checkpointer(run_id:)
93
+ return unless @config.respond_to?(:checkpoint_enabled) && @config.checkpoint_enabled
94
+
95
+ HistoryCheckpointer.new(history_store:, config: @config, run_id:)
55
96
  end
56
97
 
57
98
  # Reads each source file once and caches it per path, so Result consumes
@@ -1,14 +1,24 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "digest"
3
4
  module Henitai
4
- # Samples mutants in a strategy-aware, deterministic way.
5
+ # Samples mutants deterministically, stratified by operator within each subject.
6
+ #
7
+ # Per subject, the sample size is ceil(size * ratio), at least one and at most
8
+ # size. Mutants are grouped into strata by operator. Each stratum is ordered by
9
+ # a seeded SHA256 key derived from the mutant's stable id, so a mutant's rank
10
+ # does not depend on other mutants. Strata are then visited round-robin, which
11
+ # spreads the sample across operators and positions. Kept mutants are returned
12
+ # in their input order.
5
13
  class SamplingStrategy
6
- def sample(mutants, ratio:, strategy: :stratified)
14
+ DEFAULT_SEED = 0
15
+
16
+ def sample(mutants, ratio:, strategy: :stratified, seed: DEFAULT_SEED)
7
17
  strategy = strategy.to_sym if strategy.respond_to?(:to_sym)
8
18
 
9
19
  case strategy
10
20
  when :stratified
11
- stratified_sample(Array(mutants), ratio:)
21
+ stratified_sample(Array(mutants), ratio:, seed:)
12
22
  else
13
23
  raise ArgumentError, "Unsupported sampling strategy: #{strategy}"
14
24
  end
@@ -16,12 +26,32 @@ module Henitai
16
26
 
17
27
  private
18
28
 
19
- def stratified_sample(mutants, ratio:)
29
+ def stratified_sample(mutants, ratio:, seed:)
20
30
  return [] if ratio.to_f <= 0.0
21
31
 
22
- mutants.group_by { |mutant| mutant.subject.expression }.flat_map do |_subject, group|
23
- group.take(sample_count(group.size, ratio))
32
+ kept = Set.new.compare_by_identity
33
+ mutants.group_by { |mutant| mutant.subject.expression }.each_value do |group|
34
+ select_within_subject(group, ratio:, seed:).each { |mutant| kept << mutant }
24
35
  end
36
+ mutants.select { |mutant| kept.include?(mutant) }
37
+ end
38
+
39
+ def select_within_subject(group, ratio:, seed:)
40
+ strata = group.group_by { |mutant| mutant.operator.to_s }.sort.map do |_operator, members|
41
+ members.sort_by { |mutant| sort_key(mutant, seed) }
42
+ end
43
+
44
+ round_robin(strata, sample_count(group.size, ratio))
45
+ end
46
+
47
+ def round_robin(strata, count)
48
+ depth = strata.map(&:size).max || 0
49
+
50
+ (0...depth).flat_map { |index| strata.filter_map { |stratum| stratum[index] } }.first(count)
51
+ end
52
+
53
+ def sort_key(mutant, seed)
54
+ Digest::SHA256.hexdigest("#{seed}\0#{mutant.stable_id}")
25
55
  end
26
56
 
27
57
  def sample_count(size, ratio)
@@ -3,7 +3,7 @@
3
3
  module Henitai
4
4
  # Captures the result of one baseline or mutant test run.
5
5
  class ScenarioExecutionResult
6
- attr_reader :status, :stdout, :stderr, :exit_status, :log_path
6
+ attr_reader :status, :status_reason, :stdout, :stderr, :exit_status, :log_path, :killing_tests, :hanging_test
7
7
 
8
8
  def self.build(wait_result:, stdout:, stderr:, log_path:)
9
9
  new(
@@ -15,12 +15,50 @@ module Henitai
15
15
  )
16
16
  end
17
17
 
18
- def initialize(status:, stdout:, stderr:, log_path:, exit_status: nil)
18
+ # Copies the reason behind a harness status onto the mutant the result was
19
+ # produced for. Tolerates results and mutants that carry no reason.
20
+ def self.copy_reason(result, mutant)
21
+ return unless result.respond_to?(:status_reason) && mutant.respond_to?(:status_reason=)
22
+
23
+ mutant.status_reason = result.status_reason
24
+ end
25
+
26
+ # The verdict of a child that could not be spawned at all.
27
+ def self.spawn_failure(error)
28
+ new(status: :compile_error, stdout: "", stderr: "spawn failed: #{error.message}", log_path: "/dev/null")
29
+ end
30
+
31
+ # Classifies a mutant run from the child's report (see MutantVerdict).
32
+ # +running_test+ is the test file the child was executing when it was
33
+ # killed; it is kept only for a timeout (see #hanging_test).
34
+ # rubocop:disable Metrics/ParameterLists -- one keyword per captured field
35
+ def self.build_for_mutant(wait_result:, report:, stdout:, stderr:, log_path:, running_test: nil)
36
+ # rubocop:enable Metrics/ParameterLists
37
+ verdict = MutantVerdict.new(wait_result:, report:, stdout:, stderr:)
38
+ status, status_reason = verdict.to_a
39
+ new(status:, status_reason:, stdout:, stderr:, log_path:, exit_status: exit_status_for(wait_result),
40
+ killing_tests: verdict.killing_tests, hanging_test: hanging_test_for(status, running_test))
41
+ end
42
+
43
+ # rubocop:disable Metrics/ParameterLists -- one keyword per captured field
44
+ def initialize(status:, stdout:, stderr:, log_path:, exit_status: nil, status_reason: nil, killing_tests: [],
45
+ hanging_test: nil)
46
+ # rubocop:enable Metrics/ParameterLists
19
47
  @status = status
48
+ @status_reason = status_reason
20
49
  @stdout = stdout.to_s
21
50
  @stderr = stderr.to_s
22
51
  @log_path = log_path
23
52
  @exit_status = exit_status
53
+ @killing_tests = killing_tests
54
+ @hanging_test = hanging_test
55
+ end
56
+
57
+ # The same run under a different verdict, e.g. a detection a failing
58
+ # control reclassified (ADR-14). Output and exit data are kept.
59
+ def reclassified(status:, status_reason:)
60
+ self.class.new(status:, status_reason:, stdout:, stderr:, log_path:, exit_status:, killing_tests:,
61
+ hanging_test:)
24
62
  end
25
63
 
26
64
  # Frees the captured child output once it has been consumed (e.g. by the
@@ -89,6 +127,11 @@ module Henitai
89
127
  class << self
90
128
  private
91
129
 
130
+ # The test file a timed-out child was running; nil for any other verdict.
131
+ def hanging_test_for(status, running_test)
132
+ status == :timeout ? running_test : nil
133
+ end
134
+
92
135
  def status_for(wait_result, stdout:, stderr:)
93
136
  return :timeout if wait_result == :timeout
94
137
  return :compile_error if no_examples_found?(stdout, stderr)
@@ -107,14 +150,17 @@ module Henitai
107
150
  end
108
151
 
109
152
  def no_examples_found?(stdout, stderr)
110
- stdout.to_s.include?("No examples found.") || stderr.to_s.include?("No examples found.")
153
+ output = [stdout.to_s, stderr.to_s].join("\n")
154
+ return false unless ExampleSummary::NO_EXAMPLES_FOUND.match?(output)
155
+
156
+ last_summary = output.scan(ExampleSummary::SUMMARY).last
157
+ last_summary.nil? || last_summary == ["0"]
111
158
  end
112
159
 
113
160
  def zero_examples_failure?(wait_result, stdout, stderr)
114
161
  return false unless exit_status_for(wait_result) == 1
115
162
 
116
- output = [stdout.to_s, stderr.to_s].join("\n")
117
- output.include?("0 examples, 0 failures")
163
+ ExampleSummary.none_ran?([stdout.to_s, stderr.to_s].join("\n"))
118
164
  end
119
165
  end
120
166
 
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Henitai
4
+ # Holds INT, TERM and HUP back while a block runs, then re-sends the first
5
+ # one that arrived (ADR-19). A history write therefore commits or rolls
6
+ # back as a whole before the signal takes effect.
7
+ #
8
+ # `Thread.handle_interrupt` cannot do this: it does not defer the
9
+ # `Interrupt` Ruby raises for a signal on the main thread.
10
+ module SignalDeferral
11
+ SIGNALS = %w[INT TERM HUP].freeze
12
+ RESEND = ->(signal) { Process.kill(signal, Process.pid) }
13
+
14
+ module_function
15
+
16
+ def call(resend: RESEND)
17
+ pending = nil
18
+ saved = SIGNALS.to_h { |signal| [signal, Signal.trap(signal) { pending ||= signal }] }
19
+ yield
20
+ ensure
21
+ saved&.each { |signal, handler| Signal.trap(signal, handler) }
22
+ resend.call(pending) if pending
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Henitai
4
+ # Whether a mutant sits on its subject's def (signature) line. Line coverage
5
+ # credits that line only to the test that loaded the file, so the tests that
6
+ # exercise it are not knowable from the per-test map alone.
7
+ module SignatureLine
8
+ module_function
9
+
10
+ # A subject without a source range (a recipe stub) has an unknown def
11
+ # line, so it is treated as one: that only widens test selection and
12
+ # blocks verdict reuse.
13
+ def on?(mutant)
14
+ subject = mutant.respond_to?(:subject) ? mutant.subject : nil
15
+ return false unless subject.respond_to?(:source_range)
16
+
17
+ range = subject.source_range
18
+ range.nil? || range.begin == mutant.location[:start_line]
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Henitai
4
+ class SlotScheduler
5
+ # Control jobs (ADR-19 §2): the unmutated method of a group whose first
6
+ # detection a {ControlGate} is holding. A control job is not a mutant job:
7
+ #
8
+ # - it is spawned ahead of pending mutants, with its group's test files
9
+ # (no reselection);
10
+ # - it runs as a local child (`spawn_local` when the integration is the
11
+ # fork-server runner, which registers the pid with the server runtime
12
+ # and applies a boot-inclusive timeout); the server never saw it;
13
+ # - it is never retried, and it is neither a result nor progress;
14
+ # - every terminal outcome -- exit, timeout, spawn failure -- reaches the
15
+ # listener once. A control interrupted by shutdown reports nothing: the
16
+ # gate's held detections are dropped with the run.
17
+ #
18
+ # Mixed into {SlotScheduler}; relies on its slot table and spawn helpers.
19
+ module ControlSlots
20
+ ControlJob = Struct.new(:key, :mutant, :test_files)
21
+
22
+ def enqueue_control(key, mutant, test_files)
23
+ control_jobs << ControlJob.new(key, mutant, test_files)
24
+ end
25
+
26
+ private
27
+
28
+ def control_jobs = @control_jobs ||= []
29
+
30
+ def spawn_control_into_slot(job)
31
+ worker_index = slot_table.next_free_worker_index(worker_count)
32
+ with_worker_slot(worker_index) do
33
+ handle = spawn_control_child(job)
34
+ timeout = handle.timeout || slot_timeout(job.mutant, job.test_files)
35
+ register_slot(handle, job.mutant, worker_index, timeout, control_key: job.key)
36
+ end
37
+ rescue StandardError => e
38
+ report_control(job.key, ScenarioExecutionResult.spawn_failure(e))
39
+ end
40
+
41
+ def spawn_control_child(job)
42
+ spawner = integration.respond_to?(:spawn_local) ? :spawn_local : :spawn_mutant
43
+ integration.public_send(spawner, mutant: job.mutant, test_files: job.test_files)
44
+ end
45
+
46
+ def complete_control(slot, wait_result)
47
+ slot_table.delete(slot.slot_id)
48
+ report_control(slot.control_key, integration.build_result(wait_result, slot.log_paths))
49
+ end
50
+
51
+ # The gate keeps only the control's verdict, never its output.
52
+ def report_control(key, result)
53
+ @control_listener&.control_finished(key, result)
54
+ result.release_output! if result.respond_to?(:release_output!)
55
+ end
56
+ end
57
+ end
58
+ end