polyrun 3.2.0-java

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 (225) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +234 -0
  3. data/CODE_OF_CONDUCT.md +26 -0
  4. data/CONTRIBUTING.md +23 -0
  5. data/LICENSE +21 -0
  6. data/README.md +251 -0
  7. data/SECURITY.md +25 -0
  8. data/bin/polyrun +6 -0
  9. data/docs/QUALITY.md +82 -0
  10. data/docs/QUALITY_CONFIGURATION.md +95 -0
  11. data/docs/SETUP_PROFILE.md +139 -0
  12. data/lib/polyrun/benchmark/pressure/cooker.rb +191 -0
  13. data/lib/polyrun/benchmark/pressure/process_sample.rb +127 -0
  14. data/lib/polyrun/benchmark/pressure.rb +144 -0
  15. data/lib/polyrun/benchmark/profile.rb +191 -0
  16. data/lib/polyrun/benchmark/report.rb +87 -0
  17. data/lib/polyrun/cli/benchmark_commands.rb +66 -0
  18. data/lib/polyrun/cli/ci_shard_hooks.rb +129 -0
  19. data/lib/polyrun/cli/ci_shard_run_command.rb +177 -0
  20. data/lib/polyrun/cli/ci_shard_run_parse.rb +68 -0
  21. data/lib/polyrun/cli/config_command.rb +42 -0
  22. data/lib/polyrun/cli/coverage_commands.rb +150 -0
  23. data/lib/polyrun/cli/coverage_merge_io.rb +150 -0
  24. data/lib/polyrun/cli/database_commands.rb +163 -0
  25. data/lib/polyrun/cli/default_run.rb +144 -0
  26. data/lib/polyrun/cli/doctor_command.rb +94 -0
  27. data/lib/polyrun/cli/env_commands.rb +43 -0
  28. data/lib/polyrun/cli/failure_commands.rb +99 -0
  29. data/lib/polyrun/cli/graph_command.rb +68 -0
  30. data/lib/polyrun/cli/help.rb +83 -0
  31. data/lib/polyrun/cli/helpers.rb +162 -0
  32. data/lib/polyrun/cli/hooks_command.rb +97 -0
  33. data/lib/polyrun/cli/init_command.rb +108 -0
  34. data/lib/polyrun/cli/mutation_command.rb +67 -0
  35. data/lib/polyrun/cli/partition_diagnostics.rb +22 -0
  36. data/lib/polyrun/cli/plan_command.rb +184 -0
  37. data/lib/polyrun/cli/prepare_command.rb +70 -0
  38. data/lib/polyrun/cli/prepare_recipe.rb +82 -0
  39. data/lib/polyrun/cli/quality_commands.rb +65 -0
  40. data/lib/polyrun/cli/queue_command.rb +161 -0
  41. data/lib/polyrun/cli/quick_command.rb +13 -0
  42. data/lib/polyrun/cli/report_commands.rb +108 -0
  43. data/lib/polyrun/cli/run_queue_command.rb +127 -0
  44. data/lib/polyrun/cli/run_shards_command.rb +164 -0
  45. data/lib/polyrun/cli/run_shards_parallel_children.rb +112 -0
  46. data/lib/polyrun/cli/run_shards_parallel_wait.rb +252 -0
  47. data/lib/polyrun/cli/run_shards_plan_boot_phases.rb +207 -0
  48. data/lib/polyrun/cli/run_shards_plan_options.rb +74 -0
  49. data/lib/polyrun/cli/run_shards_planning.rb +123 -0
  50. data/lib/polyrun/cli/run_shards_run.rb +171 -0
  51. data/lib/polyrun/cli/run_shards_worker_interrupt.rb +101 -0
  52. data/lib/polyrun/cli/skip_env.rb +34 -0
  53. data/lib/polyrun/cli/spec_quality_commands.rb +149 -0
  54. data/lib/polyrun/cli/start_bootstrap.rb +126 -0
  55. data/lib/polyrun/cli/timing_command.rb +31 -0
  56. data/lib/polyrun/cli/tool_options.rb +48 -0
  57. data/lib/polyrun/cli/validate_command.rb +26 -0
  58. data/lib/polyrun/cli.rb +272 -0
  59. data/lib/polyrun/config/dotted_path.rb +21 -0
  60. data/lib/polyrun/config/effective.rb +82 -0
  61. data/lib/polyrun/config/resolver.rb +114 -0
  62. data/lib/polyrun/config/schema.rb +39 -0
  63. data/lib/polyrun/config/suite.rb +109 -0
  64. data/lib/polyrun/config/tool_defaults.rb +42 -0
  65. data/lib/polyrun/config/tool_validation.rb +79 -0
  66. data/lib/polyrun/config/tools.rb +120 -0
  67. data/lib/polyrun/config.rb +97 -0
  68. data/lib/polyrun/coverage/cobertura_zero_lines.rb +32 -0
  69. data/lib/polyrun/coverage/collector.rb +169 -0
  70. data/lib/polyrun/coverage/collector_blob.rb +53 -0
  71. data/lib/polyrun/coverage/collector_finish.rb +98 -0
  72. data/lib/polyrun/coverage/collector_fragment_meta.rb +57 -0
  73. data/lib/polyrun/coverage/config_resolve.rb +131 -0
  74. data/lib/polyrun/coverage/example_diff.rb +184 -0
  75. data/lib/polyrun/coverage/example_diff_snapshot.rb +44 -0
  76. data/lib/polyrun/coverage/example_diff_track_filter.rb +51 -0
  77. data/lib/polyrun/coverage/file_stats_report.rb +36 -0
  78. data/lib/polyrun/coverage/filter.rb +22 -0
  79. data/lib/polyrun/coverage/formatter.rb +137 -0
  80. data/lib/polyrun/coverage/merge/formatters.rb +188 -0
  81. data/lib/polyrun/coverage/merge/formatters_html.rb +221 -0
  82. data/lib/polyrun/coverage/merge/html/_file_list.html.erb +21 -0
  83. data/lib/polyrun/coverage/merge/html/_file_section.html.erb +26 -0
  84. data/lib/polyrun/coverage/merge/html/_groups_table.html.erb +18 -0
  85. data/lib/polyrun/coverage/merge/html/_overview.html.erb +47 -0
  86. data/lib/polyrun/coverage/merge/html/report.css +147 -0
  87. data/lib/polyrun/coverage/merge/html/report.js +48 -0
  88. data/lib/polyrun/coverage/merge/html/template.html.erb +30 -0
  89. data/lib/polyrun/coverage/merge.rb +160 -0
  90. data/lib/polyrun/coverage/merge_fragment_meta.rb +58 -0
  91. data/lib/polyrun/coverage/merge_merge_two.rb +168 -0
  92. data/lib/polyrun/coverage/merge_native.rb +39 -0
  93. data/lib/polyrun/coverage/rails.rb +126 -0
  94. data/lib/polyrun/coverage/reporting.rb +41 -0
  95. data/lib/polyrun/coverage/result.rb +18 -0
  96. data/lib/polyrun/coverage/track_files.rb +150 -0
  97. data/lib/polyrun/data/cached_fixtures.rb +122 -0
  98. data/lib/polyrun/data/factory_counts.rb +48 -0
  99. data/lib/polyrun/data/factory_instrumentation.rb +50 -0
  100. data/lib/polyrun/data/fixtures.rb +68 -0
  101. data/lib/polyrun/data/parallel_provisioning.rb +93 -0
  102. data/lib/polyrun/data/snapshot.rb +84 -0
  103. data/lib/polyrun/database/clone_shards.rb +106 -0
  104. data/lib/polyrun/database/provision.rb +83 -0
  105. data/lib/polyrun/database/shard.rb +64 -0
  106. data/lib/polyrun/database/url_builder/connection/infer.rb +53 -0
  107. data/lib/polyrun/database/url_builder/connection/url_builders.rb +43 -0
  108. data/lib/polyrun/database/url_builder/connection.rb +191 -0
  109. data/lib/polyrun/database/url_builder/template_prepare.rb +21 -0
  110. data/lib/polyrun/database/url_builder.rb +188 -0
  111. data/lib/polyrun/debug.rb +81 -0
  112. data/lib/polyrun/env/ci.rb +65 -0
  113. data/lib/polyrun/error.rb +3 -0
  114. data/lib/polyrun/export/csv.rb +25 -0
  115. data/lib/polyrun/export/markdown.rb +47 -0
  116. data/lib/polyrun/graph/client.rb +64 -0
  117. data/lib/polyrun/graph/error.rb +13 -0
  118. data/lib/polyrun/graph/index.rb +75 -0
  119. data/lib/polyrun/graph/inspect.rb +58 -0
  120. data/lib/polyrun/graph/plan.rb +134 -0
  121. data/lib/polyrun/graph/planner.rb +117 -0
  122. data/lib/polyrun/graph/syntax.rb +114 -0
  123. data/lib/polyrun/graph/transaction.rb +81 -0
  124. data/lib/polyrun/graph/worker.rb +55 -0
  125. data/lib/polyrun/graph/workspace.rb +117 -0
  126. data/lib/polyrun/hooks/dsl.rb +128 -0
  127. data/lib/polyrun/hooks/shell_runner.rb +33 -0
  128. data/lib/polyrun/hooks/worker_runner.rb +27 -0
  129. data/lib/polyrun/hooks/worker_shell.rb +50 -0
  130. data/lib/polyrun/hooks.rb +190 -0
  131. data/lib/polyrun/log.rb +86 -0
  132. data/lib/polyrun/minitest_support.rb +60 -0
  133. data/lib/polyrun/mutation/candidates.rb +91 -0
  134. data/lib/polyrun/mutation/operators.rb +51 -0
  135. data/lib/polyrun/mutation/runner.rb +133 -0
  136. data/lib/polyrun/mutation/subjects.rb +88 -0
  137. data/lib/polyrun/partition/constraints.rb +80 -0
  138. data/lib/polyrun/partition/hrw.rb +70 -0
  139. data/lib/polyrun/partition/min_heap.rb +64 -0
  140. data/lib/polyrun/partition/paths.rb +175 -0
  141. data/lib/polyrun/partition/paths_build.rb +141 -0
  142. data/lib/polyrun/partition/plan.rb +250 -0
  143. data/lib/polyrun/partition/plan_lpt.rb +91 -0
  144. data/lib/polyrun/partition/plan_sharding.rb +56 -0
  145. data/lib/polyrun/partition/reports.rb +139 -0
  146. data/lib/polyrun/partition/stable_shuffle.rb +18 -0
  147. data/lib/polyrun/partition/suite.rb +120 -0
  148. data/lib/polyrun/partition/timing_diagnostics.rb +138 -0
  149. data/lib/polyrun/partition/timing_keys.rb +86 -0
  150. data/lib/polyrun/prepare/artifacts.rb +40 -0
  151. data/lib/polyrun/prepare/assets.rb +64 -0
  152. data/lib/polyrun/process_stdio.rb +96 -0
  153. data/lib/polyrun/quality/command.rb +84 -0
  154. data/lib/polyrun/quality/measure.rb +38 -0
  155. data/lib/polyrun/quality/observe.rb +53 -0
  156. data/lib/polyrun/quality/observe_hook.rb +103 -0
  157. data/lib/polyrun/quality/sandbox.rb +70 -0
  158. data/lib/polyrun/queue/duration.rb +30 -0
  159. data/lib/polyrun/queue/file_store.rb +413 -0
  160. data/lib/polyrun/queue/file_store_intent.rb +188 -0
  161. data/lib/polyrun/queue/file_store_pending.rb +48 -0
  162. data/lib/polyrun/queue/worker_loop.rb +73 -0
  163. data/lib/polyrun/quick/assertions.rb +32 -0
  164. data/lib/polyrun/quick/config.rb +56 -0
  165. data/lib/polyrun/quick/errors.rb +6 -0
  166. data/lib/polyrun/quick/example_group.rb +111 -0
  167. data/lib/polyrun/quick/example_runner.rb +129 -0
  168. data/lib/polyrun/quick/matchers.rb +159 -0
  169. data/lib/polyrun/quick/matchers_predicates.rb +122 -0
  170. data/lib/polyrun/quick/reporter.rb +76 -0
  171. data/lib/polyrun/quick/runner.rb +224 -0
  172. data/lib/polyrun/quick.rb +1 -0
  173. data/lib/polyrun/railtie.rb +7 -0
  174. data/lib/polyrun/reporting/failure_merge.rb +171 -0
  175. data/lib/polyrun/reporting/junit.rb +126 -0
  176. data/lib/polyrun/reporting/junit_emit.rb +58 -0
  177. data/lib/polyrun/reporting/junit_report.rb +87 -0
  178. data/lib/polyrun/reporting/rspec_failure_fragment_formatter.rb +95 -0
  179. data/lib/polyrun/reporting/rspec_junit.rb +39 -0
  180. data/lib/polyrun/rspec_support/active_record_timeout_recovery.rb +51 -0
  181. data/lib/polyrun/rspec_support/example_debug.rb +167 -0
  182. data/lib/polyrun/rspec_support/example_debug_instrumentation.rb +73 -0
  183. data/lib/polyrun/rspec_support/sharded_formatter_compat.rb +57 -0
  184. data/lib/polyrun/rspec_support.rb +110 -0
  185. data/lib/polyrun/spec_quality/config.rb +139 -0
  186. data/lib/polyrun/spec_quality/fragment.rb +39 -0
  187. data/lib/polyrun/spec_quality/merge.rb +78 -0
  188. data/lib/polyrun/spec_quality/minitest_hook.rb +42 -0
  189. data/lib/polyrun/spec_quality/plan_loader.rb +47 -0
  190. data/lib/polyrun/spec_quality/profile.rb +102 -0
  191. data/lib/polyrun/spec_quality/report.rb +363 -0
  192. data/lib/polyrun/spec_quality/rspec_hook.rb +55 -0
  193. data/lib/polyrun/spec_quality/sql_counter.rb +34 -0
  194. data/lib/polyrun/spec_quality.rb +212 -0
  195. data/lib/polyrun/sus_support.rb +55 -0
  196. data/lib/polyrun/templates/POLYRUN.md +51 -0
  197. data/lib/polyrun/templates/ci_matrix.polyrun.yml +22 -0
  198. data/lib/polyrun/templates/minimal_gem.polyrun.yml +13 -0
  199. data/lib/polyrun/templates/polyrun_hooks_spec_quality.rb +12 -0
  200. data/lib/polyrun/templates/polyrun_spec_quality.yml +20 -0
  201. data/lib/polyrun/templates/rails_prepare.polyrun.yml +51 -0
  202. data/lib/polyrun/templates/rails_prepare_task.rake +16 -0
  203. data/lib/polyrun/timing/merge.rb +36 -0
  204. data/lib/polyrun/timing/rspec_example_formatter.rb +60 -0
  205. data/lib/polyrun/timing/stats.rb +76 -0
  206. data/lib/polyrun/timing/summary.rb +78 -0
  207. data/lib/polyrun/timing/variance_report.rb +51 -0
  208. data/lib/polyrun/version.rb +3 -0
  209. data/lib/polyrun/worker_output.rb +181 -0
  210. data/lib/polyrun/worker_output_forwarders.rb +94 -0
  211. data/lib/polyrun/worker_ping.rb +77 -0
  212. data/lib/polyrun.rb +59 -0
  213. data/polyrun.gemspec +49 -0
  214. data/sig/polyrun/cli.rbs +6 -0
  215. data/sig/polyrun/config.rbs +20 -0
  216. data/sig/polyrun/debug.rbs +12 -0
  217. data/sig/polyrun/log.rbs +12 -0
  218. data/sig/polyrun/minitest_support.rbs +7 -0
  219. data/sig/polyrun/quick.rbs +19 -0
  220. data/sig/polyrun/rspec_support.rbs +21 -0
  221. data/sig/polyrun/sus_support.rbs +7 -0
  222. data/sig/polyrun/worker_output.rbs +11 -0
  223. data/sig/polyrun/worker_ping.rbs +10 -0
  224. data/sig/polyrun.rbs +11 -0
  225. metadata +463 -0
