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
@@ -6,7 +6,7 @@ require_relative "source_parser"
6
6
  module Henitai
7
7
  # Traverses a subject's AST and asks operators to build mutants.
8
8
  class MutantGenerator
9
- def generate(subjects, operators, config: nil)
9
+ def generate(subjects, operators, config: nil, sample: true)
10
10
  normalized_operators = normalize_operators(operators)
11
11
  arid_node_filter = AridNodeFilter.new
12
12
  syntax_validator = SyntaxValidator.new
@@ -22,7 +22,12 @@ module Henitai
22
22
  )
23
23
  end
24
24
 
25
- sample_mutants(mutants, config:, sampling_strategy:)
25
+ # Deduplicate programs before sampling: unsampled generation (survivor reruns) must keep the same
26
+ # representative of a duplicate program as a sampled run, or a reported survivor's stable id would
27
+ # not be found again. Sampling is stratified by operator within each subject, using a seeded
28
+ # per-mutant order, and returns kept mutants in input order.
29
+ unique = distinct_programs(distinct_identities(mutants))
30
+ sample ? sample_mutants(unique, config:, sampling_strategy:) : unique
26
31
  end
27
32
 
28
33
  private
@@ -71,14 +76,12 @@ module Henitai
71
76
  def walk(node, parent: nil)
72
77
  return unless node.is_a?(Parser::AST::Node)
73
78
 
74
- # Str children of a non-heredoc dstr are raw text segments embedded
75
- # inside a quoted interpolated string. They have no surrounding quotes
76
- # in the source, so replacing them via source-fragment substitution
77
- # would insert a quoted literal into the raw-text position and produce
78
- # a SyntaxError when the mutant is activated.
79
- # Heredoc dstr children are exempt: the heredoc body is plain text, so
80
- # inserting "" there stays valid Ruby.
81
- return if embedded_non_heredoc_dstr_str?(node, parent)
79
+ # A str node inside an interpolated string, heredoc, symbol, command,
80
+ # regexp or word array is raw text without quotes of its own.
81
+ # Replacing it would insert a quoted literal into the text -- a
82
+ # different mutation than reported, or a SyntaxError -- so it is not
83
+ # a StringLiteral site; its container is mutated instead.
84
+ return if raw_text_segment?(node, parent) || shorthand_value?(node, parent)
82
85
 
83
86
  apply_operators(node) if node_within_subject_range?(node)
84
87
  node.children.each do |child|
@@ -86,18 +89,29 @@ module Henitai
86
89
  end
87
90
  end
88
91
 
89
- def embedded_non_heredoc_dstr_str?(node, parent)
90
- node.type == :str &&
91
- parent&.type == :dstr &&
92
- !heredoc_node?(parent)
92
+ RAW_TEXT_CONTAINERS = %i[dstr dsym xstr regexp].freeze
93
+ private_constant :RAW_TEXT_CONTAINERS
94
+
95
+ def raw_text_segment?(node, parent)
96
+ return false unless node.type == :str && parent
97
+
98
+ RAW_TEXT_CONTAINERS.include?(parent.type) || word_array?(parent)
93
99
  end
94
100
 
95
- def heredoc_node?(node)
96
- node.location.respond_to?(:heredoc_body) && node.location.heredoc_body
101
+ # The value of +build(config:)+ is an implicit call that shares its
102
+ # source range with the key; replacing it would rewrite the key.
103
+ def shorthand_value?(node, parent)
104
+ return false unless parent&.type == :pair && node.equal?(parent.children[1])
105
+
106
+ node.location.expression == parent.children[0].location.expression
107
+ end
108
+
109
+ def word_array?(node)
110
+ node.type == :array && node.location.begin&.source.to_s.start_with?("%")
97
111
  end
98
112
 
99
113
  def apply_operators(node)
100
- return if @arid_node_filter.suppressed?(node, @config)
114
+ return if @arid_node_filter.suppressed?(node)
101
115
 
102
116
  @operators_by_node_type[node.type].each do |operator|
103
117
  operator.mutate(node, subject: @subject).each do |mutant|
@@ -132,6 +146,35 @@ module Henitai
132
146
  end
133
147
  end
134
148
 
