binpacker 0.4.0 → 0.6.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 98842f3601fe059ff372b62a214ee73e5e96d0b2c01cf5b651063f04e3f00184
4
- data.tar.gz: 94e73ac26474bf1da1942509f35618e8576d230b685ee69fe09579d4b9387898
3
+ metadata.gz: 7a54ccc149cfd16f8e0b0d5e77bd91aaa9cbd3b521aa1522eb53b1489c419c80
4
+ data.tar.gz: f4f764a98514a624239cf719926f71c9b3ef86657a5fb2554671089b17dce661
5
5
  SHA512:
6
- metadata.gz: 6a983e121b41c7a9e62dad700ee5541813b84c2553e7fc479c3dbedf996358669a9508d2fd7f3eb8df21831c583421ee91382a453ac73a60beead9bf03da0675
7
- data.tar.gz: 657ac41276da7094a5ea54d53936a9237b1b3139f53b741c954427b57f2d781dca56df91746972e33e93f49edb7a93a2155d5b92561653d672f87ca73373669a
6
+ metadata.gz: 6a5af54cb448cbea6b2817357598f10b62c8f5e8194027b66ff9b0edbf0181301264e5d0c80ef2aec0ec216061bbf5ded54fbfcc2995aab0f9b27f5513de0ff0
7
+ data.tar.gz: b14adfb8f4d565b5fcc8ef3907d90fbae23a72517c3495b6f2a347a13eb2b5ae7e2c0ae76622e43cfd58e2e3e63fe07b74c448a8558d16254ce064827b8bdb9a
data/lib/binpacker/cli.rb CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env ruby
2
2
  # frozen_string_literal: true
3
3
 
4
- require "optparse"
4
+ require 'optparse'
5
5
 
6
6
  module Binpacker
7
7
  class CLI
@@ -17,31 +17,40 @@ module Binpacker
17
17
  @quiet = false
18
18
  @incremental = false
19
19
  @report_path = nil
20
+ @base_path = nil
21
+ @output_path = nil
20
22
  @skill_list = false
21
23
  @skill_path = false
22
24
  @skill_describe = false
23
25
  @skill_name = nil
26
+ # A CI matrix sets env vars far more easily than it rewrites the command a Makefile target runs, so
27
+ # BINPACKER_SHARD is a first-class way in; an explicit --shard still wins over it.
28
+ @shard_spec = ENV.fetch('BINPACKER_SHARD', nil)
24
29
  parse!
25
30
  end
26
31
 
27
32
  def run
28
33
  case @command
29
- when "calibrate"
34
+ when 'calibrate'
30
35
  cmd_calibrate
31
- when "run"
36
+ when 'run'
32
37
  cmd_run
33
- when "init"
38
+ when 'shards-check'
39
+ cmd_shards_check
40
+ when 'shards-merge'
41
+ cmd_shards_merge
42
+ when 'init'
34
43
  cmd_init
35
- when "skill"
44
+ when 'skill'
36
45
  cmd_skill
37
- when "describe"
46
+ when 'describe'
38
47
  cmd_describe
39
- when "--version", "-v"
48
+ when '--version', '-v'
40
49
  puts "binpacker #{Binpacker::VERSION}"
41
- when "--help", "-h", nil
50
+ when '--help', '-h', nil
42
51
  print_help
43
52
  else
44
- $stderr.puts "unknown command: #{@command}"
53
+ warn "unknown command: #{@command}"
45
54
  print_help
46
55
  exit 1
47
56
  end
@@ -51,47 +60,59 @@ module Binpacker
51
60
 
52
61
  def parse!
53
62
  parser = OptionParser.new do |opts|
54
- opts.banner = "Usage: binpacker <command> [options]"
63
+ opts.banner = 'Usage: binpacker <command> [options]'
55
64
 
56
- opts.on("--profile PROFILE", "Profile name from binpacker.yml") do |v|
65
+ opts.on('--profile PROFILE', 'Profile name from binpacker.yml') do |v|
57
66
  @profile = v
58
67
  end
59
68
 
60
- opts.on("--version", "Show version") do
61
- @command ||= "--version"
69
+ opts.on('--version', 'Show version') do
70
+ @command ||= '--version'
62
71
  end
63
72
 
64
- opts.on("--help", "Show help") do
65
- @command ||= "--help"
73
+ opts.on('--help', 'Show help') do
74
+ @command ||= '--help'
66
75
  end
67
76
 
68
- opts.on("--quiet", "Suppress worker output") do
77
+ opts.on('--quiet', 'Suppress worker output') do
69
78
  @quiet = true
70
79
  end
71
80
 
72
- opts.on("--incremental", "Calibrate only tests without timing data") do
81
+ opts.on('--incremental', 'Calibrate only tests without timing data') do
73
82
  @incremental = true
74
83
  end
75
84
 
76
- opts.on("--report PATH", "(run) Write a JSON run report to PATH") do |v|
85
+ opts.on('--report PATH', '(run) Write a JSON run report to PATH') do |v|
77
86
  @report_path = v
78
87
  end
79
88
 
80
- opts.on("--list", "(skill) List bundled skills") do
89
+ opts.on('--shard K/N', '(run) Run only shard K of N (1-based)') do |v|
90
+ @shard_spec = v
91
+ end
92
+
93
+ opts.on('--base PATH', '(shards-merge) The timing file every shard started from') do |v|
94
+ @base_path = v
95
+ end
96
+
97
+ opts.on('--output PATH', '(shards-merge) Where to write the merged timing file') do |v|
98
+ @output_path = v
99
+ end
100
+
101
+ opts.on('--list', '(skill) List bundled skills') do
81
102
  @skill_list = true
82
103
  end
83
104
 
84
- opts.on("--path", "(skill) Print the SKILL.md path for <name>") do
105
+ opts.on('--path', '(skill) Print the SKILL.md path for <name>') do
85
106
  @skill_path = true
86
107
  end
87
108
 
88
- opts.on("--describe", "(skill) Report project state and next skill") do
109
+ opts.on('--describe', '(skill) Report project state and next skill') do
89
110
  @skill_describe = true
90
111
  end
91
112
  end
92
113
 
93
114
  # Extract passthrough arguments after "--"
94
- if (split_idx = @args.index("--"))
115
+ if (split_idx = @args.index('--'))
95
116
  @passthrough = @args[(split_idx + 1)..] || []
96
117
  @args = @args[0...split_idx]
97
118
  end
@@ -100,11 +121,14 @@ module Binpacker
100
121
  # A positional command wins; otherwise keep any command an option set
101
122
  # (e.g. --version), so `binpacker --version` isn't clobbered to nil.
102
123
  @command = remaining.shift || @command
103
- @skill_name = remaining.shift
124
+ @skill_name = remaining.first
125
+ # `shards-check` and `shards-merge` take a list of paths, so the positionals stay available in full rather
126
+ # than being consumed into the single-name slot `skill` uses.
127
+ @shard_reports = remaining
104
128
  end
105
129
 
106
130
  def cmd_init
