polyrun 2.2.8 → 3.0.0

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 (47) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +23 -8
  3. data/README.md +7 -6
  4. data/docs/SETUP_PROFILE.md +2 -1
  5. data/ext/polyrun_coverage_merge/coverage_merge.c +34 -15
  6. data/lib/polyrun/benchmark/pressure/cooker.rb +191 -0
  7. data/lib/polyrun/benchmark/pressure/process_sample.rb +127 -0
  8. data/lib/polyrun/benchmark/pressure.rb +144 -0
  9. data/lib/polyrun/cli/ci_shard_run_command.rb +31 -0
  10. data/lib/polyrun/cli/default_run.rb +10 -3
  11. data/lib/polyrun/cli/help.rb +5 -3
  12. data/lib/polyrun/cli/run_shards_command.rb +17 -0
  13. data/lib/polyrun/cli.rb +5 -2
  14. data/lib/polyrun/coverage/collector.rb +21 -49
  15. data/lib/polyrun/coverage/collector_blob.rb +53 -0
  16. data/lib/polyrun/coverage/merge.rb +33 -6
  17. data/lib/polyrun/coverage/merge_fragment_meta.rb +7 -1
  18. data/lib/polyrun/coverage/merge_merge_two.rb +2 -0
  19. data/lib/polyrun/coverage/merge_native.rb +2 -0
  20. data/lib/polyrun/data/parallel_provisioning.rb +2 -2
  21. data/lib/polyrun/hooks/dsl.rb +6 -6
  22. data/lib/polyrun/{minitest.rb → minitest_support.rb} +4 -4
  23. data/lib/polyrun/partition/paths.rb +95 -48
  24. data/lib/polyrun/partition/suite.rb +10 -6
  25. data/lib/polyrun/quick/config.rb +56 -0
  26. data/lib/polyrun/quick/example_group.rb +49 -4
  27. data/lib/polyrun/quick/example_runner.rb +30 -7
  28. data/lib/polyrun/quick/matchers.rb +6 -3
  29. data/lib/polyrun/quick/matchers_predicates.rb +122 -0
  30. data/lib/polyrun/quick/reporter.rb +40 -6
  31. data/lib/polyrun/quick/runner.rb +30 -16
  32. data/lib/polyrun/reporting/rspec_failure_fragment_formatter.rb +1 -1
  33. data/lib/polyrun/reporting/rspec_junit.rb +2 -2
  34. data/lib/polyrun/{rspec → rspec_support}/active_record_timeout_recovery.rb +1 -1
  35. data/lib/polyrun/{rspec → rspec_support}/example_debug.rb +1 -1
  36. data/lib/polyrun/{rspec → rspec_support}/example_debug_instrumentation.rb +1 -1
  37. data/lib/polyrun/{rspec → rspec_support}/sharded_formatter_compat.rb +1 -1
  38. data/lib/polyrun/{rspec.rb → rspec_support.rb} +12 -12
  39. data/lib/polyrun/sus_support.rb +55 -0
  40. data/lib/polyrun/templates/POLYRUN.md +1 -1
  41. data/lib/polyrun/timing/rspec_example_formatter.rb +2 -2
  42. data/lib/polyrun/version.rb +1 -1
  43. data/lib/polyrun/worker_ping.rb +9 -6
  44. data/sig/polyrun/{minitest.rbs → minitest_support.rbs} +1 -1
  45. data/sig/polyrun/{rspec.rbs → rspec_support.rbs} +1 -1
  46. data/sig/polyrun/sus_support.rbs +7 -0
  47. metadata +17 -9
@@ -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"
@@ -141,6 +141,37 @@ module Polyrun
141
141
  Polyrun::Log.warn "polyrun ci-shard-rspec: #{paths.size} path(s) → #{shard_processes} process(es) on this host (NxM: matrix jobs × local processes)"
142
142
  ci_shard_run_fanout!(ctx)
143
143
  end