149
+ # Mutants sharing an identity are told apart by where their original node
150
+ # ends; those that also end at the same place are the same mutation
151
+ # twice, and only the first is kept.
152
+ def distinct_identities(mutants)
153
+ mutants.group_by { |mutant| MutantIdentity.stable_id(mutant) }.each_value do |group|
154
+ group.each { |mutant| mutant.identity_discriminator = node_end(mutant) } if group.size > 1
155
+ end
156
+ mutants.uniq { |mutant| MutantIdentity.stable_id(mutant) }
157
+ end
158
+
159
+ # Different operators can produce the same program -- BooleanLiteral's
160
+ # `return false` for `return true if x` is also ReturnValue's. Running it
161
+ # twice would count one result twice; the first mutant is kept. Mutants
162
+ # without a computable activation are left to the later checks.
163
+ def distinct_programs(mutants)
164
+ seen = {}
165
+ mutants.select do |mutant|
166
+ program = Mutant::Activator.activation_source_for(mutant)
167
+ key = [mutant.subject, program]
168
+ program.nil? || (!seen.key?(key) && (seen[key] = true))
169
+ end
170
+ end
171
+
172
+ def node_end(mutant)
173
+ range = mutant.original_node&.location&.expression
174
+ start = mutant.subject.source_range&.begin
175
+ range && start ? "#{range.last_line - start}:#{range.last_column}" : range&.end_pos.to_s
176
+ end
177
+
135
178
  def sample_mutants(mutants, config:, sampling_strategy:)
136
179
  sampling = config&.sampling
137
180
  return mutants unless sampling
@@ -140,7 +183,8 @@ module Henitai
140
183
  sampling_strategy.sample(
141
184
  mutants,
142
185
  ratio: sampling[:ratio],
143
- strategy: sampling[:strategy] || :stratified
186
+ strategy: sampling[:strategy] || :stratified,
187
+ seed: sampling[:seed] || SamplingStrategy::DEFAULT_SEED
144
188
  )
145
189
  end
146
190
 
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Henitai
4
+ class MutantHistoryStore
5
+ # Connection, schema and transaction handling for {MutantHistoryStore}.
6
+ # Mixed in; relies on its +path+.
7
+ module Database
8
+ private
9
+
10
+ # One transaction per write, committed or rolled back as a whole: signals
11
+ # wait until it ends, and any exception -- not only a StandardError, which
12
+ # is all sqlite3's block form rolls back for -- undoes it.
13
+ def write
14
+ FileUtils.mkdir_p(File.dirname(path))
15
+ SignalDeferral.call do
16
+ with_database do |db|
17
+ ensure_schema(db)
18
+ atomically(db) { yield db }
19
+ end
20
+ end
21
+ end
22
+
23
+ def atomically(db)
24
+ db.transaction
25
+ yield
26
+ db.commit
27
+ rescue Exception # rubocop:disable Lint/RescueException -- an Interrupt must roll back too
28
+ db.rollback if db.transaction_active?
29
+ raise
30
+ end
31
+
32
+ def with_database
33
+ db = SQLite3::Database.new(path)
34
+ db.results_as_hash = true
35
+ yield db
36
+ ensure
37
+ db&.close
38
+ end
39
+
40
+ def ensure_schema(db)
41
+ db.execute_batch(Sql::RUNS_TABLE)
42
+ db.execute_batch(Sql::MUTANTS_TABLE)
43
+ migrate_subject_scans_table(db)
44
+ db.execute_batch(SubjectScans::SUBJECT_SCANS_TABLE)
45
+ migrate_mutants_table(db)
46
+ end
47
+
48
+ # Additive, idempotent in-place migration: databases created before the
49
+ # verdict-cache columns existed gain them on first contact, with existing
50
+ # rows left intact (NULL hashes — valid but never reusable).
51
+ def migrate_mutants_table(db)
52
+ existing = db.execute("PRAGMA table_info(mutants)").map { |row| row["name"] }
53
+ Sql::MIGRATION_COLUMNS.each do |column, type|
54
+ next if existing.include?(column)
55
+
56
+ db.execute("ALTER TABLE mutants ADD COLUMN #{column} #{type}")
57
+ end
58
+ end
59
+ end
60
+ end
61
+ end
@@ -54,7 +54,9 @@ module Henitai
54
54
  # filter treats as never-reusable — the correct conservative behavior.
55
55
  MIGRATION_COLUMNS = {
56
56
  "subject_source_hash" => "TEXT",
57
- "covered_tests_fingerprint" => "TEXT"
57
+ "covered_tests_fingerprint" => "TEXT",
58
+ "subject_expression" => "TEXT",
59
+ "operators" => "TEXT"
58
60
  }.freeze