107
- config_path = Pathname.pwd.join("binpacker.yml")
131
+ config_path = Pathname.pwd.join('binpacker.yml')
108
132
  if config_path.exist?
109
133
  puts "binpacker.yml already exists at #{config_path}"
110
134
  exit 1
@@ -112,11 +136,11 @@ module Binpacker
112
136
 
113
137
  framework = detect_framework
114
138
  unless ProjectState::SUPPORTED_FRAMEWORKS.include?(framework)
115
- $stderr.puts "Detected #{framework} — binpacker supports rspec and minitest only."
116
- $stderr.puts "No binpacker.yml was created."
139
+ warn "Detected #{framework} — binpacker supports rspec and minitest only."
140
+ warn 'No binpacker.yml was created.'
117
141
  exit 1
118
142
  end
119
- pattern = framework == "minitest" ? "test/**/*_test.rb" : "spec/**/*_spec.rb"
143
+ pattern = framework == 'minitest' ? 'test/**/*_test.rb' : 'spec/**/*_spec.rb'
120
144
  runner = framework
121
145
 
122
146
  yaml = <<~YAML
@@ -137,15 +161,15 @@ module Binpacker
137
161
  config_path.write(yaml)
138
162
  puts "Created #{config_path}"
139
163
  puts "Detected test framework: #{framework}"
140
- puts ""
141
- puts "Next steps:"
142
- puts " 1. binpacker calibrate (seed timing data)"
143
- puts " 2. binpacker run (run in parallel)"
164
+ puts ''
165
+ puts 'Next steps:'
166
+ puts ' 1. binpacker calibrate (seed timing data)'
167
+ puts ' 2. binpacker run (run in parallel)'
144
168
  end
145
169
 
146
170
  def cmd_calibrate
147
171
  config = Config.new(profile: @profile)
148
- discovery_klass = config.test_runner == "rspec" ? RSpecDiscovery : MinitestDiscovery
172
+ discovery_klass = config.test_runner == 'rspec' ? RSpecDiscovery : MinitestDiscovery
149
173
  tests = discovery_klass.new(config).enumerate
150
174
 
151
175
  cal = Calibration.new(config)
@@ -175,7 +199,7 @@ module Binpacker
175
199
  if path
176
200
  puts path
177
201
  else
178
- $stderr.puts "unknown skill: #{@skill_name}"
202
+ warn "unknown skill: #{@skill_name}"
179
203
  exit 1
180
204
  end
181
205
  elsif @skill_name && !@skill_list
@@ -187,12 +211,12 @@ module Binpacker
187
211
 
188
212
  def cmd_describe
189
213
  state = ProjectState.new
190
- puts "binpacker project state:"
214
+ puts 'binpacker project state:'
191
215
  puts " config (binpacker.yml): #{state.config_present? ? 'present' : 'missing'}"
192
216
  puts " timing data: #{state.timing_present? ? 'present' : 'missing'}"
193
217
  puts " test framework: #{state.framework || 'not detected'}"
194
218
  puts " CI wired for binpacker: #{state.ci_wired? ? 'yes' : 'no'}"
195
- puts ""
219
+ puts ''
196
220
 
197
221
  unless state.supported_framework?
198
222
  puts "binpacker supports rspec and minitest; #{state.framework} is not supported yet."
@@ -208,45 +232,52 @@ module Binpacker
208
232
  def list_skills
209
233
  skills = Skills.list
210
234
  if skills.empty?
211
- puts "No bundled skills found."
235
+ puts 'No bundled skills found.'
212
236
  return
213
237
  end
214
- puts "Bundled skills:"
238
+ puts 'Bundled skills:'
215
239
  skills.each { |s| puts " #{s[:name]}" }
216
- puts ""
240
+ puts ''
217
241
  puts "Print a skill's instructions with `binpacker skill <name>`."
218
242
  end
219
243
 
220
244
  def print_skill(name)
221
245
  unless Skills.exist?(name)
222
- $stderr.puts "unknown skill: #{name}"
223
- $stderr.puts "Run `binpacker skill` to list bundled skills."
246
+ warn "unknown skill: #{name}"
247
+ warn 'Run `binpacker skill` to list bundled skills.'
224
248
  exit 1
225
249
  end
226
250
 
227
251
  puts "# Skill: #{name}"
228
252
  puts "# Source: #{Skills.path(name)}"
229
- puts ""
253
+ puts ''
230
254
  puts Skills.body(name)
231
255
  end
232
256
 
233
257
  def cmd_run
234
258
  config = Config.new(profile: @profile)
235
259
  report_path = @report_path || config.report_file
260
+ shard = Shard.parse(@shard_spec)
236
261
  orchestrator = Orchestrator.new(
237
- config, passthrough: @passthrough, quiet: @quiet, report_path: report_path
262
+ config, passthrough: @passthrough, quiet: @quiet, report_path: report_path, shard: shard
238
263
  )
239
264
 
240
- puts "binpacker starting (#{config.worker_count} workers, profile: #{config.profile})"
265
+ start_line = "binpacker starting (#{config.worker_count} workers, profile: #{config.profile}"
266
+ start_line += ", shard: #{shard}" if shard
267
+ puts "#{start_line})"
241
268
  result = orchestrator.run
242
269
  puts "Run report written to #{report_path}" if report_path
243
270
  unit = test_unit_label(config)
271
+ # Named in the summary because a sharded run's totals are its slice's, not the suite's — a reader
272
+ # comparing "10203 examples" with "3401 examples" needs to see which of the two this was.
273
+ scope = shard ? " (shard #{shard})" : ''
244
274
 
245
275
  if result[:passed]
246
- puts "All #{result[:total]} #{pluralize(result[:total], unit)} passed across #{config.worker_count} workers."
276
+ puts "All #{result[:total]} #{pluralize(result[:total], unit)} passed across " \
277
+ "#{config.worker_count} workers#{scope}."
247
278
  exit 0
248
279
  elsif result[:empty_filter]
249
- puts "No tests matched the Minitest filter."
280
+ puts 'No tests matched the Minitest filter.'
250
281
  exit 1
251
282
  else
252
283
  failed = result[:total] - result[:passed_count]
@@ -255,8 +286,49 @@ module Binpacker
255
286
  end
256
287
  end
257
288
 
