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,141 @@
1
+ require "fileutils"
2
+ require "pathname"
3
+ require "set"
4
+
5
+ module Polyrun
6
+ module Partition
7
+ # Writes +partition.paths_file+ from +partition.paths_build+
8
+ module PathsBuild
9
+ module_function
10
+
11
+ # @return [Integer] 0 on success or skip, 2 on configuration error
12
+ def apply!(partition:, cwd: Dir.pwd)
13
+ return 0 if skip_paths_build?
14
+
15
+ pb = partition["paths_build"] || partition[:paths_build]
16
+ return 0 unless pb.is_a?(Hash) && !pb.empty?
17
+
18
+ paths_file = (partition["paths_file"] || partition[:paths_file] || "spec/spec_paths.txt").to_s
19
+ out_abs = File.expand_path(paths_file, cwd)
20
+ lines = build_ordered_paths(pb, cwd)
21
+ FileUtils.mkdir_p(File.dirname(out_abs))
22
+ File.write(out_abs, lines.join("\n") + "\n")
23
+ Polyrun::Log.warn "polyrun paths-build: wrote #{lines.size} path(s) → #{paths_file}"
24
+ 0
25
+ rescue Polyrun::Error => e
26
+ Polyrun::Log.warn "polyrun paths-build: #{e.message}"
27
+ 2
28
+ end
29
+
30
+ def skip_paths_build?
31
+ v = ENV["POLYRUN_SKIP_PATHS_BUILD"].to_s.downcase
32
+ %w[1 true yes].include?(v)
33
+ end
34
+
35
+ # Builds ordered path strings relative to +cwd+ (forward slashes).
36
+ def build_ordered_paths(pb, cwd)
37
+ pb = stringify_keys(pb)
38
+ all_glob = pb["all_glob"].to_s
39
+ all_glob = "spec/**/*_spec.rb" if all_glob.empty?
40
+
41
+ pool = glob_under_cwd(all_glob, cwd)
42
+ pool.uniq!
43
+ pool = reject_exclude_prefixes(pool, pb)
44
+ stages = Array(pb["stages"])
45
+ return sort_paths(pool) if stages.empty?
46
+
47
+ apply_stages_to_pool(stages, pool, cwd)
48
+ end
49
+
50
+ def reject_exclude_prefixes(pool, pb)
51
+ prefixes = Array(pb["exclude_prefixes"]).map(&:to_s).reject(&:empty?)
52
+ return pool if prefixes.empty?
53
+
54
+ pool.reject { |path| prefixes.any? { |prefix| path.start_with?(prefix) } }
55
+ end
56
+
57
+ def apply_stages_to_pool(stages, pool, cwd)
58
+ remaining = Set.new(pool)
59
+ out = []
60
+ stages.each do |raw|
61
+ st = stringify_keys(raw)
62
+ taken =
63
+ if st["glob"]
64
+ take_glob_paths(st, remaining)
65
+ elsif st["regex"]
66
+ take_regex_paths(st, remaining)
67
+ else
68
+ raise Polyrun::Error, 'paths_build stage needs "glob" or "regex"'
69
+ end
70
+ out.concat(taken)
71
+ remaining.subtract(taken)
72
+ end
73
+ out.concat(sort_paths(remaining.to_a))
74
+ out
75
+ end
76
+
77
+ def take_glob_paths(st, remaining)
78
+ pattern = st["glob"].to_s
79
+ taken = remaining.to_a.select { |p| path_matches_glob?(p, pattern) }
80
+ if st["sort_by_substring_order"]
81
+ subs = Array(st["sort_by_substring_order"]).map(&:to_s)
82
+ def_prio = int_or(st["default_priority"], int_or(st["default_sort_key"], 99))
83
+ taken.sort_by! { |p| [substring_priority(p, subs, def_prio), p] }
84
+ else
85
+ sort_paths!(taken)
86
+ end
87
+ taken
88
+ end
89
+
90
+ def take_regex_paths(st, remaining)
91
+ ic = st["ignore_case"]
92
+ ignore_case = ic == true || %w[1 true yes].include?(ic.to_s.downcase)
93
+ rx = Regexp.new(st["regex"].to_s, ignore_case ? Regexp::IGNORECASE : 0)
94
+ taken = remaining.to_a.select { |p| rx.match?(p) || rx.match?(File.basename(p)) }
95
+ sort_paths!(taken)
96
+ taken
97
+ end
98
+
99
+ def glob_under_cwd(pattern, cwd)
100
+ root = File.expand_path(cwd)
101
+ Dir.glob(File.join(root, pattern)).map { |p| normalize_rel(p, cwd) }
102
+ end
103
+
104
+ def path_matches_glob?(rel_path, pattern)
105
+ File.fnmatch?(pattern, rel_path, File::FNM_PATHNAME | File::FNM_EXTGLOB)
106
+ end
107
+
108
+ def normalize_rel(path, cwd)
109
+ abs = File.expand_path(path, cwd)
110
+ Pathname.new(abs).relative_path_from(Pathname.new(File.expand_path(cwd))).to_s.tr("\\", "/")
111
+ end
112
+
113
+ def sort_paths(paths)
114
+ paths.sort
115
+ end
116
+
117
+ def sort_paths!(paths)
118
+ paths.sort!
119
+ end
120
+
121
+ def substring_priority(path, substrings, default)
122
+ substrings.each_with_index do |s, i|
123
+ return i if path.include?(s)
124
+ end
125
+ default
126
+ end
127
+
128
+ def stringify_keys(h)
129
+ return {} unless h.is_a?(Hash)
130
+
131
+ h.each_with_object({}) { |(k, v), o| o[k.to_s] = v }
132
+ end
133
+
134
+ def int_or(v, fallback)
135
+ Integer(v)
136
+ rescue ArgumentError, TypeError
137
+ fallback
138
+ end
139
+ end
140
+ end
141
+ end
@@ -0,0 +1,250 @@
1
+ # rubocop:disable Polyrun/FileLength, Metrics/ClassLength -- partition strategies + constraints
2
+ require_relative "timing_keys"
3
+ require_relative "constraints"
4
+ require_relative "hrw"
5
+ require_relative "min_heap"
6
+ require_relative "stable_shuffle"
7
+ module Polyrun
8
+ module Partition
9
+ # Assigns discrete items (e.g. spec paths, or +path:line+ example locators) to shards (spec_queue.md).
10
+ #
11
+ # Strategies:
12
+ # - +round_robin+ — sorted paths, assign by index mod +total_shards+.
13
+ # - +random_round_robin+ — Fisher–Yates shuffle (optional +seed+), then same mod assignment.
14
+ # - +cost_binpack+ (+cost+, +binpack+, +timing+) — LPT greedy binpack using per-item weights;
15
+ # optional {Constraints} for pins / serial globs before LPT on the rest.
16
+ # Default +timing_granularity+ is +file+ (one weight per spec file). Experimental +:example+
17
+ # uses +path:line+ locators and per-example weights in the timing JSON.
18
+ # - +hrw+ (+rendezvous+) — rendezvous hashing for minimal remapping when m changes; optional constraints.
19
+ # - +weighted_hrw+ — rendezvous with per-shard weights (+shard_weights+); use +stable_cost_binpack+ for path costs.
20
+ # - +lazy_robin+ — sorted round-robin assignment with timing loaded for diagnostics and +shard_seconds+.
21
+ # - +preserve_order_round_robin+ — round-robin in paths-file order (no sort); membership from +paths_build+ only.
22
+ class Plan
23
+ COST_STRATEGIES = %w[cost cost_binpack binpack timing stable_cost_binpack].freeze
24
+ HRW_STRATEGIES = %w[hrw rendezvous weighted_hrw].freeze
25
+ LAZY_ROBIN_STRATEGIES = %w[lazy_robin].freeze
26
+ MOD_STRATEGIES = %w[round_robin random_round_robin lazy_robin preserve_order_round_robin].freeze
27
+
28
+ attr_reader :items, :total_shards, :strategy, :seed, :constraints, :timing_granularity, :root
29
+
30
+ def initialize(items:, total_shards:, strategy: "round_robin", seed: nil, costs: nil, constraints: nil, root: nil, timing_granularity: :file, stable_assignment: nil, stable_imbalance_threshold: 1.30, shard_weights: nil)
31
+ @timing_granularity = TimingKeys.normalize_granularity(timing_granularity)
32
+ @root = root ? File.expand_path(root) : Dir.pwd
33
+ @stable_assignment = normalize_stable_assignment(stable_assignment)
34
+ @stable_imbalance_threshold = stable_imbalance_threshold.to_f
35
+ @items = items.map do |x|
36
+ if @timing_granularity == :example
37
+ TimingKeys.normalize_locator(x, @root, :example)
38
+ else
39
+ x.to_s.strip
40
+ end
41
+ end.freeze
42
+ @total_shards = Integer(total_shards)
43
+ raise Polyrun::Error, "total_shards must be >= 1" if @total_shards < 1
44
+
45
+ @strategy = strategy.to_s
46
+ @seed = seed
47
+ @constraints = normalize_constraints(constraints)
48
+ @costs = normalize_costs(costs)
49
+ @shard_weights = shard_weights
50
+
51
+ validate_constraints_strategy_combo!
52
+ if cost_strategy? && (@costs.nil? || @costs.empty?)
53
+ raise Polyrun::Error,
54
+ "strategy #{@strategy} requires a timing map (path => seconds or path:line => seconds), e.g. merged polyrun_timing.json"
55
+ end
56
+ if lazy_robin_strategy? && (@costs.nil? || @costs.empty?)
57
+ raise Polyrun::Error,
58
+ "strategy lazy_robin requires a timing map (path => seconds), e.g. merged polyrun_timing.json"
59
+ end
60
+ end
61
+
62
+ def ordered_items
63
+ @ordered_items ||= case strategy
64
+ when "round_robin", "lazy_robin"
65
+ items.sort
66
+ when "preserve_order_round_robin"
67
+ items.dup
68
+ when "random_round_robin"
69
+ StableShuffle.call(items.sort, random_seed)
70
+ when "cost", "cost_binpack", "binpack", "timing"
71
+ items.sort
72
+ when "hrw", "rendezvous", "weighted_hrw"
73
+ items.sort
74
+ else
75
+ raise Polyrun::Error, "unknown partition strategy: #{strategy}"
76
+ end
77
+ end
78
+
79
+ def shard(shard_index)
80
+ idx = Integer(shard_index)
81
+ raise Polyrun::Error, "shard_index out of range" if idx < 0 || idx >= total_shards
82
+
83
+ if cost_strategy?
84
+ cost_shards[idx]
85
+ elsif hrw_strategy?
86
+ hrw_shards[idx]
87
+ else
88
+ mod_shards[idx]
89
+ end
90
+ end
91
+
92
+ def shard_weight_totals
93
+ if cost_strategy?
94
+ cost_shards.map { |paths| paths.sum { |p| weight_for(p) } }
95
+ elsif hrw_strategy?
96
+ hrw_shards.map { |paths| paths.sum { |p| weight_for_optional(p) } }
97
+ elsif lazy_robin_strategy? && @costs&.any?
98
+ mod_shards.map { |paths| paths.sum { |p| weight_for(p) } }
99
+ else
100
+ []
101
+ end
102
+ end
103
+
104
+ def file_weight(path)
105
+ (lazy_robin_strategy? || cost_strategy?) ? weight_for(path) : weight_for_optional(path)
106
+ end
107
+
108
+ def shard_file_weights(shard_index)
109
+ shard(shard_index).map { |p| [p, file_weight(p)] }.sort_by { |(_, w)| [-w, p] }
110
+ end
111
+
112
+ def default_weight
113
+ @default_weight ||= begin
114
+ vals = @costs&.values || []
115
+ vals.empty? ? 1.0 : vals.sum / vals.size
116
+ end
117
+ end
118
+
119
+ def stable_strategy?
120
+ strategy == "stable_cost_binpack"
121
+ end
122
+
123
+ attr_reader :stable_imbalance_threshold
124
+
125
+ def stable_assignment_map
126
+ @stable_assignment
127
+ end
128
+
129
+ def manifest(shard_index)
130
+ m = {
131
+ "shard_index" => Integer(shard_index),
132
+ "shard_total" => total_shards,
133
+ "strategy" => strategy,
134
+ "seed" => seed,
135
+ "paths" => shard(shard_index)
136
+ }
137
+ m["timing_granularity"] = timing_granularity.to_s if timing_granularity == :example
138
+ secs = shard_weight_totals
139
+ m["shard_seconds"] = secs if emit_shard_seconds?(secs)
140
+ m
141
+ end
142
+
143
+ def self.load_timing_costs(path, granularity: :file, root: nil)
144
+ TimingKeys.load_costs_json_file(path, granularity, root: root)
145
+ end
146
+
147
+ def self.cost_strategy?(name)
148
+ COST_STRATEGIES.include?(name.to_s)
149
+ end
150
+
151
+ def self.hrw_strategy?(name)
152
+ HRW_STRATEGIES.include?(name.to_s)
153
+ end
154
+
155
+ def self.lazy_robin_strategy?(name)
156
+ LAZY_ROBIN_STRATEGIES.include?(name.to_s)
157
+ end
158
+
159
+ def self.timing_load_strategy?(name)
160
+ cost_strategy?(name) || hrw_strategy?(name) || lazy_robin_strategy?(name)
161
+ end
162
+
163
+ private
164
+
165
+ def cost_strategy?
166
+ self.class.cost_strategy?(strategy)
167
+ end
168
+
169
+ def hrw_strategy?
170
+ self.class.hrw_strategy?(strategy)
171
+ end
172
+
173
+ def lazy_robin_strategy?
174
+ self.class.lazy_robin_strategy?(strategy)
175
+ end
176
+
177
+ def emit_shard_seconds?(secs)
178
+ return false if secs.empty?
179
+
180
+ cost_strategy? || lazy_robin_strategy? || (hrw_strategy? && secs.any? { |x| x > 0 })
181
+ end
182
+
183
+ def normalize_constraints(c)
184
+ return nil if c.nil?
185
+
186
+ c.is_a?(Constraints) ? c : Constraints.from_hash(c, root: @root)
187
+ end
188
+
189
+ def normalize_stable_assignment(map)
190
+ return nil if map.nil? || map.empty?
191
+
192
+ out = {}
193
+ map.each do |k, v|
194
+ out[TimingKeys.normalize_locator(k.to_s, @root, @timing_granularity)] = Integer(v)
195
+ end
196
+ out
197
+ end
198
+
199
+ def normalize_costs(costs)
200
+ return nil if costs.nil?
201
+
202
+ c = {}
203
+ costs.each do |k, v|
204
+ c[TimingKeys.normalize_locator(k.to_s, @root, @timing_granularity)] = v.to_f
205
+ end
206
+ c
207
+ end
208
+
209
+ def validate_constraints_strategy_combo!
210
+ return unless @constraints&.any?
211
+ return if cost_strategy? || hrw_strategy?
212
+
213
+ raise Polyrun::Error,
214
+ "partition constraints require strategy cost_binpack (with --timing) or hrw/rendezvous"
215
+ end
216
+
217
+ def weight_for(path)
218
+ key = cost_lookup_key(path.to_s)
219
+ return @costs[key] if @costs&.key?(key)
220
+
221
+ default_weight
222
+ end
223
+
224
+ def weight_for_optional(path)
225
+ key = cost_lookup_key(path.to_s)
226
+ return @costs[key] if @costs&.key?(key)
227
+
228
+ 0.0
229
+ end
230
+
231
+ def cost_lookup_key(path)
232
+ TimingKeys.normalize_locator(path, @root, @timing_granularity)
233
+ end
234
+
235
+ def cost_shards
236
+ @cost_shards ||= build_lpt_buckets
237
+ end
238
+
239
+ def build_lpt_buckets
240
+ PlanLptBuckets.new(self).build
241
+ end
242
+ end
243
+ end
244
+ end
245
+
246
+ require_relative "plan_sharding"
247
+ require_relative "plan_lpt"
248
+ require_relative "timing_diagnostics"
249
+ require_relative "reports"
250
+ # rubocop:enable Polyrun/FileLength, Metrics/ClassLength
@@ -0,0 +1,91 @@
1
+ require_relative "min_heap"
2
+
3
+ module Polyrun
4
+ module Partition
5
+ # LPT greedy binpack for cost strategies (extracted from {Plan} for size limits).
6
+ class PlanLptBuckets
7
+ def initialize(plan)
8
+ @plan = plan
9
+ end
10
+
11
+ def build
12
+ if @plan.stable_strategy? && @plan.stable_assignment_map&.any?
13
+ stable = build_from_stable_map
14
+ return stable if imbalance_ratio(stable) <= @plan.stable_imbalance_threshold
15
+ end
16
+
17
+ buckets = Array.new(@plan.total_shards) { [] }
18
+ totals = Array.new(@plan.total_shards, 0.0)
19
+ forced_pairs, free = partition_forced_and_free
20
+ lpt_apply_forced!(buckets, totals, forced_pairs)
21
+ lpt_balance_free!(buckets, totals, free)
22
+ buckets
23
+ end
24
+
25
+ def build_from_stable_map
26
+ buckets = Array.new(@plan.total_shards) { [] }
27
+ map = @plan.stable_assignment_map
28
+ @plan.items.each do |item|
29
+ key = @plan.send(:cost_lookup_key, item)
30
+ j = map[key]
31
+ j = Integer(j) if j
32
+ j = fallback_shard_for(item) unless j && j >= 0 && j < @plan.total_shards
33
+ buckets[j] << item
34
+ end
35
+ buckets
36
+ end
37
+
38
+ def fallback_shard_for(item)
39
+ Hrw.shard_for(path: item, total_shards: @plan.total_shards, seed: @plan.send(:hrw_salt))
40
+ end
41
+
42
+ def imbalance_ratio(buckets)
43
+ totals = buckets.map { |paths| paths.sum { |p| @plan.send(:weight_for, p) } }
44
+ return 1.0 if totals.empty?
45
+
46
+ avg = totals.sum / totals.size.to_f
47
+ return 1.0 unless avg.positive?
48
+
49
+ totals.max / avg
50
+ end
51
+
52
+ private
53
+
54
+ def partition_forced_and_free
55
+ forced_pairs = []
56
+ free = []
57
+ @plan.items.each do |item|
58
+ if @plan.constraints && (j = @plan.constraints.forced_shard_for(item))
59
+ forced_pairs << [item, Integer(j)]
60
+ else
61
+ free << item
62
+ end
63
+ end
64
+ [forced_pairs, free]
65
+ end
66
+
67
+ def lpt_apply_forced!(buckets, totals, forced_pairs)
68
+ forced_pairs.each do |item, j|
69
+ raise Polyrun::Error, "constraint shard #{j} out of range" if j < 0 || j >= @plan.total_shards
70
+
71
+ buckets[j] << item
72
+ totals[j] += @plan.send(:weight_for, item)
73
+ end
74
+ end
75
+
76
+ def lpt_balance_free!(buckets, totals, free)
77
+ pairs = free.map { |p| [p, @plan.send(:weight_for, p)] }
78
+ pairs.sort_by! { |(p, w)| [-w, p] }
79
+
80
+ heap = MinHeap.new
81
+ @plan.total_shards.times { |j| heap.push(totals[j], j) }
82
+
83
+ pairs.each do |path, w|
84
+ load, j = heap.pop_min
85
+ buckets[j] << path
86
+ heap.push(load + w, j)
87
+ end
88
+ end
89
+ end
90
+ end
91
+ end
@@ -0,0 +1,56 @@
1
+ require_relative "hrw"
2
+
3
+ module Polyrun
4
+ module Partition
5
+ class Plan
6
+ def hrw_shards
7
+ @hrw_shards ||= begin
8
+ buckets = Array.new(total_shards) { [] }
9
+ salt = hrw_salt
10
+ weighted = strategy == "weighted_hrw"
11
+ items.each do |path|
12
+ j =
13
+ if @constraints && (fj = @constraints.forced_shard_for(path))
14
+ Integer(fj)
15
+ elsif weighted
16
+ Hrw.weighted_shard_for(
17
+ path: path,
18
+ total_shards: total_shards,
19
+ seed: salt,
20
+ shard_weights: @shard_weights
21
+ )
22
+ else
23
+ Hrw.shard_for(path: path, total_shards: total_shards, seed: salt)
24
+ end
25
+ raise Polyrun::Error, "constraint shard out of range" if j < 0 || j >= total_shards
26
+
27
+ buckets[j] << path
28
+ end
29
+ buckets
30
+ end
31
+ end
32
+
33
+ # One pass over +ordered_items+ (round_robin / random_round_robin); avoids O(workers × n) rescans in +shard+.
34
+ def mod_shards
35
+ @mod_shards ||= begin
36
+ list = ordered_items
37
+ buckets = Array.new(total_shards) { [] }
38
+ list.each_with_index { |path, i| buckets[i % total_shards] << path }
39
+ buckets
40
+ end
41
+ end
42
+
43
+ def hrw_salt
44
+ s = seed
45
+ (s.nil? || s.to_s.empty?) ? "polyrun-hrw" : s.to_s
46
+ end
47
+
48
+ def random_seed
49
+ s = seed
50
+ return Integer(s) if s && s != ""
51
+
52
+ 0
53
+ end
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,139 @@
1
+ module Polyrun
2
+ module Partition
3
+ # Imbalance and dominant-file reports from {Plan} shard weights.
4
+ module Reports
5
+ IMBALANCE_WARN = 1.20
6
+ IMBALANCE_ATTENTION = 1.50
7
+ DOMINANT_SHARD_FRACTION = 0.40
8
+
9
+ module_function
10
+
11
+ def emit_all!(plan)
12
+ totals = plan.shard_weight_totals
13
+ return if totals.empty? || totals.all?(&:zero?)
14
+
15
+ emit_imbalance!(plan, totals)
16
+ emit_dominant_files!(plan, totals)
17
+ end
18
+
19
+ def imbalance_metrics(totals)
20
+ return nil if totals.empty?
21
+
22
+ max = totals.max
23
+ min = totals.min
24
+ avg = totals.sum / totals.size.to_f
25
+ ratio = avg.positive? ? max / avg : 1.0
26
+ slowest = totals.each_with_index.max_by { |v, _| v }&.last
27
+ {
28
+ max_shard_seconds: max,
29
+ min_shard_seconds: min,
30
+ avg_shard_seconds: avg,
31
+ imbalance_ratio: ratio,
32
+ slowest_shard: slowest
33
+ }
34
+ end
35
+
36
+ # rubocop:disable Metrics/AbcSize -- imbalance summary lines
37
+ def emit_imbalance!(plan, totals = nil)
38
+ totals ||= plan.shard_weight_totals
39
+ m = imbalance_metrics(totals)
40
+ return unless m
41
+
42
+ lines = []
43
+ lines << "polyrun partition imbalance:"
44
+ lines << format(
45
+ " max=%.2fs min=%.2fs avg=%.2fs imbalance_ratio=%.2f slowest_shard=%d",
46
+ m[:max_shard_seconds],
47
+ m[:min_shard_seconds],
48
+ m[:avg_shard_seconds],
49
+ m[:imbalance_ratio],
50
+ m[:slowest_shard]
51
+ )
52
+
53
+ slow_idx = m[:slowest_shard]
54
+ slow_paths = plan.shard(slow_idx)
55
+ slow_total = totals[slow_idx]
56
+ if slow_total.positive? && slow_paths.any?
57
+ top = plan.shard_file_weights(slow_idx).first
58
+ if top
59
+ _path, w = top
60
+ pct = (w / slow_total) * 100.0
61
+ lines << format(" largest_file_percent_of_shard=%.1f%%", pct)
62
+ if pct > DOMINANT_SHARD_FRACTION * 100.0
63
+ lines << " hint: single file dominates slowest shard; try --timing-granularity example or split the file"
64
+ end
65
+ end
66
+ end
67
+
68
+ plan.total_shards.times do |i|
69
+ top5 = plan.shard_file_weights(i).first(5)
70
+ next if top5.empty?
71
+
72
+ lines << " shard #{i} top files:"
73
+ top5.each do |path, w|
74
+ lines << format(" %.2fs %s", w, path)
75
+ end
76
+ end
77
+
78
+ if m[:imbalance_ratio] > IMBALANCE_ATTENTION
79
+ lines << " Attention required: slowest shard is #{format("%.2f", m[:imbalance_ratio])}x average"
80
+ elsif m[:imbalance_ratio] > IMBALANCE_WARN
81
+ lines << " Warning: imbalance_ratio > #{IMBALANCE_WARN}"
82
+ end
83
+
84
+ lines.each { |ln| Polyrun::Log.warn ln }
85
+ end
86
+ # rubocop:enable Metrics/AbcSize
87
+
88
+ def dominant_candidates(plan, totals = nil)
89
+ totals ||= plan.shard_weight_totals
90
+ return [] if totals.empty?
91
+
92
+ suite_total = totals.sum
93
+ return [] if suite_total <= 0
94
+
95
+ target = suite_total / plan.total_shards.to_f
96
+ slow_idx = totals.each_with_index.max_by { |v, _| v }&.last
97
+ slow_total = slow_idx ? totals[slow_idx] : 0.0
98
+
99
+ weights = file_weights_aggregated(plan)
100
+ weights.filter_map do |path, w|
101
+ next if w <= target
102
+
103
+ mult = w / target
104
+ reasons = []
105
+ reasons << "#{format("%.1f", mult)}x target shard time" if mult > 1.0
106
+ reasons << "split candidate" if slow_total.positive? && w > DOMINANT_SHARD_FRACTION * slow_total
107
+ {path: path, seconds: w, target: target, multiple: mult, reasons: reasons}
108
+ end.sort_by { |h| -h[:seconds] }
109
+ end
110
+
111
+ def emit_dominant_files!(plan, totals = nil)
112
+ candidates = dominant_candidates(plan, totals)
113
+ return if candidates.empty?
114
+
115
+ Polyrun::Log.warn "Attention:"
116
+ candidates.first(10).each do |c|
117
+ Polyrun::Log.warn format(" %s: %.1fs", c[:path], c[:seconds])
118
+ Polyrun::Log.warn format(" This single file is %.1fx the target shard time.", c[:multiple])
119
+ Polyrun::Log.warn " Try --timing-granularity example or split this file."
120
+ end
121
+ end
122
+
123
+ def file_weights_aggregated(plan)
124
+ by_file = Hash.new(0.0)
125
+ plan.items.each do |p|
126
+ w = plan.file_weight(p)
127
+ key =
128
+ if plan.timing_granularity == :example
129
+ TimingDiagnostics.file_from_locator(p.to_s)
130
+ else
131
+ p.to_s
132
+ end
133
+ by_file[key] += w
134
+ end
135
+ by_file
136
+ end
137
+ end
138
+ end
139
+ end
@@ -0,0 +1,18 @@
1
+ module Polyrun
2
+ module Partition
3
+ # Deterministic Fisher–Yates shuffle (spec_queue.md).
4
+ module StableShuffle
5
+ module_function
6
+
7
+ def call(items, seed)
8
+ rng = Random.new(Integer(seed))
9
+ a = items.dup
10
+ (a.size - 1).downto(1) do |i|
11
+ j = rng.rand(i + 1)
12
+ a[i], a[j] = a[j], a[i]
13
+ end
14
+ a
15
+ end
16
+ end
17
+ end
18
+ end