59
61
 
60
62
  UPSERT_MUTANT = <<~SQL
@@ -68,9 +70,13 @@ module Henitai
68
70
  status_history,
69
71
  days_alive,
70
72
  subject_source_hash,
71
- covered_tests_fingerprint
72
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
73
+ covered_tests_fingerprint,
74
+ subject_expression,
75
+ operators
76
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
73
77
  ON CONFLICT(mutant_id) DO UPDATE SET
78
+ subject_expression = excluded.subject_expression,
79
+ operators = excluded.operators,
74
80
  last_seen_version = excluded.last_seen_version,
75
81
  last_seen_at = excluded.last_seen_at,
76
82
  current_status = excluded.current_status,
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Henitai
4
+ class MutantHistoryStore
5
+ # Tracks when each subject was last mutated in full, which is what lets
6
+ # the trend export tell a retired mutant identity ("its subject was
7
+ # regenerated and this id was not among the results") from one that was
8
+ # merely out of scope ("no run has mutated that subject since").
9
+ #
10
+ # Without the per-subject baseline any narrow run — `--since`, a single
11
+ # subject pattern — would retire every mutant it did not re-record.
12
+ # Mixed into {MutantHistoryStore}.
13
+ module SubjectScans
14
+ # When each subject was last mutated in full. Partial reruns
15
+ # (`--survivors-from`) deliberately do not touch this table: they
16
+ # record a subset of a subject's mutants, which must not make the rest
17
+ # look retired.
18
+ # Keyed by operator set as well as subject: a `light` scan regenerates
19
+ # only the light mutants, so it can speak for those and no others.
20
+ SUBJECT_SCANS_TABLE = <<~SQL
21
+ CREATE TABLE IF NOT EXISTS subject_scans (
22
+ subject_expression TEXT NOT NULL,
23
+ operators TEXT NOT NULL,
24
+ last_scanned_at TEXT NOT NULL,
25
+ PRIMARY KEY (subject_expression, operators)
26
+ );
27
+ SQL
28
+
29
+ UPSERT_SUBJECT_SCAN = <<~SQL
30
+ INSERT INTO subject_scans (subject_expression, operators, last_scanned_at)
31
+ VALUES (?, ?, ?)
32
+ ON CONFLICT(subject_expression, operators) DO UPDATE SET
33
+ last_scanned_at = excluded.last_scanned_at
34
+ WHERE excluded.last_scanned_at > subject_scans.last_scanned_at
35
+ SQL
36
+
37
+ # A mutant is retired when its own subject has been mutated in full
38
+ # since it was last seen: the scan regenerated that subject's mutants
39
+ # and this identity was not among them, so it can never match again.
40
+ # Rows predating the subject_expression column (NULL) have no scan to
41
+ # compare against and stay live — the conservative reading.
42
+ LOAD_MUTANTS = <<~SQL
43
+ SELECT mutants.*
44
+ FROM mutants
45
+ LEFT JOIN subject_scans
46
+ ON subject_scans.subject_expression = mutants.subject_expression
47
+ AND subject_scans.operators = mutants.operators
48
+ WHERE subject_scans.last_scanned_at IS NULL
49
+ OR mutants.last_seen_at >= subject_scans.last_scanned_at
50
+ ORDER BY mutants.first_seen_at, mutants.mutant_id
51
+ SQL
52
+
53
+ private
54
+
55
+ # subject_scans carries a composite primary key, which SQLite cannot add
56
+ # by ALTER TABLE. The table is a derived retirement baseline, never a
57
+ # record of anything: dropping it means "no subject has been scanned
58
+ # yet", so the next export retires nothing until a full scan rebuilds it.
59
+ # Losing it is conservative; migrating it in place is not possible.
60
+ def migrate_subject_scans_table(db)
61
+ columns = db.execute("PRAGMA table_info(subject_scans)").map { |row| row["name"] }
62
+ return if columns.empty? || columns.include?("operators")
63
+
64
+ db.execute("DROP TABLE subject_scans")
65
+ end
66
+
67
+ # Only a run that regenerated a subject's mutants in full may advance
68
+ # its baseline. Three things narrow a run below that bar, and all three
69
+ # must leave the baseline alone or they retire mutants they merely did
70
+ # not produce:
71
+ #
72
+ # - partial reruns (`--survivors-from`), which re-record only survivors
73
+ # - sampling (`mutation.sampling.ratio`), which cuts the generated set
74
+ # at generation time — this repo's own config samples at 0.05
75
+ # - a narrower operator set, handled by keying the scan on `operators`
76
+ # so a `light` scan never speaks for `full`-only mutants
77
+ # Only a run that generated every mutant of its subjects under a known
78
+ # operator set may advance the retirement baseline.
79
+ def complete_scan?(result, full_scan, operators)
80
+ full_scan && operators && !partial_rerun?(result)
81
+ end
82
+
83
+ def record_subject_scans(db, result, recorded_at, operators)
84
+ subject_expressions(result).each do |expression|
85
+ db.execute(
86
+ UPSERT_SUBJECT_SCAN,
87
+ [expression, operators.to_s, recorded_at.iso8601]
88
+ )
89
+ end
90
+ end
91
+
92
+ def subject_expressions(result)
93
+ Array(result.mutants).filter_map { |mutant| mutant_subject_expression(mutant) }.uniq
94
+ end
95
+
96
+ def mutant_subject_expression(mutant)
97
+ mutant.subject&.expression
98
+ end
99
+ end
100
+ end
101
+ end
@@ -21,16 +21,39 @@ module Henitai
21
21
  status = mutant.status.to_s