289
+ # Run after a sharded matrix, over every shard's `--report`. A shard cannot tell "not mine" from "does
290
+ # not exist", so this is the only place a partition that dropped tests can be caught.
291
+ def cmd_shards_check
292
+ result = ShardCheck.call(@shard_reports)
293
+
294
+ if result.ok?
295
+ puts result.summary
296
+ exit 0
297
+ end
298
+
299
+ warn result.summary
300
+ result.problems.each { |problem| warn " #{problem}" }
301
+ exit 1
302
+ end
303
+
304
+ # Run after a sharded matrix, over the timing file each shard wrote back. Each shard measured only its
305
+ # own slice, so keeping any one of their files throws the other slices' measurements away.
306
+ def cmd_shards_merge
307
+ problems = []
308
+ problems << '--output PATH is required' unless @output_path
309
+ problems << 'no shard timing files given' if @shard_reports.empty?
310
+ missing = @shard_reports.reject { |path| File.exist?(path) }
311
+ problems.concat(missing.map { |path| "shard timing file not found: #{path}" })
312
+ if @base_path && !File.exist?(@base_path)
313
+ problems << "base timing file not found: #{@base_path} (omit --base on a cold start)"
314
+ end
315
+ unless problems.empty?
316
+ problems.each { |problem| warn problem }
317
+ exit 1
318
+ end
319
+
320
+ result = ShardMerge.call(base: @base_path, shards: @shard_reports, output: @output_path)
321
+ puts "Merged #{@shard_reports.size} shard timing #{pluralize(@shard_reports.size, 'file')} into " \
322
+ "#{@output_path}: #{result.updated} of #{result.tests} #{pluralize(result.tests, 'test')} re-measured."
323
+ return if result.conflicts.zero?
324
+
325
+ warn "#{result.conflicts} #{pluralize(result.conflicts, 'test')} re-measured by more than one shard " \
326
+ '(the later file won): an overlapping split, which `binpacker shards-check` reports, or a shared ' \
327
+ 'example group run by several shards.'
328
+ end
329
+
258
330
  def test_unit_label(config)
259
- config.test_runner == "rspec" ? "example" : "test"
331
+ config.test_runner == 'rspec' ? 'example' : 'test'
260
332
  end
261
333
 
262
334
  def pluralize(count, word)
@@ -269,6 +341,8 @@ module Binpacker
269
341
 
270
342
  Commands:
271
343
  run Execute tests across worker processes
344
+ shards-check Verify a sharded matrix's run reports cover the whole suite
345
+ shards-merge Fold the timing files a sharded matrix wrote into one
272
346
  calibrate Run tests serially to generate timing data
273
347
  init Create binpacker.yml with auto-detected settings
274
348
  describe Report project state and recommend the next skill
@@ -278,6 +352,9 @@ module Binpacker
278
352
  --profile NAME Select profile from binpacker.yml
279
353
  --incremental (calibrate) Measure only tests without timing data
280
354
  --report PATH (run) Write a JSON run report to PATH
355
+ --shard K/N (run) Run only shard K of N (1-based; env: BINPACKER_SHARD)
356
+ --base PATH (shards-merge) The timing file every shard started from
357
+ --output PATH (shards-merge) Where to write the merged timing file
281
358
  --list (skill) List bundled skills
282
359
  --path (skill) Print the SKILL.md path for <name>
283
360
  --describe (skill) Report project state and next skill
@@ -287,6 +364,9 @@ module Binpacker
287
364
  binpacker init
288
365
  binpacker run --profile ci
289
366
  binpacker run -- --tag ~slow
367
+ binpacker run --shard 2/3 --report shard-2.json
368
+ binpacker shards-check shard-*.json
369
+ binpacker shards-merge --base base.timings --output merged.timings shard-*.timings
290
370
  binpacker calibrate --incremental
291
371
  binpacker describe
292
372
  binpacker skill binpacker-setup
@@ -294,7 +374,7 @@ module Binpacker
294
374
  end
295
375
 
296
376
  def detect_framework
297
- ProjectState.new.framework || "rspec"
377
+ ProjectState.new.framework || 'rspec'
298
378
  end
299
379
  end
300
380
  end
@@ -15,6 +15,7 @@ module Binpacker
15
15
  "test_pattern" => "spec/**/*_spec.rb",
16
16
  "test_exclude" => [],
17
17
  "report_file" => nil,
18
+ "normalize_speed" => false,
18
19
  "scheduler" => {
19
20
  "strategy" => "static",
20
21
  "steal_enabled" => false,
@@ -24,20 +24,28 @@ module Binpacker
24
24
  # worker that gave the best makespan in the PR #12 simulation.
25
25
  COLD_START_BATCHES_PER_WORKER = 5
26
26
 
27
- def initialize(config, passthrough: [], quiet: false, report_path: nil)
27
+ def initialize(config, passthrough: [], quiet: false, report_path: nil, shard: nil)
28
28
  @config = config
29
29
  @passthrough = passthrough
30
30
  @quiet = quiet
31
31
  @report_path = report_path
32
+ @shard = shard
32
33
  end
33
34
 
34
35
  def run
35
36
  tests = discover
36
37
  timing = Timing.new(@config.timing_file)
38
+ # Weights are computed over the WHOLE suite before slicing, so every shard cuts against the same
39
+ # numbers and the partition they agree on covers every test exactly once.
37
40
  timings = timing.load_with_fallback(tests)
38
41
  @timings = timings
39
42
 
40
43
  scheduler = Scheduler.for(@config.scheduler['algorithm'])
44
+ @discovered_count = tests.size
45
+ tests = @shard.select(tests: tests, timings: timings, scheduler: scheduler) if @shard
46
+ @selected_count = tests.size
47
+ @selected_keys = tests.map(&:key)
48
+
41
49
  queues = scheduler.partition(
42
50
  tests: tests,
43
51
  worker_count: @config.worker_count,
@@ -121,6 +129,7 @@ module Binpacker
121
129
  }
122
130
  end
123
131
  progress.summary(worker_stats)
132
+ @speed_factor = timing.speed_factor(all_timings)
124
133
  write_report(worker_stats, all_timings)
125
134
 
126
135
  finalize(timing, all_timings, all_passed, total_examples, passed_examples, tests)
@@ -229,6 +238,7 @@ module Binpacker
229
238
  }
230
239
  end
231
240
  progress.summary(worker_stats)
241
+ @speed_factor = timing.speed_factor(all_timings)
232
242
  write_report(worker_stats, all_timings)
233
243
 
234
244
  workers.each(&:cleanup)
@@ -244,7 +254,14 @@ module Binpacker
244
254
  predicted_loads: @predicted_loads,
245
255
  worker_stats: worker_stats,
246
256
  all_timings: all_timings,
247
- timings: @timings
257
+ # Only this run's own tests: the weights cover the whole suite (a shard cuts from all of them), and
258
+ # comparing them with a slice's measurements lists every other shard's files as "actual 0.0".
259
+ timings: @timings.slice(*@selected_keys),
260
+ speed_factor: @speed_factor,
261
+ normalized: normalize?,
262
+ shard: @shard,
263
+ discovered: @discovered_count,
264
+ selected: @selected_count
248
265
  ).write(@report_path)
249
266
  end
250
267
 
@@ -282,7 +299,7 @@ module Binpacker
282
299
 
283
300
  def finalize(timing, all_timings, all_passed, total_examples, passed_examples, tests)
284
301
  unless all_timings.empty?
285
- timing.append_all(all_timings)
302
+ timing.append_all(normalize? ? normalized(all_timings) : all_timings)
286
303
  timing.compact!
287
304
  end
288
305
  empty_filter = minitest_empty_filter?(tests, total_examples)