144
+
145
+ # Same as +ci-shard-run -- bundle exec sus+ with an optional second segment for Sus-only flags:
146
+ # +polyrun ci-shard-sus [plan options] [-- [sus args]]+
147
+ def cmd_ci_shard_sus(argv, config_path)
148
+ sep = argv.index("--")
149
+ plan_argv = sep ? argv[0...sep] : argv
150
+ sus_argv = sep ? argv[(sep + 1)..] : []
151
+
152
+ cfg = Polyrun::Config.load(path: config_path || ENV["POLYRUN_CONFIG"])
153
+ pc = cfg.partition
154
+ shard_processes, perr = ci_shard_parse_shard_processes!(plan_argv, pc)
155
+ return perr if perr
156
+
157
+ shard_processes, err = ci_shard_normalize_shard_processes(shard_processes)
158
+ return err if err
159
+
160
+ paths, code = ci_shard_planned_paths!(plan_argv, config_path, command_label: "ci-shard-sus")
161
+ return code if code != 0
162
+
163
+ cmd = ["bundle", "exec", "sus", *sus_argv]
164
+
165
+ if shard_processes <= 1
166
+ return ci_shard_run_single!(cmd, paths, cfg, pc, config_path)
167
+ end
168
+
169
+ ctx = ci_shard_fanout_context(
170
+ cfg: cfg, pc: pc, paths: paths, shard_processes: shard_processes, cmd: cmd, config_path: config_path
171
+ )
172
+ Polyrun::Log.warn "polyrun ci-shard-sus: #{paths.size} path(s) → #{shard_processes} process(es) on this host (NxM: matrix jobs × local processes)"
173
+ ci_shard_run_fanout!(ctx)
174
+ end
144
175
  end
145
176
  end
146
177
  end
@@ -29,6 +29,11 @@ module Polyrun
29
29
  return code if code != 0
30
30
 
31
31
  cmd_parallel_minitest([], config_path)
32
+ when :sus
33
+ code = start_bootstrap!(cfg, [], config_path)
34
+ return code if code != 0
35
+
36
+ cmd_parallel_sus([], config_path)
32
37
  when :quick
33
38
  code = start_bootstrap!(cfg, [], config_path)
34
39
  return code if code != 0
@@ -69,7 +74,7 @@ module Polyrun
69
74
 
70
75
  suite = Polyrun::Partition::Paths.infer_suite_from_paths(expanded)
71
76
  if suite == :invalid
72
- Polyrun::Log.warn "polyrun: mixing _spec.rb and _test.rb paths in one run is not supported"
77
+ Polyrun::Log.warn "polyrun: mixing path families in one run is not supported"
73
78
  return 2
74
79
  end
75
80
  if suite.nil?
@@ -88,6 +93,8 @@ module Polyrun
88
93
  cmd_start(combined, config_path)
89
94
  when :minitest
90
95
  cmd_parallel_minitest(combined, config_path)
96
+ when :sus
97
+ cmd_parallel_sus(combined, config_path)
91
98
  when :quick
92
99
  cmd_parallel_quick(combined, config_path)
93
100
  else
@@ -119,10 +126,10 @@ module Polyrun
119
126
  if File.directory?(abs)
120
127
  spec = Dir.glob(File.join(abs, "**", "*_spec.rb")).sort
121
128
  test = Dir.glob(File.join(abs, "**", "*_test.rb")).sort
122
- quick = Dir.glob(File.join(abs, "**", "*.rb")).sort.reject do |f|
129
+ other = Dir.glob(File.join(abs, "**", "*.rb")).sort.reject do |f|
123
130
  File.basename(f).end_with?("_spec.rb", "_test.rb")
124
131
  end