22
22
  return [nil, nil] unless CACHEABLE_STATUSES.include?(status)
23
23
  return existing_cache_bindings(existing_row) if from_cache?(mutant)
24
+ return [nil, nil] if retry_cut_short?(mutant)
24
25
  return killed_cache_bindings(mutant) if status == "killed"
25
26
 
26
27
  survived_cache_bindings(mutant, existing_row)
27
28
  end
28
29
 
29
30
  def killed_cache_bindings(mutant)
30
- [
31
- VerdictFingerprint.subject_source_hash(mutant),
32
- VerdictFingerprint.tests_fingerprint(covered_tests_for(mutant))
33
- ]
31
+ tests = covered_tests_for(mutant)
32
+ executed_bindings(mutant, tests) do
33
+ [
34
+ VerdictFingerprint.subject_source_hash(mutant),
35
+ VerdictFingerprint.tests_fingerprint(tests, context_sha: reuse_context&.fingerprint)
36
+ ]
37
+ end
38
+ end
39
+
40
+ # Fingerprints describe the inputs that were executed only while the
41
+ # provenance reports them unchanged since the run's capture (ADR-19).
42
+ # Checked before and after hashing, so an edit during hashing cannot
43
+ # slip in either.
44
+ def executed_bindings(mutant, test_paths)
45
+ paths = [subject_source_file(mutant), *Array(test_paths)].compact
46
+ return [nil, nil] unless inputs_intact?(paths)
47
+
48
+ bindings = yield
49
+ inputs_intact?(paths) ? bindings : [nil, nil]
50
+ end
51
+
52
+ def inputs_intact?(paths) = provenance.nil? || provenance.intact?(paths)
53
+
54
+ def subject_source_file(mutant)
55
+ subject = mutant.subject
56
+ subject.source_file if subject.respond_to?(:source_file)
34
57
  end
35
58
 
36
59
  # Survived rows fingerprint the full-map intersection set — the same
@@ -38,32 +61,35 @@ module Henitai
38
61
  # which reflects selector fallback and test_excludes and would
39
62
  # permanently mismatch the live set. When the fingerprint cannot be
40
63
  # recomputed (no per-test map, recipe stubs without a source range),
41
- # the previously stored bindings are kept: the filter re-validates
42
- # everything live before reuse, so a carried-forward fingerprint can
43
- # never validate a changed state.
64
+ # the previously stored bindings are kept, but only from a survived
65
+ # row of the same subject source: a killed row's or an edited method's
66
+ # fingerprints would vouch for a state this survivor never ran in.
44
67
  def survived_cache_bindings(mutant, existing_row)
68
+ tests = per_test_coverage&.tests_covering(mutant)
69
+ executed_bindings(mutant, tests) { survived_bindings(mutant, tests, existing_row) }
70
+ end
71
+
72
+ def survived_bindings(mutant, tests, existing_row)
45
73
  bindings = [
46
74
  VerdictFingerprint.subject_source_hash(mutant),
47
- survived_tests_fingerprint(mutant)
75
+ survived_tests_fingerprint(tests)
48
76
  ]
49
77
  return bindings unless bindings.any?(&:nil?)