@@ -297,6 +314,17 @@ module Binpacker
297
314
  }
298
315
  end
299
316
 
317
+ # `normalize_speed: true` records each sample divided by the run's speed factor (Timing#speed_factor),
318
+ # so a history fed by runners of different speeds stays on one scale. Off by default: on one machine
319
+ # the factor is noise around 1.0, and the recorded seconds stop being wall-clock seconds.
320
+ def normalize?
321
+ @config.normalize_speed && !@speed_factor.nil?
322
+ end
323
+
324
+ def normalized(entries)
325
+ entries.map { |e| e.merge(time: e[:time] / @speed_factor) }
326
+ end
327
+
300
328
  def minitest_empty_filter?(tests, total_examples)
301
329
  return false unless @config.test_runner == 'minitest'
302
330
  return false unless tests.any?
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "json"
3
+ require 'json'
4
4
 
5
5
  module Binpacker
6
6
  # Builds the machine-readable Run report: predicted versus actual per-Worker
@@ -9,13 +9,19 @@ module Binpacker
9
9
  SCHEMA = 1
10
10
  DRIFT_LIMIT = 10
11
11
 
12
- def initialize(profile:, algorithm:, predicted_loads:, worker_stats:, all_timings:, timings:)
12
+ def initialize(profile:, algorithm:, predicted_loads:, worker_stats:, all_timings:, timings:,
13
+ speed_factor: nil, normalized: false, shard: nil, discovered: nil, selected: nil)
13
14
  @profile = profile
14
15
  @algorithm = algorithm
15
16
  @predicted_loads = predicted_loads
16
17
  @worker_stats = worker_stats
17
18
  @all_timings = all_timings
18
19
  @timings = timings
20
+ @speed_factor = speed_factor
21
+ @normalized = normalized
22
+ @shard = shard
23
+ @discovered = discovered
24
+ @selected = selected
19
25
  end
20
26
 
21
27
  def to_h
@@ -26,6 +32,7 @@ module Binpacker
26
32
  schema: SCHEMA,
27
33
  profile: @profile,
28
34
  algorithm: @algorithm,
35
+ shard: shard_section,
29
36
  worker_count: @worker_stats.size,
30
37
  predicted_makespan: round(predicted.max || 0.0),
31
38
  actual_makespan: round(actual.max || 0.0),
@@ -34,6 +41,10 @@ module Binpacker
34
41
  predicted_deviation_pct: deviation_pct(predicted),
35
42
  actual_deviation_pct: deviation_pct(actual)
36
43
  },
44
+ speed: {
45
+ factor: @speed_factor&.round(3),
46
+ normalized: @normalized
47
+ },
37
48
  drift: drift
38
49
  }
39
50
  end
@@ -44,6 +55,29 @@ module Binpacker
44
55
 
45
56
  private
46
57
 
58
+ # The audit trail for a sharded run, and the reason `discovered` is recorded at all.
59
+ #
60
+ # Shards never talk to each other: each computes the same N-way partition and trusts the others to have
61
+ # computed it identically. They do so only while they agree on the timing data the partition is cut
62
+ # from, which in CI means every shard restoring the same timing cache. A shard that restores a
63
+ # different one — a cache miss where its siblings hit — partitions differently, and the failure is
64
+ # silent: tests land in no shard at all and the build stays green.
65
+ #
66
+ # `discovered` is the whole-suite count before slicing, so it agrees across shards that see the same
67
+ # repository. `selected` is this shard's slice. Summing `selected` over a matrix's reports and
68
+ # comparing to the shared `discovered` turns that silent skip into a failure —
69
+ # `binpacker shards-check` does exactly that.
70
+ def shard_section
71
+ return nil unless @shard
72
+
73
+ {
74
+ index: @shard.index,
75
+ total: @shard.total,
76
+ discovered_tests: @discovered,
77
+ selected_tests: @selected
78
+ }
79
+ end
80
+
47
81
  def workers
48
82
  @worker_stats.map.with_index do |s, i|
