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
@@ -8,7 +8,20 @@ module Henitai
8
8
  module RspecChildRunner
9
9
  private
10
10
 
11
- def run_rspec_runner(test_files)
11
+ def run_rspec_runner(test_files, &after_load)
12
+ log = child_debug_log
13
+ runner = @preloaded_runner || prepare_rspec_runner(test_files)
14
+ return 1 unless ready_to_run?(after_load)
15
+
16
+ run_rspec_specs(runner, example_groups_to_run(test_files))
17
+ rescue SystemExit => e
18
+ log.write("[henitai-debug-child] runner_run_system_exit status=#{e.status.inspect}")
19
+ raise
20
+ ensure
21
+ child_debug_log.write("[henitai-debug-child] runner_run_ensure")
22
+ end
23
+
24
+ def prepare_rspec_runner(test_files)
12
25
  log = child_debug_log
13
26
  log.write("[henitai-debug-child] build_rspec_runner_start")
14
27
  runner = build_rspec_runner
@@ -17,12 +30,35 @@ module Henitai
17
30
  configure_rspec_runner(runner)
18
31
  log.write("[henitai-debug-child] configure_rspec_runner_return")
19
32
  load_rspec_spec_files(test_files)
20
- run_rspec_specs(runner)
21
- rescue SystemExit => e
22
- log.write("[henitai-debug-child] runner_run_system_exit status=#{e.status.inspect}")
23
- raise
24
- ensure
25
- child_debug_log.write("[henitai-debug-child] runner_run_ensure")
33
+ runner
34
+ end
35
+
36
+ # A fork-server process loaded the union of the run's spec files; each
37
+ # mutant process runs only the groups defined in its own files.
38
+ # The groups run in the order of test_files, so the child's fail-fast
39
+ # stops at the file the parent expects to fail first, whatever RSpec's
40
+ # random ordering did to the top-level groups.
41
+ def example_groups_to_run(test_files)
42
+ groups = ::RSpec.world.ordered_example_groups
43
+ groups = filter_to_wanted_files(groups, test_files) if @preloaded_runner
44
+ RspecFileOrder.new(test_files).sort(groups)
45
+ end
46
+
47
+ def filter_to_wanted_files(groups, test_files)
48
+ wanted = test_files.map { |file| File.expand_path(file) }
49
+ groups.select { |group| wanted.include?(RspecFileOrder.file_of(group)) }
50
+ end
51
+
52
+ # The after-load hook (mutant activation) runs only when every spec file
53
+ # loaded; a falsy hook result also skips the run.
54
+ def ready_to_run?(after_load)
55
+ rspec_loaded_cleanly? && (after_load.nil? || after_load.call)
56
+ end
57
+
58
+ # RSpec records a spec file that failed to load and quits before running.
59
+ def rspec_loaded_cleanly?
60
+ world = ::RSpec.world
61
+ !(world.wants_to_quit || world.rspec_is_quitting)
26
62
  end
27
63
 
28
64
  def build_rspec_runner
@@ -51,9 +87,13 @@ module Henitai
51
87
  child_debug_log.write("[henitai-debug-child] load_spec_files_return")
52
88
  end
53
89
 
54
- def run_rspec_specs(runner)
90
+ # One failing example kills the mutant, so the run stops there. Set
91
+ # after the spec files loaded, so a project's own fail_fast setting
92
+ # cannot turn it off.
93
+ def run_rspec_specs(runner, example_groups)
94
+ ::RSpec.configuration.fail_fast = 1
55
95
  child_debug_log.write("[henitai-debug-child] run_specs_start")
56
- result = runner.send(:run_specs, ::RSpec.world.ordered_example_groups)
96
+ result = runner.send(:run_specs, example_groups)
57
97
  child_debug_log.write("[henitai-debug-child] run_specs_return result=#{result.inspect}")
58
98
  result
59
99
  end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Henitai
