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,128 @@
1
+ require "monitor"
2
+
3
+ require_relative "../log"
4
+
5
+ module Polyrun
6
+ class Hooks
7
+ # Ruby DSL for +hooks.ruby+ / +hooks.ruby_file+ in +polyrun.yml+ (see README).
8
+ #
9
+ # Example file (+config/polyrun_hooks.rb+):
10
+ #
11
+ # before(:suite) { |env| puts env["POLYRUN_HOOK_PHASE"] }
12
+ # after(:each) { |env| }
13
+ #
14
+ # Blocks receive a hash with string keys (same env as shell hooks).
15
+ module Dsl
16
+ class Registry
17
+ def initialize
18
+ @phases = Hash.new { |h, k| h[k] = [] }
19
+ end
20
+
21
+ def add(phase, proc)
22
+ @phases[phase.to_sym] << proc
23
+ end
24
+
25
+ # @param env [Hash] string-keyed env
26
+ def run(phase, env)
27
+ @phases[phase.to_sym].each { |pr| pr.call(env) }
28
+ end
29
+
30
+ def any?(phase)
31
+ @phases[phase.to_sym].any?
32
+ end
33
+
34
+ def empty?
35
+ @phases.values.all?(&:empty?)
36
+ end
37
+
38
+ def worker_hooks?
39
+ any?(:before_worker) || any?(:after_worker)
40
+ end
41
+ end
42
+
43
+ # Evaluates a hook file with +before+ / +after+ (+before(:suite)+, etc.).
44
+ class FileContext
45
+ def initialize(path)
46
+ @path = path
47
+ @registry = Registry.new
48
+ end
49
+
50
+ attr_reader :registry
51
+
52
+ def load_file
53
+ instance_eval(File.read(@path), @path)
54
+ @registry
55
+ end
56
+
57
+ def before(sym, &block)
58
+ @registry.add(map_before(sym), block)
59
+ end
60
+
61
+ def after(sym, &block)
62
+ @registry.add(map_after(sym), block)
63
+ end
64
+
65
+ private
66
+
67
+ def map_before(sym)
68
+ case sym.to_sym
69
+ when :suite then :before_suite
70
+ when :all then :before_shard
71
+ when :each then :before_worker
72
+ else
73
+ raise ArgumentError, "hooks DSL: before(#{sym.inspect}) — use :suite, :all, or :each"
74
+ end
75
+ end
76
+
77
+ def map_after(sym)
78
+ case sym.to_sym
79
+ when :suite then :after_suite
80
+ when :all then :after_shard
81
+ when :each then :after_worker
82
+ else
83
+ raise ArgumentError, "hooks DSL: after(#{sym.inspect}) — use :suite, :all, or :each"
84
+ end
85
+ end
86
+ end
87
+
88
+ # Load-time constant: `||=` can create two monitors.
89
+ CACHE_MU = Monitor.new
90
+ private_constant :CACHE_MU
91
+
92
+ class << self
93
+ # @return [Registry, nil]
94
+ def load_registry(path)
95
+ return nil if path.nil? || path.to_s.strip.empty?
96
+
97
+ full = File.expand_path(path.to_s, Dir.pwd)
98
+ return nil unless File.file?(full)
99
+
100
+ mtime = File.mtime(full)
101
+ CACHE_MU.synchronize do
102
+ hit = registry_cache[full]
103
+ return hit[:registry] if hit && hit[:mtime] == mtime
104
+
105
+ reg = FileContext.new(full).load_file
106
+ registry_cache[full] = {mtime: mtime, registry: reg}
107
+ reg
108
+ end
109
+ rescue => e
110
+ Polyrun::Log.warn "polyrun hooks: failed to load #{full}: #{e.class}: #{e.message}"
111
+ nil
112
+ end
113
+
114
+ def clear_cache!
115
+ CACHE_MU.synchronize { registry_cache.clear }
116
+ end
117
+
118
+ private
119
+
120
+ # rubocop:disable ThreadSafety/ClassInstanceVariable -- single-threaded hook load; Monitor protects cache
121
+ def registry_cache
122
+ @registry_cache ||= {}
123
+ end
124
+ # rubocop:enable ThreadSafety/ClassInstanceVariable
125
+ end
126
+ end
127
+ end
128
+ end
@@ -0,0 +1,33 @@
1
+ require "open3"
2
+
3
+ module Polyrun
4
+ class Hooks
5
+ # Runs shell hook commands; suppresses stdout/stderr on success unless verbose.
6
+ module ShellRunner
7
+ private
8
+
9
+ def run_shell_hook(cmd, merged)
10
+ if hook_shell_output_verbose?
11
+ ok = system(merged, "sh", "-c", cmd)
12
+ return [ok, $?.exitstatus]
13
+ end
14
+
15
+ stdout, stderr, status = Open3.capture3(merged, "sh", "-c", cmd)
16
+ unless status.success?
17
+ $stdout.print(stdout) unless stdout.empty?
18
+ $stderr.print(stderr) unless stderr.empty?
19
+ end
20
+ [status.success?, status.exitstatus]
21
+ rescue Interrupt
22
+ Polyrun::Log.warn "polyrun hooks: shell hook interrupted"
23
+ [false, 130]
24
+ end
25
+
26
+ def hook_shell_output_verbose?
27
+ Polyrun::Debug.enabled? ||
28
+ %w[1 true yes].include?(ENV["POLYRUN_VERBOSE"]&.to_s&.downcase) ||
29
+ %w[1 true yes].include?(ENV["POLYRUN_HOOKS_VERBOSE"]&.to_s&.downcase)
30
+ end
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,27 @@
1
+ require_relative "../log"
2
+
3
+ module Polyrun
4
+ class Hooks
5
+ # Invoked by worker shell wrapper (+ruby -e+). Requires +POLYRUN_HOOKS_RUBY_FILE+.
6
+ module WorkerRunner
7
+ module_function
8
+
9
+ # @return [Integer] exit code (0 on success)
10
+ def run!(phase)
11
+ phase = phase.to_sym
12
+ path = ENV["POLYRUN_HOOKS_RUBY_FILE"]
13
+ return 0 if path.nil? || path.empty?
14
+
15
+ registry = Dsl.load_registry(path)
16
+ return 0 if registry.nil? || !registry.any?(phase)
17
+
18
+ env = ENV.to_h
19
+ registry.run(phase, env)
20
+ 0
21
+ rescue => e
22
+ Polyrun::Log.warn "polyrun hooks worker #{phase}: #{e.class}: #{e.message}"
23
+ 1
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,50 @@
1
+ require "shellwords"
2
+ require "rbconfig"
3
+
4
+ module Polyrun
5
+ class Hooks
6
+ # Builds +sh -c+ script for worker processes (shell + Ruby +before_worker+ / +after_worker+).
7
+ module WorkerShell
8
+ # @param cmd [Array<String>] argv before paths
9
+ # @param paths [Array<String>]
10
+ # @return [String] shell script body for +sh -c+ (worker process)
11
+ # rubocop:disable Metrics/AbcSize -- shell + ruby worker hook branches
12
+ def build_worker_shell_script(cmd, paths)
13
+ main = Shellwords.join(cmd + paths)
14
+ rb = RbConfig.ruby
15
+ bw_shell = commands_for(:before_worker)
16
+ aw_shell = commands_for(:after_worker)
17
+ bw_ruby = ruby_registry&.any?(:before_worker)
18
+ aw_ruby = ruby_registry&.any?(:after_worker)
19
+
20
+ lines = []
21
+ lines << "export POLYRUN_HOOK_PHASE=before_worker"
22
+ if bw_ruby || bw_shell.any?
23
+ lines << "set -e"
24
+ lines << worker_ruby_line(rb, :before_worker) if bw_ruby
25
+ bw_shell.each { |c| lines << c }
26
+ end
27
+ lines << "set +e"
28
+ lines << main
29
+ lines << "ec=$?"
30
+ lines << "export POLYRUN_HOOK_PHASE=after_worker"
31
+ if aw_ruby || aw_shell.any?
32
+ lines << "set +e"
33
+ aw_shell.each { |c| lines << "( #{c} ) || true" }
34
+ lines << worker_ruby_line(rb, :after_worker, wrap_allow_fail: true) if aw_ruby
35
+ end
36
+ lines << "exit $ec"
37
+ lines.join("\n")
38
+ end
39
+ # rubocop:enable Metrics/AbcSize
40
+
41
+ private
42
+
43
+ def worker_ruby_line(rb_exe, phase, wrap_allow_fail: false)
44
+ code = %(require "polyrun"; Polyrun::Hooks::WorkerRunner.run!(:#{phase}))
45
+ line = "#{rb_exe} -e #{Shellwords.escape(code)}"
46
+ wrap_allow_fail ? "( #{line} ) || true" : line
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,190 @@
1
+ require "shellwords"
2
+
3
+ require_relative "log"
4
+ require_relative "hooks/dsl"
5
+ require_relative "hooks/shell_runner"
6
+ require_relative "hooks/worker_runner"
7
+ require_relative "hooks/worker_shell"
8
+
9
+ module Polyrun
10
+ # Shell and Ruby DSL hooks around parallel orchestration, named like RSpec lifecycle callbacks:
11
+ # +before_suite+ / +after_suite+ (+before(:suite)+ / +after(:suite)+),
12
+ # +before_shard+ / +after_shard+ (parent process, per partition index),
13
+ # +before_worker+ / +after_worker+ (inside each worker process, around the test command).
14
+ #
15
+ # Configure under +hooks:+ in +polyrun.yml+: shell strings, and/or +ruby:+ path to a Ruby DSL file.
16
+ # Run manually: +polyrun hook run <phase>+ (see {CLI}).
17
+ #
18
+ # Orchestration respects +POLYRUN_HOOKS_DISABLE=1+ (+run_phase_if_enabled+); +polyrun hook run+ always runs {#run_phase}.
19
+ class Hooks
20
+ include WorkerShell
21
+ include ShellRunner
22
+
23
+ PHASES = %i[
24
+ before_suite after_suite
25
+ before_shard after_shard
26
+ before_worker after_worker
27
+ ].freeze
28
+
29
+ attr_reader :ruby_file
30
+
31
+ def self.disabled?
32
+ v = ENV["POLYRUN_HOOKS_DISABLE"].to_s.downcase
33
+ %w[1 true yes].include?(v)
34
+ end
35
+
36
+ # When +POLYRUN_SHARD_TOTAL+ is greater than 1 (+ci-shard-run+ matrix), suite hooks are skipped by default; set
37
+ # +POLYRUN_HOOKS_SUITE_PER_MATRIX_JOB=1+ to run +before_suite+ / +after_suite+ on every matrix job (legacy).
38
+ def self.suite_per_matrix_job?
39
+ v = ENV["POLYRUN_HOOKS_SUITE_PER_MATRIX_JOB"].to_s.downcase
40
+ %w[1 true yes].include?(v)
41
+ end
42
+
43
+ def self.from_config(cfg)
44
+ raw = cfg.respond_to?(:hooks) ? cfg.hooks : {}
45
+ new(raw.is_a?(Hash) ? raw : {})
46
+ end
47
+
48
+ # Maps CLI or YAML-style names (+before_suite+, +"before(:suite)"+) to a phase symbol or +nil+.
49
+ def self.parse_phase(str)
50
+ new({}).send(:canonical_key, str)
51
+ end
52
+
53
+ # @param raw [Hash] +hooks+ block from YAML
54
+ def initialize(raw)
55
+ @ruby_file = extract_ruby_file(raw)
56
+ h = {}
57
+ raw.each do |k, v|
58
+ next if %w[ruby ruby_file].include?(k.to_s)
59
+
60
+ ck = canonical_key(k)
61
+ next if ck.nil?
62
+
63
+ h[ck] = v
64
+ end
65
+ @raw = h.freeze
66
+ @ruby_registry_loaded = false
67
+ @ruby_registry = nil
68
+ end
69
+
70
+ def empty?
71
+ no_shell = PHASES.all? { |p| commands_for(p).empty? }
72
+ return false unless no_shell
73
+
74
+ return true if @ruby_file.nil? || @ruby_file.to_s.strip.empty?
75
+ return true unless File.file?(File.expand_path(@ruby_file, Dir.pwd))
76
+
77
+ reg = ruby_registry
78
+ reg.nil? || reg.empty?
79
+ end
80
+
81
+ def worker_hooks?
82
+ return true if commands_for(:before_worker).any? || commands_for(:after_worker).any?
83
+
84
+ !!ruby_registry&.worker_hooks?
85
+ end
86
+
87
+ # Merges +POLYRUN_HOOKS_RUBY_FILE+ when a DSL file is configured (for worker +ruby -e+).
88
+ def merge_worker_ruby_env(env)
89
+ return env unless @ruby_file
90
+ abs = File.expand_path(@ruby_file, Dir.pwd)
91
+ return env unless File.file?(abs)
92
+
93
+ env.merge("POLYRUN_HOOKS_RUBY_FILE" => abs)
94
+ end
95
+
96
+ # @param phase [Symbol]
97
+ # @return [Array<String>]
98
+ def commands_for(phase)
99
+ v = @raw[phase.to_sym]
100
+ case v
101
+ when nil then []
102
+ when Array then v.map(&:to_s).map(&:strip).reject(&:empty?)
103
+ else
104
+ s = v.to_s.strip
105
+ s.empty? ? [] : [s]
106
+ end
107
+ end
108
+
109
+ # Runs Ruby DSL blocks (if any), then shell commands for +phase+.
110
+ # @return [Integer] exit code (0 if no commands)
111
+ def run_phase(phase, env)
112
+ return 0 unless PHASES.include?(phase.to_sym)
113
+
114
+ merged = stringify_env_for_hook(env).merge(
115
+ "POLYRUN_HOOK_PHASE" => phase.to_s,
116
+ "POLYRUN_HOOK" => "1"
117
+ )
118
+
119
+ reg = ruby_registry
120
+ if reg&.any?(phase)
121
+ begin
122
+ reg.run(phase, merged)
123
+ rescue Interrupt
124
+ Polyrun::Log.warn "polyrun hooks: #{phase} ruby hook interrupted"
125
+ return 130
126
+ rescue => e
127
+ Polyrun::Log.warn "polyrun hooks: #{phase} ruby hook failed: #{e.class}: #{e.message}"
128
+ return 1
129
+ end
130
+ end
131
+
132
+ commands_for(phase).each do |cmd|
133
+ ok, exitstatus = run_shell_hook(cmd, merged)
134
+ return exitstatus unless ok
135
+ end
136
+ 0
137
+ end
138
+
139
+ # Like {#run_phase}, but no-ops when {disabled?} (+POLYRUN_HOOKS_DISABLE=1+). Used by run-shards / ci-shard orchestration.
140
+ def run_phase_if_enabled(phase, env)
141
+ return 0 if self.class.disabled?
142
+
143
+ run_phase(phase, env)
144
+ end
145
+
146
+ private
147
+
148
+ def extract_ruby_file(raw)
149
+ v = raw["ruby"] || raw[:ruby] || raw["ruby_file"] || raw[:ruby_file]
150
+ return nil if v.nil?
151
+
152
+ s = v.to_s.strip
153
+ s.empty? ? nil : s
154
+ end
155
+
156
+ def ruby_registry
157
+ return @ruby_registry if @ruby_registry_loaded
158
+
159
+ @ruby_registry_loaded = true
160
+ @ruby_registry = Dsl.load_registry(@ruby_file)
161
+ end
162
+
163
+ def stringify_env_for_hook(env)
164
+ h = {}
165
+ env.each { |k, v| h[k.to_s] = v }
166
+ h
167
+ end
168
+
169
+ # Accept RSpec-style quoted keys from YAML, e.g. +"before(:suite)"+.
170
+ def canonical_key(k)
171
+ s = k.to_s.strip
172
+ sym = if s.match?(/\Abefore\(\s*:suite\s*\)\z/i)
173
+ :before_suite
174
+ elsif s.match?(/\Aafter\(\s*:suite\s*\)\z/i)
175
+ :after_suite
176
+ elsif s.match?(/\Abefore\(\s*:all\s*\)\z/i)
177
+ :before_shard
178
+ elsif s.match?(/\Aafter\(\s*:all\s*\)\z/i)
179
+ :after_shard
180
+ elsif s.match?(/\Abefore\(\s*:each\s*\)\z/i)
181
+ :before_worker
182
+ elsif s.match?(/\Aafter\(\s*:each\s*\)\z/i)
183
+ :after_worker
184
+ else
185
+ s.downcase.tr("-", "_").to_sym
186
+ end
187
+ PHASES.include?(sym) ? sym : nil
188
+ end
189
+ end
190
+ end
@@ -0,0 +1,86 @@
1
+ # rubocop:disable ThreadSafety/ClassAndModuleAttributes, ThreadSafety/ClassInstanceVariable -- process-global IO routing for CLI
2
+ module Polyrun
3
+ # Swappable sinks for CLI and library output. Defaults match +Kernel#warn+ (stderr) and +puts+/+print+ (stdout).
4
+ #
5
+ # Assign an IO, +StringIO+, Ruby +Logger+, or any object responding to +puts+, +write+, or +warn+ (Logger).
6
+ #
7
+ # Polyrun::Log.stderr = Logger.new($stderr)
8
+ # Polyrun::Log.stdout = StringIO.new
9
+ #
10
+ # Orchestration (+orchestration_warn+): worker timeout and SIGINT lines use the same sink as +warn+ unless
11
+ # +POLYRUN_ORCHESTRATION_STDERR=1+ and stderr is not process +$stderr+ (then the summary is copied to +$stderr+).
12
+ module Log
13
+ class << self
14
+ attr_writer :stderr
15
+ attr_writer :stdout
16
+
17
+ def stderr
18
+ @stderr || $stderr
19
+ end
20
+
21
+ def stdout
22
+ @stdout || $stdout
23
+ end
24
+
25
+ def warn(msg = nil)
26
+ return if msg.nil?
27
+
28
+ emit_line(stderr, msg)
29
+ end
30
+
31
+ # Like {#warn}, and when +POLYRUN_ORCHESTRATION_STDERR=1+ and {#stderr} is not the process +$stderr+,
32
+ # also writes one line to +$stderr+ so timeout/interrupt attribution survives custom/null Log sinks.
33
+ def orchestration_warn(msg)
34
+ warn(msg)
35
+ return unless %w[1 true yes].include?(ENV["POLYRUN_ORCHESTRATION_STDERR"]&.downcase)
36
+ return if stderr.equal?($stderr)
37
+
38
+ # Intentionally the real stderr stream (+Kernel#warn+ routes through +Log.stderr+).
39
+ # rubocop:disable Style/StderrPuts
40
+ $stderr.puts(msg.to_s.chomp)
41
+ # rubocop:enable Style/StderrPuts
42
+ end
43
+
44
+ def puts(msg = "")
45
+ if msg.nil?
46
+ stdout.write("\n")
47
+ else
48
+ emit_line(stdout, msg)
49
+ end
50
+ end
51
+
52
+ def print(msg = "")
53
+ io = stdout
54
+ if io.respond_to?(:write)
55
+ io.write(msg.to_s)
56
+ elsif io.respond_to?(:print)
57
+ io.print(msg.to_s)
58
+ end
59
+ end
60
+
61
+ # Clears custom sinks so +stderr+ / +stdout+ resolve to the current global +$stderr+ / +$stdout+ (e.g. after tests).
62
+ def reset_io!
63
+ @stderr = nil
64
+ @stdout = nil
65
+ end
66
+
67
+ private
68
+
69
+ def emit_line(io, msg)
70
+ s = msg.to_s
71
+ if logger_like?(io)
72
+ io.warn(s.chomp)
73
+ elsif io.respond_to?(:puts)
74
+ io.puts(s)
75
+ else
76
+ io.write(s.end_with?("\n") ? s : "#{s}\n")
77
+ end
78
+ end
79
+
80
+ def logger_like?(io)
81
+ io.respond_to?(:warn) && !io.is_a?(IO)
82
+ end
83
+ end
84
+ end
85
+ end
86
+ # rubocop:enable ThreadSafety/ClassAndModuleAttributes, ThreadSafety/ClassInstanceVariable
@@ -0,0 +1,60 @@
1
+ require_relative "../polyrun"
2
+
3
+ module Polyrun
4
+ # Optional Minitest-oriented wiring (require +polyrun/minitest_support+ explicitly).
5
+ #
6
+ # Does not load the +minitest+ gem. Call {install_parallel_provisioning!} from +test/test_helper.rb+
7
+ # after Rails / DB configuration (same timing as a direct call to
8
+ # {Data::ParallelProvisioning.run_suite_hooks!}).
9
+ module MinitestSupport
10
+ module WorkerPingTestHook
11
+ def setup
12
+ Polyrun::WorkerPing.ping!(location: polyrun_minitest_location)
13
+ super
14
+ end
15
+
16
+ def teardown
17
+ super
18
+ Polyrun::WorkerPing.ping!(location: polyrun_minitest_location)
19
+ end
20
+
21
+ private
22
+
23
+ def polyrun_minitest_location
24
+ file, line = method(name).source_location
25
+ (file && line) ? "#{file}:#{line}" : nil
26
+ rescue NameError
27
+ nil
28
+ end
29
+ end
30
+
31
+ module_function
32
+
33
+ # Runs {Data::ParallelProvisioning.run_suite_hooks!} (serial vs shard worker hooks).
34
+ def install_parallel_provisioning!
35
+ Polyrun::Data::ParallelProvisioning.run_suite_hooks!
36
+ end
37
+
38
+ # Same ping semantics as {RSpecSupport.install_worker_ping!}: +ping!+ at test +setup+ and +teardown+.
39
+ # Requires +minitest+ to be loaded first (+Minitest::Test+ defined).
40
+ def install_worker_ping!
41
+ require_relative "worker_ping"
42
+ unless defined?(::Minitest::Test)
43
+ Polyrun::Log.warn "polyrun minitest_support: install_worker_ping! skipped (load minitest/autorun or minitest/test first)"
44
+ return
45
+ end
46
+
47
+ ::Minitest::Test.send(:prepend, WorkerPingTestHook)
48
+ Polyrun::WorkerPing.ensure_interval_ping_thread!
49
+ end
50
+
51
+ # Per-test spec quality when +POLYRUN_SPEC_QUALITY=1+ (requires stdlib +Coverage+ for line deltas).
52
+ def install_spec_quality!(only_if: nil, root: nil, output_path: nil)
53
+ pred = only_if || -> { Polyrun::SpecQuality.enabled?(root: root || Dir.pwd) }
54
+ return unless pred.call
55
+
56
+ require_relative "spec_quality/minitest_hook"
57
+ Polyrun::SpecQuality::MinitestHook.install!(only_if: pred, root: root, output_path: output_path)
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,91 @@
1
+ require "prism"
2
+ require "digest"
3
+ require_relative "../graph/syntax"
4
+ require_relative "../graph/workspace"
5
+ require_relative "operators"
6
+
7
+ module Polyrun
8
+ module Mutation
9
+ class Candidates
10
+ def initialize(root, operators: nil, limit: nil, settings: {})
11
+ settings = Config::Tools.runtime("mutation", settings)
12
+ graph = settings.slice(*Config::ToolDefaults.for("graph").keys)
13
+ @workspace = Graph::Workspace.new(root, settings: graph)
14
+ @operators = operators || Operators.select(settings["operators"])
15
+ @limit = limit || settings["max_mutations"]
16
+ @count = 0
17
+ @seen = {}
18
+ end
19
+
20
+ def call(subjects)
21
+ inventory = source_inventory
22
+ subjects.flat_map do |subject|
23
+ matches = select_methods(inventory, subject)
24
+ matches.flat_map { |path, source, method| generate(path, source, method) }
25
+ end.uniq { |mutation| [mutation["path"], mutation["source_hash"]] }
26
+ end
27
+
28
+ private
29
+
30
+ def source_inventory
31
+ nodes = 0
32
+ @workspace.hashes.keys.map do |relative|
33
+ source = File.binread(@workspace.path(relative))
34
+ syntax = Graph::Syntax.new(relative, source, max_nodes: @workspace.settings["max_nodes"]).parse
35
+ nodes += syntax.methods.size + syntax.calls.size
36
+ raise ArgumentError, "mutation source exceeds configured node limit" if nodes > @workspace.settings["max_nodes"]
37
+
38
+ [relative, source, syntax.methods]
39
+ end
40
+ end
41
+
42
+ def select_methods(inventory, subject)
43
+ matches = inventory.flat_map { |path, source, methods| methods.filter_map { |method| [path, source, method] if match?(subject, method["subject"]) } }
44
+ raise ArgumentError, "unknown mutation subject: #{subject}" if matches.empty?
45
+ names = matches.map { |_, _, method| method["subject"] }
46
+ raise ArgumentError, "ambiguous mutation subject: #{subject}" unless names.uniq.length == names.length
47
+
48
+ matches
49
+ end
50
+
51
+ def match?(selector, subject)
52
+ subject && (selector == subject || (selector.include?("*") && File.fnmatch?(selector, subject)))
53
+ end
54
+
55
+ def generate(path, source, method)
56
+ parsed = Prism.parse(source)
57
+ nodes = [parsed.value]
58
+ edits = []
59
+ until nodes.empty?
60
+ node = nodes.pop
61
+ location = node.location
62
+ if location.start_offset >= method["byte_start"] && location.end_offset <= method["byte_end"]
63
+ @operators.each { |operator| edits.concat(operator.call(node)) }
64
+ end
65
+ nodes.concat(node.compact_child_nodes)
66
+ end
67
+ edits.filter_map do |location, replacement, operator|
68
+ next if source.byteslice(location.start_offset, location.length) == replacement
69
+
70
+ changed = source.byteslice(0, location.start_offset) + replacement.b + source.byteslice(location.end_offset..)
71
+ next if Prism.parse(changed).failure?
72
+
73
+ build_candidate(path, source, changed, method, location, replacement, operator)
74
+ end
75
+ end
76
+
77
+ def build_candidate(path, source, changed, method, location, replacement, operator)
78
+ digest = Digest::SHA256.hexdigest(changed)
79
+ return if @seen[[path, digest]]
80
+
81
+ @seen[[path, digest]] = true
82
+ @count += 1
83
+ raise ArgumentError, "mutation limit exceeded; narrow subjects or raise --max-mutations" if @count > @limit
84
+
85
+ {"id" => "mutation-#{Digest::SHA256.hexdigest(path + digest)[0, 24]}", "subject" => method["subject"],
86
+ "path" => path, "line" => location.start_line, "operator" => operator, "start" => location.start_offset,
87
+ "end" => location.end_offset, "replacement" => replacement, "original_hash" => Digest::SHA256.hexdigest(source), "source_hash" => digest}
88
+ end
89
+ end
90
+ end
91
+ end