49
83
  {
@@ -60,7 +94,11 @@ module Binpacker
60
94
  # are compared at the same granularity even when timings are recorded
61
95
  # per example. Both sides are aggregated to normalized file paths.
62
96
  def drift
63
- actual = aggregate_by_file(@all_timings.map { |e| [e[:file], e[:time]] })
97
+ # A normalized run's history is on the normalized scale, so its measurements are put on that scale too:
98
+ # otherwise a slow runner drifts every file by its factor and the heaviest files crowd out the ones
99
+ # whose cost really changed.
100
+ scale = @normalized && @speed_factor ? @speed_factor : 1.0
101
+ actual = aggregate_by_file(@all_timings.map { |e| [e[:file], e[:time] / scale] })
64
102
  predicted = aggregate_by_file(@timings.map { |(file, _name), weight| [file, weight] })
65
103
 
66
104
  (actual.keys | predicted.keys)
@@ -84,13 +122,15 @@ module Binpacker
84
122
  end
85
123
 
86
124
  def normalize_file(file)
87
- file.to_s.sub(%r{\A\./}, "")
125
+ file.to_s.sub(%r{\A\./}, '')
88
126
  end
89
127
 
90
128
  def deviation_pct(loads)
91
129
  return 0.0 if loads.empty?
130
+
92
131
  mean = loads.sum / loads.size
93
132
  return 0.0 unless mean.positive?
133
+
94
134
  max_dev = loads.map { |t| (t - mean).abs }.max
95
135
  round(max_dev / mean * 100)
96
136
  end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Binpacker
4
+ # One slice of the suite, for splitting a run across independent machines.
5
+ #
6
+ # Workers divide a suite across the cores of ONE machine and share its wall clock; a shard divides it
7
+ # across machines that have no wall clock in common. So the two compose rather than compete: a CI matrix
8
+ # of N jobs each passing `--shard k/N` runs `worker_count` workers over its own slice, and the suite's
9
+ # wall time becomes roughly the slowest shard rather than the whole.
10
+ #
11
+ # The slice is cut by the SAME weight-balanced partitioner that assigns work to workers, over the same
12
+ # measured timings — shards are just a coarser bin-packing of the same problem, so an equal-count split
13
+ # would balance no better than round-robin. That also makes the cut deterministic: given one timing file,
14
+ # every shard computes the identical N-way partition and takes only its own bin, so no shard needs to
15
+ # know what the others decided, and every test lands in exactly one shard.
16
+ class Shard
17
+ attr_reader :index, :total
18
+
19
+ # Parses the `k/n` form used by `--shard` and BINPACKER_SHARD. `k` is 1-based, so a matrix can pass its
20
+ # own 1-based job number straight through.
21
+ #
22
+ # @param spec [String, nil]
23
+ # @return [Shard, nil] nil when `spec` is nil or empty, i.e. an unsharded run.
24
+ def self.parse(spec)
25
+ return nil if spec.nil? || spec.to_s.strip.empty?
26
+
27
+ match = %r{\A\s*(\d+)\s*/\s*(\d+)\s*\z}.match(spec.to_s)
28
+ raise ConfigError, "invalid shard #{spec.inspect}: expected the form K/N, e.g. 1/3" unless match
29
+
30
+ new(index: Integer(match[1]), total: Integer(match[2]))
31
+ end
32
+
33
+ def initialize(index:, total:)
34
+ raise ConfigError, "shard count must be at least 1, got #{total}" if total < 1
35
+ raise ConfigError, "shard index must be between 1 and #{total}, got #{index}" unless (1..total).cover?(index)
36
+
37
+ @index = index
38
+ @total = total
39
+ freeze
40
+ end
41
+
42
+ def to_s
43
+ "#{index}/#{total}"
44
+ end
45
+
46
+ # Whole-suite runs still construct no Shard, so this is only ever true for an explicit `--shard 1/1`.
47
+ def whole_suite?
48
+ total == 1
49
+ end
50
+
51
+ # @param tests [Array<Test>] every test discovered, before any slicing
52
+ # @param timings [Hash] predicted weight per test key, as `Timing#load_with_fallback` returns
53
+ # @param scheduler [Scheduler] the same partitioner the run uses for workers
54
+ # @return [Array<Test>] the tests belonging to this shard
55
+ def select(tests:, timings:, scheduler:)
56
+ return tests if whole_suite?
57
+
58
+ bins = scheduler.partition(tests: tests, worker_count: total, timings: timings)
59
+ bins[index - 1].remaining
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,127 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+
5
+ module Binpacker
6
+ # Fan-in audit for a sharded matrix: did the shards, between them, actually run the whole suite?
7
+ #
8
+ # Shards never coordinate. Each cuts the same N-way partition from the timing data it loaded and takes
9
+ # its own bin, which is correct exactly as long as they all loaded the SAME data. In CI that means every
10
+ # shard job restoring the same timing cache — and the failure mode when one does not is the bad one:
11
+ # it partitions differently, some tests land in no shard, and every job still reports success. Nothing
12
+ # inside a single shard can notice, because a shard cannot tell "not mine" from "does not exist".
13
+ #
14
+ # So the check belongs after the matrix, over the run reports it produced. Point it at every shard's
15
+ # report and it fails unless the reports describe one coherent split of one suite.
16
+ class ShardCheck
17
+ Result = Struct.new(:ok, :problems, :summary, keyword_init: true) do
18
+ def ok? = ok
19
+ end
20
+
21
+ def self.call(paths) = new(paths).call
22
+
23
+ def initialize(paths)
24
+ @paths = Array(paths)
25
+ end
26
+
27
+ def call
28
+ return failure(['no run reports given']) if @paths.empty?
29
+
30
+ reports, unreadable = load_reports
31
+ return failure(unreadable) unless unreadable.empty?
32
+
33
+ shards = reports.filter_map { |path, data| shard_of(path, data) }
34
+ missing = reports.map(&:first) - shards.map { |s| s[:path] }
35
+ return failure(missing.map { |p| "#{p}: no `shard` section — was it run with --shard?" }) unless missing.empty?
36
+
37
+ problems = check(shards)
38
+ problems.empty? ? success(shards) : failure(problems)
39
+ end
40
+
41
+ private
42
+
43
+ def load_reports
44
+ reports = []
45
+ unreadable = []
46
+ @paths.each do |path|
47
+ reports << [path, JSON.parse(File.read(path))]
48
+ rescue Errno::ENOENT
49
+ unreadable << "#{path}: no such file"
50
+ rescue JSON::ParserError => e
51
+ unreadable << "#{path}: not valid JSON (#{e.message})"
52
+ end
53
+ [reports, unreadable]
54
+ end
55
+
56
+ def shard_of(path, data)
57
+ section = data['shard']
58
+ return nil unless section.is_a?(Hash)
59
+
60
+ {
61
+ path: path,
62
+ index: section['index'],
63
+ total: section['total'],
64
+ discovered: section['discovered_tests'],
65
+ selected: section['selected_tests']
66
+ }
67
+ end
68
+
69
+ def check(shards)
70
+ problems = []
71
+ problems.concat(agreement_problems(shards, :total, 'shard count'))
72
+ problems.concat(agreement_problems(shards, :discovered, 'discovered test count'))
73
+ problems.concat(completeness_problems(shards))
74
+ problems.concat(coverage_problems(shards))
75
+ problems
76
+ end
77
+
78
+ # Every report must describe the same matrix. Disagreement here means the reports were not produced by
79
+ # one run, and no coverage conclusion drawn from them would mean anything.
80
+ def agreement_problems(shards, field, label)
81
+ values = shards.map { |s| s[field] }.uniq
82
+ return [] if values.size <= 1
83
+
84
+ ["shards disagree on #{label}: #{values.sort_by(&:to_s).inspect}"]
85
+ end
86
+
87
+ # A matrix that lost a job silently drops that job's slice, which looks exactly like a smaller suite.
88
+ def completeness_problems(shards)
89
+ total = shards.first[:total]
90
+ return [] if total.nil?
91
+
92
+ seen = shards.map { |s| s[:index] }
93
+ duplicates = seen.tally.select { |_, n| n > 1 }.keys.sort
94
+ problems = []
95
+ problems << "shard #{duplicates.join(', ')} reported more than once" unless duplicates.empty?
96
+
97
+ absent = (1..total).to_a - seen
98
+ problems << "no report for shard #{absent.join(', ')} of #{total}" unless absent.empty?
99
+ problems
100
+ end
101
+
102
+ # The check this class exists for: the slices must add up to the suite.
103
+ def coverage_problems(shards)
104
+ discovered = shards.first[:discovered]
105
+ return [] if discovered.nil?
106
+
107
+ selected = shards.sum { |s| s[:selected].to_i }
108
+ return [] if selected == discovered
109
+
110
+ verb = selected < discovered ? 'ran no shard' : 'ran in more than one shard'
111
+ ["shards cover #{selected} of #{discovered} tests — #{(discovered - selected).abs} #{verb}. " \
112
+ 'The shards partitioned different timing data; make every shard load the same timing file.']
113
+ end
114
+
115
+ def success(shards)
116
+ Result.new(
117
+ ok: true,
118
+ problems: [],
119
+ summary: "#{shards.size} shards cover all #{shards.first[:discovered]} tests"
120
+ )
121
+ end
122
+
123
+ def failure(problems)
124
+ Result.new(ok: false, problems: problems, summary: 'shard coverage check failed')
125
+ end
126
+ end
127
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Binpacker
4
+ # Folds the timing files a sharded matrix wrote back into one.
5
+ #
6
+ # Every shard starts from the same timing file (it must, to cut the same partition), measures only its own
7
+ # slice, and writes the whole file back: its slice's tests with a fresh sample, everyone else's exactly as
8
+ # restored. A CI cache can keep one of those files, not all of them, so without a merge each run's history
9
+ # gains one shard's measurements and loses the rest — the other slices' weights age until a run happens to
10
+ # put their files in the shard whose file was kept.
11
+ #
12
+ # The merge needs no record of which shard ran what: a test a shard did not run is byte-for-byte what the
13
+ # base held, so per test, the shard whose samples differ from the base is the one that measured it. In a
14
+ # coherent split that is at most one shard. Should two disagree anyway — an overlapping partition, or rspec
15
+ # filing a shared example group's timings under the group's own file, which two shards can both run — the
16
+ # later file on the command line wins, and the test is counted in Result#conflicts rather than dropped.
17
+ class ShardMerge
18
+ Result = Struct.new(:tests, :updated, :conflicts, keyword_init: true)
19
+
20
+ def self.call(base:, shards:, output:)
21
+ new(base: base, shards: shards, output: output).call
22
+ end
23
+
24
+ def initialize(base:, shards:, output:)
25
+ @base = base
26
+ @shards = shards
27
+ @output = output
28
+ end
29
+
30
+ def call
31
+ # Compared as the shards will have written it back: compaction trims every test to its most recent
32
+ # samples, so against an uncompacted base every test would look re-measured by every shard.
33
+ base = (@base ? Timing.new(@base).samples : {}).transform_values { |t| t.last(Timing::MAX_SAMPLES_PER_TEST) }
34
+ merged = base.dup
35
+ writers = Hash.new(0)
36
+
37
+ @shards.each do |path|
38
+ Timing.new(path).samples.each do |key, times|
39
+ next if base[key] == times
40
+
41
+ writers[key] += 1
42
+ merged[key] = times
43
+ end
44
+ end
45
+
46
+ Timing.new(@output).write_samples(merged)
47
+ Result.new(tests: merged.size, updated: writers.size, conflicts: writers.count { |_key, n| n > 1 })
48
+ end
49
+ end
50
+ end
@@ -13,6 +13,23 @@ module Binpacker
13
13
  # run (GC pause, noisy CI neighbour) unable to move the weight.
14
14
  MAX_SAMPLES_PER_TEST = 3
15
15
 
16
+ # A run's speed factor is the median, over the files it measured that
17
+ # already carry history, of measured / predicted seconds. Files lighter
18
+ # than this are left out: their few-millisecond weights swing on noise
19
+ # that says nothing about the machine.
20
+ SPEED_FACTOR_MIN_FILE_WEIGHT = 1.0
21
+
22
+ # Fewer qualifying files than this and the run's factor is not
23
+ # estimated at all: a median over a handful of files mostly measures
24
+ # those files' own changes.
25
+ SPEED_FACTOR_MIN_FILES = 5
26
+
27
+ # A factor this close to 1.0 is recorded as 1.0. Each run's factor is an
28
+ # estimate, and dividing by it every run would compound that estimate's
29
+ # noise into a slow drift of the whole history's scale; inside the band
30
+ # the run's samples are kept as measured seconds.
31
+ SPEED_FACTOR_DEADBAND = 0.05
32
+
16
33
  def initialize(path)
17
34
  @path = Pathname(path)
18
35
  end
@@ -57,6 +74,49 @@ module Binpacker
57
74
  samples = samples_by_test
58
75
  return if samples.empty?
59
76
 
77
+ write_samples(samples)
78
+ end
79
+
80
+ # How fast the machine that produced +entries+ (one run's measured
81
+ # timings) ran against the history in this file: the median, over the
82
+ # files both sides know, of measured / predicted seconds. 2.0 means the
83
+ # run took twice as long as its history predicts; nil when too few
84
+ # files qualify to say (see SPEED_FACTOR_MIN_FILES).
85
+ #
86
+ # CI runners are not one machine. The same slice of a suite has run in
87
+ # 664s on one runner and 1208s on another, and a sample recorded on the
88
+ # slow one inflates its files' weights against every other file's, so
89
+ # the next partition is cut on a skewed scale. Dividing a run's samples
90
+ # by its factor before recording them keeps the history on one scale.
91
+ # The median is over files, not a ratio of sums, so one file that
92
+ # genuinely got slower in this run cannot move the factor much.
93
+ def speed_factor(entries)
94
+ predicted = load_per_file
95
+ actual = entries.each_with_object(Hash.new(0.0)) do |e, acc|
96
+ acc[normalize_path(e[:file])] += e[:time].to_f
97
+ end
98
+
99
+ ratios = actual.filter_map do |file, seconds|
100
+ weight = predicted[file]
101
+ next if weight.nil? || weight < SPEED_FACTOR_MIN_FILE_WEIGHT || !seconds.positive?
102
+
103
+ seconds / weight
104
+ end
105
+ return nil if ratios.size < SPEED_FACTOR_MIN_FILES
106
+
107
+ factor = median(ratios)
108
+ (factor - 1.0).abs < SPEED_FACTOR_DEADBAND ? 1.0 : factor
109
+ end
110
+
111
+ # [normalized file, name] => [sample, ...] in append (= run) order.
112
+ def samples
113
+ samples_by_test.transform_values(&:dup)
114
+ end
115
+
116
+ # Replaces the file's contents with +samples+ (the shape #samples
117
+ # returns), keeping the most recent MAX_SAMPLES_PER_TEST per test.
118
+ def write_samples(samples)
119
+ @path.dirname.mkpath unless @path.dirname.directory?
60
120
  tmp = Pathname("#{@path}.tmp")
61
121
  tmp.open('w', encoding: 'UTF-8') do |io|
62
122
  samples.each do |(file, name), times|
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Binpacker
4
- VERSION = "0.4.0"
4
+ VERSION = "0.6.0"
5
5
  end
data/lib/binpacker.rb CHANGED
@@ -1,19 +1,22 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "binpacker/version"
4
- require_relative "binpacker/config"
5
- require_relative "binpacker/timing"
6
- require_relative "binpacker/test_discovery"
7
- require_relative "binpacker/worker_queue"
8
- require_relative "binpacker/scheduler"
9
- require_relative "binpacker/worker"
10
- require_relative "binpacker/test_runner"
11
- require_relative "binpacker/calibration"
12
- require_relative "binpacker/report"
13
- require_relative "binpacker/skills"
14
- require_relative "binpacker/project_state"
15
- require_relative "binpacker/orchestrator"
16
- require_relative "binpacker/progress"
3
+ require_relative 'binpacker/version'
4
+ require_relative 'binpacker/config'
5
+ require_relative 'binpacker/timing'
6
+ require_relative 'binpacker/test_discovery'
7
+ require_relative 'binpacker/worker_queue'
8
+ require_relative 'binpacker/scheduler'
9
+ require_relative 'binpacker/shard'
10
+ require_relative 'binpacker/shard_check'
11
+ require_relative 'binpacker/shard_merge'
12
+ require_relative 'binpacker/worker'
13
+ require_relative 'binpacker/test_runner'
14
+ require_relative 'binpacker/calibration'
15
+ require_relative 'binpacker/report'
16
+ require_relative 'binpacker/skills'
17
+ require_relative 'binpacker/project_state'
18
+ require_relative 'binpacker/orchestrator'
19
+ require_relative 'binpacker/progress'
17
20
 
18
21
  module Binpacker
19
22
  Error = Class.new(StandardError)
@@ -8,6 +8,7 @@ module Binpacker
8
8
  def test_exclude: () -> Array[String]
9
9
  def test_granularity: () -> String
10
10
  def report_file: () -> String?
11
+ def normalize_speed: () -> bool
11
12
  def profile: () -> String
12
13
  end
13
14
  end
@@ -7,10 +7,15 @@ module Binpacker
7
7
  @passthrough: untyped
8
8
  @quiet: untyped
9
9
  @report_path: untyped
10
+ @shard: Binpacker::Shard?
11
+ @discovered_count: Integer
12
+ @selected_count: Integer
10
13
  @timings: Hash[untyped, Float]
11
14
  @predicted_loads: Array[Float]
15
+ @selected_keys: Array[untyped]
16
+ @speed_factor: Float?
12
17
 
13
- def initialize: (untyped, ?passthrough: untyped, ?quiet: untyped, ?report_path: untyped) -> void
18
+ def initialize: (untyped, ?passthrough: untyped, ?quiet: untyped, ?report_path: untyped, ?shard: Binpacker::Shard?) -> void
14
19
  def run: () -> { passed: untyped, total: untyped, passed_count: untyped, timings: Array[untyped], empty_filter: untyped }
15
20
 
16
21
  private
@@ -22,6 +27,8 @@ module Binpacker
22
27
  def min_batch_weight: (Binpacker::Timing, Hash[untyped, Float]) -> Float
23
28
  def drain_batch: (Binpacker::WorkerQueue?, Float) -> Array[untyped]
24
29
  def finalize: (Binpacker::Timing, Array[untyped], untyped, untyped, untyped, untyped) -> { passed: untyped, total: untyped, passed_count: untyped, timings: Array[untyped], empty_filter: untyped }
30
+ def normalize?: () -> bool
31
+ def normalized: (Array[Hash[Symbol, untyped]]) -> Array[Hash[Symbol, untyped]]
25
32
  def minitest_empty_filter?: (untyped, untyped) -> bool
26
33
  def minitest_include_filter?: () -> bool
27
34
  end
@@ -3,7 +3,8 @@ module Binpacker
3
3
  SCHEMA: Integer
4
4
  DRIFT_LIMIT: Integer
5
5
 
6
- def initialize: (profile: untyped, algorithm: untyped, predicted_loads: untyped, worker_stats: untyped, all_timings: untyped, timings: untyped) -> void
6
+ def initialize: (profile: untyped, algorithm: untyped, predicted_loads: untyped, worker_stats: untyped, all_timings: untyped, timings: untyped, ?speed_factor: Float?, ?normalized: bool, ?shard: Binpacker::Shard?, ?discovered: Integer?, ?selected: Integer?) -> void
7
+ def shard_section: () -> Hash[Symbol, untyped]?
7
8
  def to_h: () -> Hash[Symbol, untyped]
8
9
  def write: (untyped) -> untyped
9
10
  end
@@ -1,5 +1,16 @@
1
1
  module Binpacker
2
2
  class Scheduler
3
3
  def self.for: (untyped) -> (Binpacker::LptScheduler | Binpacker::MultifitScheduler)
4
+
5
+ # Declared on the base so a caller holding a `Scheduler` can partition; the base body raises
6
+ # NotImplementedError and every concrete scheduler overrides it.
7
+ def partition: (tests: Array[untyped], worker_count: Integer, timings: Hash[untyped, Float]) -> Array[Binpacker::WorkerQueue]
8
+ end
9
+
10
+ class LptScheduler < Scheduler
11
+ end
12
+
13
+ class MultifitScheduler < Scheduler
14
+ ITERATIONS: Integer
4
15
  end
5
16
  end
@@ -0,0 +1,13 @@
1
+ module Binpacker
2
+ class Shard
3
+ attr_reader index: Integer
4
+ attr_reader total: Integer
5
+
6
+ def self.parse: (String?) -> Binpacker::Shard?
7
+
8
+ def initialize: (index: Integer, total: Integer) -> void
9
+ def to_s: () -> String
10
+ def whole_suite?: () -> bool
11
+ def select: (tests: Array[untyped], timings: Hash[untyped, Float], scheduler: Binpacker::Scheduler) -> Array[untyped]
12
+ end
13
+ end
@@ -0,0 +1,29 @@
1
+ module Binpacker
2
+ class ShardCheck
3
+ class Result
4
+ attr_accessor ok: bool
5
+ attr_accessor problems: Array[String]
6
+ attr_accessor summary: String
7
+
8
+ def ok?: () -> bool
9
+ end
10
+
11
+ @paths: Array[String]
12
+
13
+ def self.call: (Array[String]) -> Binpacker::ShardCheck::Result
14
+
15
+ def initialize: (Array[String]) -> void
16
+ def call: () -> Binpacker::ShardCheck::Result
17
+
18
+ private
19
+
20
+ def load_reports: () -> [Array[[String, untyped]], Array[String]]
21
+ def shard_of: (String, untyped) -> Hash[Symbol, untyped]?
22
+ def check: (Array[Hash[Symbol, untyped]]) -> Array[String]
23
+ def agreement_problems: (Array[Hash[Symbol, untyped]], Symbol, String) -> Array[String]
24
+ def completeness_problems: (Array[Hash[Symbol, untyped]]) -> Array[String]
25
+ def coverage_problems: (Array[Hash[Symbol, untyped]]) -> Array[String]
26
+ def success: (Array[Hash[Symbol, untyped]]) -> Binpacker::ShardCheck::Result
27
+ def failure: (Array[String]) -> Binpacker::ShardCheck::Result
28
+ end
29
+ end
@@ -0,0 +1,18 @@
1
+ module Binpacker
2
+ class ShardMerge
3
+ class Result
4
+ attr_accessor tests: Integer
5
+ attr_accessor updated: Integer
6
+ attr_accessor conflicts: Integer
7
+ end
8
+
9
+ @base: String?
10
+ @shards: Array[String]
11
+ @output: String
12
+
13
+ def self.call: (base: String?, shards: Array[String], output: String) -> Binpacker::ShardMerge::Result
14
+
15
+ def initialize: (base: String?, shards: Array[String], output: String) -> void
16
+ def call: () -> Binpacker::ShardMerge::Result
17
+ end
18
+ end
@@ -3,13 +3,19 @@ module Binpacker
3
3
  def initialize: (untyped) -> void
4
4
  DEFAULT_WEIGHT: Float
5
5
  MAX_SAMPLES_PER_TEST: Integer
6
+ SPEED_FACTOR_MIN_FILE_WEIGHT: Float
7
+ SPEED_FACTOR_MIN_FILES: Integer
8
+ SPEED_FACTOR_DEADBAND: Float
6
9
  def calibrated?: () -> bool
7
10
  def load_with_fallback: (untyped) -> Hash[untyped, Float]
8
11
  def load_raw: () -> (Hash[[String, untyped], untyped] | {})
9
12
  def load_per_file: () -> (Hash[String, untyped] | {})
10
13
  def normalize_path: (untyped) -> String
11
14
  def measured?: (file: untyped, name: untyped) -> bool
12
- def compact!: () -> nil
15
+ def compact!: () -> void
16
+ def speed_factor: (Array[Hash[Symbol, untyped]]) -> Float?
17
+ def samples: () -> Hash[[String, untyped], Array[Float]]
18
+ def write_samples: (Hash[[String, untyped], Array[Float]]) -> void
13
19
  def append_all: (untyped) -> nil
14
20
  class Entry
15
21
  end
@@ -1,8 +1,17 @@
1
1
  module Binpacker
2
2
  class WorkerQueue
3
+ include Enumerable[untyped]
4
+
5
+ attr_reader worker_id: Integer
6
+
3
7
  def initialize: (untyped, ?untyped) -> void
4
8
  def empty?: () -> (false | true)
5
9
  def pop: () -> untyped
10
+ def peek: () -> untyped
11
+ def size: () -> Integer
12
+ def remaining: () -> Array[untyped]
6
13
  def total_weight: (Hash[untyped, Float]) -> Float
14
+ def push: (untyped) -> untyped
15
+ def each: () { (untyped) -> void } -> void
7
16
  end
8
17
  end
@@ -22,8 +22,11 @@ Collect several recent reports so you can see trends, not just one run. Each rep
22
22
 
23
23
  ## 2. Analyze
24
24
 
25
+ **On a sharded matrix, first rule out causes that are not binpacker's.** Compare each shard's `predicted_makespan`: when they agree, the partition is already equal and the jobs' wall-clock difference came from somewhere else — most often steps pinned to one matrix arm (`if: matrix.shard == 1`) that the matrix runs once and parked arbitrarily. No config lever fixes that; the step needs its own job. Say so plainly rather than proposing a scheduler change that cannot help.
26
+
25
27
  Look for patterns across the reports:
26
28
 
29
+ - **One file over the per-worker budget** — divide total predicted weight by shards × workers to get the floor every shard should reach, then look for a single `predicted` above it. That file occupies a whole worker and sets its shard's makespan alone, and no partition or shard count can beat it. Attribute it per-example from the timing file (see the README's sharding section) before proposing a split — the cost is usually concentrated in one block, which makes the seam obvious.
27
30
  - **Persistent worker skew** — the same worker is consistently slowest → the partition or worker count is off.