4
+ module Integration
5
+ # Orders RSpec example groups by the position of their spec file in the
6
+ # list handed to the child. The sort is stable: groups from one file keep
7
+ # RSpec's own order, and groups from files not in the list come last.
8
+ class RspecFileOrder
9
+ # @param group [RSpec::Core::ExampleGroup] a top-level example group
10
+ # @return [String] the group's absolute spec file path
11
+ def self.file_of(group)
12
+ metadata = group.metadata
13
+ metadata[:absolute_file_path] || File.expand_path(metadata[:file_path])
14
+ end
15
+
16
+ # @param test_files [Array<String>] spec files in the order to run them
17
+ def initialize(test_files)
18
+ expanded = test_files.map { |file| File.expand_path(file) }.uniq
19
+ @positions = expanded.each_with_index.to_h
20
+ end
21
+
22
+ # @param groups [Array<RSpec::Core::ExampleGroup>] groups in RSpec's order
23
+ # @return [Array<RSpec::Core::ExampleGroup>] groups sorted by file position
24
+ def sort(groups)
25
+ groups.each_with_index
26
+ .sort_by { |group, index| [position(group), index] }
27
+ .map(&:first)
28
+ end
29
+
30
+ private
31
+
32
+ def position(group)
33
+ @positions.fetch(self.class.file_of(group), @positions.size)
34
+ end
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Henitai
4
+ module Integration
5
+ # Lets the fork server (ADR-15) boot the RSpec environment once. The
6
+ # booted runner stays in the server; every forked mutant process then runs
7
+ # its own subset of the loaded example groups.
8
+ module RspecPreload
9
+ class PreloadError < StandardError; end
10
+
11
+ def fork_server_supported?
12
+ true
13
+ end
14
+
15
+ # Loads RSpec, its configured requires (spec_helper, rails_helper, ...)
16
+ # and the given spec files, without activating a mutant or running a
17
+ # test. Coverage startup is suppressed before anything loads, as it is
18
+ # in every mutant child.
19
+ #
20
+ # @raise [PreloadError] when a spec file failed to load
21
+ def preload_environment(test_files)
22
+ CoverageRuntimeSuppressors.suppress_simplecov!
23
+ CoverageRuntimeSuppressors.suppress_coverage!
24
+ subprocess_env.each { |key, value| ENV[key] = value }
25
+ require "rspec/core"
26
+ ::RSpec.configuration.fail_if_no_examples = true
27
+ runner = prepare_rspec_runner(test_files)
28
+ raise PreloadError, "the spec files failed to load" unless rspec_loaded_cleanly?
29
+
30
+ @preloaded_runner = runner
31
+ nil
32
+ end
33
+ end
34
+ end
35
+ end
@@ -52,20 +52,13 @@ module Henitai
52
52
  end
53
53
 
54
54
  # Captures the PID and log paths for a spawned mutant child process.
55
- ChildHandle = Struct.new(:pid, :log_paths)
55
+ # +timeout+ is set only when the spawner knows better than the scheduler's
56
+ # resolver how long this child may run (a fallback child that boots the
57
+ # suite itself while the fork server is active).
58
+ ChildHandle = Struct.new(:pid, :log_paths, :timeout)
56
59
 
57
60
  # Runs RSpec child and suite processes on behalf of the integration.
58
61
  class RspecProcessRunner
59
- def run_mutant(integration, mutant:, test_files:, timeout:)
60
- handle = integration.spawn_mutant(mutant:, test_files:)
61
- SchedulerDiagnostics.child_started(handle.pid)
62
- wait_result = integration.wait_with_timeout(handle.pid, timeout)
63
- integration.build_result(wait_result, handle.log_paths)
64
- ensure
65
- SchedulerDiagnostics.child_ended(handle&.pid)
66
- finalize_mutant_run(integration, handle&.pid, wait_result)
67
- end
68
-
69
62
  def run_suite(integration, test_files, timeout:)
70
63
  log_paths = integration.scenario_log_paths("baseline")
