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,120 @@
1
+ module Polyrun
2
+ module Partition
3
+ # Chooses the parallel runner suite for bare +polyrun+ and validates command vs path lists.
4
+ module Suite
5
+ ALLOWED = %w[auto rspec minitest sus quick].freeze
6
+
7
+ module_function
8
+
9
+ # Resolve suite for default CLI dispatch.
10
+ # Order: explicit +partition.suite+ (not auto) → infer from +paths_file+ → +detect_auto_suite+.
11
+ # Returns +{ suite: :rspec|:minitest|:sus|:quick }+ or +{ error: "..." }+.
12
+ def resolve_default(cwd: Dir.pwd, partition: {})
13
+ configured = configured_suite(partition)
14
+ return {error: "unknown partition.suite: #{configured.inspect} (expected auto, rspec, minitest, sus, quick)"} unless
15
+ ALLOWED.include?(configured)
16
+
17
+ inferred = infer_from_paths_file(cwd, partition)
18
+ return inferred if inferred.is_a?(Hash) && inferred[:error]
19
+
20
+ if configured != "auto"
21
+ suite = configured.to_sym
22
+ if inferred && inferred != suite
23
+ return {
24
+ error: "partition.suite is #{suite} but paths_file infers #{inferred} " \
25
+ "(fix partition.suite or the paths file)"
26
+ }
27
+ end
28
+ return {suite: suite}
29
+ end
30
+
31
+ return {suite: inferred} if inferred
32
+
33
+ auto = Paths.detect_auto_suite(cwd)
34
+ return {suite: auto} if auto
35
+
36
+ {
37
+ error: "no tests found (spec/**/*_spec.rb, Sus config/sus.rb + test/**/*.rb, " \
38
+ "test/**/*_test.rb, or Polyrun quick files). See polyrun help."
39
+ }
40
+ end
41
+
42
+ def infer_from_command(cmd)
43
+ tokens = Array(cmd).map(&:to_s)
44
+ return nil if tokens.empty?
45
+
46
+ return :rspec if tokens.any? { |t| File.basename(t) == "rspec" }
47
+ return :sus if tokens.any? { |t| %w[sus sus-parallel].include?(File.basename(t)) }
48
+ return :quick if tokens.include?("quick") && tokens.any? { |t| File.basename(t).include?("polyrun") }
49
+ return :minitest if minitest_command?(tokens)
50
+
51
+ nil
52
+ end
53
+
54
+ def command_mismatch_message(items, cmd)
55
+ path_suite = Paths.infer_suite_from_paths(Array(items))
56
+ cmd_suite = infer_from_command(cmd)
57
+
58
+ if path_suite == :invalid
59
+ return nil unless cmd_suite
60
+
61
+ return "mixing path families is not supported with a #{cmd_suite} command " \
62
+ "(use a suite-agnostic custom command, or split the path list)"
63
+ end
64
+
65
+ return nil if path_suite.nil?
66
+ return nil if cmd_suite.nil?
67
+ return nil if path_suite == cmd_suite
68
+
69
+ "paths infer #{path_suite} but command looks like #{cmd_suite} " \
70
+ "(use parallel-#{path_suite}, fix partition.paths_file, or pass a matching command after --)"
71
+ end
72
+
73
+ def configured_suite(partition)
74
+ suite = (partition["suite"] || partition[:suite] || "auto").to_s.downcase
75
+ suite.empty? ? "auto" : suite
76
+ end
77
+ private_class_method :configured_suite
78
+
79
+ def infer_from_paths_file(cwd, partition)
80
+ paths_file = partition["paths_file"] || partition[:paths_file]
81
+ return nil unless paths_file
82
+
83
+ abs = File.expand_path(paths_file.to_s, cwd)
84
+ return nil unless File.file?(abs)
85
+
86
+ items = Paths.read_lines(abs)
87
+ inferred = Paths.infer_suite_from_paths(items)
88
+ return {error: "paths_file mixes path families (not supported in one run)"} if inferred == :invalid
89
+
90
+ inferred
91
+ end
92
+ private_class_method :infer_from_paths_file
93
+
94
+ def minitest_command?(tokens)
95
+ return true if tokens.any? { |t| File.basename(t) == "rails" } && tokens.include?("test")
96
+ return true if ruby_with_test_load_path?(tokens)
97
+
98
+ false
99
+ end
100
+ private_class_method :minitest_command?
101
+
102
+ def ruby_with_test_load_path?(tokens)
103
+ tokens.each_with_index do |tok, i|
104
+ next unless File.basename(tok) == "ruby"
105
+
106
+ rest = tokens[(i + 1)..] || []
107
+ rest.each_with_index do |arg, j|
108
+ return true if arg == "-Itest"
109
+ return true if arg == "-I" && rest[j + 1] == "test"
110
+ next unless arg.start_with?("-I") && arg.length > 2
111
+
112
+ return true if arg[2..].split(/[=:]/).include?("test")
113
+ end
114
+ end
115
+ false
116
+ end
117
+ private_class_method :ruby_with_test_load_path?
118
+ end
119
+ end
120
+ end
@@ -0,0 +1,138 @@
1
+ require "set"
2
+
3
+ module Polyrun
4
+ module Partition
5
+ # Stale / missing timing coverage before cost-based partition.
6
+ module TimingDiagnostics
7
+ SUSPICIOUS_BASENAME = /system|feature|integration|playwright|capybara/i
8
+
9
+ module_function
10
+
11
+ # @return [Hash] analysis result with :missing_files, :stale_entries, :coverage, etc.
12
+ # rubocop:disable Metrics/AbcSize -- timing coverage scan
13
+ def analyze(items:, costs:, timing_path:, root:, granularity: :file)
14
+ root = File.expand_path(root || Dir.pwd)
15
+ g = TimingKeys.normalize_granularity(granularity)
16
+ item_keys = items.map { |p| lookup_key(p, root, g) }
17
+ cost_keys = costs&.keys || []
18
+
19
+ item_keys_set = item_keys.to_set
20
+ stale = cost_keys.reject { |k| item_keys_set.include?(k) }
21
+ if g == :example
22
+ cost_keys_set = cost_keys.to_set
23
+ cost_file_keys_set = cost_keys.map { |k| file_from_locator(k) }.uniq.to_set
24
+ known = item_keys.count do |ik|
25
+ cost_keys_set.include?(ik) || cost_file_keys_set.include?(file_from_locator(ik))
26
+ end
27
+ missing = item_keys.reject do |ik|
28
+ cost_keys_set.include?(ik) || cost_file_keys_set.include?(file_from_locator(ik))
29
+ end
30
+ else
31
+ known = item_keys.count { |k| costs&.key?(k) }
32
+ missing = item_keys.reject { |k| costs&.key?(k) }
33
+ end
34
+ total = item_keys.size
35
+
36
+ coverage = total.zero? ? 1.0 : known.to_f / total
37
+ default_weight = default_weight_for(costs)
38
+ suspicious = missing.select { |k| suspicious_path?(k) }
39
+
40
+ {
41
+ missing_files: missing,
42
+ stale_entries: stale,
43
+ coverage: coverage,
44
+ known_files: known,
45
+ total_files: total,
46
+ timing_file_age: timing_file_age(timing_path),
47
+ default_weight: default_weight,
48
+ suspicious_missing: suspicious
49
+ }
50
+ end
51
+ # rubocop:enable Metrics/AbcSize
52
+
53
+ # rubocop:disable Metrics/AbcSize -- stale/missing timing warnings
54
+ def emit_warnings!(analysis)
55
+ cov = analysis[:coverage]
56
+ if cov < 0.50
57
+ Polyrun::Log.warn "polyrun: timing coverage #{format_percent(cov)} — binpack quality low; run full timing capture first"
58
+ elsif cov < 0.80
59
+ Polyrun::Log.warn "polyrun: timing coverage #{format_percent(cov)} (< 80%)"
60
+ end
61
+
62
+ dw = analysis[:default_weight]
63
+ Polyrun::Log.warn "polyrun: default weight for missing files: #{format("%.4f", dw)}s (mean of known costs)"
64
+
65
+ if analysis[:timing_file_age]
66
+ Polyrun::Log.warn "polyrun: timing file age: #{analysis[:timing_file_age]}"
67
+ end
68
+
69
+ missing = analysis[:missing_files]
70
+ unless missing.empty?
71
+ Polyrun::Log.warn "polyrun: #{missing.size} file(s) without timing data"
72
+ missing.first(10).each { |p| Polyrun::Log.warn " missing: #{p}" }
73
+ Polyrun::Log.warn " ..." if missing.size > 10
74
+ end
75
+
76
+ stale = analysis[:stale_entries]
77
+ unless stale.empty?
78
+ Polyrun::Log.warn "polyrun: #{stale.size} timing entry(ies) for files not in suite"
79
+ stale.first(5).each { |p| Polyrun::Log.warn " stale: #{p}" }
80
+ Polyrun::Log.warn " ..." if stale.size > 5
81
+ end
82
+
83
+ suspicious = analysis[:suspicious_missing]
84
+ return if suspicious.empty?
85
+
86
+ Polyrun::Log.warn "polyrun: suspicious missing timing (#{suspicious.size} slow-path pattern(s)):"
87
+ suspicious.first(5).each { |p| Polyrun::Log.warn " suspicious: #{p}" }
88
+ end
89
+ # rubocop:enable Metrics/AbcSize
90
+
91
+ def lookup_key(path, root, granularity)
92
+ TimingKeys.normalize_locator(path.to_s, root, granularity)
93
+ end
94
+
95
+ def file_from_locator(key)
96
+ s = key.to_s
97
+ m = s.match(/\A(.+):(\d+)\z/)
98
+ m ? m[1] : s
99
+ end
100
+
101
+ def suspicious_path?(key)
102
+ base = File.basename(file_from_locator(key))
103
+ base.match?(SUSPICIOUS_BASENAME)
104
+ end
105
+
106
+ def default_weight_for(costs)
107
+ vals = costs&.values || []
108
+ return 1.0 if vals.empty?
109
+
110
+ vals.sum / vals.size.to_f
111
+ end
112
+
113
+ def timing_file_age(timing_path)
114
+ return nil unless timing_path
115
+
116
+ abs = File.expand_path(timing_path.to_s, Dir.pwd)
117
+ return nil unless File.file?(abs)
118
+
119
+ age_sec = Time.now - File.mtime(abs)
120
+ format_age(age_sec)
121
+ end
122
+
123
+ def format_age(sec)
124
+ if sec < 3600
125
+ format("%.0fm ago", sec / 60.0)
126
+ elsif sec < 86_400
127
+ format("%.1fh ago", sec / 3600.0)
128
+ else
129
+ format("%.1fd ago", sec / 86_400.0)
130
+ end
131
+ end
132
+
133
+ def format_percent(ratio)
134
+ format("%.1f%%", ratio * 100.0)
135
+ end
136
+ end
137
+ end
138
+ end
@@ -0,0 +1,86 @@
1
+ require "json"
2
+
3
+ require_relative "../log"
4
+ require_relative "../timing/stats"
5
+
6
+ module Polyrun
7
+ module Partition
8
+ # Normalizes partition item keys and timing JSON keys for +file+ vs experimental +example+ granularity.
9
+ #
10
+ # * +file+ — one item per spec file; keys are absolute paths (see {#canonical_file_path}).
11
+ # * +example+ — one item per example (RSpec-style +path:line+); keys are +"#{absolute_path}:#{line}+".
12
+ module TimingKeys
13
+ module_function
14
+
15
+ # Resolves the parent directory with +File.realpath+ so +/var/...+ and +/private/var/...+ (macOS
16
+ # tmpdirs) and symlink segments map to one key for the same file.
17
+ def canonical_file_path(abs_path)
18
+ dir = File.dirname(abs_path)
19
+ base = File.basename(abs_path)
20
+ File.join(File.realpath(dir), base)
21
+ rescue SystemCallError
22
+ abs_path
23
+ end
24
+
25
+ # @return [:file, :example]
26
+ def normalize_granularity(value)
27
+ case value.to_s.strip.downcase
28
+ when "example", "examples"
29
+ :example
30
+ else
31
+ :file
32
+ end
33
+ end
34
+
35
+ # File path only (for partition constraints) when +item+ is +path:line+.
36
+ def file_part_for_constraint(item)
37
+ s = item.to_s
38
+ m = s.match(/\A(.+):(\d+)\z/)
39
+ return nil unless m && m[2].match?(/\A\d+\z/)
40
+
41
+ m[1]
42
+ end
43
+
44
+ # Normalize a path or +path:line+ locator relative to +root+ for cost maps and +Plan+ items.
45
+ def normalize_locator(raw, root, granularity)
46
+ s = raw.to_s.strip
47
+ return canonical_file_path(File.expand_path(s, root)) if s.empty?
48
+
49
+ if granularity == :example && (m = s.match(/\A(.+):(\d+)\z/)) && m[2].match?(/\A\d+\z/)
50
+ fp = canonical_file_path(File.expand_path(m[1], root))
51
+ return "#{fp}:#{m[2]}"
52
+ end
53
+
54
+ canonical_file_path(File.expand_path(s, root))
55
+ end
56
+
57
+ # Loads merged timing JSON (+path => seconds+ or +path:line => seconds+).
58
+ #
59
+ # @param root [String, nil] directory for normalizing relative keys (default: +Dir.pwd+). Use the
60
+ # same working directory (or pass the same +root+ as {Partition::Plan}+'s +root+) as when
61
+ # generating the timing file so keys align.
62
+ def load_costs_json_file(path, granularity, root: nil)
63
+ abs = File.expand_path(path.to_s, Dir.pwd)
64
+ return {} unless File.file?(abs)
65
+
66
+ data = JSON.parse(File.read(abs))
67
+ return {} unless data.is_a?(Hash)
68
+
69
+ g = normalize_granularity(granularity)
70
+ root = File.expand_path(root || Dir.pwd)
71
+ out = {}
72
+ data.each do |k, v|
73
+ key = normalize_locator(k.to_s, root, g)
74
+ fv = Polyrun::Timing::Stats.binpack_weight(v)
75
+ if out.key?(key) && out[key] != fv
76
+ Polyrun::Log.warn(
77
+ "polyrun: timing JSON duplicate key #{key.inspect} after normalize (#{out[key]} vs #{fv}); using #{fv}"
78
+ )
79
+ end
80
+ out[key] = fv
81
+ end
82
+ out
83
+ end
84
+ end
85
+ end
86
+ end
@@ -0,0 +1,40 @@
1
+ require "digest/sha2"
2
+ require "json"
3
+
4
+ module Polyrun
5
+ module Prepare
6
+ # Writes +polyrun-artifacts.json+ (spec2 §3) for cache keys and CI upload lists.
7
+ module Artifacts
8
+ VERSION = 1
9
+
10
+ module_function
11
+
12
+ # +entries+ is array of hashes: { "path" => ..., "kind" => "file"|"directory", optional "digest", "size" }
13
+ def write!(root:, recipe:, entries:, dry_run: false)
14
+ list = entries.map { |e| normalize_entry(e) }
15
+ doc = {
16
+ "version" => VERSION,
17
+ "recipe" => recipe,
18
+ "dry_run" => dry_run,
19
+ "generated_at" => Time.now.utc.iso8601,
20
+ "artifacts" => list
21
+ }
22
+ path = File.join(root, "polyrun-artifacts.json")
23
+ File.write(path, JSON.pretty_generate(doc))
24
+ path
25
+ end
26
+
27
+ def normalize_entry(e)
28
+ h = e.transform_keys(&:to_s)
29
+ p = h["path"].to_s
30
+ kind = h["kind"] || (File.directory?(p) ? "directory" : "file")
31
+ out = {"path" => p, "kind" => kind}
32
+ if File.exist?(p)
33
+ out["size"] = File.size(p) if File.file?(p)
34
+ out["digest"] = h["digest"] || (File.file?(p) ? "sha256:#{Digest::SHA256.file(p).hexdigest}" : nil)
35
+ end
36
+ out.compact
37
+ end
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,64 @@
1
+ require "digest/md5"
2
+ require "fileutils"
3
+ require_relative "../process_stdio"
4
+
5
+ module Polyrun
6
+ module Prepare
7
+ # Asset digest and optional Rails +assets:precompile+, stdlib only.
8
+ module Assets
9
+ module_function
10
+
11
+ # Stable digest of a list of files (sorted). Directories are expanded to all files recursively.
12
+ def digest_sources(*paths)
13
+ files = []
14
+ paths.flatten.compact.each do |p|
15
+ next unless p
16
+
17
+ path = p.to_s
18
+ if File.directory?(path)
19
+ Dir.glob(File.join(path, "**", "*"), File::FNM_DOTMATCH).each do |f|
20
+ files << f if File.file?(f)
21
+ end
22
+ elsif File.file?(path)
23
+ files << path
24
+ end
25
+ end
26
+ files.sort!
27
+ combined = files.map { |f| "#{f}:#{Digest::MD5.file(f).hexdigest}" }.join("|")
28
+ Digest::MD5.hexdigest(combined)
29
+ end
30
+
31
+ # Writes digest to +marker_path+ if missing or content differs (caller runs compile when needed).
32
+ def stale?(marker_path, *digest_paths)
33
+ return true unless File.file?(marker_path)
34
+
35
+ File.read(marker_path).strip != digest_sources(*digest_paths)
36
+ end
37
+
38
+ def write_marker!(marker_path, *digest_paths)
39
+ FileUtils.mkdir_p(File.dirname(marker_path))
40
+ File.write(marker_path, digest_sources(*digest_paths))
41
+ end
42
+
43
+ # Shells out to +bin/rails assets:precompile+ when +rails_root+ contains +bin/rails+.
44
+ # +silent: true+ discards child stdio (+File::NULL+); +silent: false+ inherits the terminal.
45
+ def precompile!(rails_root:, silent: true)
46
+ exe = File.join(rails_root, "bin", "rails")
47
+ raise Polyrun::Error, "Prepare::Assets: no #{exe}" unless File.executable?(exe)
48
+
49
+ st, out, err = Polyrun::ProcessStdio.spawn_wait(
50
+ nil,
51
+ exe,
52
+ "assets:precompile",
53
+ chdir: rails_root,
54
+ silent: silent
55
+ )
56
+ unless st.success?
57
+ raise Polyrun::Error, Polyrun::ProcessStdio.format_failure_message("assets:precompile", st, out, err)
58
+ end
59
+
60
+ true
61
+ end
62
+ end
63
+ end
64
+ end
@@ -0,0 +1,96 @@
1
+ require "tempfile"
2
+
3
+ module Polyrun
4
+ # Run a subprocess without +Open3+ pipe reader threads (avoids noisy +IOError+s on SIGINT when
5
+ # streams close). By default stdin/stdout/stderr are inherited so output streams live and the
6
+ # child can use the TTY for prompts.
7
+ module ProcessStdio
8
+ MAX_FAILURE_CAPTURE_BYTES = 32_768
9
+
10
+ class << self
11
+ # @param env [Hash, nil] optional environment for the child (only forwarded when a Hash)
12
+ # @param argv [Array<String>] command argv
13
+ # @param silent [Boolean] if true, connect stdin/stdout/stderr to +File::NULL+ (no terminal output;
14
+ # non-interactive). Still no Open3 pipe threads.
15
+ # @return [Process::Status]
16
+ def inherit_stdio_spawn_wait(env, *argv, chdir: nil, silent: false)
17
+ st, = spawn_wait(env, *argv, chdir: chdir, silent: silent)
18
+ st
19
+ end
20
+
21
+ # Like {#inherit_stdio_spawn_wait}, but returns captured stdout/stderr when +silent+ is true.
22
+ # On success those strings are empty (not read). When +silent+ is false, output goes to the TTY
23
+ # and returned captures are empty.
24
+ #
25
+ # @return [Array(Process::Status, String, String)] status, stdout capture, stderr capture
26
+ def spawn_wait(env, *argv, chdir: nil, silent: false)
27
+ if chdir && RUBY_ENGINE == "jruby"
28
+ # JRuby's shell launch can continue after its chdir fails.
29
+ argv = ["/bin/sh", "-c", 'cd -- "$1" && shift && exec "$@"', "polyrun", chdir, *argv]
30
+ chdir = nil
31
+ end
32
+ args = spawn_argv(env, *argv)
33
+ return spawn_wait_inherit(args, chdir) unless silent
34
+
35
+ spawn_wait_silent(args, chdir)
36
+ end
37
+
38
+ # Builds a diagnostic string for failed subprocesses (used when +silent: true+ hid live output).
39
+ def format_failure_message(label, status, stdout, stderr)
40
+ msg = "#{label} failed (exit #{status.exitstatus})"
41
+ s = stdout.to_s
42
+ e = stderr.to_s
43
+ msg << "\n--- stdout ---\n#{s}" unless s.strip.empty?
44
+ msg << "\n--- stderr ---\n#{e}" unless e.strip.empty?
45
+ msg
46
+ end
47
+
48
+ private
49
+
50
+ def spawn_argv(env, *argv)
51
+ a = []
52
+ a << env if env.is_a?(Hash)
53
+ a.concat(argv)
54
+ a
55
+ end
56
+
57
+ def spawn_wait_inherit(args, chdir)
58
+ opts = {in: :in, out: :out, err: :err}
59
+ opts[:chdir] = chdir if chdir
60
+ pid = Process.spawn(*args, **opts)
61
+ st = Process.wait2(pid).last
62
+ [st, "", ""]
63
+ end
64
+
65
+ def spawn_wait_silent(args, chdir)
66
+ Tempfile.create("polyrun-out") do |tfout|
67
+ Tempfile.create("polyrun-err") do |tferr|
68
+ tfout.close
69
+ tferr.close
70
+ out_path = tfout.path
71
+ err_path = tferr.path
72
+ opts = {in: File::NULL, out: out_path, err: err_path}
73
+ opts[:chdir] = chdir if chdir
74
+ pid = Process.spawn(*args, **opts)
75
+ st = Process.wait2(pid).last
76
+ if st.success?
77
+ [st, "", ""]
78
+ else
79
+ [st, read_failure_capture(out_path), read_failure_capture(err_path)]
80
+ end
81
+ end
82
+ end
83
+ end
84
+
85
+ def read_failure_capture(path)
86
+ File.open(path, "rb") do |capture|
87
+ size = capture.size
88
+ return capture.read(MAX_FAILURE_CAPTURE_BYTES).to_s if size <= MAX_FAILURE_CAPTURE_BYTES
89
+
90
+ capture.seek(size - MAX_FAILURE_CAPTURE_BYTES)
91
+ "... (#{size} bytes total; showing last #{MAX_FAILURE_CAPTURE_BYTES} bytes)\n" + capture.read(MAX_FAILURE_CAPTURE_BYTES).to_s
92
+ end
93
+ end
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,84 @@
1
+ require "io/wait"
2
+
3
+ module Polyrun
4
+ module Quality
5
+ module Command
6
+ DEFAULT_OUTPUT_LIMIT = 1_048_576
7
+
8
+ module_function
9
+
10
+ # rubocop:disable Metrics/AbcSize -- keep descriptor ownership and process cleanup in the same scope
11
+ def call(argv, root:, timeout:, env: {}, max_output: DEFAULT_OUTPUT_LIMIT)
12
+ timeout = Float(timeout)
13
+ validate!(argv, timeout, max_output)
14
+
15
+ started = monotonic
16
+ streams = []
17
+ 2.times { streams << IO.pipe }
18
+ output = {"stdout" => +"".b, "stderr" => +"".b}
19
+ pid = Process.spawn(env, [argv.first, argv.first], *argv.drop(1), chdir: root, in: File::NULL, out: streams[0][1], err: streams[1][1], pgroup: true)
20
+ streams.each { |_, writer| writer.close }
21
+ code = collect(pid, streams.map(&:first), output, started + timeout, max_output)
22
+ output.each_value { |value| value.force_encoding(Encoding::UTF_8).scrub!("") }
23
+ output.merge("exitstatus" => code, "wall_s" => monotonic - started)
24
+ rescue Errno::ENOENT => e
25
+ {"stdout" => "", "stderr" => e.message, "exitstatus" => 127, "wall_s" => monotonic - started}
26
+ ensure
27
+ terminate(pid) if pid
28
+ streams&.flatten&.each { |stream| stream.close unless stream.closed? }
29
+ end
30
+ # rubocop:enable Metrics/AbcSize
31
+
32
+ def collect(pid, readers, output, deadline, limit)
33
+ active = readers.dup
34
+ status = nil
35
+ loop do
36
+ status ||= Process.waitpid2(pid, Process::WNOHANG)&.last
37
+ return status.exitstatus || 128 + status.termsig if status && active.empty?
38
+ return 124 if monotonic >= deadline
39
+
40
+ return 122 if drain(active, readers, output, deadline, limit)
41
+ end
42
+ end
43
+
44
+ def drain(active, readers, output, deadline, limit)
45
+ ready = IO.select(active, nil, nil, (deadline - monotonic).clamp(0.0001, 0.001))&.first || []
46
+ ready.each do |reader|
47
+ chunk = reader.read_nonblock(16_384, exception: false)
48
+ if chunk.nil?
49
+ active.delete(reader)
50
+ elsif chunk != :wait_readable
51
+ key = (reader == readers.first) ? "stdout" : "stderr"
52
+ remaining = limit - output.values.sum(&:bytesize)
53
+ output[key] << chunk.byteslice(0, remaining)
54
+ return true if chunk.bytesize > remaining
55
+ end
56
+ end
57
+ false
58
+ end
59
+
60
+ def validate!(argv, timeout, max_output)
61
+ raise ArgumentError, "timeout must be finite and positive" unless timeout.finite? && timeout.positive?
62
+ raise ArgumentError, "command must not be empty" unless argv.is_a?(Array) && !argv.empty?
63
+ raise ArgumentError, "output limit must be positive" unless max_output.is_a?(Integer) && max_output.positive?
64
+ end
65
+
66
+ def terminate(pid)
67
+ Process.kill("KILL", -pid)
68
+ rescue Errno::ESRCH
69
+ nil
70
+ ensure
71
+ begin
72
+ Process.waitpid(pid)
73
+ rescue Errno::ECHILD
74
+ nil
75
+ end
76
+ end
77
+
78
+ def monotonic
79
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
80
+ end
81
+ private_class_method :collect, :drain, :validate!, :terminate, :monotonic
82
+ end
83
+ end
84
+ end
@@ -0,0 +1,38 @@
1
+ require_relative "command"
2
+ require_relative "../benchmark/pressure/process_sample"
3
+
4
+ module Polyrun
5
+ module Quality
6
+ module Measure
7
+ module_function
8
+
9
+ def call(command, root:, timeout:, label:, ceilings: {}, max_output: Command::DEFAULT_OUTPUT_LIMIT)
10
+ validate_ceilings!(ceilings)
11
+ before = Process.times
12
+ result = Command.call(command, root: root, timeout: timeout, max_output: max_output)
13
+ metrics = process_metrics(before).merge("wall_s" => result["wall_s"])
14
+ failures = ceilings.keys.select { |key| !metrics[key].is_a?(Numeric) || metrics[key] > ceilings[key] }
15
+ result.merge("ok" => result["exitstatus"].zero? && failures.empty?, "label" => label, "metrics" => metrics,
16
+ "failures" => failures, "memory_probe_class" => "orchestrator_sample", "network" => "not_measured", "energy_proxy" => "cpu_seconds")
17
+ end
18
+
19
+ def process_metrics(before)
20
+ after = Process.times
21
+ rss = Benchmark::Pressure::ProcessSample.rss_bytes
22
+ {
23
+ "cpu_s" => after.utime + after.stime - before.utime - before.stime,
24
+ "child_cpu_s" => after.cutime + after.cstime - before.cutime - before.cstime,
25
+ "orchestrator_rss_bytes" => rss.positive? ? rss : nil
26
+ }
27
+ end
28
+
29
+ def validate_ceilings!(ceilings)
30
+ raise ArgumentError, "ceilings must be an object" unless ceilings.is_a?(Hash)
31
+ unless ceilings.values.all? { |value| value.is_a?(Numeric) && value.finite? && value >= 0 }
32
+ raise ArgumentError, "ceilings must be finite nonnegative numbers"
33
+ end
34
+ end
35
+ private_class_method :process_metrics, :validate_ceilings!
36
+ end
37
+ end
38
+ end