28
31
  - **Predicted vs actual gap** — `actual_makespan` far above `predicted_makespan` → timing data is stale; the scheduler is planning against wrong Weights.
29
32
  - **Recurring high-drift files** — the same files top the `drift` list every run → their timing data is stale or they are outliers.
@@ -38,6 +41,9 @@ Present a concrete `binpacker.yml` diff and/or commands, with the evidence behin
38
41
  - **`scheduler.steal_enabled`** — enable when static balance is poor but runtime stealing would recover it.
39
42
  - **Re-calibrate** — when drift is high or timing is stale, recommend `binpacker calibrate --incremental` to refresh the drifting Tests.
40
43
  - **Commit a baseline** — when the cache misses often (dependency-bump churn) or timings have stabilised, recommend committing `binpacker.timings` as a durable baseline (cold-start floor). See `docs/adr/0005-two-tier-timing-persistence.md`.
44
+ - **Discard the history** — after any test file was split, renamed or deleted. binpacker never drops entries for tests that no longer exist, so the old path stays charged for them while the new one falls back to filesize. A high-drift file whose `predicted` far exceeds its `actual` is the signature; check whether it was recently split before recalibrating. See the README's "Timing data after a file moves".
45
+
46
+ Read `predicted` against `actual` before trusting any of the above: a report whose CI job logged a timing-cache miss was partitioned on filesize weighting, and its balance says nothing about the config.
41
47
 