71
64
  wait_result = nil
@@ -102,15 +95,6 @@ module Henitai
102
95
  end
103
96
  ChildHandle.new(pid:, log_paths:)
104
97
  end
105
-
106
- private
107
-
108
- def finalize_mutant_run(integration, pid, wait_result)
109
- return unless pid
110
-
111
- integration.cleanup_process_group(pid) unless wait_result == :timeout
112
- integration.reap_child(pid) if wait_result.nil?
113
- end
114
98
  end
115
99
  end
116
100
  end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "fileutils"
4
+ require_relative "capped_log_sink"
4
5
 
5
6
  module Henitai
6
7
  module Integration
@@ -12,6 +13,9 @@ module Henitai
12
13
  MAX_LOG_BYTES_ENV = "HENITAI_MAX_LOG_BYTES"
13
14
  DEFAULT_MAX_LOG_BYTES = 5_000_000
14
15
  DRAIN_CHUNK_BYTES = 65_536
16
+ # Bound on the reads of the final drain, so a grandchild that keeps
17
+ # writing cannot hold the close up.
18
+ DRAIN_AVAILABLE_READS = 16
15
19
 
16
20
  def capture_child_output(log_paths)
17
21
  output_files = open_child_output(log_paths)
@@ -69,37 +73,46 @@ module Henitai
69
73
  file = File.new(path, "wb")
70
74
  file.sync = true
71
75
  reader, writer = IO.pipe
72
- thread = Thread.new { drain_capped(reader, file, cap) }
73
- { file:, reader:, writer:, thread: }
74
- end
75
-
76
- def drain_capped(reader, file, cap)
77
- written = 0
78
- truncated = false
76
+ sink = CappedLogSink.new(file, cap)
77
+ stop_reader, stop_writer = IO.pipe
78
+ thread = Thread.new { drain_capped(reader, stop_reader, sink) }
79
+ { file:, reader:, writer:, stop_reader:, stop_writer:, thread: }
80
+ end
81
+
82
+ # Drains until EOF or until +stop_reader+ becomes readable. Never killed:
83
+ # the stop signal ends it cooperatively between sink writes.
84
+ # Uses Kernel#select rather than IO.select: the drain runs beside the
85
+ # tests under mutation, and specs that stub or count IO.select must not
86
+ # see the harness's own waits.
87
+ def drain_capped(reader, stop_reader, sink)
79
88
  loop do
80
- chunk = reader.readpartial(DRAIN_CHUNK_BYTES)
81
- next unless written < cap
82
-
83
- slice = chunk.byteslice(0, cap - written)
84
- file.write(slice)
85
- written += slice.bytesize
86
- next unless written >= cap && !truncated
89
+ ready, = select([reader, stop_reader])
90
+ break drain_available(reader, sink) if ready.include?(stop_reader)
87
91
 
88
- file.write("\n[henitai] output truncated at #{cap} bytes\n")
89
- truncated = true
92
+ sink.write(reader.readpartial(DRAIN_CHUNK_BYTES))
90
93
  end
91
94
  rescue IOError
92
95
  # EOFError (a subclass) on writer close, or a closed pipe: draining done.
93
96
  nil
94
97
  end
95
98
 
99
+ # Closing the writer lets the drain thread reach EOF. A grandchild may
100
+ # still hold a copy of the writer, so EOF is not awaited: the stop pipe
101
+ # makes the thread take what is readable right now and exit.
96
102
  def finish_capped_stream(stream)
97
103
  return unless stream
98
104
 
99
105
  stream[:writer].close
106
+ stream[:stop_writer].close
100
107
  stream[:thread].join
101
- stream[:reader].close
102
- stream[:file].close
108
+ %i[reader stop_reader file].each { |key| stream[key].close }
109
+ end
110
+
111
+ def drain_available(reader, sink)
112
+ DRAIN_AVAILABLE_READS.times { sink.write(reader.read_nonblock(DRAIN_CHUNK_BYTES)) }
113
+ rescue IO::WaitReadable, IOError
114
+ # Nothing more buffered right now, or the pipe is closed.
115
+ nil
103
116
  end
