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,144 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require "json"
5
+ require "socket"
6
+ require_relative "pressure/process_sample"
7
+
8
+ module Polyrun
9
+ module Benchmark
10
+ # Process resource sampler for pressure / load benches.
11
+ #
12
+ # Measures wall time, CPU (user+system), RSS, GC / heap, optional storage and
13
+ # network byte counters. Callers raise load (N, threads, payload size) and lower
14
+ # resource targets after each successful round.
15
+ #
16
+ # Usage:
17
+ # result = Polyrun::Benchmark::Pressure.measure(label: "merge_disk", ops: 8) do
18
+ # merge_files(...)
19
+ # end
20
+ # Polyrun::Benchmark::Pressure.write_results!([result], repository_root: Dir.pwd)
21
+ module Pressure
22
+ module_function
23
+
24
+ DEFAULT_TARGET_FACTOR = 0.85
25
+
26
+ def sample
27
+ ProcessSample.sample
28
+ end
29
+
30
+ def diff(before, after_sample, extras: {})
31
+ ProcessSample.diff(before, after_sample, extras: extras)
32
+ end
33
+
34
+ def measure(label:, ops: nil, gc_start: true, extras: {})
35
+ GC.start if gc_start
36
+ before = sample
37
+ started = ProcessSample.monotonic_s
38
+ yield
39
+ wall_s = ProcessSample.monotonic_s - started
40
+ after_sample = sample
41
+ metrics = diff(before, after_sample, extras: extras)
42
+ metrics["wall_s"] = wall_s
43
+ metrics["cpu_pct"] = wall_s.positive? ? (metrics["cpu_s"] / wall_s) * 100.0 : 0.0
44
+ result = {
45
+ "label" => label.to_s,
46
+ "ops" => ops,
47
+ "ops_per_s" => (ops && wall_s.positive?) ? ops / wall_s : nil,
48
+ "metrics" => metrics,
49
+ "targets" => extras["targets"],
50
+ "pass" => targets_met?(metrics, extras["targets"])
51
+ }
52
+ result["report"] = format_report(result)
53
+ result
54
+ end
55
+
56
+ def targets_from(metrics, factor: DEFAULT_TARGET_FACTOR)
57
+ {
58
+ "wall_s" => metrics["wall_s"] * factor,
59
+ "cpu_s" => metrics["cpu_s"] * factor,
60
+ "rss_delta_bytes" => [metrics["rss_delta_bytes"] * factor, 0].max,
61
+ "heap_delta_bytes" => [metrics["heap_delta_bytes"] * factor, 0].max,
62
+ "storage_delta_bytes" => [metrics["storage_delta_bytes"] * factor, 0].max,
63
+ "network_in_bytes" => metrics["network_in_bytes"] * factor,
64
+ "network_out_bytes" => metrics["network_out_bytes"] * factor
65
+ }
66
+ end
67
+
68
+ def targets_met?(metrics, targets)
69
+ return nil if targets.nil? || targets.empty?
70
+
71
+ targets.all? do |key, limit|
72
+ next true if limit.nil?
73
+ next true unless metrics.key?(key)
74
+
75
+ metrics[key].to_f <= limit.to_f
76
+ end
77
+ end
78
+
79
+ def format_report(result)
80
+ m = result["metrics"]
81
+ parts = format_report_core(result, m)
82
+ append_format_report_extras!(parts, result, m)
83
+ parts.join(" | ")
84
+ end
85
+
86
+ def write_results!(results, repository_root: Dir.pwd, name: "load")
87
+ dir = File.join(repository_root, "benchmarks", "output")
88
+ FileUtils.mkdir_p(dir)
89
+ stamp = Time.now.utc.strftime("%Y%m%d%H%M%S")
90
+ path = File.join(dir, "#{stamp}_#{name}.json")
91
+ payload = {
92
+ "meta" => {
93
+ "recorded_at" => Time.now.utc.iso8601,
94
+ "ruby" => RUBY_VERSION,
95
+ "engine" => RUBY_ENGINE,
96
+ "platform" => RUBY_PLATFORM,
97
+ "polyrun_version" => defined?(Polyrun::VERSION) ? Polyrun::VERSION : nil,
98
+ "hostname" => Socket.gethostname
99
+ },
100
+ "results" => results
101
+ }
102
+ File.write(path, JSON.pretty_generate(payload))
103
+ path
104
+ end
105
+
106
+ def human_bytes(value)
107
+ n = value.to_f
108
+ units = %w[B KiB MiB GiB]
109
+ i = 0
110
+ while n.abs >= 1024.0 && i < units.length - 1
111
+ n /= 1024.0
112
+ i += 1
113
+ end
114
+ format("%.1f%s", n, units[i])
115
+ end
116
+
117
+ def format_report_core(result, metrics)
118
+ [
119
+ result["label"],
120
+ format("wall=%.4fs", metrics["wall_s"]),
121
+ format("cpu=%.4fs (%.0f%%)", metrics["cpu_s"], metrics["cpu_pct"]),
122
+ format("rss=%s (Δ%s)", human_bytes(metrics["rss_bytes"]), human_bytes(metrics["rss_delta_bytes"])),
123
+ format("heap_Δ=%s", human_bytes(metrics["heap_delta_bytes"])),
124
+ format("alloc=%d", metrics.dig("gc", "allocated_objects") || 0)
125
+ ]
126
+ end
127
+
128
+ def append_format_report_extras!(parts, result, metrics)
129
+ parts << format("ops/s=%.1f", result["ops_per_s"]) if result["ops_per_s"]
130
+ if metrics["storage_delta_bytes"].to_i != 0
131
+ parts << format("storage_Δ=%s", human_bytes(metrics["storage_delta_bytes"]))
132
+ end
133
+ net = metrics["network_in_bytes"].to_i + metrics["network_out_bytes"].to_i
134
+ parts << format("net=%s", human_bytes(net)) if net != 0
135
+ return if result["pass"].nil?
136
+
137
+ parts << (result["pass"] ? "PASS" : "FAIL targets")
138
+ end
139
+ private_class_method :format_report_core, :append_format_report_extras!
140
+ end
141
+ end
142
+ end
143
+
144
+ require_relative "pressure/cooker"
@@ -0,0 +1,191 @@
1
+ require "fileutils"
2
+ require "json"
3
+ require "open3"
4
+
5
+ module Polyrun
6
+ module Benchmark
7
+ # Records benchmark output during performance specs and writes profile artifacts.
8
+ # Set POLYRUN_BENCH=1 to echo lines to stdout. JSON sidecar enables report-benchmark exports.
9
+ module Profile
10
+ module_function
11
+
12
+ def reset!
13
+ lines_storage.clear
14
+ metrics_storage.clear
15
+ current_section_storage.replace(["default"])
16
+ end
17
+
18
+ def log(message = "")
19
+ line = message.to_s
20
+ lines_storage << line
21
+ section = detect_section_title(line) || current_section_storage.first
22
+ current_section_storage[0] = section if detect_section_title(line)
23
+ $stdout.puts(line) if verbose? && !line.empty?
24
+ line
25
+ end
26
+
27
+ def record_metric!(name:, value:, unit: "seconds", section: nil)
28
+ section_name = section || current_section_storage.first
29
+ metric = {
30
+ "section" => section_name.to_s,
31
+ "name" => name.to_s,
32
+ "value" => value,
33
+ "unit" => unit.to_s
34
+ }
35
+ metrics_storage << metric
36
+ log(format_metric_line(metric))
37
+ metric
38
+ end
39
+
40
+ def snapshot
41
+ {
42
+ "meta" => profile_meta,
43
+ "lines" => lines_storage.dup,
44
+ "metrics" => metrics_storage.dup
45
+ }
46
+ end
47
+
48
+ def write!(repository_root: default_repository_root)
49
+ data = snapshot
50
+ return if data["lines"].empty? && data["metrics"].empty?
51
+
52
+ log_path = output_path(repository_root: repository_root, extension: "log")
53
+ json_path = output_path(repository_root: repository_root, extension: "json")
54
+ FileUtils.mkdir_p(File.dirname(log_path))
55
+ File.write(log_path, profile_header(data["meta"]) + data["lines"].join("\n") + "\n")
56
+ File.write(json_path, JSON.pretty_generate(data))
57
+ export_sidecars!(data, json_path)
58
+ $stdout.puts("\nBenchmark profile written to #{log_path}") if verbose?
59
+ log_path
60
+ end
61
+
62
+ def export_sidecars!(data, json_path)
63
+ formats = export_formats
64
+ return if formats.empty?
65
+
66
+ require_relative "report"
67
+ base = json_path.sub(/\.json\z/, "")
68
+ formats.each do |format|
69
+ path = "#{base}.#{export_extension(format)}"
70
+ File.write(path, Report.render(data, format: format))
71
+ end
72
+ end
73
+
74
+ def export_formats
75
+ raw = ENV["POLYRUN_BENCH_FORMATS"]
76
+ return [] if raw.nil? || raw.to_s.strip.empty?
77
+
78
+ raw.split(",").map(&:strip).reject(&:empty?)
79
+ end
80
+
81
+ def export_extension(format)
82
+ case format.to_s.downcase
83
+ when "markdown", "md" then "md"
84
+ when "text", "console", "txt" then "txt"
85
+ else format.to_s.downcase
86
+ end
87
+ end
88
+
89
+ def verbose?
90
+ %w[1 true yes].include?(ENV["POLYRUN_BENCH"]&.to_s&.downcase)
91
+ end
92
+
93
+ def output_path(repository_root: default_repository_root, extension: "log", commit_sha: nil, working_tree_clean: nil, timestamp: nil)
94
+ commit_identifier = commit_sha || self.commit_sha(repository_root: repository_root)
95
+ clean_tree = working_tree_clean.nil? ? working_tree_clean?(repository_root: repository_root) : working_tree_clean
96
+ filename = if clean_tree
97
+ "profile_#{commit_identifier}.#{extension}"
98
+ else
99
+ recorded_at = timestamp || self.timestamp
100
+ "profile_#{commit_identifier}_#{recorded_at}.#{extension}"
101
+ end
102
+
103
+ File.join(repository_root, "tmp", "benchmarks", filename)
104
+ end
105
+
106
+ def profile_meta(repository_root: default_repository_root)
107
+ {
108
+ "commit" => commit_sha(repository_root: repository_root),
109
+ "recorded_at" => Time.now.utc.iso8601,
110
+ "working_tree_clean" => working_tree_clean?(repository_root: repository_root),
111
+ "ruby" => RUBY_VERSION,
112
+ "polyrun_version" => Polyrun::VERSION
113
+ }
114
+ end
115
+
116
+ def profile_header(meta)
117
+ [
118
+ "# Benchmark profile",
119
+ "# commit: #{meta["commit"]}",
120
+ "# recorded_at: #{meta["recorded_at"]}",
121
+ "# working_tree_clean: #{meta["working_tree_clean"]}",
122
+ "# ruby: #{meta["ruby"]}",
123
+ ""
124
+ ].join("\n")
125
+ end
126
+
127
+ def commit_sha(repository_root: default_repository_root)
128
+ git_command("git rev-parse HEAD", repository_root: repository_root) || "unknown"
129
+ end
130
+
131
+ def working_tree_clean?(repository_root: default_repository_root)
132
+ git_command("git status --porcelain", repository_root: repository_root).to_s.empty?
133
+ end
134
+
135
+ def timestamp
136
+ Time.now.utc.strftime("%Y%m%d%H%M%S")
137
+ end
138
+
139
+ def git_command(command, repository_root:)
140
+ stdout, status = Open3.capture2(command, chdir: repository_root)
141
+ return nil unless status.success?
142
+
143
+ stdout.strip
144
+ rescue
145
+ nil
146
+ end
147
+
148
+ def detect_section_title(line)
149
+ return unless line.is_a?(String)
150
+ return if line.strip.empty?
151
+ return if line.start_with?("#")
152
+ return unless line.end_with?(":")
153
+
154
+ line.strip.delete_suffix(":")
155
+ end
156
+
157
+ def format_metric_line(metric)
158
+ value = metric["value"]
159
+ unit = metric["unit"]
160
+ suffix = (unit == "seconds") ? "s" : " #{unit}"
161
+ format(" %s: %s%s", metric["name"], value, suffix)
162
+ end
163
+
164
+ STORAGE_KEY = :polyrun_benchmark_profile_storage
165
+
166
+ def storage
167
+ Thread.current[STORAGE_KEY] ||= {
168
+ "lines" => [],
169
+ "metrics" => [],
170
+ "current_section" => ["default"]
171
+ }
172
+ end
173
+
174
+ def lines_storage
175
+ storage["lines"]
176
+ end
177
+
178
+ def metrics_storage
179
+ storage["metrics"]
180
+ end
181
+
182
+ def current_section_storage
183
+ storage["current_section"]
184
+ end
185
+
186
+ def default_repository_root
187
+ Dir.pwd
188
+ end
189
+ end
190
+ end
191
+ end
@@ -0,0 +1,87 @@
1
+ require "json"
2
+
3
+ require_relative "../export/csv"
4
+ require_relative "../export/markdown"
5
+
6
+ module Polyrun
7
+ module Benchmark
8
+ # Formats benchmark profile JSON for humans and downstream tools.
9
+ module Report
10
+ METRIC_HEADERS = %w[section name value unit].freeze
11
+ LINE_HEADERS = %w[index text].freeze
12
+
13
+ module_function
14
+
15
+ def load(path)
16
+ ext = File.extname(path).downcase
17
+ if ext == ".json"
18
+ JSON.parse(File.read(path))
19
+ else
20
+ {"meta" => {}, "lines" => File.read(path).lines.map(&:chomp), "metrics" => []}
21
+ end
22
+ end
23
+
24
+ def render(data, format: "text")
25
+ case format.to_s.downcase
26
+ when "text", "console", "txt" then format_text(data)
27
+ when "json" then JSON.pretty_generate(data)
28
+ when "csv" then format_csv(data)
29
+ when "markdown", "md" then format_markdown(data)
30
+ else
31
+ raise Polyrun::Error, "report-benchmark: unknown format #{format.inspect} (use text, json, csv, or markdown)"
32
+ end
33
+ end
34
+
35
+ def format_text(data)
36
+ meta = data["meta"] || {}
37
+ header = [
38
+ "Benchmark profile",
39
+ "commit: #{meta["commit"]}",
40
+ "recorded_at: #{meta["recorded_at"]}",
41
+ "ruby: #{meta["ruby"]}",
42
+ ""
43
+ ]
44
+ (header + Array(data["lines"])).join("\n") + "\n"
45
+ end
46
+
47
+ def format_csv(data)
48
+ metrics = Array(data["metrics"])
49
+ if metrics.any?
50
+ rows = metrics.map { |metric| [metric["section"], metric["name"], metric["value"], metric["unit"]] }
51
+ return Export::Csv.generate(METRIC_HEADERS, rows)
52
+ end
53
+
54
+ rows = Array(data["lines"]).each_with_index.map { |line, index| [index + 1, line] }
55
+ Export::Csv.generate(LINE_HEADERS, rows)
56
+ end
57
+
58
+ def format_markdown(data)
59
+ meta = data["meta"] || {}
60
+ sections = [
61
+ {
62
+ heading: "Metadata",
63
+ headers: %w[key value],
64
+ rows: meta.sort_by { |key, _| key.to_s }
65
+ }
66
+ ]
67
+
68
+ metrics = Array(data["metrics"])
69
+ if metrics.any?
70
+ sections << {
71
+ heading: "Metrics",
72
+ headers: METRIC_HEADERS,
73
+ rows: metrics.map { |metric| [metric["section"], metric["name"], metric["value"], metric["unit"]] }
74
+ }
75
+ end
76
+
77
+ line_rows = Array(data["lines"]).reject(&:empty?).zip
78
+ sections << {
79
+ heading: "Log",
80
+ headers: %w[line],
81
+ rows: line_rows.empty? ? [["(empty)"]] : line_rows
82
+ }
83
+ Export::Markdown.document("Polyrun benchmark profile", sections)
84
+ end
85
+ end
86
+ end
87
+ end
@@ -0,0 +1,66 @@
1
+ require "optparse"
2
+
3
+ require_relative "../benchmark/profile"
4
+ require_relative "../benchmark/report"
5
+
6
+ module Polyrun
7
+ class CLI
8
+ module BenchmarkCommands
9
+ private
10
+
11
+ def cmd_report_benchmark(argv)
12
+ input = nil
13
+ out_file = nil
14
+ report_format = "text"
15
+ OptionParser.new do |opts|
16
+ opts.banner = "usage: polyrun report-benchmark -i FILE [-o PATH] [--format text|json|csv|markdown]"
17
+ opts.on("-i", "--input PATH", "Benchmark profile .json or .log from tmp/benchmarks/") { |v| input = v }
18
+ opts.on("-o", "--output PATH", "Write report to file instead of stdout") { |v| out_file = v }
19
+ opts.on("--format VAL", "text (default), json, csv, or markdown") { |v| report_format = v }
20
+ end.parse!(argv)
21
+ input ||= argv.first
22
+
23
+ unless input && File.file?(input)
24
+ Polyrun::Log.warn "report-benchmark: need -i FILE"
25
+ return 2
26
+ end
27
+
28
+ data = Polyrun::Benchmark::Report.load(File.expand_path(input))
29
+ begin
30
+ text = Polyrun::Benchmark::Report.render(data, format: report_format)
31
+ rescue Polyrun::Error => e
32
+ Polyrun::Log.warn e.message.to_s
33
+ return 2
34
+ end
35
+
36
+ if out_file
37
+ File.write(File.expand_path(out_file), text)
38
+ Polyrun::Log.puts File.expand_path(out_file)
39
+ else
40
+ Polyrun::Log.print text
41
+ end
42
+ 0
43
+ end
44
+
45
+ def cmd_bench(argv)
46
+ tag = "benchmark"
47
+ paths = %w[spec/performance/benchmark_spec.rb spec/performance/benchmark_merge_spec.rb]
48
+ env = {
49
+ "BENCH_FILES" => ENV.fetch("BENCH_FILES", "110"),
50
+ "BENCH_LINES" => ENV.fetch("BENCH_LINES", "310"),
51
+ "BENCH_FRAGMENTS" => ENV.fetch("BENCH_FRAGMENTS", "8"),
52
+ "BENCH_MERGE_REPS" => ENV.fetch("BENCH_MERGE_REPS", "3"),
53
+ "BENCH_LINE_COUNT_REPS" => ENV.fetch("BENCH_LINE_COUNT_REPS", "5"),
54
+ "BENCH_PEEK_REPS" => ENV.fetch("BENCH_PEEK_REPS", "200")
55
+ }
56
+ formats = ENV["POLYRUN_BENCH_FORMATS"]
57
+ env["POLYRUN_BENCH_FORMATS"] = formats if formats && !formats.to_s.strip.empty?
58
+ bench_argv = paths + ["--tag", tag]
59
+ bench_argv.concat(argv) unless argv.empty?
60
+ Polyrun::Log.warn "polyrun bench: running performance specs (#{paths.join(", ")})" if @verbose
61
+ success = system(env, "bundle", "exec", "rspec", *bench_argv)
62
+ success ? 0 : ($?.exitstatus || 1)
63
+ end
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,129 @@
1
+ module Polyrun
2
+ class CLI
3
+ # Suite / shard / worker shell hooks for +ci-shard-run+ / +ci-shard-rspec+.
4
+ module CiShardHooks
5
+ private
6
+
7
+ # rubocop:disable Metrics/AbcSize -- suite hooks + spawn/wait + failure paths
8
+ def ci_shard_run_fanout!(ctx)
9
+ hook_cfg = Polyrun::Hooks.from_config(ctx[:cfg])
10
+ suite_started = false
11
+ exit_code = 1
12
+
13
+ begin
14
+ env_suite = ENV.to_h.merge(
15
+ "POLYRUN_HOOK_ORCHESTRATOR" => "1",
16
+ "POLYRUN_SHARD_TOTAL" => ctx[:workers].to_s
17
+ )
18
+ code = hook_cfg.run_phase_if_enabled(:before_suite, env_suite)
19
+ return code if code != 0
20
+
21
+ suite_started = true
22
+
23
+ pids, spawn_err = run_shards_spawn_workers(ctx, hook_cfg)
24
+ if spawn_err
25
+ exit_code = spawn_err
26
+ return spawn_err
27
+ end
28
+ return 1 if pids.empty?
29
+
30
+ run_shards_warn_interleaved(ctx[:parallel], pids.size)
31
+ shard_results, wait_hook_err = run_shards_wait_all_children(pids, hook_cfg, ctx)
32
+ failed = shard_results.reject { |r| r[:success] }.map { |r| r[:shard] }
33
+
34
+ if failed.any?
35
+ Polyrun::Log.warn "polyrun ci-shard: finished #{pids.size} worker(s) (some failed)"
36
+ run_shards_log_failed_reruns(failed, shard_results, ctx[:plan], ctx[:parallel], ctx[:workers], ctx[:cmd])
37
+ exit_code = 1
38
+ exit_code = 1 if wait_hook_err != 0
39
+ return exit_code
40
+ end
41
+
42
+ exit_code = (wait_hook_err == 0) ? 0 : 1
43
+ Polyrun::Log.warn "polyrun ci-shard: finished #{pids.size} worker(s) (exit 0)" if exit_code == 0
44
+ exit_code
45
+ ensure
46
+ if suite_started
47
+ env_after = ENV.to_h.merge(
48
+ "POLYRUN_HOOK_ORCHESTRATOR" => "1",
49
+ "POLYRUN_SHARD_TOTAL" => ctx[:workers].to_s,
50
+ "POLYRUN_SUITE_EXIT_STATUS" => exit_code.to_s
51
+ )
52
+ begin
53
+ hook_cfg.run_phase_if_enabled(:after_suite, env_after)
54
+ rescue Interrupt
55
+ Polyrun::Log.warn "polyrun ci-shard: after_suite hook interrupted"
56
+ end
57
+ end
58
+ end
59
+ end
60
+ # rubocop:enable Metrics/AbcSize
61
+
62
+ # One matrix shard, one OS process: same hook phases as +run-shards+ with +--workers 1+ (no +exec+ when hooks exist).
63
+ # rubocop:disable Metrics/AbcSize -- suite / shard / worker lifecycle
64
+ def ci_shard_run_single!(cmd, paths, cfg, pc, _config_path)
65
+ hook_cfg = Polyrun::Hooks.from_config(cfg)
66
+ if hook_cfg.empty? || Polyrun::Hooks.disabled?
67
+ exec(*cmd, *paths)
68
+ end
69
+
70
+ si = Polyrun::Config::Resolver.resolve_shard_index(pc)
71
+ st = Polyrun::Config::Resolver.resolve_shard_total(pc)
72
+ suite_started = false
73
+ exit_code = 1
74
+ # Distributed CI matrix (N > 1 global shards): each job is one shard; suite hooks are pipeline-wide.
75
+ # Run them once via +polyrun hook run before_suite+ / +after_suite+ (e.g. dedicated job), or set
76
+ # +POLYRUN_HOOKS_SUITE_PER_MATRIX_JOB=1+ to run suite hooks on every matrix job.
77
+ matrix_shards = st > 1
78
+ run_suite_hooks = !matrix_shards || Polyrun::Hooks.suite_per_matrix_job?
79
+
80
+ begin
81
+ env_orch = ENV.to_h.merge(
82
+ "POLYRUN_HOOK_ORCHESTRATOR" => "1",
83
+ "POLYRUN_SHARD_INDEX" => si.to_s,
84
+ "POLYRUN_SHARD_TOTAL" => st.to_s
85
+ )
86
+ if run_suite_hooks
87
+ code = hook_cfg.run_phase_if_enabled(:before_suite, env_orch)
88
+ return code if code != 0
89
+
90
+ suite_started = true
91
+ end
92
+
93
+ code = hook_cfg.run_phase_if_enabled(:before_shard, env_orch)
94
+ return code if code != 0
95
+
96
+ mx, mt = ci_shard_matrix_context(pc, 1)
97
+ child_env = shard_child_env(cfg: cfg, workers: 1, shard: 0, matrix_index: mx, matrix_total: mt)
98
+ child_env = child_env.merge("POLYRUN_HOOK_ORCHESTRATOR" => "0")
99
+ child_env = hook_cfg.merge_worker_ruby_env(child_env)
100
+
101
+ if hook_cfg.worker_hooks? && !Polyrun::Hooks.disabled?
102
+ system(child_env, "sh", "-c", hook_cfg.build_worker_shell_script(cmd, paths))
103
+ else
104
+ system(child_env, *cmd, *paths)
105
+ end
106
+ exit_code = $?.exitstatus
107
+
108
+ rc = hook_cfg.run_phase_if_enabled(:after_shard, env_orch.merge(
109
+ "POLYRUN_WORKER_EXIT_STATUS" => exit_code.to_s
110
+ ))
111
+ exit_code = rc if rc != 0
112
+
113
+ exit_code
114
+ ensure
115
+ if suite_started
116
+ begin
117
+ hook_cfg.run_phase_if_enabled(:after_suite, env_orch.merge(
118
+ "POLYRUN_SUITE_EXIT_STATUS" => exit_code.to_s
119
+ ))
120
+ rescue Interrupt
121
+ Polyrun::Log.warn "polyrun ci-shard: after_suite hook interrupted"
122
+ end
123
+ end
124
+ end
125
+ end
126
+ # rubocop:enable Metrics/AbcSize
127
+ end
128
+ end
129
+ end