42
48
  ## 4. Confirm and apply
43
49
 
@@ -54,10 +54,15 @@ Check the summary's `Balance: max deviation`. A large deviation on the first run
54
54
  Add (or extend) a CI workflow so the suite runs under binpacker. The workflow should:
55
55
 
56
56
  - Install binpacker (via the project's dependency manager or `gem install binpacker`).
57
- - Restore and save `binpacker.timings` with `actions/cache` (key includes OS + a hash of the test files). This is the runtime timing layer.
57
+ - Restore and save `binpacker.timings` with `actions/cache` (key includes OS + a hash of the test files). This is the runtime timing layer. Put a **generation token** in the key (`binpacker-timings-v1-…`) so the history can be discarded later — it has to be, whenever a test file is split, renamed or deleted.
58
58
  - Run `binpacker run --profile ci` (which emits the run report via `report_file`).
59
59
  - Upload the run report with `actions/upload-artifact` so `binpacker-improve` can read it later.
60
60
 
61
+ Two things that only fail on a cache miss, so verify them rather than assuming the first green run proved them:
62
+
63
+ - **The `--report` directory must already exist.** binpacker creates the timing file's directory but not the report's, so `--report tmp/report.json` raises `ENOENT` unless something made `tmp/` first. A restored timing cache creates it as a side effect, which hides the problem until the first genuine miss — and then the whole matrix fails with every test passing. Add an explicit `mkdir -p`.
64
+ - **A cache-key bump costs two cold runs.** Caches saved on a feature branch are invisible to the default branch, so the first run after the merge is cold too.
65
+
61
66
  Propose the workflow YAML and let the user review it before writing.
62
67
 
63
68
  ## 6. Handoff
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: binpacker
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.4.0
4
+ version: 0.6.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - megurine
@@ -29,6 +29,9 @@ files:
29
29
  - lib/binpacker/project_state.rb
30
30
  - lib/binpacker/report.rb
31
31
  - lib/binpacker/scheduler.rb
32
+ - lib/binpacker/shard.rb
33
+ - lib/binpacker/shard_check.rb
34
+ - lib/binpacker/shard_merge.rb
32
35
  - lib/binpacker/skills.rb
33
36
  - lib/binpacker/test_discovery.rb
34
37
  - lib/binpacker/test_runner.rb
@@ -44,6 +47,9 @@ files:
44
47
  - sig/binpacker/project_state.rbs
45
48
  - sig/binpacker/report.rbs
46
49
  - sig/binpacker/scheduler.rbs
50
+ - sig/binpacker/shard.rbs
51
+ - sig/binpacker/shard_check.rbs
52
+ - sig/binpacker/shard_merge.rbs
47
53
  - sig/binpacker/skills.rbs
48
54
  - sig/binpacker/test_discovery.rbs
49
55
  - sig/binpacker/test_runner.rbs
@@ -72,7 +78,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
72
78
  - !ruby/object:Gem::Version
73
79
  version: '0'
74
80
  requirements: []
75
- rubygems_version: 4.0.10
81
+ rubygems_version: 4.0.16
76
82
  specification_version: 4
77
83
  summary: Reduce CI test-suite makespan via identical-machines scheduling
78
84
  test_files: []