104
117
 
105
118
  def redirect_child_output(output_files)
@@ -6,12 +6,16 @@ require_relative "process_wakeup"
6
6
  require_relative "integration/child_bootstrap"
7
7
  require_relative "integration/rspec_process_runner"
8
8
  require_relative "integration/scenario_log_support"
9
+ require_relative "integration/child_report_store"
9
10
  require_relative "integration/coverage_suppression"
10
11
  require_relative "integration/child_debug_log"
11
12
  require_relative "integration/loaded_features"
12
13
  require_relative "integration/base"
13
14
  require_relative "integration/mutant_run_support"
15
+ require_relative "integration/rspec_file_order"
14
16
  require_relative "integration/rspec_child_runner"
17
+ require_relative "rspec_outcomes"
18
+ require_relative "integration/rspec_preload"
15
19
  require_relative "integration/rspec_test_selection"
16
20
 
17
21
  module Henitai
@@ -50,17 +54,16 @@ module Henitai
50
54
  class Rspec < Base
51
55
  include MutantRunSupport
52
56
  include RspecChildRunner
57
+ include RspecPreload
53
58
  include RspecTestSelection
54
59
 
55
- DEFAULT_SUITE_TIMEOUT = 300.0
56
-
57
60
  def test_files = spec_files
58
61
 
59
62
  def per_test_coverage_supported?
60
63
  true
61
64
  end
62
65
 
63
- def run_suite(test_files, timeout: DEFAULT_SUITE_TIMEOUT)
66
+ def run_suite(test_files, timeout: Configuration::DEFAULT_SUITE_TIMEOUT)
64
67
  RspecProcessRunner.new.run_suite(self, test_files, timeout:)
65
68
  end
66
69
 
@@ -98,7 +101,7 @@ module Henitai
98
101
  File.open(log_paths[:stdout_path], "w") do |stdout_file|
99
102
  File.open(log_paths[:stderr_path], "w") do |stderr_file|