78
+ return [nil, nil] unless carry_survived_bindings?(bindings.first, existing_row)
50
79
 
51
80
  existing_cache_bindings(existing_row)
52
81
  end
53
82
 
54
- def survived_tests_fingerprint(mutant)
55
- return nil unless per_test_coverage
83
+ def carry_survived_bindings?(source_hash, existing_row)
84
+ return false unless existing_row && existing_row["current_status"] == "survived"
56
85
 
57
- VerdictFingerprint.survivor_tests_fingerprint(
58
- per_test_coverage.tests_covering(mutant),
59
- dependency_sha: recording_dependency_sha
60
- )
86
+ source_hash.nil? || source_hash == existing_row["subject_source_hash"]
61
87
  end
62
88
 
63
- # One dependency sha per record call set, computed lazily so runs
64
- # without survivors never touch the dependency files.
65
- def recording_dependency_sha
66
- @recording_dependency_sha ||= VerdictFingerprint.dependency_fingerprint
89
+ def survived_tests_fingerprint(tests)
90
+ return nil unless tests
91
+
92
+ VerdictFingerprint.survivor_tests_fingerprint(tests, context_sha: reuse_context&.fingerprint)
67
93
  end
68
94
 
69
95
  def existing_cache_bindings(existing_row)
@@ -76,6 +102,10 @@ module Henitai
76
102
  mutant.respond_to?(:from_cache?) && mutant.from_cache?
77
103
  end
78
104
 
105
+ def retry_cut_short?(mutant)
106
+ mutant.respond_to?(:retry_cut_short?) && mutant.retry_cut_short?
107
+ end
108
+
79
109
  def covered_tests_for(mutant)
80
110
  mutant.respond_to?(:covered_by) ? mutant.covered_by : nil
81
111
  end
@@ -7,37 +7,71 @@ require "sqlite3"
7
7
  require "time"
8
8
  require_relative "mutant_identity"
9
9
  require_relative "mutant_history_store/sql"
10
+ require_relative "mutant_history_store/subject_scans"
10
11
  require_relative "mutant_history_store/verdict_cache"
12
+ require_relative "mutant_history_store/database"
11
13
 
12
14
  module Henitai
13
15
  # Persists mutant outcomes across runs in a lightweight SQLite database.
14
16
  class MutantHistoryStore
17
+ # What every mutant row of one write shares.
18
+ UpsertContext = Data.define(:version, :recorded_at, :run_id, :operators)
19
+
20
+ include SubjectScans
15
21
  include VerdictCache
22
+ include Database
16
23
 
17
24
  # @param per_test_coverage [PerTestCoverage, nil] live per-test coverage
18
25
  # view used to record the full-map intersection set for survived
19
26
  # verdicts; without it survived rows stay NULL (never reusable).
20
- def initialize(path:, per_test_coverage: nil)
27
+ # @param reuse_context [ReuseContext, nil] fingerprint recorded with every
28
+ # cached verdict; without it no verdict is cached (never reusable).
29
+ # @param provenance [ExecutionProvenance, nil] fingerprints are written
30
+ # only for verdicts whose inputs it reports intact (ADR-19); nil skips
31
+ # the check.
32
+ def initialize(path:, per_test_coverage: nil, reuse_context: nil, provenance: nil)
21
33
  @path = path
22
34
  @per_test_coverage = per_test_coverage
35
+ @reuse_context = reuse_context
36
+ @provenance = provenance
23
37
  end
24
38
 
25
39
  attr_reader :path
26
40
 