125
- spec + test + quick
132
+ spec + test + other
126
133
  elsif /[*?\[]/.match?(p)
127
134
  Dir.glob(abs).sort
128
135
  elsif File.file?(abs)
@@ -5,7 +5,7 @@ module Polyrun
5
5
  Polyrun::Log.puts <<~HELP
6
6
  usage: polyrun [global options] [<command> | <paths...>]
7
7
 
8
- With no command, runs parallel tests for the resolved suite: partition.suite when set; else suite inferred from partition.paths_file; else filesystem auto-detect (RSpec under spec/ before Minitest under test/, then Polyrun Quick). If the first argument is a known subcommand name, it is dispatched. Otherwise, path-like tokens (optionally with run-shards flags such as --workers) shard those files in parallel; see commands below.
8
+ With no command, runs parallel tests for the resolved suite: partition.suite when set; else suite inferred from partition.paths_file; else filesystem auto-detect (RSpec under spec/, then Sus when config/sus.rb + test/**/*.rb, then Minitest *_test.rb, then Polyrun Quick). If the first argument is a known subcommand name, it is dispatched. Otherwise, path-like tokens (optionally with run-shards flags such as --workers) shard those files in parallel; see commands below.
9
9
 
10
10
  global:
11
11
  -c, --config PATH polyrun.yml path (or POLYRUN_CONFIG)
@@ -14,7 +14,7 @@ module Polyrun
14
14
  -h, --help
15
15
 
16
16
  Trace timing (stderr): DEBUG=1 or POLYRUN_DEBUG=1
17
- Coverage: POLYRUN_COVERAGE=1 (or config/polyrun_coverage.yml + POLYRUN_QUICK_COVERAGE=1); POLYRUN_COVERAGE_DISABLE=1 skips; POLYRUN_COVERAGE_BRANCHES=1 for branch data in fragments; POLYRUN_COVERAGE_VERBOSE=1 for per-worker and merged console summaries
17
+ Coverage: POLYRUN_COVERAGE=1 or Covered-style COVERAGE=<report>; (or config/polyrun_coverage.yml + POLYRUN_QUICK_COVERAGE=1); POLYRUN_COVERAGE_DISABLE=1 skips; POLYRUN_COVERAGE_BRANCHES=1 for branch data in fragments; POLYRUN_COVERAGE_VERBOSE=1 for per-worker and merged console summaries
18
18
  Benchmark profiles: POLYRUN_BENCH=1 (stdout); JSON sidecar in tmp/benchmarks/; POLYRUN_BENCH_FORMATS=csv,markdown for extra exports; report-benchmark / bench
19
19
  Hooks shell output: POLYRUN_HOOKS_VERBOSE=1 or -v / POLYRUN_VERBOSE=1 (or DEBUG); failures always print
20
20
  Merge profiling (stderr): POLYRUN_PROFILE_MERGE=1 (or verbose / DEBUG)
@@ -45,15 +45,17 @@ module Polyrun
45
45
  run-shards fan out N parallel OS processes (POLYRUN_SHARD_*; not Ruby threads); optional --merge-coverage / --merge-failures / --merge-spec-quality
46
46
  parallel-rspec run-shards + merge-coverage (defaults to: bundle exec rspec after --); no start prepare/DB bootstrap
47
47
  parallel-minitest run-shards + merge-coverage (defaults to: bundle exec rails test or ruby -I test after --); no start prepare/DB bootstrap
48
+ parallel-sus run-shards + merge-coverage (defaults to: bundle exec sus after --); no start prepare/DB bootstrap
48
49
  parallel-quick run-shards + merge-coverage (defaults to: bundle exec polyrun quick after --); no start prepare/DB bootstrap
49
50
  start parallel-rspec; auto-runs prepare (shell/assets) and db:setup-* when polyrun.yml configures them; legacy script/build_spec_paths.rb if paths_build absent
50
51
  ci-shard-run CI matrix: build-paths + plan for POLYRUN_SHARD_INDEX / POLYRUN_SHARD_TOTAL (or config), then run your command with that shard's paths after --; optional --shard-processes M or --workers M (POLYRUN_SHARD_PROCESSES; not POLYRUN_WORKERS) for N×M jobs × processes on this host
51
52
  ci-shard-rspec same as ci-shard-run -- bundle exec rspec; optional --shard-processes / --workers / -- [rspec-only flags]
53
+ ci-shard-sus same as ci-shard-run -- bundle exec sus; optional --shard-processes / --workers / -- [sus-only flags]
52
54
  build-paths write partition.paths_file from partition.paths_build (same as auto step before plan/run-shards)
53
55
  init write a starter polyrun.yml or POLYRUN.md from built-in templates (see docs/SETUP_PROFILE.md)
54
56
  queue file-backed batch queue: init (optional --shard/--total etc. as plan, then claim/ack/reclaim/status --json)
55
57
  run-queue init queue and run N workers that claim batches until drained
56
- quick quick test runner (describe/it, before/after, let, expect…to, assert_*; optional capybara!)
58
+ quick quick test runner (describe/with/it, before/after/around, let/subject, expect…to, assert_*; config/polyrun_quick.rb; optional capybara!)
57
59
  hook run <phase> run one shell hook from polyrun.yml hooks: (e.g. before_suite); optional --shard/--total
58
60
  report-coverage write all coverage formats from one JSON file
59
61
  report-junit RSpec JSON or Polyrun testcase JSON → JUnit XML, CSV, or Markdown
@@ -72,6 +72,23 @@ module Polyrun
72
72
  cmd_run_shards(combined, config_path)
73
73
  end
74
74
 
75
+ # Same as parallel-rspec but runs +bundle exec sus+ after +--+ (one Sus process per shard).
76
+ # Does not run +start+ prepare/database bootstrap (use +polyrun start+ or bare +polyrun+ for that).
77
+ # Prefer OS-process shards here when workers need isolated databases; Sus's own +sus-parallel+ is in-process threads.
78
+ def cmd_parallel_sus(argv, config_path)
79
+ sep = argv.index("--")
80
+ combined =
81
+ if sep
82
+ head = argv[0...sep]
83
+ tail = argv[sep..]
84
+ head + ["--merge-coverage"] + tail
85
+ else
86
+ argv + ["--merge-coverage", "--", "bundle", "exec", "sus"]
87
+ end
88
+ Polyrun::Debug.log_kv(parallel_sus: "combined argv", argv: combined)
89
+ cmd_run_shards(combined, config_path)
90
+ end
91
+
75
92
  def minitest_parallel_cmd
76
93
  rails_bin = File.expand_path("bin/rails", Dir.pwd)
77
94
  if File.file?(rails_bin)
data/lib/polyrun/cli.rb CHANGED
@@ -30,14 +30,15 @@ module Polyrun
30
30
  class CLI
31
31
  CI_SHARD_COMMANDS = {
32
32
  "ci-shard-run" => :cmd_ci_shard_run,
33
- "ci-shard-rspec" => :cmd_ci_shard_rspec
33
+ "ci-shard-rspec" => :cmd_ci_shard_rspec,
34
+ "ci-shard-sus" => :cmd_ci_shard_sus
34
35
  }.freeze
35
36
 
36
37
  # Keep in sync with +dispatch_cli_command_subcommands+ (+when+ branches). Used for implicit path routing.
37
38
  DISPATCH_SUBCOMMAND_NAMES = %w[
38
39
  plan prepare merge-coverage merge-failures merge-spec-quality report-coverage report-junit report-timing report-spec-quality report-benchmark bench
39
40
  env config merge-timing db:setup-template db:setup-shard db:clone-shards
40
- run-shards parallel-rspec parallel-minitest parallel-quick start build-paths init queue run-queue quick hook validate doctor
41
+ run-shards parallel-rspec parallel-minitest parallel-sus parallel-quick start build-paths init queue run-queue quick hook validate doctor
41
42
  ].freeze
42
43
 
43
44
  # First argv token that is a normal subcommand (not a path); if argv[0] is not here but looks like paths, run implicit parallel.
@@ -219,6 +220,8 @@ module Polyrun
219
220
  cmd_parallel_rspec(argv, config_path)
220
221
  when "parallel-minitest"
221
222
  cmd_parallel_minitest(argv, config_path)
223
+ when "parallel-sus"
224
+ cmd_parallel_sus(argv, config_path)
222
225
  when "parallel-quick"
223
226
  cmd_parallel_quick(argv, config_path)
224
227
  when "start"
@@ -96,11 +96,13 @@ module Polyrun
96
96
  instance_variable_defined?(:@config) && @config
97
97
  end
98
98
 
99
- # Whether +polyrun quick+ should call {Rails.start!} before loading quick files: not disabled,
100
- # and (+POLYRUN_COVERAGE=1+ or (+config/polyrun_coverage.yml+ exists and +POLYRUN_QUICK_COVERAGE=1+)).
99
+ # Whether +polyrun quick+ / Sus helpers should call {Rails.start!} / {start!} before loading tests:
100
+ # not disabled, and (+POLYRUN_COVERAGE=1+ or Covered-style +COVERAGE+ set, or
101
+ # (+config/polyrun_coverage.yml+ exists and +POLYRUN_QUICK_COVERAGE=1+)).
101
102
  def self.coverage_requested_for_quick?(root = Dir.pwd)
102
103
  return false if disabled?
103
- return true if %w[1 true yes].include?(ENV["POLYRUN_COVERAGE"]&.to_s&.downcase)
104
+ return true if polyrun_coverage_env_enabled?
105
+ return true if covered_env_enabled?
104
106
 
105
107
  path = File.join(File.expand_path(root), "config", "polyrun_coverage.yml")
106
108
  return false unless File.file?(path)
@@ -110,6 +112,21 @@ module Polyrun
110
112
  %w[1 true yes].include?(ENV["POLYRUN_QUICK_COVERAGE"]&.to_s&.downcase)
111
113
  end
112
114
 
115
+ # +POLYRUN_COVERAGE=1/true/yes+.
116
+ def self.polyrun_coverage_env_enabled?
117
+ %w[1 true yes].include?(ENV["POLYRUN_COVERAGE"]&.to_s&.downcase)
118
+ end
119
+
120
+ # Covered sets +COVERAGE+ to a report name (e.g. +PartialSummary+) or +true+.
121
+ # Empty / +0+ / +false+ / +no+ / +off+ stay off.
122
+ def self.covered_env_enabled?
123
+ value = ENV["COVERAGE"].to_s
124
+ return false if value.empty?
125
+ return false if %w[0 false no off].include?(value.downcase)
126
+
127
+ true
128
+ end
129
+
113
130
  # When +POLYRUN_SHARD_TOTAL+ > 1, each worker only writes the JSON fragment; merged reports
114
131
  # (+merge-coverage+ / +report-coverage+) are authoritative. Set +POLYRUN_COVERAGE_WORKER_FORMATS=1+
115
132
  # to force per-worker formatter output (debug only; duplicates work N times).
@@ -138,54 +155,9 @@ module Polyrun
138
155
  end
139
156
  m
140
157
  end
141
-
142
- # Normalizes stdlib Coverage.result to merge-compatible file entries (lines; branches when collected).
143
- def result_to_blob(raw)
144
- out = {}
145
- raw.each do |path, cov|
146
- next unless cov.is_a?(Hash)
147
-
148
- lines = cov[:lines] || cov["lines"]
149
- next unless lines.is_a?(Array)
150
-
151
- entry = {"lines" => lines.map { |x| x }}
152
- br = cov[:branches] || cov["branches"]
153
- entry["branches"] = br if br
154
- out[path.to_s] = entry
155
- end
156
- out
157
- end
158
-
159
- def normalize_blob_paths(blob, root)
160
- root = File.expand_path(root)
161
- blob.each_with_object({}) do |(path, entry), acc|
162
- acc[File.expand_path(path.to_s, root)] = entry
163
- end
164
- end
165
-
166
- def normalize_groups(groups)
167
- return nil if groups.nil?
168
-
169
- h = groups.is_a?(Hash) ? groups : {}
170
- return nil if h.empty?
171
-
172
- h.transform_keys(&:to_s).transform_values(&:to_s)
173
- end
174
-
175
- def keep_under_root(blob, root, track_under)
176
- return blob if track_under.nil? || track_under.empty?
177
-
178
- root = File.expand_path(root)
179
- prefixes = track_under.map { |d| File.join(root, d) }
180
- blob.each_with_object({}) do |(path, entry), acc|
181
- p = path.to_s
182
- next unless prefixes.any? { |pre| p == pre || p.start_with?(pre + "/") }
183
-
184
- acc[path] = entry
185
- end
186
- end
187
158
  end
188
159
  end
189
160
  end
190
161
 
162
+ require_relative "collector_blob"
191
163
  require_relative "collector_finish"
@@ -0,0 +1,53 @@
1
+ module Polyrun
2
+ module Coverage
3
+ module Collector
4
+ module_function
5
+
6
+ # Normalizes stdlib Coverage.result to merge-compatible file entries (lines; branches when collected).
7
+ def result_to_blob(raw)
8
+ out = {}
9
+ raw.each do |path, cov|
10
+ next unless cov.is_a?(Hash)
11
+
12
+ lines = cov[:lines] || cov["lines"]
13
+ next unless lines.is_a?(Array)
14
+
15
+ entry = {"lines" => lines.map { |x| x }}
16
+ br = cov[:branches] || cov["branches"]
17
+ entry["branches"] = br if br
18
+ out[path.to_s] = entry
19
+ end
20
+ out
21
+ end
22
+
23
+ def normalize_blob_paths(blob, root)
24
+ root = File.expand_path(root)
25
+ blob.each_with_object({}) do |(path, entry), acc|
26
+ acc[File.expand_path(path.to_s, root)] = entry
27
+ end
28
+ end
29
+
30
+ def normalize_groups(groups)
31
+ return nil if groups.nil?
32
+
33
+ h = groups.is_a?(Hash) ? groups : {}
34
+ return nil if h.empty?
35
+
36
+ h.transform_keys(&:to_s).transform_values(&:to_s)
37
+ end
38
+
39
+ def keep_under_root(blob, root, track_under)
40
+ return blob if track_under.nil? || track_under.empty?
41
+
42
+ root = File.expand_path(root)
43
+ prefixes = track_under.map { |d| File.join(root, d) }
44
+ blob.each_with_object({}) do |(path, entry), acc|
45
+ p = path.to_s
46
+ next unless prefixes.any? { |pre| p == pre || p.start_with?(pre + "/") }
47
+
48
+ acc[path] = entry
49
+ end
50
+ end
51
+ end
52
+ end
53
+ end
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require "json"
2
4
 
3
5
  module Polyrun
@@ -26,15 +28,15 @@ module Polyrun
26
28
  def merge_fragments(paths)
27
29
  return {blob: {}, meta: {}, groups: nil} if paths.empty?
28
30
 
29
- # Parse one fragment at a time: keep only meta + blob so peak RSS drops after each fold step.
31
+ # Fold one fragment at a time so peak RSS does not retain every blob concurrently.
30
32
  metas = []
31
- blobs = []
33
+ merged_blob = nil
32
34
  paths.each do |path|
33
- doc = JSON.parse(File.read(path))
35
+ doc = JSON.parse(File.binread(path))
34
36
  metas << extract_doc_meta(doc)
35
- blobs << extract_coverage_blob(doc)
37
+ blob = coverage_blob_from_doc(doc)
38
+ merged_blob = merged_blob.nil? ? blob : merge_two(merged_blob, blob)
36
39
  end
37
- merged_blob = merge_blob_tree(blobs)
38
40
  merged_meta = merge_fragment_metas_from_metas(metas)
39
41
  merged_blob = apply_track_files_once_after_merge(merged_blob, merged_meta)
40
42
  groups_payload = recompute_groups_from_meta(merged_blob, merged_meta)
@@ -96,13 +98,33 @@ module Polyrun
96
98
  end
97
99
 
98
100
  def parse_file(path)
99
- text = File.read(path)
101
+ text = File.binread(path)
100
102
  data = JSON.parse(text)
101
103
  extract_coverage_blob(data)
102
104
  end
103
105
 
104
106
  # Picks top-level export `coverage`, merges all suite entries (e.g. RSpec + Minitest),
105
107
  # and combines both when present.
108
+ # Hot path: cooker and worker fragments are { "coverage" => Hash, "meta" => ... } without
109
+ # nested per-tool suites under extra top-level keys.
110
+ def coverage_blob_from_doc(doc)
111
+ return extract_coverage_blob(doc) unless doc.is_a?(Hash)
112
+
113
+ top = doc["coverage"]
114
+ return extract_coverage_blob(doc) unless top.is_a?(Hash)
115
+
116
+ doc.each_key do |k|
117
+ next if k == "coverage"
118
+
119
+ v = doc[k]
120
+ if v.is_a?(Hash) && v["coverage"].is_a?(Hash)
121
+ return extract_coverage_blob(doc)
122
+ end
123
+ end
124
+
125
+ top
126
+ end
127
+
106
128
  def extract_coverage_blob(data)
107
129
  return {} unless data.is_a?(Hash)
108
130
 
@@ -121,6 +143,11 @@ module Polyrun
121
143
  return {}
122
144
  end
123
145
 
146
+ if nested.size == 1
147
+ only = nested.first
148
+ return top.is_a?(Hash) ? merge_two(top, only) : only
149
+ end
150
+
124
151
  merged = nested.reduce { |acc, el| merge_two(acc, el) }
125
152
  top.is_a?(Hash) ? merge_two(top, merged) : merged
126
153
  end
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Polyrun
2
4
  module Coverage
3
5
  module Merge
@@ -9,6 +11,7 @@ module Polyrun
9
11
 
10
12
  def merge_fragment_metas_from_metas(metas)
11
13
  return {} if metas.empty?
14
+ return {} if metas.all? { |m| m.nil? || m.empty? }
12
15
 
13
16
  base = metas.first.dup
14
17
  roots = metas.map { |m| m["polyrun_coverage_root"] }.compact
@@ -43,7 +46,10 @@ module Polyrun
43
46
  end
44
47
 
45
48
  def merge_fragment_meta_warn_track_files!(tfs)
46
- return if tfs.map { |tf| JSON.generate(normalize_track_files_meta(tf)) }.uniq.size <= 1
49
+ return if tfs.empty?
50
+
51
+ normalized = tfs.map { |tf| normalize_track_files_meta(tf) }
52
+ return if normalized.uniq.size <= 1
47
53
 
48
54
  Polyrun::Log.warn "Polyrun merge-coverage: polyrun_track_files differs across fragments; using first."
49
55
  end
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Polyrun
2
4
  module Coverage
3
5
  module Merge
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Polyrun
2
4
  module Coverage
3
5
  module MergeNative
@@ -12,8 +12,8 @@ module Polyrun
12
12
  # # In spec_helper after configure:
13
13
  # Polyrun::Data::ParallelProvisioning.run_suite_hooks!
14
14
  #
15
- # Or use {Polyrun::RSpec.install_parallel_provisioning!} (+before(:suite)+) or {Polyrun::Minitest.install_parallel_provisioning!}
16
- # (+require+ +polyrun/minitest+ from +test/test_helper.rb+).
15
+ # Or use {Polyrun::RSpecSupport.install_parallel_provisioning!} (+before(:suite)+) or {Polyrun::MinitestSupport.install_parallel_provisioning!}
16
+ # (+require+ +polyrun/minitest_support+ from +test/test_helper.rb+).
17
17
  module ParallelProvisioning
18
18
  class Configuration
19
19
  attr_accessor :serial_hook, :parallel_worker_hook
@@ -85,6 +85,10 @@ module Polyrun
85
85
  end
86
86
  end
87
87
 
88
+ # Load-time constant: `||=` can create two monitors.
89
+ CACHE_MU = Monitor.new
90
+ private_constant :CACHE_MU
91
+
88
92
  class << self
89
93
  # @return [Registry, nil]
90
94
  def load_registry(path)
@@ -94,7 +98,7 @@ module Polyrun
94
98
  return nil unless File.file?(full)
95
99
 
96
100
  mtime = File.mtime(full)
97
- cache_mu.synchronize do
101
+ CACHE_MU.synchronize do
98
102
  hit = registry_cache[full]
99
103
  return hit[:registry] if hit && hit[:mtime] == mtime
100
104
 
@@ -108,16 +112,12 @@ module Polyrun
108
112
  end
109
113
 
110
114
  def clear_cache!
111
- cache_mu.synchronize { registry_cache.clear }
115
+ CACHE_MU.synchronize { registry_cache.clear }
112
116
  end
113
117
 
114
118
  private
115
119
 
116
120
  # rubocop:disable ThreadSafety/ClassInstanceVariable -- single-threaded hook load; Monitor protects cache
117
- def cache_mu
118
- @cache_mu ||= Monitor.new
119
- end
120
-
121
121
  def registry_cache
122
122
  @registry_cache ||= {}
123
123
  end
@@ -1,12 +1,12 @@
1
1
  require_relative "../polyrun"
2
2
 
3
3
  module Polyrun
4
- # Optional Minitest-oriented wiring (require +polyrun/minitest+ explicitly).
4
+ # Optional Minitest-oriented wiring (require +polyrun/minitest_support+ explicitly).
5
5
  #
6
6
  # Does not load the +minitest+ gem. Call {install_parallel_provisioning!} from +test/test_helper.rb+
7
7
  # after Rails / DB configuration (same timing as a direct call to
8
8
  # {Data::ParallelProvisioning.run_suite_hooks!}).
9
- module Minitest
9
+ module MinitestSupport
10
10
  module WorkerPingTestHook
11
11
  def setup
12
12
  Polyrun::WorkerPing.ping!(location: polyrun_minitest_location)
@@ -35,12 +35,12 @@ module Polyrun
35
35
  Polyrun::Data::ParallelProvisioning.run_suite_hooks!
36
36
  end
37
37
 
38
- # Same ping semantics as {RSpec.install_worker_ping!}: +ping!+ at test +setup+ and +teardown+.
38
+ # Same ping semantics as {RSpecSupport.install_worker_ping!}: +ping!+ at test +setup+ and +teardown+.
39
39
  # Requires +minitest+ to be loaded first (+Minitest::Test+ defined).
40
40
  def install_worker_ping!
41
41
  require_relative "worker_ping"
42
42
  unless defined?(::Minitest::Test)
43
- Polyrun::Log.warn "polyrun minitest: install_worker_ping! skipped (load minitest/autorun or minitest/test first)"
43
+ Polyrun::Log.warn "polyrun minitest_support: install_worker_ping! skipped (load minitest/autorun or minitest/test first)"
44
44
  return
45
45
  end
46
46