100
103
  Process.spawn(
101
- subprocess_env,
104
+ suite_process_env,
102
105
  *suite_command(test_files),
103
106
  out: stdout_file,
104
107
  err: stderr_file,
@@ -110,14 +113,23 @@ module Henitai
110
113
 
111
114
  private
112
115
 
113
- def run_tests(test_files)
116
+ def outcome_recording_hook(outcomes, after_load)
117
+ lambda do
118
+ RspecOutcomes.register(outcomes, ::RSpec.__send__(:configuration).reporter)
119
+ after_load.nil? || after_load.call
120
+ end
121
+ end
122
+
123
+ # Yields once the spec files are loaded and before they run; a falsy
124
+ # block result skips the run (see MutantRunSupport#run_tests_in_child).
125
+ def run_tests(test_files, outcomes, &after_load)
114
126
  require "rspec/core"
115
127
  ::RSpec.__send__(:configuration).fail_if_no_examples = true
116
128
  log = child_debug_log
117
129
  log.rspec_trace(test_files:, rspec_options: [], rspec_argv: test_files)
118
130
  log.example_count("before_run")
119
131
  log.write("[henitai-debug-child] runner_run_start")
120
- status = run_rspec_runner(test_files)
132
+ status = run_rspec_runner(test_files, &outcome_recording_hook(outcomes, after_load))
121
133
  log.write("[henitai-debug-child] runner_run_return status=#{status.inspect}")
122
134
  log.example_count("after_run")
123
135
  log.rspec_exit(status)
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require "json"
5
+
6
+ module Henitai
7
+ class KillHistory
8
+ # Reads and writes the `henitai_test_order.json` file behind {KillHistory}.
9
+ #
10
+ # Paths are stored relative to Dir.pwd (the project root) when they are
11
+ # inside it and absolute otherwise; they are expanded again on read. A
12
+ # missing, invalid or foreign-version file reads as empty.
13
+ module Store
14
+ VERSION = 1
15
+ Snapshot = Struct.new(:kills, :hangs)
16
+
17
+ module_function
18
+
19
+ # @return [Snapshot] kills (expanded path => count) and hangs (subject =>
20
+ # expanded paths), both empty when the file is unusable
21
+ def read(path)
22
+ data = parse(path)
23
+ return Snapshot.new({}, {}) unless data.is_a?(Hash) && data["version"] == VERSION
24
+
25
+ Snapshot.new(expand_kills(data["kills"]), expand_hangs(data["hangs"]))
26
+ end
27
+
28
+ def write(path, kills:, hangs:)
29
+ FileUtils.mkdir_p(File.dirname(path))
30
+ File.write(path, JSON.pretty_generate(payload(kills, hangs)))
31
+ end
32
+
33
+ def parse(path)
34
+ JSON.parse(File.read(path))
35
+ rescue Errno::ENOENT, JSON::ParserError
36
+ nil
37
+ end
38
+
39
+ def expand_kills(raw)
40
+ return {} unless raw.is_a?(Hash)
41
+
42
+ raw.select { |_file, count| count.is_a?(Integer) }
43
+ .to_h { |file, count| [File.expand_path(file), count] }
44
+ end
45
+
46
+ def expand_hangs(raw)
47
+ return {} unless raw.is_a?(Hash)
48
+
49
+ raw.to_h { |subject, files| [subject, Array(files).map { |file| File.expand_path(file) }] }
50
+ end
51
+
52
+ def payload(kills, hangs)
53
+ {
54
+ "version" => VERSION,
55
+ "kills" => kills.to_h { |file, count| [stored_path(file), count] }.sort.to_h,
56
+ "hangs" => hangs.to_h { |subject, files| [subject, files.map { |file| stored_path(file) }.uniq.sort] }
57
+ .sort.to_h
58
+ }
59
+ end
60
+
61
+ def stored_path(file)
62
+ root = File.join(Dir.pwd, "")
63
+ file.start_with?(root) ? file.delete_prefix(root) : file
64
+ end
65
+ end
66
+ end
67
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "kill_history/store"
4
+
5
+ module Henitai
6
+ # Counts, per test file, the mutants it killed so far in this run, so
7
+ # {TestPrioritizer} can put proven killers first for the mutants still to
8
+ # come. A progress observer behind the {ControlGate}: only final kills
9
+ # count, never one a failed control reclassified.
10
+ #
11
+ # It also remembers which test file was running when a child timed out, per
12
+ # subject: a file that hung for one mutant of a subject is probably the
13
+ # hang for the others, so the prioritizer runs it last.
14
+ #
15
+ # Both are persisted in `henitai_test_order.json` (see {Store}): the next run
16
+ # starts from the loaded kills and hangs. A file that killed in this run
17
+ # gets this run's count saved; other files keep their loaded count.
18
+ class KillHistory
19
+ FILE_NAME = "henitai_test_order.json"
20
+
21
+ # @return [KillHistory] seeded from +path+; empty when the file is missing
22
+ def self.load(path)
23
+ snapshot = Store.read(path)
24
+ new(loaded_kills: snapshot.kills, loaded_hangs: snapshot.hangs)
25
+ end
26
+
27
+ def initialize(loaded_kills: {}, loaded_hangs: {})
28
+ @loaded_kills = loaded_kills
29
+ @run_kills = Hash.new(0)
30
+ @hung = {}
31
+ loaded_hangs.each { |subject, files| files.each { |file| @hung[[subject, file]] = true } }
32
+ end
33
+
34
+ # Saves the kills and hangs to +path+, creating its directory.
35
+ def write(path)
36
+ Store.write(path, kills: @loaded_kills.merge(@run_kills), hangs: hangs_by_subject)
37
+ end
38
+
39
+ def progress(mutant, scenario_result: nil)
40
+ case scenario_result&.status
41
+ when :killed then count_kills(scenario_result)
42
+ when :timeout then remember_hang(mutant, scenario_result)
43
+ end
44
+ end
45
+
46
+ # @return [Integer, Object] kills of +file+ (an expanded path), or
47
+ # +default+ when it killed nothing yet
48
+ def fetch(file, default = nil)
49
+ return default unless @loaded_kills.key?(file) || @run_kills.key?(file)
50
+
51
+ @loaded_kills.fetch(file, 0) + @run_kills.fetch(file, 0)
52
+ end
53
+
54
+ # @return [Boolean] whether +file+ hung for a mutant of the same subject
55
+ def hung?(mutant, file)
56
+ key = subject_key(mutant)
57
+ return false unless key && file
58
+
59
+ @hung.key?([key, File.expand_path(file)])
60
+ end
61
+
62
+ private
63
+
64
+ def count_kills(scenario_result)
65
+ scenario_result.killing_tests.each { |file| @run_kills[file] += 1 }
66
+ end
67
+
68
+ def hangs_by_subject
69
+ @hung.keys.group_by(&:first).transform_values { |pairs| pairs.map(&:last) }
70
+ end
71
+
72
+ def remember_hang(mutant, scenario_result)
73
+ key = subject_key(mutant)
74
+ hanging_test = scenario_result.hanging_test if scenario_result.respond_to?(:hanging_test)
75
+ return unless key && hanging_test
76
+
77
+ @hung[[key, File.expand_path(hanging_test)]] = true
78
+ end
79
+
80
+ def subject_key(mutant)
81
+ subject = mutant.subject if mutant.respond_to?(:subject)
82
+ subject.expression if subject.respond_to?(:expression)
83
+ end
84
+ end
85
+ end
@@ -2,6 +2,8 @@
2
2
 
3
3
  require "minitest"
4
4
  require "henitai/per_test_coverage_collector"
5
+ require "henitai/test_file_outcomes"
6
+ require "henitai/minitest_result_file"
5
7
 
6
8
  module Henitai
7
9
  # Minitest reporter that collects per-test line coverage deltas.
@@ -11,26 +13,40 @@ module Henitai
11
13
  # to PerTestCoverageCollector so the JSON output format is identical to the
12
14
  # RSpec integration.
13
15
  class MinitestCoverageReporter < Minitest::Reporter
14
- def initialize(io = $stdout, options = {})
16
+ def initialize(io = $stdout, options = {}, boot_clock: SuiteBootClock.from_env(ENV))
17
+ super(io, options)
18
+ @collector = PerTestCoverageCollector.new(boot_clock:)
19
+ @outcomes = TestFileOutcomes.new
20
+ end
21
+
22
+ def prerecord(klass, name)
15
23
  super
16
- @collector = PerTestCoverageCollector.new
24
+ @collector.test_started
17
25
  end
18
26
 
19
27
  def record(result)
20
28
  super
21
- @collector.record_test(
22
- relative_to_pwd(result.source_location.first),
23
- duration: result.time
24
- )
29
+ record_coverage(result)
30
+ MinitestResultFile.record(@outcomes, result)
25
31
  end
26
32
 
27
33
  def report
28
34
  super
29
35
  @collector.write_report
36
+ @outcomes.write(TestFileOutcomes.default_report_path)
30
37
  end
31
38
 
32
39
  private
33
40
 
41
+ # A result without a resolvable file is skipped, so its coverage delta is
42
+ # not attributed to the next recorded test.
43
+ def record_coverage(result)
44
+ file = MinitestResultFile.for(result)
45
+ return @collector.skip_test unless file
46
+
47
+ @collector.record_test(relative_to_pwd(file), duration: result.time)
48
+ end
49
+
34
50
  def relative_to_pwd(path)
35
51
  prefix = "#{Dir.pwd}#{File::SEPARATOR}"
36
52
  path.start_with?(prefix) ? path.sub(prefix, "") : path
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Henitai
4
+ # Finds the test file a Minitest result belongs to.
5
+ #
6
+ # `Result#source_location` is where the test method is defined. For tests
7
+ # inherited from a base class or an included module that is a shared file,
8
+ # not the file of the test class that ran, so the file that defines the
9
+ # result's class is used for those. A method defined directly on the class
10
+ # keeps its own file: the class may have been reopened in another test file.
11
+ # The method location is also the fallback for classes that cannot be
12
+ # resolved (anonymous or removed).
13
+ module MinitestResultFile
14
+ module_function
15
+
16
+ # Records the result's outcome; a failure with no usable file is
17
+ # recorded as unattributed rather than dropped.
18
+ def record(outcomes, result)
19
+ failed = !result.passed? && !result.skipped?
20
+ file = self.for(result)
21
+ if file
22
+ outcomes.record(file, failed:)
23
+ elsif failed
24
+ outcomes.record_unattributed_failure
25
+ end
26
+ end
27
+
28
+ # @return [String, nil] the test file, or nil when none can be found
29
+ def for(result)
30
+ return usable(method_file(result)) || usable(class_file(result)) if defined_on_class?(result)
31
+
32
+ usable(class_file(result)) || usable(method_file(result))
33
+ end
34
+
35
+ def defined_on_class?(result)
36
+ klass = Object.const_get(result.klass.to_s)
37
+ klass.instance_method(result.name).owner == klass
38
+ rescue NameError
39
+ false
40
+ end
41
+
42
+ def class_file(result)
43
+ class_file_of(result.klass.to_s)
44
+ end
45
+
46
+ # The file that defines the named class; nil for anonymous or unknown names.
47
+ def class_file_of(name)
48
+ usable(Object.const_source_location(name)&.first)
49
+ rescue NameError
50
+ nil
51
+ end
52
+
53
+ def method_file(result)
54
+ result.source_location&.first
55
+ end
56
+
57
+ # Minitest reports no location for some results and "unknown" for others.
58
+ def usable(file)
59
+ file if file.is_a?(String) && !file.empty? && file != "unknown" && file != "(eval)"
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Henitai
4
+ class Mutant
5
+ # The Ruby source that puts a mutant in place, and how to evaluate it.
6
+ #
7
+ # +mode+ is :toplevel for a real +def+ re-evaluated inside the original
8
+ # module and class openers (ADR-13), evaluated at the top level with
9
+ # +file+ and +line+ so +__FILE__+, +__LINE__+ and backtraces stay those of
10
+ # the original source; +def_offset+ is the index of the +def+ line within
11
+ # +source+. +mode+ is :class_eval for the +define_method+ fallback,
12
+ # evaluated inside the target module.
13
+ #
14
+ # For :toplevel, +lexical_scope+ holds the opener lines (e.g. "module A",
15
+ # "class B"), +owner+ the expression the +def+ is defined on ("self" or
16
+ # the receiver of +def Other.name+), and +singleton+ whether it is a
17
+ # +defs+. They let a replayed recipe reopen the scope without the AST.
18
+ Activation = Struct.new(:source, :mode, :file, :line, :def_offset, :lexical_scope, :owner, :singleton,
19
+ keyword_init: true) do
20
+ def self.from_h(hash)
21
+ new(source: hash.fetch("source"), mode: hash.fetch("mode").to_sym, file: hash["file"],
22
+ line: hash["line"], def_offset: hash["defOffset"], lexical_scope: hash["lexicalScope"],
23
+ owner: hash["owner"], singleton: hash["singleton"])
24
+ end
25
+
26
+ def to_h
27
+ { "source" => source, "mode" => mode.to_s, "file" => file, "line" => line, "defOffset" => def_offset,
28
+ "lexicalScope" => lexical_scope, "owner" => owner, "singleton" => singleton }
29
+ end
30
+ end
31
+ end
32
+ end