27
- def record(result, version:, recorded_at: Time.now.utc)
28
- FileUtils.mkdir_p(File.dirname(path))
29
-
30
- with_database do |db|
31
- ensure_schema(db)
32
- db.transaction do
33
- insert_run(db, result, version, recorded_at) unless partial_rerun?(result)
34
- Array(result.mutants).each do |mutant|
35
- upsert_mutant(db, mutant, version, recorded_at)
36
- end
37
- end
41
+ # Timestamps are normalized to UTC on the way in: they are stored as
42
+ # ISO8601 strings and compared lexicographically (retirement compares a
43
+ # mutant's last_seen_at against its subject's scan), and callers pass
44
+ # local-zone times — `Runner#run` hands over `Time.now`. Mixing offsets
45
+ # makes "2026-01-01T13:00:00Z" < "2026-01-01T14:00:00+02:00" as strings
46
+ # while the opposite is true as instants. `getutc`, not `utc`, so the
47
+ # caller's Time object is not mutated.
48
+ # @param operators [Symbol, nil] the operator set this run generated from;
49
+ # stored per mutant so a later scan only retires mutants recorded under
50
+ # the same set.
51
+ # @param full_scan [Boolean] whether this run regenerated each touched
52
+ # subject's mutants in full. False for sampled runs, which produce a
53
+ # fraction of the set and must not advance the retirement baseline.
54
+ # @param run_id [String, nil] one history entry per mutant and run: a
55
+ # second write of the same run replaces the entry its checkpoint wrote.
56
+ # rubocop:disable Metrics/ParameterLists -- one keyword per recorded fact
57
+ def record(result, version:, recorded_at: Time.now, operators: nil, full_scan: false, run_id: nil)
58
+ # rubocop:enable Metrics/ParameterLists
59
+ recorded_at = recorded_at.getutc
60
+ write do |db|
61
+ insert_run(db, result, version, recorded_at) if full_run?(result)
62
+ record_subject_scans(db, result, recorded_at, operators) if complete_scan?(result, full_scan, operators)
63
+ upsert_mutants(db, result.mutants, UpsertContext.new(version:, recorded_at:, run_id:, operators:))
38
64
  end
39
65
  end
40
66
 
67
+ # Persists verdicts while a run is in progress (ADR-19): mutant rows
68
+ # only, never a run row. @return [Integer] how many mutants were written
69
+ def checkpoint(mutants, version:, run_id:, operators: nil, recorded_at: Time.now)
70
+ context = UpsertContext.new(version:, recorded_at: recorded_at.getutc, run_id:, operators:)
71
+ write { |db| upsert_mutants(db, mutants, context) }
72
+ Array(mutants).size
73
+ end
74
+
41
75
  # Verdict-cache lookup for `--incremental`: returns the stored hashes for
42
76
  # the mutant's LATEST verdict when it is Killed or Survived — the upsert
43
77
  # keeps exactly one row per stable id, so current_status is always the
@@ -72,7 +106,7 @@ module Henitai
72
106
 
73
107
  private
74
108
 
75
- attr_reader :per_test_coverage
109
+ attr_reader :per_test_coverage, :reuse_context, :provenance
76
110
 
77
111
  def verdict_from_row(row)
78
112
  return nil unless row && VerdictCache::CACHEABLE_STATUSES.include?(row["current_status"])
@@ -85,44 +119,27 @@ module Henitai
85
119
  }
86
120
  end
87
121
 
88
- def partial_rerun?(result)
89
- result.respond_to?(:partial_rerun?) && result.partial_rerun?
90
- end
91
-
92
- def with_database
93
- db = SQLite3::Database.new(path)
94
- db.results_as_hash = true
95
- yield db
96
- ensure
97
- db&.close
122
+ def full_run?(result)
123
+ authoritative = !result.respond_to?(:authoritative?) || result.authoritative?
124
+ authoritative && !partial_rerun?(result)
98
125
  end
99
126
 
100
- def ensure_schema(db)
101
- db.execute_batch(Sql::RUNS_TABLE)
102
- db.execute_batch(Sql::MUTANTS_TABLE)
103
- migrate_mutants_table(db)
127
+ def partial_rerun?(result)
128
+ result.respond_to?(:partial_rerun?) && result.partial_rerun?
104
129
  end
105
130
 
106
- # Additive, idempotent in-place migration: databases created before the
107
- # verdict-cache columns existed gain them on first contact, with existing
108
- # rows left intact (NULL hashes — valid but never reusable).
109
- def migrate_mutants_table(db)
110
- existing = db.execute("PRAGMA table_info(mutants)").map { |row| row["name"] }
111
- Sql::MIGRATION_COLUMNS.each do |column, type|
112
- next if existing.include?(column)
113
-
114
- db.execute("ALTER TABLE mutants ADD COLUMN #{column} #{type}")
115
- end
131
+ def upsert_mutants(db, mutants, context)
132
+ Array(mutants).each { |mutant| upsert_mutant(db, mutant, context) }
116
133
  end
117
134
 
118
135
  def insert_run(db, result, version, recorded_at)
119
136
  db.execute(Sql::INSERT_RUN, insert_run_bindings(result, version, recorded_at))
120
137
  end
121
138
 
