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,127 @@
1
+ require "json"
2
+ require "optparse"
3
+ require "shellwords"
4
+
5
+ require_relative "../queue/duration"
6
+ require_relative "../queue/worker_loop"
7
+
8
+ module Polyrun
9
+ class CLI
10
+ module RunQueueCommand
11
+ private
12
+
13
+ # rubocop:disable Metrics/AbcSize -- queue worker argv + spawn loop
14
+ def cmd_run_queue(argv, config_path)
15
+ dir = ".polyrun-queue"
16
+ batch = 5
17
+ on_failure = "exit"
18
+ paths_file = nil
19
+ workers = nil
20
+
21
+ sep = argv.index("--")
22
+ unless sep
23
+ Polyrun::Log.warn "polyrun run-queue: need -- before the command"
24
+ return 2
25
+ end
26
+
27
+ head = argv[0...sep]
28
+ cmd = argv[(sep + 1)..].map(&:to_s)
29
+ return 2 if cmd.empty?
30
+
31
+ cfg = Polyrun::Config.load(path: config_path || ENV["POLYRUN_CONFIG"])
32
+ pc = cfg.partition
33
+ ctx = plan_command_initial_context(pc)
34
+
35
+ OptionParser.new do |opts|
36
+ opts.banner = "usage: polyrun run-queue [--workers N] [--batch N] [--dir DIR] [--on-failure exit|requeue] [partition options] -- <command>"
37
+ opts.on("--workers N", Integer) { |v| workers = v }
38
+ opts.on("--batch N", Integer) { |v| batch = v }
39
+ opts.on("--dir PATH") { |v| dir = v }
40
+ opts.on("--paths-file PATH", String) { |v| paths_file = v }
41
+ opts.on("--on-failure MODE", "exit (default) or requeue") { |v| on_failure = v }
42
+ plan_command_register_partition_options!(opts, ctx)
43
+ end.parse!(head)
44
+
45
+ workers ||= Polyrun::Config::Resolver.parallel_worker_count(cfg)
46
+ unless workers.is_a?(Integer) && workers.between?(1, Polyrun::Config::MAX_PARALLEL_WORKERS)
47
+ Polyrun::Log.warn "polyrun run-queue: --workers must be between 1 and #{Polyrun::Config::MAX_PARALLEL_WORKERS}"
48
+ return 2
49
+ end
50
+ unless batch.is_a?(Integer) && batch >= 1
51
+ Polyrun::Log.warn "polyrun run-queue: --batch must be >= 1"
52
+ return 2
53
+ end
54
+ paths_file ||= pc["paths_file"] || pc[:paths_file]
55
+ unless paths_file
56
+ Polyrun::Log.warn "polyrun run-queue: need --paths-file or partition.paths_file"
57
+ return 2
58
+ end
59
+
60
+ code = Polyrun::Partition::PathsBuild.apply!(partition: pc, cwd: Dir.pwd)
61
+ return code if code != 0
62
+
63
+ store = Polyrun::Queue::FileStore.new(dir)
64
+ if File.file?(File.join(File.expand_path(dir), "queue.json"))
65
+ Polyrun::Log.warn "polyrun run-queue: queue already exists at #{dir}; remove it or use --dir"
66
+ return 2
67
+ end
68
+
69
+ ordered, code = queue_partition_manifest_and_ordered_paths(cfg, pc, ctx, paths_file)
70
+ return code if code != 0
71
+
72
+ store.init!(ordered)
73
+ Polyrun::Log.warn "polyrun run-queue: #{ordered.size} path(s), #{workers} worker(s), batch=#{batch}" if @verbose
74
+
75
+ run_t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
76
+ pids = run_queue_spawn_workers(store: store, workers: workers, batch: batch, cmd: cmd, on_failure: on_failure)
77
+ results = run_queue_wait_workers(pids, store: store, on_failure: on_failure)
78
+ wall = Process.clock_gettime(Process::CLOCK_MONOTONIC) - run_t0
79
+
80
+ stat = store.status(detailed: true)
81
+ Polyrun::Log.warn format(
82
+ "polyrun run-queue: done pending=%d done=%d leases=%d wall=%.1fs batches_ok=%d batches_fail=%d",
83
+ stat["pending"], stat["done"], stat["leases"], wall, results[:ok], results[:fail]
84
+ )
85
+
86
+ results[:fail].positive? ? 1 : 0
87
+ end
88
+ # rubocop:enable Metrics/AbcSize
89
+
90
+ def run_queue_spawn_workers(store:, workers:, batch:, cmd:, on_failure:)
91
+ pids = []
92
+ workers.times do |i|
93
+ wid = "worker-#{i}"
94
+ pid = Process.fork do
95
+ result = Polyrun::Queue::WorkerLoop.run(
96
+ store: store, worker_id: wid, batch: batch, cmd: cmd, on_failure: on_failure
97
+ )
98
+ # exit! skips parent at_exit hooks (Coverage finish, RSpec autorun) loaded in this process.
99
+ exit! result[:exit_code]
100
+ end
101
+ pids << {pid: pid, worker_id: wid}
102
+ end
103
+ pids
104
+ end
105
+
106
+ def run_queue_wait_workers(pids, store:, on_failure:)
107
+ ok = 0
108
+ fail = 0
109
+ pid_to_worker = pids.each_with_object({}) { |entry, h| h[entry[:pid]] = entry[:worker_id] }
110
+ while pid_to_worker.any?
111
+ pid, st = Process.wait2(-1)
112
+ worker_id = pid_to_worker.delete(pid)
113
+ next unless worker_id
114
+
115
+ if st.success?
116
+ ok += 1
117
+ else
118
+ fail += 1
119
+ reclaimed = store.reclaim!(worker_id: worker_id)
120
+ Polyrun::Log.warn "polyrun run-queue: reclaimed #{reclaimed} path(s) from #{worker_id}" if reclaimed.positive?
121
+ end
122
+ end
123
+ {ok: ok, fail: fail}
124
+ end
125
+ end
126
+ end
127
+ end
@@ -0,0 +1,164 @@
1
+ require "optparse"
2
+ require "rbconfig"
3
+
4
+ require_relative "start_bootstrap"
5
+ require_relative "failure_commands"
6
+ require_relative "spec_quality_commands"
7
+ require_relative "run_shards_run"
8
+
9
+ module Polyrun
10
+ class CLI
11
+ module RunShardsCommand
12
+ include StartBootstrap
13
+ include FailureCommands
14
+ include SpecQualityCommands
15
+ include RunShardsRun
16
+
17
+ private
18
+
19
+ # Default and upper bound for parallel OS processes (POLYRUN_WORKERS / --workers); see {Polyrun::Config}.
20
+
21
+ # Spawns N OS processes (not Ruby threads) with POLYRUN_SHARD_INDEX / POLYRUN_SHARD_TOTAL so
22
+ # {Coverage::Collector} writes coverage/polyrun-fragment-worker<N>.json (or shard<S>-worker<W>.json in N×M CI). Merge with merge-coverage.
23
+ def cmd_run_shards(argv, config_path)
24
+ run_shards_run!(argv, config_path)
25
+ end
26
+
27
+ # Same as run-shards with --merge-coverage; if you omit --, runs `bundle exec rspec`.
28
+ def cmd_parallel_rspec(argv, config_path)
29
+ sep = argv.index("--")
30
+ combined =
31
+ if sep
32
+ head = argv[0...sep]
33
+ tail = argv[sep..]
34
+ head + ["--merge-coverage"] + tail
35
+ else
36
+ argv + ["--merge-coverage", "--", "bundle", "exec", "rspec"]
37
+ end
38
+ Polyrun::Debug.log_kv(parallel_rspec: "combined argv", argv: combined)
39
+ cmd_run_shards(combined, config_path)
40
+ end
41
+
42
+ # Same as parallel-rspec but runs +bundle exec rails test+ or +bundle exec ruby -I test+ after +--+.
43
+ # Does not run +start+ prepare/database bootstrap (use +polyrun start+ or bare +polyrun+ for that).
44
+ def cmd_parallel_minitest(argv, config_path)
45
+ sep = argv.index("--")
46
+ combined =
47
+ if sep
48
+ head = argv[0...sep]
49
+ tail = argv[sep..]
50
+ head + ["--merge-coverage"] + tail
51
+ else
52
+ argv + ["--merge-coverage", "--"] + minitest_parallel_cmd
53
+ end
54
+ Polyrun::Debug.log_kv(parallel_minitest: "combined argv", argv: combined)
55
+ cmd_run_shards(combined, config_path)
56
+ end
57
+
58
+ # Same as parallel-rspec but runs +bundle exec polyrun quick+ after +--+ (one Quick process per shard).
59
+ # Run from the app root with +bundle exec+ so workers resolve the same gem as the parent (same concern as +bundle exec rspec+).
60
+ # Does not run +start+ prepare/database bootstrap (use +polyrun start+ or bare +polyrun+ for that).
61
+ def cmd_parallel_quick(argv, config_path)
62
+ sep = argv.index("--")
63
+ combined =
64
+ if sep
65
+ head = argv[0...sep]
66
+ tail = argv[sep..]
67
+ head + ["--merge-coverage"] + tail
68
+ else
69
+ argv + ["--merge-coverage", "--", "bundle", "exec", "polyrun", "quick"]
70
+ end
71
+ Polyrun::Debug.log_kv(parallel_quick: "combined argv", argv: combined)
72
+ cmd_run_shards(combined, config_path)
73
+ end
74
+
75
+ # Same as parallel-rspec but runs +bundle exec sus+ after +--+ (one Sus process per shard).
76
+ # Does not run +start+ prepare/database bootstrap (use +polyrun start+ or bare +polyrun+ for that).
77
+ # Prefer OS-process shards here when workers need isolated databases; Sus's own +sus-parallel+ is in-process threads.
78
+ def cmd_parallel_sus(argv, config_path)
79
+ sep = argv.index("--")
80
+ combined =
81
+ if sep
82
+ head = argv[0...sep]
83
+ tail = argv[sep..]
84
+ head + ["--merge-coverage"] + tail
85
+ else
86
+ argv + ["--merge-coverage", "--", "bundle", "exec", "sus"]
87
+ end
88
+ Polyrun::Debug.log_kv(parallel_sus: "combined argv", argv: combined)
89
+ cmd_run_shards(combined, config_path)
90
+ end
91
+
92
+ def minitest_parallel_cmd
93
+ rails_bin = File.expand_path("bin/rails", Dir.pwd)
94
+ if File.file?(rails_bin)
95
+ ["bundle", "exec", "rails", "test"]
96
+ else
97
+ ["bundle", "exec", "ruby", "-I", "test"]
98
+ end
99
+ end
100
+
101
+ # Convenience alias: optional legacy script/build_spec_paths.rb (if present and partition.paths_build unset), then parallel-rspec.
102
+ def cmd_start(argv, config_path)
103
+ cfg = Polyrun::Config.load(path: config_path || ENV["POLYRUN_CONFIG"])
104
+ code = start_bootstrap!(cfg, argv, config_path)
105
+ return code if code != 0
106
+
107
+ unless skip_build_spec_paths?
108
+ unless partition_paths_build?(cfg.partition)
109
+ build_script = File.expand_path("script/build_spec_paths.rb", Dir.pwd)
110
+ if File.file?(build_script)
111
+ ok = system({"RUBYOPT" => nil}, RbConfig.ruby, build_script)
112
+ return 1 unless ok
113
+ end
114
+ end
115
+ end
116
+ cmd_parallel_rspec(argv, config_path)
117
+ end
118
+
119
+ def partition_paths_build?(partition)
120
+ pb = partition["paths_build"] || partition[:paths_build]
121
+ pb.is_a?(Hash) && !pb.empty?
122
+ end
123
+
124
+ def skip_build_spec_paths?
125
+ v = ENV["POLYRUN_SKIP_BUILD_SPEC_PATHS"].to_s.downcase
126
+ %w[1 true yes].include?(v)
127
+ end
128
+
129
+ # ENV for a worker process: POLYRUN_SHARD_* plus per-shard database URLs from polyrun.yml or DATABASE_URL.
130
+ # When +matrix_total+ > 1 with multiple local workers, sets +POLYRUN_SHARD_MATRIX_INDEX+ / +POLYRUN_SHARD_MATRIX_TOTAL+
131
+ # so {Coverage::Collector} can name fragments uniquely across CI matrix jobs (NxM sharding).
132
+ # rubocop:disable Metrics/AbcSize -- shard ENV: matrix, DB URLs, fragment flags
133
+ def shard_child_env(cfg:, workers:, shard:, matrix_index: nil, matrix_total: nil, failure_fragments: false, spec_quality_fragments: false)
134
+ child_env = ENV.to_h.merge(
135
+ Polyrun::Database::Shard.env_map(shard_index: shard, shard_total: workers)
136
+ )
137
+ child_env["POLYRUN_FAILURE_FRAGMENTS"] = "1" if failure_fragments
138
+ child_env["POLYRUN_SPEC_QUALITY_FRAGMENTS"] = "1" if spec_quality_fragments
139
+ mt = matrix_total.nil? ? 0 : Integer(matrix_total)
140
+ if mt > 1
141
+ if matrix_index.nil?
142
+ Polyrun::Log.warn "polyrun run-shards: matrix_total=#{mt} but matrix_index is nil; omit POLYRUN_SHARD_MATRIX_*"
143
+ else
144
+ child_env["POLYRUN_SHARD_MATRIX_INDEX"] = Integer(matrix_index).to_s
145
+ child_env["POLYRUN_SHARD_MATRIX_TOTAL"] = mt.to_s
146
+ end
147
+ end
148
+ dh = cfg.databases
149
+ if dh.is_a?(Hash) && !dh.empty?
150
+ child_env.merge!(Polyrun::Database::UrlBuilder.env_exports_for_databases(dh, shard_index: shard))
151
+ elsif workers > 1 && (u = ENV["DATABASE_URL"]) && !u.to_s.strip.empty?
152
+ child_env["DATABASE_URL"] = Polyrun::Database::Shard.database_url_with_shard(u, shard)
153
+ end
154
+ child_env
155
+ end
156
+ # rubocop:enable Metrics/AbcSize
157
+
158
+ def cmd_build_paths(config_path)
159
+ cfg = Polyrun::Config.load(path: config_path || ENV["POLYRUN_CONFIG"])
160
+ Polyrun::Partition::PathsBuild.apply!(partition: cfg.partition, cwd: Dir.pwd)
161
+ end
162
+ end
163
+ end
164
+ end
@@ -0,0 +1,112 @@
1
+ require "fileutils"
2
+
3
+ require_relative "../worker_output"
4
+ require_relative "run_shards_parallel_wait"
5
+
6
+ module Polyrun
7
+ class CLI
8
+ # Spawns worker processes for +run-shards+ / +ci-shard-*+ fan-out. See {RunShardsParallelWait} for wait/timeout.
9
+ module RunShardsParallelChildren
10
+ include RunShardsParallelWait
11
+
12
+ private
13
+
14
+ # @return [Array(Array, Integer, nil)] +[pids, spawn_error_code]+; +spawn_error_code+ is +nil+ when all spawns succeeded
15
+ # rubocop:disable Metrics/AbcSize -- shard loop: spawn + shard hooks + env
16
+ def run_shards_spawn_workers(ctx, hook_cfg)
17
+ workers = ctx[:workers]
18
+ cmd = ctx[:cmd]
19
+ cfg = ctx[:cfg]
20
+ plan = ctx[:plan]
21
+ parallel = ctx[:parallel]
22
+ mx = ctx[:matrix_shard_index]
23
+ mt = ctx[:matrix_shard_total]
24
+
25
+ pids = []
26
+ Polyrun::WorkerOutput.prepare_log_dir! if Polyrun::WorkerOutput.routing_enabled?
27
+ begin
28
+ workers.times do |shard|
29
+ paths = plan.shard(shard)
30
+ if paths.empty?
31
+ Polyrun::Log.warn "polyrun run-shards: shard #{shard} skipped (no paths)" if @verbose || parallel
32
+ next
33
+ end
34
+
35
+ env_shard = ENV.to_h.merge(
36
+ "POLYRUN_HOOK_ORCHESTRATOR" => "1",
37
+ "POLYRUN_SHARD_INDEX" => shard.to_s,
38
+ "POLYRUN_SHARD_TOTAL" => workers.to_s
39
+ )
40
+ code = hook_cfg.run_phase_if_enabled(:before_shard, env_shard)
41
+ if code != 0
42
+ run_shards_terminate_children!(pids)
43
+ return [pids, code]
44
+ end
45
+
46
+ child_env = shard_child_env(
47
+ cfg: cfg,
48
+ workers: workers,
49
+ shard: shard,
50
+ matrix_index: mx,
51
+ matrix_total: mt,
52
+ failure_fragments: ctx[:merge_failures],
53
+ spec_quality_fragments: ctx[:merge_spec_quality]
54
+ )
55
+ child_env = child_env.merge("POLYRUN_HOOK_ORCHESTRATOR" => "0")
56
+ child_env = hook_cfg.merge_worker_ruby_env(child_env)
57
+
58
+ ping_path = run_shards_prepare_worker_ping!(ctx, child_env, shard)
59
+
60
+ Polyrun::Log.warn "polyrun run-shards: shard #{shard} → #{paths.size} file(s)" if @verbose
61
+ spawned_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
62
+ pid = run_shards_spawn_one_worker(child_env, cmd, paths, hook_cfg)
63
+ pids << {pid: pid, shard: shard, spawned_at: spawned_at, ping_path: ping_path}
64
+ Polyrun::Debug.log("[parent pid=#{$$}] run-shards: Process.spawn shard=#{shard} child_pid=#{pid} spec_files=#{paths.size}")
65
+ Polyrun::Log.warn "polyrun run-shards: started shard #{shard} pid=#{pid} (#{paths.size} file(s))" if parallel
66
+ if Polyrun::WorkerOutput.routing_enabled? && parallel
67
+ Polyrun::Log.warn "polyrun run-shards: shard #{shard} log → #{Polyrun::WorkerOutput.log_path_for(shard)}"
68
+ end
69
+ end
70
+ [pids, nil]
71
+ rescue StandardError, ScriptError => e
72
+ Polyrun::Log.warn "polyrun run-shards: spawn failed (#{e.class}: #{e.message}); stopping #{pids.size} worker(s)"
73
+ run_shards_terminate_children!(pids)
74
+ [pids, 1]
75
+ end
76
+ end
77
+ # rubocop:enable Metrics/AbcSize
78
+
79
+ def run_shards_prepare_worker_ping!(ctx, child_env, shard)
80
+ idle_sec = ctx[:worker_idle_timeout_sec]
81
+ idle_sec = nil if idle_sec.is_a?(Numeric) && idle_sec <= 0
82
+ return nil unless idle_sec
83
+
84
+ dir = File.join(Dir.pwd, "tmp", "polyrun")
85
+ FileUtils.mkdir_p(dir)
86
+ path = File.expand_path("worker-ping-#{$$}-#{shard}.txt", dir)
87
+ File.binwrite(path, "")
88
+ child_env["POLYRUN_WORKER_PING_FILE"] = path
89
+ interval = ENV["POLYRUN_WORKER_PING_INTERVAL_SEC"].to_s.strip
90
+ child_env["POLYRUN_WORKER_PING_INTERVAL_SEC"] = interval.empty? ? "15" : interval
91
+ path
92
+ end
93
+
94
+ # Workers start in their own process group so TERM/KILL can reach hook shell grandchildren.
95
+ def run_shards_spawn_one_worker(child_env, cmd, paths, hook_cfg)
96
+ return Polyrun::WorkerOutput.spawn_worker(child_env, cmd, paths, hook_cfg) if Polyrun::WorkerOutput.routing_enabled?
97
+
98
+ if hook_cfg.worker_hooks? && !Polyrun::Hooks.disabled?
99
+ Process.spawn(
100
+ child_env,
101
+ "sh",
102
+ "-c",
103
+ hook_cfg.build_worker_shell_script(cmd, paths),
104
+ pgroup: true
105
+ )
106
+ else
107
+ Process.spawn(child_env, *cmd, *paths, pgroup: true)
108
+ end
109
+ end
110
+ end
111
+ end
112
+ end
@@ -0,0 +1,252 @@
1
+ # rubocop:disable Polyrun/FileLength, Metrics/ModuleLength -- wait loop + idle/wall flush (kept out of spawn module)
2
+ module Polyrun
3
+ class CLI
4
+ # Wait, wall/idle timeout, and +after_shard+ hooks for parallel workers (+run-shards+ / +ci-shard-*+).
5
+ #
6
+ # Per-worker wait states: running → normal_exit | wall_timeout (124) | idle_timeout (125).
7
+ # When wall or idle caps are set, the multiplex loop polls every live PID each tick so timeouts
8
+ # apply fairly across shards (not only the worker currently in Process.wait).
9
+ module RunShardsParallelWait
10
+ WORKER_TIMEOUT_EXIT_STATUS = 124
11
+ WORKER_IDLE_TIMEOUT_EXIT_STATUS = 125
12
+
13
+ private
14
+
15
+ # @return [Array(Array, Integer)] +[shard_results, after_shard_hook_error_code]+ (0 when all +after_shard+ hooks passed)
16
+ # rubocop:disable Metrics/AbcSize -- wait loop + timeout flush
17
+ def run_shards_wait_all_children(pids, hook_cfg, ctx)
18
+ workers = ctx[:workers]
19
+ shard_results = []
20
+ after_hook_err = 0
21
+ timeout_sec = ctx[:worker_timeout_sec]
22
+ timeout_sec = nil if timeout_sec.is_a?(Numeric) && timeout_sec <= 0
23
+ idle_sec = ctx[:worker_idle_timeout_sec]
24
+ idle_sec = nil if idle_sec.is_a?(Numeric) && idle_sec <= 0
25
+
26
+ run_shards_with_interrupt_handlers do
27
+ Polyrun::Debug.time("Process.wait (#{pids.size} worker process(es))") do
28
+ if timeout_sec || idle_sec
29
+ run_shards_wait_all_children_multiplex(
30
+ pids, hook_cfg, ctx, workers, timeout_sec, idle_sec, shard_results, after_hook_err
31
+ )
32
+ else
33
+ run_shards_wait_all_children_sequential(pids, hook_cfg, workers, shard_results, after_hook_err)
34
+ end
35
+ end
36
+ rescue Interrupt
37
+ run_shards_shutdown_on_signal!(pids, 130)
38
+ rescue SignalException => e
39
+ raise unless e.signm == "SIGTERM"
40
+
41
+ run_shards_shutdown_on_signal!(pids, 143)
42
+ end
43
+ end
44
+ # rubocop:enable Metrics/AbcSize
45
+
46
+ def run_shards_wait_all_children_sequential(pids, hook_cfg, workers, shard_results, after_hook_err)
47
+ pids.each do |h|
48
+ Process.wait(h[:pid])
49
+ st = $?
50
+ after_hook_err = run_shards_finalize_reaped_worker!(h, hook_cfg, workers, st, shard_results, after_hook_err)
51
+ end
52
+ [shard_results, after_hook_err]
53
+ end
54
+
55
+ # Poll every live PID each tick so wall and idle timeouts apply to all workers, not only the first in wait order.
56
+ def run_shards_wait_all_children_multiplex(pids, hook_cfg, ctx, workers, timeout_sec, idle_sec, shard_results, after_hook_err)
57
+ pending = pids.dup
58
+
59
+ loop do
60
+ pending.delete_if do |h|
61
+ wpid = Process.wait(h[:pid], Process::WNOHANG)
62
+ next false unless wpid == h[:pid]
63
+
64
+ st = $?
65
+ after_hook_err = run_shards_finalize_reaped_worker!(h, hook_cfg, workers, st, shard_results, after_hook_err)
66
+ true
67
+ end
68
+
69
+ return [shard_results, after_hook_err] if pending.empty?
70
+
71
+ now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
72
+ violation = run_shards_timeout_violation(pending, ctx, now, timeout_sec, idle_sec)
73
+ if violation
74
+ reason, timed_h = violation
75
+ code = case reason
76
+ when :wall_timeout
77
+ run_shards_warn_worker_timeout!(timed_h, ctx, timeout_sec)
78
+ WORKER_TIMEOUT_EXIT_STATUS
79
+ when :idle_timeout
80
+ run_shards_warn_worker_idle!(timed_h, ctx, idle_sec)
81
+ WORKER_IDLE_TIMEOUT_EXIT_STATUS
82
+ end
83
+ return run_shards_wait_flush_after_timeout!(
84
+ timed_h, pending, hook_cfg, code, workers, shard_results, after_hook_err
85
+ )
86
+ end
87
+
88
+ delay = timeout_sec ? run_shards_wall_deadline(pending.first, ctx, timeout_sec) - now : 0.2
89
+ sleep([0.2, delay].min)
90
+ end
91
+ end
92
+
93
+ # @return [(Symbol, Hash), nil] e.g. +[:wall_timeout, h]+ when a limit is exceeded
94
+ def run_shards_timeout_violation(pending, ctx, now, timeout_sec, idle_sec)
95
+ # Polling removes completed workers in place, preserving spawn order.
96
+ first = pending.first
97
+ if timeout_sec && now >= run_shards_wall_deadline(first, ctx, timeout_sec)
98
+ return [:wall_timeout, first]
99
+ end
100
+ return unless idle_sec
101
+
102
+ pending.each do |h|
103
+ next unless h[:ping_path]
104
+
105
+ t, = run_shards_read_worker_ping_payload(h[:ping_path])
106
+ return [:idle_timeout, h] if t && (now - t) > idle_sec
107
+ end
108
+
109
+ nil
110
+ end
111
+
112
+ def run_shards_wall_deadline(worker, ctx, timeout_sec)
113
+ (worker[:spawned_at] || ctx[:run_t0]) + timeout_sec
114
+ end
115
+
116
+ def run_shards_finalize_reaped_worker!(h, hook_cfg, workers, st, shard_results, after_hook_err)
117
+ exitstatus = st.exitstatus || (128 + st.termsig)
118
+ Polyrun::Debug.log("[parent pid=#{$$}] run-shards: Process.wait child_pid=#{h[:pid]} shard=#{h[:shard]} exit=#{exitstatus} success=#{st.success?}")
119
+ run_shards_finalize_worker!(h, hook_cfg, workers, exitstatus, shard_results, after_hook_err)
120
+ end
121
+
122
+ def run_shards_finalize_worker!(h, hook_cfg, workers, exitstatus, shard_results, after_hook_err)
123
+ Polyrun::WorkerOutput.finish_worker(h[:pid])
124
+ run_shards_unlink_ping_path(h[:ping_path])
125
+ rc = run_shards_invoke_after_shard!(hook_cfg, h[:shard], workers, exitstatus)
126
+ shard_results << {shard: h[:shard], exitstatus: exitstatus, success: exitstatus == 0}
127
+ after_hook_err.zero? ? rc : after_hook_err
128
+ end
129
+
130
+ def run_shards_unlink_ping_path(path)
131
+ s = path.to_s.strip
132
+ return if s.empty?
133
+
134
+ File.unlink(s) if File.file?(s)
135
+ rescue SystemCallError
136
+ # best-effort cleanup of tmp/polyrun/worker-ping-*.txt
137
+ end
138
+
139
+ def run_shards_read_worker_ping_time(path)
140
+ run_shards_read_worker_ping_payload(path)[0]
141
+ end
142
+
143
+ # @return [Array(Float?, String?)] monotonic time and optional location line (path:line)
144
+ def run_shards_read_worker_ping_payload(path)
145
+ return [nil, nil] unless path && File.file?(path)
146
+
147
+ s = File.binread(path)
148
+ return [nil, nil] if s.nil? || s.strip.empty?
149
+
150
+ time_line, rest = s.split("\n", 2)
151
+ first = time_line.to_s.strip
152
+ return [nil, nil] if first.empty?
153
+
154
+ f = first.to_f
155
+ t = f.positive? ? f : nil
156
+ loc = rest.to_s.strip
157
+ loc = nil if loc.empty?
158
+ [t, loc]
159
+ rescue SystemCallError
160
+ [nil, nil]
161
+ end
162
+
163
+ def run_shards_wait_flush_after_timeout!(timed_h, pending, hook_cfg, code, workers, shard_results, after_hook_err)
164
+ run_shards_force_stop_pid_status(timed_h[:pid])
165
+ pending.delete(timed_h)
166
+ statuses = pending.map do |worker|
167
+ run_shards_wait_or_force_stop_status(worker[:pid])&.exitstatus || code
168
+ end
169
+ after_hook_err = run_shards_finalize_worker!(timed_h, hook_cfg, workers, code, shard_results, after_hook_err)
170
+ pending.zip(statuses).each do |worker, exitstatus|
171
+ after_hook_err = run_shards_finalize_worker!(worker, hook_cfg, workers, exitstatus, shard_results, after_hook_err)
172
+ end
173
+ [shard_results, after_hook_err]
174
+ end
175
+
176
+ def run_shards_invoke_after_shard!(hook_cfg, shard, workers, exitstatus)
177
+ env_after = ENV.to_h.merge(
178
+ "POLYRUN_HOOK_ORCHESTRATOR" => "1",
179
+ "POLYRUN_SHARD_INDEX" => shard.to_s,
180
+ "POLYRUN_SHARD_TOTAL" => workers.to_s,
181
+ "POLYRUN_WORKER_EXIT_STATUS" => exitstatus.to_s
182
+ )
183
+ hook_cfg.run_phase_if_enabled(:after_shard, env_after)
184
+ end
185
+
186
+ def run_shards_warn_worker_idle!(h, ctx, idle_sec)
187
+ paths = ctx[:plan].shard(h[:shard])
188
+ sample = paths.first(5).join(", ")
189
+ suffix =
190
+ if paths.empty?
191
+ " (no paths)"
192
+ elsif paths.size > 5
193
+ " (#{paths.size} files total)"
194
+ else
195
+ ""
196
+ end
197
+ _t, loc = run_shards_read_worker_ping_payload(h[:ping_path])
198
+ ping_suffix = (loc && !loc.to_s.strip.empty?) ? "; last ping #{loc.to_s.strip}" : ""
199
+ Polyrun::Log.orchestration_warn "polyrun run-shards: WORKER IDLE TIMEOUT after #{idle_sec}s since last per-example progress ping — shard #{h[:shard]} pid #{h[:pid]}#{ping_suffix}."
200
+ Polyrun::WorkerOutput.warn_shard_log(h[:shard])
201
+ Polyrun::Log.warn "polyrun run-shards: idle shard file sample: #{sample}#{suffix}"
202
+ Polyrun::Log.warn "polyrun run-shards: enable per-example worker progress pings in your test setup so idle timeouts reflect real work; exit #{WORKER_IDLE_TIMEOUT_EXIT_STATUS}."
203
+ end
204
+
205
+ def run_shards_wait_or_force_stop_status(pid)
206
+ wpid = Process.wait(pid, Process::WNOHANG)
207
+ return $? if wpid == pid
208
+
209
+ run_shards_force_stop_pid_status(pid)
210
+ rescue Errno::ECHILD
211
+ nil
212
+ end
213
+
214
+ def run_shards_force_stop_pid_status(pid)
215
+ run_shards_kill_process_group!(:KILL, pid)
216
+ st = nil
217
+ begin
218
+ Process.wait(pid)
219
+ st = $?
220
+ rescue Errno::ECHILD
221
+ # child already reaped
222
+ end
223
+ st
224
+ rescue Errno::ESRCH, Errno::EPERM
225
+ begin
226
+ Process.wait(pid)
227
+ $?
228
+ rescue Errno::ECHILD
229
+ nil
230
+ end
231
+ end
232
+
233
+ def run_shards_warn_worker_timeout!(h, ctx, timeout_sec)
234
+ paths = ctx[:plan].shard(h[:shard])
235
+ sample = paths.first(5).join(", ")
236
+ suffix =
237
+ if paths.empty?
238
+ " (no paths)"
239
+ elsif paths.size > 5
240
+ " (#{paths.size} files total)"
241
+ else
242
+ ""
243
+ end
244
+ Polyrun::Log.orchestration_warn "polyrun run-shards: WORKER TIMEOUT after #{timeout_sec}s (wall time since worker spawn) — shard #{h[:shard]} pid #{h[:pid]}."
245
+ Polyrun::WorkerOutput.warn_shard_log(h[:shard])
246
+ Polyrun::Log.warn "polyrun run-shards: timeout shard includes: #{sample}#{suffix}"
247
+ Polyrun::Log.warn "polyrun run-shards: override with --worker-timeout SEC or POLYRUN_WORKER_TIMEOUT_SEC; recorded exit #{WORKER_TIMEOUT_EXIT_STATUS} for this worker."
248
+ end
249
+ end
250
+ end
251
+ end
252
+ # rubocop:enable Polyrun/FileLength, Metrics/ModuleLength