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,42 @@
1
+ module Polyrun
2
+ module SpecQuality
3
+ # Minitest hook: per-test spec quality (requires minitest loaded).
4
+ module MinitestHook
5
+ module SpecQualityTestHook
6
+ def setup
7
+ Polyrun::SpecQuality.start_example!(location: polyrun_minitest_location)
8
+ super
9
+ end
10
+
11
+ def teardown
12
+ super
13
+ Polyrun::SpecQuality.finish_example!(location: polyrun_minitest_location)
14
+ end
15
+
16
+ private
17
+
18
+ def polyrun_minitest_location
19
+ file, line = method(name).source_location
20
+ (file && line) ? "#{file}:#{line}" : nil
21
+ rescue NameError
22
+ nil
23
+ end
24
+ end
25
+
26
+ module_function
27
+
28
+ def install!(only_if: nil, root: nil, output_path: nil)
29
+ pred = only_if || -> { Polyrun::SpecQuality.enabled? }
30
+ return unless pred.call
31
+
32
+ unless defined?(::Minitest::Test)
33
+ Polyrun::Log.warn "polyrun minitest: install_spec_quality! skipped (load minitest first)"
34
+ return
35
+ end
36
+
37
+ Polyrun::SpecQuality::RspecHook.ensure_started!(root: root, output_path: output_path)
38
+ ::Minitest::Test.send(:prepend, SpecQualityTestHook)
39
+ end
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,47 @@
1
+ require "json"
2
+
3
+ module Polyrun
4
+ module SpecQuality
5
+ # Loads partition plan JSON for spec-quality ↔ shard correlation.
6
+ module PlanLoader
7
+ module_function
8
+
9
+ # @param paths [Array<String>] plan JSON files (+polyrun plan+ output per shard or a wrapper hash)
10
+ # @return [Hash{String=>Array<String>}] shard index string => spec file paths
11
+ def load_shards(paths)
12
+ out = {}
13
+ Array(paths).each do |path|
14
+ next unless File.file?(path)
15
+
16
+ data = JSON.parse(File.read(File.expand_path(path)))
17
+ merge_plan_data!(out, data)
18
+ end
19
+ out
20
+ end
21
+
22
+ def merge_plan_data!(out, data)
23
+ if data.is_a?(Hash) && data["shards"].is_a?(Hash)
24
+ data["shards"].each { |k, v| out[k.to_s] = Array(v).map(&:to_s) }
25
+ return
26
+ end
27
+
28
+ return unless data.is_a?(Hash)
29
+
30
+ shard = data["shard_index"]
31
+ paths = data["paths"]
32
+ return if shard.nil? || !paths.is_a?(Array)
33
+
34
+ out[shard.to_s] = paths.map(&:to_s)
35
+ end
36
+
37
+ # @return [String, nil] shard index for an example locator given plan shards
38
+ def shard_for_example(example_loc, plan_shards)
39
+ file = example_loc.to_s.sub(/:\d+\z/, "")
40
+ plan_shards.each do |shard, paths|
41
+ return shard if paths.any? { |p| file == p || file.end_with?("/#{File.basename(p)}") || file.include?(p) }
42
+ end
43
+ nil
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,102 @@
1
+ module Polyrun
2
+ module SpecQuality
3
+ # Stdlib per-example CPU / allocation / IO snapshots.
4
+ module Profile
5
+ module_function
6
+
7
+ def snapshot(dimensions: %w[cpu mem io wall])
8
+ dims = enabled_dimensions(dimensions)
9
+ capture_all = dims.empty?
10
+ out = {}
11
+
12
+ if capture_all || dims.include?("cpu") || dims.include?("wall")
13
+ cpu = Process.times
14
+ out["cpu_user"] = cpu.utime
15
+ out["cpu_system"] = cpu.stime
16
+ end
17
+
18
+ if capture_all || dims.include?("mem")
19
+ gc = GC.stat
20
+ out["gc_allocated"] = gc[:total_allocated_objects]
21
+ out["gc_heap_live"] = gc[:heap_live_slots]
22
+ end
23
+
24
+ if capture_all || dims.include?("io")
25
+ io = read_proc_io
26
+ out["io_read_bytes"] = io[:read_bytes]
27
+ out["io_write_bytes"] = io[:write_bytes]
28
+ end
29
+
30
+ out
31
+ end
32
+
33
+ def diff(before, after)
34
+ before ||= {}
35
+ after ||= {}
36
+ out = {}
37
+ %w[cpu_user cpu_system gc_allocated gc_heap_live io_read_bytes io_write_bytes].each do |k|
38
+ b = before[k]
39
+ a = after[k]
40
+ next if b.nil? && a.nil?
41
+
42
+ delta = numeric(a) - numeric(b)
43
+ out[k] = delta if delta.positive? || k.start_with?("cpu")
44
+ end
45
+ out
46
+ end
47
+
48
+ def enabled_dimensions(profile_list)
49
+ Array(profile_list).map(&:to_s).map(&:downcase)
50
+ end
51
+
52
+ # rubocop:disable Metrics/AbcSize -- profile dimension slice
53
+ def slice_profile(diff, dimensions)
54
+ dims = enabled_dimensions(dimensions)
55
+ return diff if dims.empty?
56
+
57
+ out = {}
58
+ out["wall"] = diff["wall"] if diff.key?("wall") && dims.include?("wall")
59
+ if dims.include?("cpu")
60
+ out["cpu_user"] = diff["cpu_user"] if diff.key?("cpu_user")
61
+ out["cpu_system"] = diff["cpu_system"] if diff.key?("cpu_system")
62
+ end
63
+ if dims.include?("mem")
64
+ out["gc_allocated"] = diff["gc_allocated"] if diff.key?("gc_allocated")
65
+ out["gc_heap_live"] = diff["gc_heap_live"] if diff.key?("gc_heap_live")
66
+ end
67
+ if dims.include?("io")
68
+ out["io_read_bytes"] = diff["io_read_bytes"] if diff.key?("io_read_bytes")
69
+ out["io_write_bytes"] = diff["io_write_bytes"] if diff.key?("io_write_bytes")
70
+ end
71
+ out
72
+ end
73
+ # rubocop:enable Metrics/AbcSize
74
+
75
+ def read_proc_io
76
+ path = "/proc/self/io"
77
+ return {read_bytes: nil, write_bytes: nil} unless File.readable?(path)
78
+
79
+ read_bytes = nil
80
+ write_bytes = nil
81
+ File.foreach(path) do |line|
82
+ case line
83
+ when /\Aread_bytes:\s+(\d+)/
84
+ read_bytes = Regexp.last_match(1).to_i
85
+ when /\Awrite_bytes:\s+(\d+)/
86
+ write_bytes = Regexp.last_match(1).to_i
87
+ end
88
+ end
89
+ {read_bytes: read_bytes, write_bytes: write_bytes}
90
+ rescue SystemCallError
91
+ {read_bytes: nil, write_bytes: nil}
92
+ end
93
+
94
+ def numeric(value)
95
+ return 0 if value.nil?
96
+
97
+ value.is_a?(Numeric) ? value : value.to_f
98
+ end
99
+ private_class_method :numeric
100
+ end
101
+ end
102
+ end
@@ -0,0 +1,363 @@
1
+ # rubocop:disable Polyrun/FileLength, Metrics/ModuleLength -- report analysis + text formatting
2
+ require_relative "../export/csv"
3
+ require_relative "../export/markdown"
4
+
5
+ module Polyrun
6
+ module SpecQuality
7
+ # Human-readable spec quality report from merged JSON.
8
+ module Report
9
+ module_function
10
+
11
+ # rubocop:disable Metrics/AbcSize -- merged example analysis
12
+ def analyze(merged, cfg = {}, plan_shards: nil)
13
+ cfg = default_cfg(cfg)
14
+ examples = merged["examples"] || {}
15
+ hot_lines = merged["hot_lines"] || {}
16
+ shard_summary = merged["shard_summary"] || Merge.shard_summary(examples)
17
+
18
+ zero_hit = examples.select { |_loc, row| row["unique_lines"].to_i.zero? }
19
+ churn = examples.select { |_loc, row| row["line_churn"].to_i >= cfg["min_line_churn"] }
20
+ .sort_by { |_loc, row| -row["line_churn"].to_i }
21
+ hot = hot_lines.select { |_line, h| h["example_count"].to_i >= cfg["hot_line_example_overlap"] }
22
+ .sort_by { |_line, h| [-h["example_count"].to_i, -h["total_hits"].to_i] }
23
+
24
+ outliers = build_outliers(examples, cfg)
25
+ partition_hints = partition_hints_for(hot, examples, plan_shards) if plan_shards && !plan_shards.empty?
26
+
27
+ {
28
+ zero_hit: zero_hit,
29
+ line_churn: churn,
30
+ hot_lines: hot,
31
+ outliers: outliers,
32
+ shard_summary: shard_summary,
33
+ partition_hints: partition_hints,
34
+ config: cfg
35
+ }
36
+ end
37
+ # rubocop:enable Metrics/AbcSize
38
+
39
+ def format_report(merged, cfg: {}, top: 30, profile: nil, plan_shards: nil)
40
+ analysis = analyze(merged, cfg, plan_shards: plan_shards)
41
+ lines = ["Polyrun spec quality report", ""]
42
+
43
+ lines.concat(format_shard_summary_section(analysis[:shard_summary]))
44
+ lines << ""
45
+ lines.concat(format_zero_hit_section(analysis[:zero_hit], top))
46
+ lines << ""
47
+ lines.concat(format_hot_lines_section(analysis[:hot_lines], top))
48
+ lines << ""
49
+ lines.concat(format_churn_section(analysis[:line_churn], top))
50
+ hints_section = format_partition_hints_section(analysis[:partition_hints], top)
51
+ unless hints_section.empty?
52
+ lines << ""
53
+ lines.concat(hints_section)
54
+ end
55
+ lines << ""
56
+ lines.concat(format_outliers_section(analysis[:outliers], top, profile))
57
+
58
+ lines.join("\n") + "\n"
59
+ end
60
+
61
+ EXAMPLE_CSV_HEADERS = %w[example unique_lines line_churn max_line_churn shard_index].freeze
62
+
63
+ def format_csv(merged, cfg: {}, top: 30, profile: nil, plan_shards: nil)
64
+ rows = merged.fetch("examples", {}).map do |location, row|
65
+ [
66
+ location,
67
+ row["unique_lines"],
68
+ row["line_churn"],
69
+ row["max_line_churn"],
70
+ row["polyrun_shard_index"]
71
+ ]
72
+ end.sort_by { |row| [-row[2].to_i, row[0].to_s] }
73
+ rows = rows.first(top) if top
74
+ Export::Csv.generate(EXAMPLE_CSV_HEADERS, rows)
75
+ end
76
+
77
+ def format_markdown(merged, cfg: {}, top: 30, profile: nil, plan_shards: nil)
78
+ analysis = analyze(merged, cfg, plan_shards: plan_shards)
79
+ sections = markdown_sections(analysis, top).compact
80
+ Export::Markdown.document("Polyrun spec quality report", sections)
81
+ end
82
+
83
+ def markdown_sections(analysis, top)
84
+ [
85
+ markdown_shard_section(analysis[:shard_summary]),
86
+ markdown_zero_hit_section(analysis[:zero_hit], top),
87
+ markdown_hot_lines_section(analysis[:hot_lines], top),
88
+ markdown_churn_section(analysis[:line_churn], top)
89
+ ]
90
+ end
91
+
92
+ def markdown_shard_section(shard_summary)
93
+ shard_rows = (shard_summary || {}).sort_by { |shard, _| shard.to_s }.map do |shard, stats|
94
+ [shard, stats["examples"], stats["zero_hit"], stats["line_churn"]]
95
+ end
96
+ return if shard_rows.empty?
97
+
98
+ {
99
+ heading: "Shard attribution",
100
+ headers: %w[shard examples zero_hit line_churn],
101
+ rows: shard_rows
102
+ }
103
+ end
104
+
105
+ def markdown_zero_hit_section(zero_hit, top)
106
+ zero_rows = zero_hit.keys.sort.first(top).zip
107
+ {
108
+ heading: "Zero production lines",
109
+ headers: %w[example],
110
+ rows: zero_rows.empty? ? [["(none)"]] : zero_rows
111
+ }
112
+ end
113
+
114
+ def markdown_hot_lines_section(hot_lines, top)
115
+ hot_rows = hot_lines.first(top).map do |line, stats|
116
+ [line, stats["example_count"], stats["total_hits"]]
117
+ end
118
+ {
119
+ heading: "Hot lines",
120
+ headers: %w[line example_count total_hits],
121
+ rows: hot_rows.empty? ? [["(none)", 0, 0]] : hot_rows
122
+ }
123
+ end
124
+
125
+ def markdown_churn_section(churn_rows, top)
126
+ rows = churn_rows.first(top).map do |location, row|
127
+ [location, row["line_churn"], row["max_line_churn"]]
128
+ end
129
+ {
130
+ heading: "Per-example line churn",
131
+ headers: %w[example line_churn max_line_churn],
132
+ rows: rows.empty? ? [["(none)", 0, 0]] : rows
133
+ }
134
+ end
135
+
136
+ def render(merged, format: "text", **kwargs)
137
+ case format.to_s.downcase
138
+ when "text", "console", "txt"
139
+ format_report(merged, **kwargs)
140
+ when "json"
141
+ JSON.pretty_generate(analyze(merged, kwargs[:cfg] || {}, plan_shards: kwargs[:plan_shards]))
142
+ when "csv"
143
+ format_csv(merged, **kwargs)
144
+ when "markdown", "md"
145
+ format_markdown(merged, **kwargs)
146
+ else
147
+ raise Polyrun::Error, "report-spec-quality: unknown format #{format.inspect} (use text, json, csv, or markdown)"
148
+ end
149
+ end
150
+
151
+ def gate_violations(merged, cfg = {})
152
+ cfg = default_cfg(cfg)
153
+ analysis = analyze(merged, cfg)
154
+ violations = []
155
+
156
+ max_zero = cfg["max_zero_hit_examples"]
157
+ if max_zero && analysis[:zero_hit].size > max_zero.to_i
158
+ violations << "zero_hit_examples=#{analysis[:zero_hit].size} max=#{max_zero}"
159
+ end
160
+
161
+ violations.concat(minimum_unique_line_violations(merged, cfg))
162
+
163
+ max_hot = cfg["max_hot_line_overlap"]
164
+ if max_hot
165
+ over = analysis[:hot_lines].count { |_k, h| h["example_count"].to_i > max_hot.to_i }
166
+ violations << "hot_line_overlap_count=#{over} max=#{max_hot}" if over.positive?
167
+ end
168
+
169
+ violations
170
+ end
171
+
172
+ def minimum_unique_line_violations(merged, cfg)
173
+ violations = []
174
+ min_unique = cfg["minimum_unique_lines_per_example"]
175
+ if min_unique
176
+ threshold = min_unique.to_i
177
+ examples = merged["examples"] || {}
178
+ bad = examples.select { |_loc, row| row["unique_lines"].to_i < threshold }.keys
179
+ if bad.size.positive?
180
+ violations << "examples_below_minimum_unique_lines=#{bad.size} minimum=#{min_unique}"
181
+ end
182
+ end
183
+
184
+ violations
185
+ end
186
+
187
+ def emit_warnings!(merged, cfg = {})
188
+ analyze(merged, cfg).fetch(:line_churn, {}).each do |loc, row|
189
+ Polyrun::Log.warn "polyrun spec-quality line_churn: #{loc} churn=#{row["line_churn"]}"
190
+ end
191
+ end
192
+
193
+ def default_cfg(cfg)
194
+ h = cfg.is_a?(Hash) ? cfg.transform_keys(&:to_s) : {}
195
+ SpecQuality::Config::DEFAULTS.merge(h)
196
+ end
197
+
198
+ def format_shard_summary_section(shard_summary)
199
+ lines = ["Shard attribution:"]
200
+ if shard_summary.nil? || shard_summary.empty?
201
+ lines << " (none)"
202
+ return lines
203
+ end
204
+
205
+ shard_summary.sort_by { |k, _| k.to_s }.each do |shard, stats|
206
+ lines << format(
207
+ " shard %s — examples=%d zero_hit=%d line_churn=%d",
208
+ shard,
209
+ stats["examples"],
210
+ stats["zero_hit"],
211
+ stats["line_churn"]
212
+ )
213
+ end
214
+ lines
215
+ end
216
+
217
+ def format_partition_hints_section(hints, top)
218
+ return [] if hints.nil? || hints.empty?
219
+
220
+ lines = ["Partition hints (hot lines × shard):"]
221
+ hints.first(top).each do |h|
222
+ lines << format(" %s — shard %s (%d examples)", h[:line], h[:shard], h[:example_count])
223
+ end
224
+ lines << " …" if hints.size > top
225
+ lines
226
+ end
227
+
228
+ def partition_hints_for(hot_lines, examples, plan_shards)
229
+ hot_lines.filter_map do |line, h|
230
+ example_locs = h["examples"] || []
231
+ shard_counts = Hash.new(0)
232
+ example_locs.each do |loc|
233
+ s = PlanLoader.shard_for_example(loc, plan_shards) || examples.dig(loc, "polyrun_shard_index")&.to_s
234
+ shard_counts[s] += 1 if s
235
+ end
236
+ next if shard_counts.empty?
237
+
238
+ shard, count = shard_counts.max_by { |_s, n| n }
239
+ {line: line, shard: shard, example_count: count, total_hits: h["total_hits"]}
240
+ end.sort_by { |h| [-h[:example_count], -h[:total_hits]] }
241
+ end
242
+
243
+ def format_zero_hit_section(zero_hit, top)
244
+ lines = ["Zero production lines (#{zero_hit.size} examples):"]
245
+ if zero_hit.empty?
246
+ lines << " (none)"
247
+ return lines
248
+ end
249
+
250
+ zero_hit.keys.sort.first(top).each { |loc| lines << " #{loc}" }
251
+ lines << " …" if zero_hit.size > top
252
+ lines
253
+ end
254
+
255
+ def format_hot_lines_section(hot_lines, top)
256
+ lines = ["Hot lines (shared across examples):"]
257
+ if hot_lines.empty?
258
+ lines << " (none)"
259
+ return lines
260
+ end
261
+
262
+ hot_lines.first(top).each do |line, h|
263
+ lines << format(" %s — %d examples, %d cumulative hits", line, h["example_count"], h["total_hits"])
264
+ end
265
+ lines << " …" if hot_lines.size > top
266
+ lines
267
+ end
268
+
269
+ def format_churn_section(churn_rows, top)
270
+ lines = ["Per-example line churn (top #{[top, churn_rows.size].min}):"]
271
+ if churn_rows.empty?
272
+ lines << " (none)"
273
+ return lines
274
+ end
275
+
276
+ churn_rows.first(top).each do |loc, row|
277
+ lines << format(" %s — churn=%d max_line=%d", loc, row["line_churn"], row["max_line_churn"])
278
+ end
279
+ lines
280
+ end
281
+
282
+ # rubocop:disable Metrics/AbcSize -- outlier row filter
283
+ def build_outliers(examples, cfg)
284
+ examples.filter_map do |loc, row|
285
+ prof = row["profile"] || {}
286
+ unique = row["unique_lines"].to_i
287
+ wall = prof["wall"].to_f
288
+ alloc = prof["gc_allocated"].to_i
289
+ cpu = prof["cpu_user"].to_f + prof["cpu_system"].to_f
290
+ sql = row["sql_count"].to_i
291
+ factories = (row["factory_counts"] || {}).values.sum
292
+
293
+ score = 0
294
+ reasons = []
295
+ if unique.zero?
296
+ score += 10
297
+ reasons << "zero_lines"
298
+ end
299
+ if wall > 1.0 && unique < 3
300
+ score += 5
301
+ reasons << "slow_low_coverage"
302
+ end
303
+ if alloc > 50_000 && wall > 0.5
304
+ score += 3
305
+ reasons << "high_alloc"
306
+ end
307
+ if cpu > 0.5 && unique < 3
308
+ score += 3
309
+ reasons << "high_cpu_low_coverage"
310
+ end
311
+ if sql >= cfg["min_query_count"]
312
+ score += 4
313
+ reasons << "high_sql_count"
314
+ end
315
+ if factories >= 10
316
+ score += 2
317
+ reasons << "many_factories"
318
+ end
319
+ next if score.zero?
320
+
321
+ {location: loc, score: score, reasons: reasons, row: row}
322
+ end.sort_by { |h| -h[:score] }
323
+ end
324
+ # rubocop:enable Metrics/AbcSize
325
+
326
+ # rubocop:disable Metrics/AbcSize -- outlier text formatting
327
+ def format_outliers_section(outliers, top, profile)
328
+ lines = ["Correlated outliers (slow / empty / heavy):"]
329
+ if outliers.empty?
330
+ lines << " (none)"
331
+ return lines
332
+ end
333
+
334
+ dims = profile ? profile.to_s.split(",").map(&:strip) : nil
335
+ outliers.first(top).each do |o|
336
+ row = o[:row]
337
+ prof = row["profile"] || {}
338
+ detail = o[:reasons].join(", ")
339
+ if dims.nil? || dims.empty?
340
+ lines << format(" %s — score=%d (%s)", o[:location], o[:score], detail)
341
+ else
342
+ prof_bits = dims.filter_map do |d|
343
+ case d
344
+ when "wall" then "wall=#{format("%.2f", prof["wall"])}" if prof["wall"]
345
+ when "cpu" then "cpu=#{format("%.2f", prof["cpu_user"].to_f + prof["cpu_system"].to_f)}"
346
+ when "mem" then "alloc=#{prof["gc_allocated"]}" if prof["gc_allocated"]
347
+ when "io"
348
+ r = prof["io_read_bytes"]
349
+ w = prof["io_write_bytes"]
350
+ "io=#{r}/#{w}" if r || w
351
+ end
352
+ end
353
+ lines << format(" %s — score=%d (%s) %s", o[:location], o[:score], detail, prof_bits.join(" "))
354
+ end
355
+ end
356
+ lines << " …" if outliers.size > top
357
+ lines
358
+ end
359
+ # rubocop:enable Metrics/AbcSize
360
+ end
361
+ end
362
+ end
363
+ # rubocop:enable Polyrun/FileLength, Metrics/ModuleLength
@@ -0,0 +1,55 @@
1
+ module Polyrun
2
+ module SpecQuality
3
+ # RSpec hooks for per-example spec quality recording.
4
+ module RspecHook
5
+ module_function
6
+
7
+ def install!(only_if: nil, root: nil, output_path: nil)
8
+ pred = only_if || -> { Polyrun::SpecQuality.enabled? }
9
+ return unless pred.call
10
+
11
+ require "rspec/core"
12
+ ensure_started!(root: root, output_path: output_path)
13
+
14
+ ::RSpec.configure do |config|
15
+ config.before(:each) do |example|
16
+ next if example.pending?
17
+
18
+ Polyrun::SpecQuality.start_example!(
19
+ location: example.metadata[:location] || example.location
20
+ )
21
+ end
22
+
23
+ config.after(:each) do |example|
24
+ Polyrun::SpecQuality.finish_example!(
25
+ location: example.metadata[:location] || example.location,
26
+ pending: example.pending?
27
+ )
28
+ end
29
+ end
30
+ end
31
+
32
+ def ensure_started!(root: nil, output_path: nil)
33
+ return if Polyrun::SpecQuality.started?
34
+
35
+ Polyrun::SpecQuality.start!(
36
+ root: root || infer_root,
37
+ output_path: output_path
38
+ )
39
+ end
40
+
41
+ def infer_root
42
+ if defined?(::Rails) && ::Rails.respond_to?(:root) && ::Rails.root
43
+ return ::Rails.root.to_s
44
+ end
45
+
46
+ caller_locations.each do |loc|
47
+ inferred = Polyrun::Coverage::Rails.infer_root_from_path(loc.path)
48
+ return inferred if inferred
49
+ end
50
+
51
+ Dir.pwd
52
+ end
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,34 @@
1
+ module Polyrun
2
+ module SpecQuality
3
+ # Optional per-example SQL query counting via ActiveSupport::Notifications.
4
+ module SqlCounter
5
+ class << self
6
+ def install!
7
+ return false unless notifications_available?
8
+ return true if @installed
9
+
10
+ @installed = true
11
+ @subscriber = ActiveSupport::Notifications.subscribe("sql.active_record") do |*args|
12
+ next unless Polyrun::SpecQuality.recording?
13
+
14
+ event = ActiveSupport::Notifications::Event.new(*args)
15
+ Polyrun::SpecQuality.record_sql!(event.payload[:sql].to_s)
16
+ end
17
+ true
18
+ end
19
+
20
+ def uninstall!
21
+ return unless @installed && @subscriber
22
+
23
+ ActiveSupport::Notifications.unsubscribe(@subscriber)
24
+ @subscriber = nil
25
+ @installed = false
26
+ end
27
+
28
+ def notifications_available?
29
+ defined?(ActiveSupport::Notifications)
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end