122
- def upsert_mutant(db, mutant, version, recorded_at)
139
+ def upsert_mutant(db, mutant, context)
123
140
  db.execute(
124
141
  Sql::UPSERT_MUTANT,
125
- upsert_mutant_bindings(mutant_history_data(db, mutant, version, recorded_at))
142
+ upsert_mutant_bindings(mutant_history_data(db, mutant, context), context.operators)
126
143
  )
127
144
  end
128
145
 
@@ -133,22 +150,23 @@ module Henitai
133
150
  end
134
151
  end
135
152
 
153
+ # Recipe stubs carry a precomputed id that cannot be recomputed from
154
+ # their (absent) AST nodes.
136
155
  def stable_mutant_id(mutant)
137
- MutantIdentity.stable_id(mutant)
156
+ mutant.respond_to?(:stable_id) ? mutant.stable_id : MutantIdentity.stable_id(mutant)
138
157
  end
139
158
 
140
- def mutation_history_entry(mutant, version, recorded_at)
141
- {
142
- version: version,
143
- status: mutant.status.to_s,
144
- recordedAt: recorded_at.iso8601
145
- }
159
+ def mutation_history_entry(mutant, context)
160
+ entry = { version: context.version, status: mutant.status.to_s, recordedAt: context.recorded_at.iso8601 }
161
+ context.run_id ? entry.merge(runId: context.run_id) : entry
146
162
  end
147
163
 
148
- def mutant_history_data(db, mutant, version, recorded_at)
164
+ def mutant_history_data(db, mutant, context)
165
+ version = context.version
166
+ recorded_at = context.recorded_at
149
167
  mutant_id = stable_mutant_id(mutant)
150
168
  existing = existing_mutant_row(db, mutant_id)
151
- history = existing_status_history(existing) << mutation_history_entry(mutant, version, recorded_at)
169
+ history = append_history(existing_status_history(existing), mutation_history_entry(mutant, context))
152
170
  first_seen = first_seen_metadata(existing, version, recorded_at)
153
171
 
154
172
  {
@@ -158,6 +176,12 @@ module Henitai
158
176
  }
159
177
  end
160
178
 
179
+ # A later write of the same run replaces that run's entry.
180
+ def append_history(history, entry)
181
+ history.pop if entry[:runId] && history.last&.dig(:runId) == entry[:runId]
182
+ history << entry
183
+ end
184
+
161
185
  def existing_mutant_row(db, mutant_id)
162
186
  db.get_first_row(
163
187
  "SELECT * FROM mutants WHERE mutant_id = ?",
@@ -201,7 +225,7 @@ module Henitai
201
225
  end
202
226
 
203
227
  def load_mutants(db)
204
- db.execute("SELECT * FROM mutants ORDER BY first_seen_at, mutant_id").map do |row|
228
+ db.execute(SubjectScans::LOAD_MUTANTS).map do |row|
205
229
  {
206
230
  mutantId: row["mutant_id"],
207
231
  firstSeenVersion: row["first_seen_version"],
@@ -232,7 +256,7 @@ module Henitai
232
256
  ]
233
257
  end
234
258
 
235
- def upsert_mutant_bindings(data)
259
+ def upsert_mutant_bindings(data, operators)
236
260
  mutant = data.fetch(:mutant)
237
261
  [
238
262
  data.fetch(:mutant_id),
@@ -243,7 +267,9 @@ module Henitai
243
267
  mutant.status.to_s,
244
268
  JSON.generate(data.fetch(:history)),
245
269
  data.fetch(:days_alive),
246
- *verdict_cache_bindings(mutant, data[:existing_row])
270
+ *verdict_cache_bindings(mutant, data[:existing_row]),
271
+ mutant_subject_expression(mutant),
272
+ operators&.to_s
247
273
  ]
248
274
  end
249
275
  end
@@ -19,8 +19,12 @@ module Henitai
19
19
  digest(legacy_identity_components(mutant))
20
20
  end
21
21
 
22
+ # The discriminator is present only for mutants that would otherwise
23
+ # share an identity -- nested nodes starting at the same position, such
24
+ # as the calls of `x.a.b.c` -- so every other identity stays unchanged.
22
25
  def self.identity_components(mutant)
23
- legacy_identity_components(mutant) + [site_offset(mutant)]
26
+ discriminator = mutant.respond_to?(:identity_discriminator) && mutant.identity_discriminator
27
+ legacy_identity_components(mutant) + [site_offset(mutant)] + [discriminator].compact
24
28
  end
25
29
  private_class_method :identity_components
26
30