@@ -0,0 +1,51 @@
1
+ module Polyrun
2
+ module Mutation
3
+ module Operators
4
+ class Literal
5
+ def call(node)
6
+ replacements = case node
7
+ when Prism::TrueNode then ["false"]
8
+ when Prism::FalseNode then ["true"]
9
+ when Prism::NilNode then ["true"]
10
+ when Prism::IntegerNode then ["0", "1", (node.value + 1).to_s]
11
+ when Prism::FloatNode then ["0.0", "1.0"]
12
+ when Prism::StringNode, Prism::InterpolatedStringNode then ['""']
13
+ when Prism::ArrayNode then ["[]"]
14
+ when Prism::HashNode then ["{}"]
15
+ else []
16
+ end
17
+ replacements.map { |value| [node.location, value, "literal"] }
18
+ end
19
+ end
20
+
21
+ class Operator
22
+ REPLACEMENTS = {"==" => "!=", "!=" => "==", ">" => "<=", ">=" => "<", "<" => ">=", "<=" => ">",
23
+ "+" => "-", "-" => "+", "*" => "/", "/" => "*", "&" => "|", "|" => "&"}.freeze
24
+
25
+ def call(node)
26
+ return [] unless node.is_a?(Prism::CallNode) && node.message_loc
27
+
28
+ replacement = REPLACEMENTS[node.name.to_s]
29
+ replacement ? [[node.message_loc, replacement, "operator"]] : []
30
+ end
31
+ end
32
+
33
+ class Body
34
+ def call(node)
35
+ return [] unless node.is_a?(Prism::DefNode)
36
+
37
+ return %w[false true 0].map { |value| [node.end_keyword_loc.copy(length: 0), ";#{value};", "body"] } unless node.body
38
+
39
+ %w[nil false true 0].map { |value| [node.body.location, value, "body"] }
40
+ end
41
+ end
42
+
43
+ REGISTRY = {"literal" => Literal.new, "operator" => Operator.new, "body" => Body.new}.freeze
44
+ STANDARD = REGISTRY.values.freeze
45
+
46
+ def self.select(names)
47
+ names.map { |name| REGISTRY.fetch(name) }
48
+ end
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,133 @@
1
+ require "tmpdir"
2
+ require_relative "../quality/command"
3
+ require_relative "../quality/sandbox"
4
+ require_relative "candidates"
5
+
6
+ module Polyrun
7
+ module Mutation
8
+ class Runner
9
+ def initialize(root: Dir.pwd, workers: nil, timeout: nil, arguments: [], max_mutations: nil,
10
+ max_report_bytes: nil, operators: nil, settings: {})
11
+ overrides = {"workers" => workers, "timeout" => timeout, "max_mutations" => max_mutations, "max_report_bytes" => max_report_bytes}.compact
12
+ @settings = Config::Tools.runtime("mutation", settings.merge(overrides))
13
+ raise ArgumentError, "workers exceed configured maximum" if @settings["workers"] > @settings["max_workers"]
14
+
15
+ @root, @workers, @timeout, @arguments = File.realpath(root), @settings["workers"], @settings["timeout"], arguments
16
+ @max_mutations, @max_report_bytes = @settings["max_mutations"], @settings["max_report_bytes"]
17
+ @operators = operators || Operators.select(@settings["operators"])
18
+ end
19
+
20
+ def call(subjects, shard: 1, total: 1)
21
+ subjects = select_subjects(subjects, shard, total)
22
+ return aggregate(subjects, [], nil) if subjects.empty?
23
+ raise ArgumentError, "a test command is required after --" if @arguments.empty?
24
+
25
+ mutations = Candidates.new(@root, operators: @operators, limit: @max_mutations, settings: @settings).call(subjects)
26
+ raise ArgumentError, "no supported mutations for selected subjects" if mutations.empty?
27
+ budget = {remaining: @max_report_bytes, mutex: Mutex.new}
28
+ Dir.mktmpdir("polyrun-mutations") do |template|
29
+ project = Quality::Sandbox.new(@root, settings: @settings["staging"])
30
+ enforce_copy_budget!(project.bytes, mutations.size)
31
+
32
+ project.copy_to(template)
33
+ baseline = retain_result(execute(template, nil), budget)
34
+ unless baseline["exitstatus"].zero? && baseline["code"] != "REPORT_LIMIT"
35
+ return aggregate(subjects, [], baseline).merge("ok" => false, "code" => "BASELINE_FAILED", "killed" => nil, "survived" => nil)
36
+ end
37
+ results = parallel(mutations, template, budget)
38
+ aggregate(subjects, results, baseline)
39
+ end
40
+ end
41
+
42
+ private
43
+
44
+ def enforce_copy_budget!(bytes, mutations)
45
+ raise ArgumentError, "mutation copy budget exceeded; narrow subjects or raise max_copy_bytes" if bytes * (mutations + 2) > @settings["max_copy_bytes"]
46
+ end
47
+
48
+ def parallel(mutations, template, budget)
49
+ pending = ::Queue.new
50
+ results = Array.new(mutations.size)
51
+ mutations.each_with_index { |mutation, index| pending << [mutation, index] }
52
+ threads = Array.new([@workers, mutations.size].min) do
53
+ Thread.new do # rubocop:disable ThreadSafety/NewThread -- bounded subprocess workers with isolated copies
54
+ loop do
55
+ mutation, index = pending.pop(true)
56
+ result = execute(template, mutation)
57
+ results[index] = retain_result(result, budget)
58
+ rescue ThreadError
59
+ break
60
+ end
61
+ end
62
+ end
63
+ threads.each(&:value)
64
+ results
65
+ ensure
66
+ threads&.each { |thread| thread.kill if thread.alive? }
67
+ threads&.each(&:join)
68
+ end
69
+
70
+ def execute(template, mutation)
71
+ Dir.mktmpdir("polyrun-mutation") do |directory|
72
+ project = Quality::Sandbox.new(template, settings: @settings["staging"])
73
+ project.copy_to(directory)
74
+ apply_mutation(directory, mutation) if mutation
75
+ command = @arguments.map { |argument| argument.start_with?("#{@root}/") ? File.join(directory, argument.delete_prefix("#{@root}/")) : argument }
76
+ # Baseline keeps a floor so short per-mutation timeouts do not fail the clean run under load.
77
+ timeout = mutation ? @timeout : [@timeout, 5.0].max
78
+ result = Quality::Command.call(command, root: directory, timeout: timeout, max_output: @settings["max_output_bytes"], env: Quality::Sandbox.environment(directory))
79
+ result.merge!(mutation) if mutation
80
+ result["code"] = {0 => mutation ? "SURVIVED" : "BASELINE_OK", 1 => mutation ? "KILLED" : "BASELINE_FAILED",
81
+ 122 => "OUTPUT_LIMIT", 124 => "TIMEOUT", 127 => "COMMAND_UNAVAILABLE"}.fetch(result["exitstatus"], "COMMAND_FAILED")
82
+ result
83
+ end
84
+ end
85
+
86
+ def retain_result(result, budget)
87
+ budget[:mutex].synchronize do
88
+ size = result["stdout"].bytesize + result["stderr"].bytesize
89
+ if size > budget[:remaining]
90
+ result.merge!("stdout" => "", "stderr" => "", "code" => "REPORT_LIMIT")
91
+ else
92
+ budget[:remaining] -= size
93
+ end
94
+ end
95
+ result
96
+ end
97
+
98
+ def apply_mutation(directory, mutation)
99
+ file = File.join(directory, mutation["path"])
100
+ source = File.binread(file)
101
+ raise ArgumentError, "source changed before mutation testing" unless Digest::SHA256.hexdigest(source) == mutation["original_hash"]
102
+
103
+ source[mutation["start"]...mutation["end"]] = mutation["replacement"].b
104
+ File.binwrite(file, source)
105
+ end
106
+
107
+ def select_subjects(subjects, shard, total)
108
+ unless shard.is_a?(Integer) && total.is_a?(Integer) && total.positive? && (1..total).cover?(shard)
109
+ raise ArgumentError, "shard must be between 1 and total"
110
+ end
111
+ raise ArgumentError, "at least one subject is required" unless subjects.is_a?(Array) && !subjects.empty?
112
+ raise ArgumentError, "too many mutation subjects" if subjects.size > @settings["max_subjects"]
113
+ unless subjects.all? { |subject| valid_subject?(subject) }
114
+ raise ArgumentError, "invalid mutation subject"
115
+ end
116
+
117
+ subjects.uniq.sort.each_with_index.filter_map { |subject, index| subject if index % total == shard - 1 }
118
+ end
119
+
120
+ def valid_subject?(subject)
121
+ subject.is_a?(String) && !subject.empty? && !subject.start_with?("-") && !subject.match?(/[\s\x00]/)
122
+ end
123
+
124
+ def aggregate(subjects, results, baseline)
125
+ complete = results.all? { |result| %w[KILLED SURVIVED].include?(result["code"]) }
126
+ killed = complete ? results.count { |result| result["code"] == "KILLED" } : nil
127
+ survived = complete ? results.count { |result| result["code"] == "SURVIVED" } : nil
128
+ {"ok" => complete && survived.zero?, "engine" => "polyrun", "subjects" => subjects, "mutations" => results.size,
129
+ "killed" => killed, "survived" => survived, "baseline" => baseline, "results" => results}
130
+ end
131
+ end
132
+ end
133
+ end
@@ -0,0 +1,88 @@
1
+ require "prism"
2
+ require_relative "../graph/plan"
3
+
4
+ module Polyrun
5
+ module Mutation
6
+ module Subjects
7
+ module_function
8
+
9
+ def from_observation(path, max_bytes: 16_777_216)
10
+ raise ArgumentError, "observation is too large" if File.size(path) > max_bytes
11
+
12
+ observation = JSON.parse(File.read(path))
13
+ unless observation.is_a?(Hash) && observation["provenance"] == "observed" && observation["calls"].is_a?(Array)
14
+ raise ArgumentError, "invalid observation"
15
+ end
16
+ raise ArgumentError, "truncated observation requires explicit subjects" if observation["truncated"]
17
+ unless observation["calls"].all? { |row| row.is_a?(Hash) && row["subject"].is_a?(String) }
18
+ raise ArgumentError, "observation subjects must be strings"
19
+ end
20
+
21
+ observation["calls"].map { |row| row["subject"] }
22
+ end
23
+
24
+ def from_plan(root, id, settings: {})
25
+ plan = Graph::Plan.new(root, id, settings: settings)
26
+ plan.verify_originals!
27
+ plan.metadata.fetch("pre_hashes").keys.flat_map do |relative|
28
+ original = File.binread(File.join(root, relative))
29
+ staged = File.binread(File.join(plan.tree, relative))
30
+ next [] if original == staged
31
+
32
+ before = definitions(original)
33
+ after = definitions(staged)
34
+ (before.keys | after.keys).select { |subject| before[subject] != after[subject] }
35
+ end.uniq.sort
36
+ end
37
+
38
+ def definitions(source)
39
+ parsed = Prism.parse(source)
40
+ raise ArgumentError, "cannot select subjects from invalid Ruby" if parsed.failure?
41
+
42
+ result = {}
43
+ walk(parsed.value, [], false, result)
44
+ result
45
+ end
46
+
47
+ def walk(node, owners, singleton, result)
48
+ if node.is_a?(Prism::ClassNode) || node.is_a?(Prism::ModuleNode)
49
+ owners = scope_owners(node, owners)
50
+ singleton = false
51
+ elsif node.is_a?(Prism::SingletonClassNode)
52
+ raise ArgumentError, "only self singleton classes support subject selection" unless node.expression.is_a?(Prism::SelfNode)
53
+
54
+ singleton = true
55
+ elsif node.is_a?(Prism::DefNode)
56
+ add_definition(node, owners, singleton, result)
57
+ return
58
+ end
59
+ node.compact_child_nodes.each { |child| walk(child, owners, singleton, result) }
60
+ end
61
+
62
+ def scope_owners(node, owners)
63
+ name = node.constant_path.full_name
64
+ if !owners.empty? && name.include?("::") && !name.start_with?("::")
65
+ raise ArgumentError, "qualified nested owners require explicit mutation subjects"
66
+ end
67
+
68
+ name.start_with?("::") ? [name.delete_prefix("::")] : owners + [name]
69
+ rescue Prism::ConstantPathNode::DynamicPartsInConstantPathError
70
+ raise ArgumentError, "dynamic constant owners require explicit mutation subjects"
71
+ end
72
+
73
+ def add_definition(node, owners, singleton, result)
74
+ raise ArgumentError, "top-level methods require explicit mutation subjects" if owners.empty?
75
+ if node.receiver && !node.receiver.is_a?(Prism::SelfNode)
76
+ raise ArgumentError, "dynamic method owners require explicit mutation subjects"
77
+ end
78
+
79
+ separator = (singleton || node.receiver) ? "." : "#"
80
+ subject = "#{owners.join("::")}#{separator}#{node.name}"
81
+ raise ArgumentError, "redefined methods require explicit mutation subjects" if result.key?(subject)
82
+
83
+ result[subject] = node.location.slice
84
+ end
85
+ private_class_method :definitions, :walk, :scope_owners, :add_definition
86
+ end
87
+ end
88
+ end
@@ -0,0 +1,80 @@
1
+ require_relative "timing_keys"
2
+
3
+ module Polyrun
4
+ module Partition
5
+ # Hard constraints for plan assignment (spec_queue.md): pins, serial globs.
6
+ # Pins win over serial_glob. First matching pin glob wins.
7
+ class Constraints
8
+ attr_reader :pin_map, :serial_globs, :serial_shard
9
+
10
+ # @param pin_map [Hash{String=>Integer}] glob or exact path => shard index
11
+ # @param serial_globs [Array<String>] fnmatch patterns forced to +serial_shard+ (default 0) unless pinned
12
+ # @param root [String] project root for expanding relative paths
13
+ def initialize(pin_map: {}, serial_globs: [], serial_shard: 0, root: nil)
14
+ @pin_map = pin_map.transform_keys(&:to_s).transform_values { |v| Integer(v) }
15
+ @serial_globs = Array(serial_globs).map(&:to_s)
16
+ @serial_shard = Integer(serial_shard)
17
+ @root = root ? File.expand_path(root) : Dir.pwd
18
+ end
19
+
20
+ def self.from_hash(h, root: nil)
21
+ h = h.transform_keys(&:to_s) if h.is_a?(Hash)
22
+ return new(root: root) unless h.is_a?(Hash)
23
+
24
+ pins = h["pin"] || h["pins"] || {}
25
+ serial = h["serial_glob"] || h["serial_globs"] || []
26
+ serial_shard = h["serial_shard"] || 0
27
+ new(
28
+ pin_map: pins.is_a?(Hash) ? pins : {},
29
+ serial_globs: serial.is_a?(Array) ? serial : [],
30
+ serial_shard: serial_shard,
31
+ root: root
32
+ )
33
+ end
34
+
35
+ # Returns Integer shard index if constrained, or nil if free to place by LPT/HRW.
36
+ # For +path:line+ items (example granularity), also matches pins/globs against the file path only.
37
+ def forced_shard_for(path)
38
+ rel = path.to_s
39
+ abs = File.expand_path(rel, @root)
40
+ variants = [rel, abs]
41
+ if (fp = TimingKeys.file_part_for_constraint(rel))
42
+ variants << fp
43
+ variants << File.expand_path(fp, @root)
44
+ end
45
+ variants.uniq!
46
+
47
+ @pin_map.each do |pattern, shard|
48
+ next if pattern.to_s.empty?
49
+
50
+ variants.each do |rel_i|
51
+ abs_i = File.expand_path(rel_i, @root)
52
+ return shard if match_pattern?(pattern.to_s, rel_i, abs_i)
53
+ end
54
+ end
55
+
56
+ @serial_globs.each do |g|
57
+ variants.each do |rel_i|
58
+ abs_i = File.expand_path(rel_i, @root)
59
+ return @serial_shard if match_pattern?(g, rel_i, abs_i)
60
+ end
61
+ end
62
+
63
+ nil
64
+ end
65
+
66
+ def any?
67
+ @pin_map.any? || @serial_globs.any?
68
+ end
69
+
70
+ private
71
+
72
+ def match_pattern?(pattern, rel, abs)
73
+ p = pattern.to_s
74
+ File.fnmatch?(p, rel, File::FNM_PATHNAME | File::FNM_EXTGLOB) ||
75
+ File.fnmatch?(p, abs, File::FNM_PATHNAME | File::FNM_EXTGLOB) ||
76
+ p == rel || p == abs
77
+ end
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,70 @@
1
+ require "digest"
2
+
3
+ module Polyrun
4
+ module Partition
5
+ # Rendezvous / highest-hash shard assignment (spec_queue.md): stateless, stable when m changes.
6
+ module Hrw
7
+ module_function
8
+
9
+ # @return [Integer] shard index in 0...m
10
+ def shard_for(path:, total_shards:, seed: "")
11
+ pick_shard(path: path, total_shards: total_shards, seed: seed) { |p, j, salt| score(p, j, salt) }
12
+ end
13
+
14
+ # Per-shard weights (heterogeneous nodes). Uniform weights match +shard_for+.
15
+ def weighted_shard_for(path:, total_shards:, seed: "", shard_weights: nil)
16
+ weights = normalize_shard_weights(shard_weights, total_shards)
17
+ pick_shard(path: path, total_shards: total_shards, seed: seed) do |p, j, salt|
18
+ base = score(p, j, salt).to_f
19
+ w = weights[j]
20
+ w.positive? ? base / w : base
21
+ end
22
+ end
23
+
24
+ def normalize_shard_weights(shard_weights, total_shards)
25
+ m = Integer(total_shards)
26
+ return Array.new(m, 1.0) if shard_weights.nil? || shard_weights.empty?
27
+
28
+ weights = shard_weights.map { |w| w.to_f }
29
+ if weights.size < m
30
+ weights += Array.new(m - weights.size, 1.0)
31
+ elsif weights.size > m
32
+ weights = weights[0, m]
33
+ end
34
+ weights
35
+ end
36
+
37
+ def pick_shard(path:, total_shards:, seed:)
38
+ m = Integer(total_shards)
39
+ raise Polyrun::Error, "total_shards must be >= 1" if m < 1
40
+
41
+ best_j = 0
42
+ best = -1.0
43
+ salt = seed.to_s
44
+ p = path.to_s
45
+ m.times do |j|
46
+ h = yield(p, j, salt)
47
+ if h > best
48
+ best = h
49
+ best_j = j
50
+ end
51
+ end
52
+ best_j
53
+ end
54
+
55
+ def score(path, shard_index, salt)
56
+ digest = Digest::SHA256.digest("#{salt}\n#{path}\n#{shard_index}")
57
+ if fast_score?
58
+ digest.unpack1("Q>")
59
+ else
60
+ digest.unpack1("H*").hex
61
+ end
62
+ end
63
+
64
+ def fast_score?
65
+ %w[1 true yes].include?(ENV["POLYRUN_HRW_FAST_SCORE"]&.to_s&.downcase)
66
+ end
67
+ private_class_method :fast_score?
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,64 @@
1
+ module Polyrun
2
+ module Partition
3
+ # Binary min-heap of [load, shard_index] for LPT placement (tie-break: lower shard index).
4
+ class MinHeap
5
+ def initialize
6
+ @a = []
7
+ end
8
+
9
+ def push(load, shard_index)
10
+ @a << [load.to_f, Integer(shard_index)]
11
+ sift_up(@a.size - 1)
12
+ end
13
+
14
+ def pop_min
15
+ return nil if @a.empty?
16
+
17
+ min = @a[0]
18
+ last = @a.pop
19
+ @a[0] = last if @a.any?
20
+ sift_down(0) if @a.size > 1
21
+ min
22
+ end
23
+
24
+ def empty?
25
+ @a.empty?
26
+ end
27
+
28
+ private
29
+
30
+ def sift_up(i)
31
+ while i.positive?
32
+ p = (i - 1) / 2
33
+ break unless less(@a[i], @a[p])
34
+
35
+ @a[i], @a[p] = @a[p], @a[i]
36
+ i = p
37
+ end
38
+ end
39
+
40
+ def sift_down(i)
41
+ n = @a.size
42
+ loop do
43
+ l = 2 * i + 1
44
+ r = l + 1
45
+ smallest = i
46
+ smallest = l if l < n && less(@a[l], @a[smallest])
47
+ smallest = r if r < n && less(@a[r], @a[smallest])
48
+ break if smallest == i
49
+
50
+ @a[i], @a[smallest] = @a[smallest], @a[i]
51
+ i = smallest
52
+ end
53
+ end
54
+
55
+ # Compare [load, j]: lower load wins; tie -> lower j
56
+ def less(x, y)
57
+ return true if x[0] < y[0]
58
+ return false if x[0] > y[0]
59
+
60
+ x[1] < y[1]
61
+ end
62
+ end
63
+ end
64
+ end
@@ -0,0 +1,175 @@
1
+ module Polyrun
2
+ module Partition
3
+ # Shared spec path listing for run-shards, queue init, and plan helpers.
4
+ module Paths
5
+ SUS_CONFIG_REL = "config/sus.rb"
6
+ SUS_TEST_GLOB = "test/**/*.rb"
7
+
8
+ module_function
9
+
10
+ def read_lines(path)
11
+ File.read(File.expand_path(path.to_s, Dir.pwd)).split("\n").map(&:strip).reject(&:empty?)
12
+ end
13
+
14
+ # Prefer +spec/+ RSpec files, then Sus (+config/sus.rb+ + +test/**/*.rb+), then +test/+ Minitest,
15
+ # then Polyrun Quick files (same globs as +polyrun quick+).
16
+ def detect_auto_suite(cwd = Dir.pwd)
17
+ base = File.expand_path(cwd)
18
+ return :rspec if Dir.glob(File.join(base, "spec/**/*_spec.rb")).any?
19
+
20
+ sus = sus_test_paths(base)
21
+ return :sus if sus_configured?(base) && sus.any?
22
+
23
+ return :minitest if Dir.glob(File.join(base, "test/**/*_test.rb")).any?
24
+
25
+ quick = quick_parallel_default_paths(base)
26
+ return :quick if quick.any?
27
+
28
+ nil
29
+ end
30
+
31
+ # Infer parallel suite from explicit paths.
32
+ # Recognizes RSpec-style +path:line+ locators (strips a trailing numeric locator before classifying).
33
+ # Returns +:rspec+, +:minitest+, +:sus+, +:quick+, +:invalid+ (mixed families), or +nil+ (empty).
34
+ def infer_suite_from_paths(paths)
35
+ families = Array(paths).map { |p| suite_family_for_path(p) }.compact
36
+ return nil if families.empty?
37
+
38
+ uniq = families.uniq
39
+ return :invalid if uniq.size > 1
40
+
41
+ uniq.first
42
+ end
43
+
44
+ # When +paths_file+ is set but missing, returns +{ error: "..." }+.
45
+ # Otherwise returns +{ items:, source: }+ (human-readable source label).
46
+ #
47
+ # +partition.suite+ (optional): +auto+ (default), +rspec+, +minitest+, +sus+, +quick+ — used when resolving
48
+ # from globs. Legacy +spec/spec_paths.txt+ is used only for +auto+/+rspec+ (RSpec-oriented); an
49
+ # explicit +minitest+/+sus+/+quick+ suite skips it and globs instead. Bare +polyrun+ suite selection is
50
+ # {Suite.resolve_default} (explicit suite → paths_file inference → {detect_auto_suite}).
51
+ def resolve_run_shard_items(paths_file: nil, cwd: Dir.pwd, partition: {})
52
+ if paths_file
53
+ abs = File.expand_path(paths_file.to_s, cwd)
54
+ unless File.file?(abs)
55
+ return {error: "paths file not found: #{abs}"}
56
+ end
57
+ {items: read_lines(abs), source: paths_file.to_s}
58
+ elsif use_legacy_spec_paths?(cwd, partition)
59
+ {items: read_lines(File.join(cwd, "spec", "spec_paths.txt")), source: "spec/spec_paths.txt"}
60
+ else
61
+ resolve_run_shard_items_glob(cwd: cwd, partition: partition)
62
+ end
63
+ end
64
+
65
+ def resolve_run_shard_items_glob(cwd:, partition: {})
66
+ suite = partition_suite_name(partition)
67
+ catalogs = shard_path_catalogs(File.expand_path(cwd))
68
+ case suite
69
+ when "rspec", "minitest", "sus", "quick"
70
+ resolve_named_suite_items(suite, catalogs)
71
+ when "auto"
72
+ resolve_auto_suite_items(catalogs)
73
+ else
74
+ {error: "unknown partition.suite: #{suite.inspect} (expected auto, rspec, minitest, sus, quick)"}
75
+ end
76
+ end
77
+
78
+ def partition_suite_name(partition)
79
+ suite = (partition["suite"] || partition[:suite] || "auto").to_s.downcase
80
+ suite.empty? ? "auto" : suite
81
+ end
82
+ private_class_method :partition_suite_name
83
+
84
+ def shard_path_catalogs(base)
85
+ {
86
+ base: base,
87
+ spec: Dir.glob(File.join(base, "spec/**/*_spec.rb")).sort,
88
+ test: Dir.glob(File.join(base, "test/**/*_test.rb")).sort,
89
+ sus: sus_test_paths(base),
90
+ quick: quick_parallel_default_paths(base)
91
+ }
92
+ end
93
+ private_class_method :shard_path_catalogs
94
+
95
+ def resolve_named_suite_items(suite, catalogs)
96
+ case suite
97
+ when "rspec"
98
+ return {error: "partition.suite is rspec but no spec/**/*_spec.rb files"} if catalogs[:spec].empty?
99
+
100
+ {items: catalogs[:spec], source: "spec/**/*_spec.rb glob"}
101
+ when "minitest"
102
+ return {error: "partition.suite is minitest but no test/**/*_test.rb files"} if catalogs[:test].empty?
103
+
104
+ {items: catalogs[:test], source: "test/**/*_test.rb glob"}
105
+ when "sus"
106
+ return {error: "partition.suite is sus but no test/**/*.rb files"} if catalogs[:sus].empty?
107
+
108
+ {items: catalogs[:sus], source: "test/**/*.rb glob (sus)"}
109
+ else
110
+ return {error: "partition.suite is quick but no Polyrun quick files under spec/ or test/"} if catalogs[:quick].empty?
111
+
112
+ {items: catalogs[:quick], source: "Polyrun quick glob"}
113
+ end
114
+ end
115
+ private_class_method :resolve_named_suite_items
116
+
117
+ def resolve_auto_suite_items(catalogs)
118
+ if catalogs[:spec].any?
119
+ {items: catalogs[:spec], source: "spec/**/*_spec.rb glob"}
120
+ elsif sus_configured?(catalogs[:base]) && catalogs[:sus].any?
121
+ {items: catalogs[:sus], source: "test/**/*.rb glob (sus)"}
122
+ elsif catalogs[:test].any?
123
+ {items: catalogs[:test], source: "test/**/*_test.rb glob"}
124
+ elsif catalogs[:quick].any?
125
+ {items: catalogs[:quick], source: "Polyrun quick glob"}
126
+ else
127
+ {
128
+ error: "no spec paths (spec/spec_paths.txt, partition.paths_file, or spec/**/*_spec.rb); " \
129
+ "no Sus test/**/*.rb (with config/sus.rb); no test/**/*_test.rb; no Polyrun quick files"
130
+ }
131
+ end
132
+ end
133
+ private_class_method :resolve_auto_suite_items
134
+
135
+ def quick_parallel_default_paths(base)
136
+ require_relative "../quick/runner"
137
+ Polyrun::Quick::Runner.parallel_default_paths(base)
138
+ end
139
+
140
+ def sus_configured?(base)
141
+ File.file?(File.join(base, SUS_CONFIG_REL))
142
+ end
143
+
144
+ def sus_test_paths(base)
145
+ Dir.glob(File.join(base, SUS_TEST_GLOB)).sort
146
+ end
147
+
148
+ # Strip trailing numeric locators (+path:line+ or +path:line:column+), then expand.
149
+ def suite_classify_path(path)
150
+ raw = path.to_s.sub(/(?::\d+)+\z/, "")
151
+ File.expand_path(raw)
152
+ end
153
+ private_class_method :suite_classify_path
154
+
155
+ def suite_family_for_path(path)
156
+ abs = suite_classify_path(path)
157
+ base = File.basename(abs)
158
+ return :rspec if base.end_with?("_spec.rb")
159
+ return :minitest if base.end_with?("_test.rb")
160
+ return :quick if abs.include?("polyrun_quick")
161
+ return :sus if abs.match?(%r{(?:^|/)test/})
162
+
163
+ :quick
164
+ end
165
+ private_class_method :suite_family_for_path
166
+
167
+ def use_legacy_spec_paths?(cwd, partition)
168
+ return false unless File.file?(File.join(cwd, "spec", "spec_paths.txt"))
169
+
170
+ %w[auto rspec].include?(partition_suite_name(partition))
171
+ end
172
+ private_class_method :use_legacy_spec_paths?
173
+ end
174
+ end
175
+ end