padded_cell 0.2.0-x86_64-linux-gnu → 0.4.0-x86_64-linux-gnu

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: d938c3e531357727a22bf6a2759c2f381960729f309ce98c54474087cc5e7599
4
- data.tar.gz: 6f91994847f2b887ddd3523c71e1c197028d529a55a9b2726f8146afcd847cb3
3
+ metadata.gz: ebe683991a538645ccc89454dbfac05db37da935176bbc92d253af396dbb1cf1
4
+ data.tar.gz: 6ba9ebbc9d3aebd440e6110f468ddd6ecf6e5f9d656f1496bd815460a0299439
5
5
  SHA512:
6
- metadata.gz: 703c85c4e53f4c03c6b068e688b459d0b279e3ad80117075e3ded0e342b73383975f4632bbb4694d48d6c8e5e2fe8233b7839efc7df53ee2f2e5ffb904157ab0
7
- data.tar.gz: f9d6f0dbd6e472529eabe4c82bccb669295957fcaad2c7319b2a2d8136267a52986b8e4c1dabf2ed9c71e70d1da1d79839ba9c3abbfdf5bd5c0e561a0b3e02ec
6
+ metadata.gz: 2659b68f32dc9128fa639ec4c4322798259c938e20ed442ed59d5fea2bd3c25f9457b3e018eea2b3c775f5619f7157ab0d9a07975cc6a740dfe6630554b85067
7
+ data.tar.gz: 47cc8e205342835bc98956744667dd97a7a67060cf0cebc06722f6b986143fef3caa3a620a60c52541417578a3756091645897bae743233294e2ed40dc150da0
data/CHANGELOG.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0 (2026-11-08)
4
+
5
+ - `PADDED_CELL_ASYLUM`: retries failures from the environment. N retries,
6
+ or `true`/`yes`/`on` for the default 2; `0`, `false`, `no` and `off` leave
7
+ it off. `--asylum` still wins.
8
+ - `--coverage-map PATH` (or `PADDED_CELL_COVERAGE_MAP`): the lines each test
9
+ ran, as JSON lines (`{"id":…,"file":…,"line":…,"covers":{path => lines}}`),
10
+ for CI that reruns only the tests a diff touches. Turns on
11
+ `--coverage=lines,methods` when coverage is off; never changes the summed
12
+ report. Free with `--isolation test`; with `--isolation worker`, two
13
+ coverage copies per test.
14
+
15
+ ## 0.3.0 (2026-11-08)
16
+
17
+ - `--budget SECONDS`: a deadline for the whole run, loading included. Once
18
+ it's spent, nothing more is dispatched and running tests are killed. Tests
19
+ it left out fail the run (exit 1). `--timeout` never outlives it.
20
+ - Workers that keep dying (more than 4 per worker, at least 16, in 10s) are
21
+ no longer replaced forever. padded_cell gives up, reports how many tests
22
+ never ran, and exits 1. Uses `supervisor-machines`.
23
+ - A replacement worker that died before its first test crashed the run with
24
+ `Errno::EPIPE` (exit 2). A worker reset mid-frame is now reported as dead.
25
+ - `--asylum` retry seeds keep all 64 bits: they were folded modulo 0xffff,
26
+ so large `--seed`s shared the same few retry seeds.
27
+
3
28
  ## 0.2.0 (2026-10-11)
4
29
 
5
30
  - Built-in coverage: `--coverage[=lines,branches,methods,eval]` (or
data/README.md CHANGED
@@ -69,11 +69,14 @@ $ padded_cell user_test.rb:12-30:41 # tests overlapping 12..30, or spanni
69
69
  $ padded_cell -n /refund/ -e test_slow # Minitest's --include / --exclude
70
70
  $ padded_cell -j 8 --seed 1234 # 8 workers, reproducible order
71
71
  $ padded_cell --timeout 30 # kill and fail anything running 30s
72
+ $ padded_cell --budget 600 # the whole run gets 10 minutes; what's left out fails it
72
73
  $ padded_cell --fail-fast
73
74
  $ padded_cell --asylum # retry failures; report the flaky ones (see below)
75
+ $ PADDED_CELL_ASYLUM=2 padded_cell # same, from a CI runner's env
74
76
  $ padded_cell --list # what would run, without loading anything
75
77
  $ padded_cell --shard 2/4 # CI: the second quarter of the classes
76
78
  $ padded_cell --junit tmp/junit.xml --json tmp/results.jsonl
79
+ $ PADDED_CELL_JSON=tmp/results.jsonl padded_cell # same, from a CI runner's env
77
80
  $ padded_cell --coverage # line and branch coverage (see Coverage)
78
81
  ```
79
82
 
@@ -110,6 +113,23 @@ cheap, and order-dependent tests stop depending on order.
110
113
  Rails' `parallelize`. A worker that crashes or times out is still reported
111
114
  and replaced.
112
115
 
116
+ Replaced up to a point. If workers keep dying, say a boot that segfaults or an
117
+ `after_fork` hook that calls `exit`, every remaining test would come back as a
118
+ crash report, one fork at a time. So past 4 deaths per worker in 10 seconds
119
+ (16 at least), padded_cell gives up: it lists how many tests never ran and
120
+ exits 1. The decision comes from
121
+ [supervisor_machines](https://github.com/seuros/supervisor_machines), the same
122
+ one-for-one restart intensity OTP uses.
123
+
124
+ ### Budget
125
+
126
+ `--budget SECONDS` caps the whole run, loading included. Once it's spent,
127
+ nothing more is dispatched, and a test still running is killed and fails
128
+ ("run budget of 600.0s spent"). A test's `--timeout` never outlives the
129
+ budget. If the budget left tests out, the run fails and says how many. The
130
+ deadline math comes from
131
+ [deadline_machines](https://github.com/seuros/deadline_machines).
132
+
113
133
  The default is `test`, except when Active Record fixtures are loaded: a fork
114
134
  discards Active Record's connection pool, and every test would reload its
115
135
  fixtures, so those suites default to `worker`. The `Run options:` line shows
@@ -252,6 +272,38 @@ The merge refuses files that differ between shards or from the checkout,
252
272
  and checks thresholds when every shard of the run is there. Lines that run
253
273
  while the suite loads count once per shard.
254
274
 
275
+ ### Coverage map
276
+
277
+ Which lines each test ran, so CI can rerun only the tests touching a diff:
278
+
279
+ ```console
280
+ $ padded_cell --coverage-map tmp/coverage_map.jsonl
281
+ $ PADDED_CELL_COVERAGE_MAP=tmp/coverage_map.jsonl padded_cell # same; the flag wins
282
+ ```
283
+
284
+ One JSON object per test, in id order, written at the end of the run:
285
+
286
+ ```json
287
+ {"id":"SignTest#test_zero","file":"test/calc_test.rb","line":28,"covers":{"lib/calc.rb":[[7,8],10,13]}}
288
+ ```
289
+
290
+ `covers` holds the files the coverage report shows (filters apply, `test/`
291
+ stays out), each with its line numbers ascending, `[first, last]` for a run
292
+ of consecutive ones. Lines a test runs while loading a file count for it.
293
+
294
+ Ruby's line coverage never sees a call to `def add(a, b) = a + b`: with
295
+ `methods` measured, every method a test called adds its def line. Without
296
+ `--coverage`, the map turns on `lines,methods`. With it, the map adds no
297
+ criterion, so the report is byte for byte the same as without the map:
298
+ include `methods`, or one-liners go unmapped.
299
+
300
+ First attempts only, like the report. A test whose cell or worker died is
301
+ left out: it was not measured, so a selector should run it anyway.
302
+
303
+ A cell's measure is already its test's: free under `--isolation test`. With
304
+ `--isolation worker`, Ruby copies the coverage of every loaded file twice per
305
+ test (about 24 ms with 800 files loaded, more in a big Rails app).
306
+
255
307
  ### Cost
256
308
 
257
309
  Measuring is opt-in: Ruby's instrumentation slows tests down. On a Rails
@@ -305,7 +357,9 @@ PaddedCell::Scheduler.batches(class_names, durations: seconds, seed: 42, shard:
305
357
  ## Rust
306
358
 
307
359
  The extension lives in `ext/padded_cell_native`: `core` does discovery and
308
- scheduling in plain Rust (no Ruby types), `ffi` binds it to Ruby. Neither is
360
+ scheduling in plain Rust (no Ruby types), `ffi` binds it to Ruby. Worker
361
+ supervision and deadlines come from the published `supervisor-machines` and
362
+ `deadline-machines` crates. Neither is
309
363
  published as a crate.
310
364
 
311
365
  ## Development
@@ -13,18 +13,20 @@ module PaddedCell
13
13
  class Asylum
14
14
  ALONE = 'timing, contention or state left by other tests'
15
15
  RESEEDED = 'randomness or test order'
16
+ SEEDS = 2**64
16
17
 
17
18
  # The seed of retry attempt, derived from the run's seed so a report can
18
- # be replayed. Attempt 1 keeps the run's seed.
19
+ # be replayed. Attempt 1 keeps the run's seed. Wraps within the planner's
20
+ # 64-bit seeds, as --seed accepts them.
19
21
  def self.retry_seed(seed, attempt)
20
- attempt == 1 ? seed : (seed + (attempt * 0x9e37)) % 0xffff
22
+ attempt == 1 ? seed : (seed + (attempt * 0x9e37)) % SEEDS
21
23
  end
22
24
 
23
- def initialize(tests, attempts:, seed:, timeout: nil)
25
+ def initialize(tests, attempts:, seed:, limits: Limits.new)
24
26
  @tests = tests
25
27
  @attempts = attempts
26
28
  @seed = seed
27
- @timeout = timeout
29
+ @limits = limits
28
30
  @success = true
29
31
  end
30
32
 
@@ -58,7 +60,7 @@ module PaddedCell
58
60
  def retry_round(pending, history, attempt)
59
61
  seed = self.class.retry_seed(@seed, attempt)
60
62
  passed = []
61
- pool = Pool.new(@tests, jobs: 1, isolation: :test, seed:, timeout: @timeout)
63
+ pool = Pool.new(@tests, jobs: 1, isolation: :test, seed:, limits: @limits)
62
64
  pool.run([pending.dup]) do |index, result|
63
65
  recovered = result.passed? && !result.skipped?
64
66
  history[index] << attempt_entry(seed, true, recovered ? nil : result)
@@ -9,20 +9,22 @@ module PaddedCell
9
9
  module_function
10
10
 
11
11
  # Runs klass#name in a fork and returns its Minitest::Result, or an error
12
- # result when the cell died or ran past timeout seconds.
12
+ # result when the cell died or ran past its deadline.
13
13
  #
14
- # close: descriptors the cell must not keep open (the worker's socket)
15
- # probe: the worker's Chart::Probe, which gets the cell's coverage
16
- def run(klass, name, seed:, timeout: nil, close: [], probe: nil)
14
+ # limits: the run's Limits (--timeout, --budget); nil: no deadline
15
+ # close: descriptors the cell must not keep open (the worker's socket)
16
+ # probe: the worker's Chart::Probe, which gets the cell's coverage
17
+ def run(klass, name, seed:, limits: nil, close: [], probe: nil)
17
18
  # Binary: the result is Marshal data, and with Encoding.default_internal
18
19
  # set (Rails sets it) a text-mode pipe transcodes what is written to it.
19
20
  reader, writer = IO.pipe
20
21
  [reader, writer].each(&:binmode)
21
22
  started = Minitest.clock_time
23
+ deadline = limits&.for_test
22
24
  pid = fork_cell(klass, name, seed, reader, writer, close, probe)
23
25
  writer.close
24
- delta, result = collect(pid, reader, klass, name, started, timeout)
25
- delta ? probe.absorb(delta) : probe&.lost
26
+ delta, result = collect(pid, reader, klass, name, started, deadline) { limits.message(deadline) }
27
+ delta ? probe.absorb(delta, result) : probe&.lost
26
28
  result
27
29
  ensure
28
30
  reader&.close
@@ -59,14 +61,15 @@ module PaddedCell
59
61
  end
60
62
  end
61
63
 
62
- # [coverage delta or nil, result]
63
- def collect(pid, reader, klass, name, started, timeout)
64
- data = read(reader, timeout && (started + timeout))
64
+ # [coverage delta or nil, result]. Yields for the message of a cell
65
+ # killed at its deadline.
66
+ def collect(pid, reader, klass, name, started, deadline)
67
+ data = read(reader, deadline)
65
68
  elapsed = Minitest.clock_time - started
66
69
  if data.nil?
67
70
  Process.kill(:KILL, pid)
68
71
  Process.wait(pid)
69
- return [nil, Results.crashed(klass, name, "timed out after #{timeout}s", time: elapsed)]
72
+ return [nil, Results.crashed(klass, name, yield, time: elapsed)]
70
73
  end
71
74
 
72
75
  _, status = Process.wait2(pid)
@@ -75,11 +78,11 @@ module PaddedCell
75
78
  [nil, Results.crashed(klass, name, Results.describe(status, 'cell'), time: elapsed)]
76
79
  end
77
80
 
78
- # Everything until EOF, or nil when the deadline passes first.
81
+ # Everything until EOF, or nil when the deadline (if any) passes first.
79
82
  def read(io, deadline)
80
83
  data = String.new(encoding: Encoding::BINARY)
81
84
  loop do
82
- remaining = deadline && (deadline - Minitest.clock_time)
85
+ remaining = deadline && Limits.remaining(deadline)
83
86
  return if remaining&.<= 0
84
87
  next unless io.wait_readable(remaining)
85
88
 
@@ -13,11 +13,14 @@ module PaddedCell
13
13
  attr_reader :criteria
14
14
 
15
15
  # criteria: what Ruby's Coverage measures, :lines always among them
16
- def initialize(criteria)
16
+ # map: each test's lines go on its result too (--coverage-map)
17
+ def initialize(criteria, map: false)
17
18
  @criteria = criteria
19
+ @map = map
18
20
  @root = File.realpath(Dir.pwd)
19
21
  @roots = [Dir.pwd, @root].uniq.map { "#{it}/" }
20
22
  @kept = {}
23
+ @names = {}
21
24
  @lost = 0
22
25
  @known = Set.new
23
26
  end
@@ -39,7 +42,16 @@ module PaddedCell
39
42
  # For a worker, right after its fork.
40
43
  def probe
41
44
  Probe.new(file: File.join(@frames, "#{Process.pid}.cov"), known: @known, keep: method(:keep?),
42
- methods: @criteria.include?(:methods), interval: Chart.config.interval)
45
+ methods: @criteria.include?(:methods), interval: Chart.config.interval, map: @map)
46
+ end
47
+
48
+ # A measured file's name in the report, or nil for a file the report
49
+ # leaves out (filtered, outside the root, deleted).
50
+ def project_file(path)
51
+ @names.fetch(path) do
52
+ name = relative(path)
53
+ @names[path] = (name if name && !Chart.config.skipped?(path, name))
54
+ end
43
55
  end
44
56
 
45
57
  # A worker died: what it measured since its last flush is gone.
@@ -85,19 +97,25 @@ module PaddedCell
85
97
  end
86
98
  end
87
99
 
88
- # Keys by real path relative to the root: a file required through a
89
- # symlink and through its real path is one file. A file deleted during
90
- # the run is not reported.
100
+ # Keys by real path relative to the root.
91
101
  def normalize(total)
92
102
  total.each_with_object({}) do |(path, entry), files|
93
- relative = File.realpath(path).delete_prefix("#{@root}/")
94
- next if relative.start_with?('/')
103
+ relative = relative(path)
104
+ next unless relative
95
105
 
96
106
  files[relative] ? Delta.merge!(files, { relative => entry }) : files[relative] = entry
97
- rescue SystemCallError
98
- next
99
107
  end
100
108
  end
109
+
110
+ # By real path: a file required through a symlink and through its real
111
+ # path is one file. nil outside the root, or for a file deleted during
112
+ # the run.
113
+ def relative(path)
114
+ relative = File.realpath(path).delete_prefix("#{@root}/")
115
+ relative unless relative.start_with?('/')
116
+ rescue SystemCallError
117
+ nil
118
+ end
101
119
  end
102
120
  end
103
121
  end
@@ -65,6 +65,12 @@ module PaddedCell
65
65
  end
66
66
  alias filter skip
67
67
 
68
+ # Whether a filter leaves the file out (path absolute, name relative).
69
+ def skipped?(path, name)
70
+ file = SourceFile.new(path, name)
71
+ @filters.any? { it.call(file) }
72
+ end
73
+
68
74
  # Removes every filter, the defaults included.
69
75
  def clear_filters = @filters.clear
70
76
 
@@ -51,6 +51,19 @@ module PaddedCell
51
51
  total
52
52
  end
53
53
 
54
+ # {path => [line number, ...]}: the lines that ran, ascending, by file.
55
+ # A call to `def add(a, b) = a + b` runs no line Ruby sees: methods,
56
+ # when measured, add the first line of every method that ran.
57
+ def ran(delta)
58
+ delta.each_with_object({}) do |(path, entry), ran|
59
+ lines = entry[:lines]
60
+ indices = lines.is_a?(Hash) ? lines.keys : lines.each_index.select { lines[it]&.positive? }
61
+ numbers = indices.map { it + 1 }
62
+ entry[:methods]&.each { |(_, first), (_, hits)| numbers << first if hits.positive? }
63
+ ran[path] = numbers.uniq.sort unless numbers.empty?
64
+ end
65
+ end
66
+
54
67
  # Coverage's arrays are frozen.
55
68
  def dense(data)
56
69
  {
@@ -16,15 +16,22 @@ module PaddedCell
16
16
  # A flush copies the coverage of every file Ruby loaded, gems included: a
17
17
  # few milliseconds in a small app, a few hundred in a big Rails one. The
18
18
  # interval stretches to keep flushes under 1% of a worker's time.
19
+ #
20
+ # With the map on (--coverage-map), each test's result also carries the
21
+ # lines it ran, in its metadata under :covers. A cell's delta is already
22
+ # its test's; a worker running tests itself clears Coverage around each
23
+ # one, two more copies per test. What it clears goes into its measure, so
24
+ # the sum does not change.
19
25
  class Probe
20
26
  INTERVAL = 10.0
21
27
  BUDGET = 100
22
28
 
23
- def initialize(file:, known:, keep:, methods:, interval: INTERVAL)
29
+ def initialize(file:, known:, keep:, methods:, interval: INTERVAL, map: false)
24
30
  @file = file
25
31
  @known = known
26
32
  @keep = keep
27
33
  @methods = methods
34
+ @map = map
28
35
  @interval = interval
29
36
  @wait = interval
30
37
  @pending = {}
@@ -40,8 +47,22 @@ module PaddedCell
40
47
  # The delta of a cell, at its end.
41
48
  def capture = Delta.capture(::Coverage.peek_result, @known, @keep)
42
49
 
43
- # A cell's delta, in its worker.
44
- def absorb(delta) = Delta.merge!(@pending, delta)
50
+ # A cell's delta, in its worker; with the map on, result gets the lines
51
+ # its test ran.
52
+ def absorb(delta, result = nil)
53
+ result.metadata[:covers] = Delta.ran(delta) if @map && result
54
+ Delta.merge!(@pending, delta)
55
+ end
56
+
57
+ # Runs a test in the worker (isolation :worker), which yields its result.
58
+ def measure
59
+ return yield unless @map
60
+
61
+ absorb(clear)
62
+ result = yield
63
+ absorb(clear, result)
64
+ result
65
+ end
45
66
 
46
67
  # A cell that died before reporting.
47
68
  def lost = @lost += 1
@@ -53,7 +74,7 @@ module PaddedCell
53
74
 
54
75
  def flush
55
76
  started = Minitest.clock_time
56
- delta = Delta.merge!(Delta.capture(::Coverage.result(stop: false, clear: true), @known, @keep), @pending)
77
+ delta = Delta.merge!(clear, @pending)
57
78
  frame = Marshal.dump({ delta:, lost: @lost })
58
79
  File.open(@file, 'ab') { it.write([frame.bytesize].pack('N') + frame) }
59
80
  # Dense entries brought their structure to the runner: from now on,
@@ -65,6 +86,11 @@ module PaddedCell
65
86
  # 0: after every test, whatever it costs.
66
87
  @wait = @interval.zero? ? 0 : [@interval, (@flushed - started) * BUDGET].max
67
88
  end
89
+
90
+ private
91
+
92
+ # What ran since the last clear, taken out of Coverage.
93
+ def clear = Delta.capture(::Coverage.result(stop: false, clear: true), @known, @keep)
68
94
  end
69
95
  end
70
96
  end
@@ -19,7 +19,7 @@ module PaddedCell
19
19
  loaded = loaded_features
20
20
  never, @unmeasured = tracked(files).partition { !loaded.include?(File.join(root, it)) }
21
21
  @rows = (files.map { |name, entry| row(name, entry) } + stubs(never))
22
- .reject { |path, name| skipped?(path, name) }
22
+ .reject { |path, name| @config.skipped?(path, name) }
23
23
  .sort_by { it[1] }
24
24
  end
25
25
 
@@ -72,11 +72,6 @@ module PaddedCell
72
72
  end
73
73
  end
74
74
 
75
- def skipped?(path, name)
76
- file = SourceFile.new(path, name)
77
- @config.filters.any? { it.call(file) }
78
- end
79
-
80
75
  # Required files, also under the root's real path.
81
76
  def loaded_features
82
77
  pwd = "#{Dir.pwd}/"
@@ -22,7 +22,8 @@ module PaddedCell
22
22
  # Exit status: 0 passed, 1 failed, 2 usage or load error, 3 coverage below
23
23
  # a minimum, 130 interrupted.
24
24
  def start(argv, io: $stdout)
25
- options = { io:, coverage: coverage_criteria(ENV.fetch('PADDED_CELL_COVERAGE', nil)) }
25
+ options = { io:, coverage: coverage_criteria(ENV.fetch('PADDED_CELL_COVERAGE', nil)), **report_paths,
26
+ **asylum_from_env }
26
27
  parser(options).parse!(argv)
27
28
  return merge(options) if options[:coverage_merge]
28
29
 
@@ -33,6 +34,23 @@ module PaddedCell
33
34
  2
34
35
  end
35
36
 
37
+ # Report paths a CI runner can set without touching the command line;
38
+ # --json, --junit and --coverage-map still win.
39
+ def report_paths
40
+ { json: ENV.fetch('PADDED_CELL_JSON', nil), junit: ENV.fetch('PADDED_CELL_JUNIT', nil),
41
+ coverage_map: ENV.fetch('PADDED_CELL_COVERAGE_MAP', nil) }
42
+ .reject { |_, path| path.nil? || path.empty? }
43
+ end
44
+
45
+ # PADDED_CELL_ASYLUM=N, or 1/true for the default 2 retries; --asylum wins.
46
+ def asylum_from_env
47
+ value = ENV.fetch('PADDED_CELL_ASYLUM', '').strip
48
+ return {} if value.empty? || %w[0 false no off].include?(value.downcase)
49
+ return { asylum: 2 } if %w[true yes on].include?(value.downcase)
50
+
51
+ { asylum: positive(Integer(value, 10)) }
52
+ end
53
+
36
54
  def parser(options)
37
55
  OptionParser.new do |opts|
38
56
  opts.banner = BANNER
@@ -70,6 +88,10 @@ module PaddedCell
70
88
  opts.on('--timeout SECONDS', Float, 'Kill and fail a test running longer') do
71
89
  options[:timeout] = positive(it)
72
90
  end
91
+ opts.on('--budget SECONDS', Float, 'Stop dispatching once the run has taken SECONDS (and kill and ' \
92
+ 'fail what runs past it); tests left out fail the run') do
93
+ options[:budget] = positive(it)
94
+ end
73
95
  opts.on('--fail-fast', 'Stop dispatching after the first failure') { options[:fail_fast] = true }
74
96
  opts.on('--asylum[=N]', Integer, 'Retry failed tests up to N times (default 2) after the run, alone, ' \
75
97
  'each in a fresh cell; report the flaky ones') do
@@ -87,6 +109,10 @@ module PaddedCell
87
109
  opts.on('--coverage-dir DIR', 'Write coverage reports to DIR (default: coverage, or the test helper\'s)') do
88
110
  options[:coverage_dir] = it
89
111
  end
112
+ opts.on('--coverage-map PATH', 'Write the lines each test ran to PATH, as JSON lines (measures ' \
113
+ 'lines,methods if coverage is off; or $PADDED_CELL_COVERAGE_MAP)') do
114
+ options[:coverage_map] = it
115
+ end
90
116
  opts.on('--coverage-merge DIR,DIR', Array, 'Merge the coverage of shards (their --coverage-dir) ' \
91
117
  'into one report; runs no test') do
92
118
  options[:coverage_merge] = it
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PaddedCell
4
+ # What cuts a test short: its --timeout, and what is left of the run's
5
+ # --budget. A test's deadline never outlives the run's. Deadlines are
6
+ # PaddedCellNative::Deadline values in monotonic nanoseconds: one clock for
7
+ # the runner, its workers and their cells.
8
+ class Limits
9
+ NS = 1_000_000_000
10
+
11
+ def self.now = Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond)
12
+
13
+ # Seconds left before deadline (0.0 once passed), nil when never.
14
+ def self.remaining(deadline, now = self.now) = deadline.remaining_ns(now)&./(NS.to_f)
15
+
16
+ attr_reader :timeout, :budget
17
+
18
+ # timeout: seconds per test, or nil
19
+ # budget: seconds for the whole run from started, or nil
20
+ def initialize(timeout: nil, budget: nil, started: Limits.now)
21
+ @timeout = timeout
22
+ @budget = budget
23
+ @run = budget ? PaddedCellNative::Deadline.after(started, nanoseconds(budget)) : PaddedCellNative::Deadline.never
24
+ end
25
+
26
+ # The deadline of a test starting now.
27
+ def for_test(now = Limits.now) = @run.derive(now, @timeout && nanoseconds(@timeout))
28
+
29
+ # True once the run's budget is gone: nothing more gets dispatched.
30
+ def spent?(now = Limits.now) = @run.expired?(now)
31
+
32
+ # Why a test that reached deadline was cut short.
33
+ def message(deadline)
34
+ if @budget && deadline.expires_at == @run.expires_at
35
+ "run budget of #{@budget}s spent"
36
+ else
37
+ "timed out after #{@timeout}s"
38
+ end
39
+ end
40
+
41
+ private
42
+
43
+ def nanoseconds(seconds) = (seconds * NS).round
44
+ end
45
+ end
@@ -13,20 +13,34 @@ module PaddedCell
13
13
  #
14
14
  # With isolation :test a worker forks a Cell per test; with :worker it runs
15
15
  # tests itself, faster but sharing process state. A worker that dies
16
- # mid-test, or runs past the timeout, gets its test reported as an error and
17
- # is replaced; its replacement continues the class.
16
+ # mid-test, or runs past its deadline (--timeout, --budget), gets its test
17
+ # reported as an error and is replaced; its replacement continues the class.
18
+ #
19
+ # Replaced, up to a point: workers that keep dying (a boot that segfaults,
20
+ # an after_fork hook that exits) would turn every remaining test into a
21
+ # crash report. Past PaddedCellNative::Restarts' limit the pool gives up.
22
+ # Once the run's budget is spent, it dispatches nothing more.
18
23
  class Pool
19
- Slot = Struct.new(:worker, :pid, :socket, :test, :started, :batch)
24
+ Slot = Struct.new(:worker, :pid, :socket, :test, :started, :batch, :deadline)
25
+
26
+ # Tests left undispatched by stop! (--fail-fast, the budget, giving up).
27
+ attr_reader :undispatched
28
+
29
+ # Why the pool gave up on its workers, or nil.
30
+ attr_reader :gave_up
20
31
 
21
32
  # tests: [[klass, method_name], ...], dispatched by index.
33
+ # limits: the run's Limits
22
34
  # coverage: a Chart::Accumulator when measuring coverage
23
- def initialize(tests, jobs:, isolation:, seed:, timeout: nil, coverage: nil)
35
+ def initialize(tests, jobs:, isolation:, seed:, limits: Limits.new, coverage: nil)
24
36
  @tests = tests
25
37
  @jobs = jobs
26
38
  @isolation = isolation
27
39
  @seed = seed
28
- @timeout = timeout
40
+ @limits = limits
29
41
  @coverage = coverage
42
+ @restarts = PaddedCellNative::Restarts.new(jobs)
43
+ @undispatched = 0
30
44
  end
31
45
 
32
46
  # Runs batches of test indices in order (consuming them), yielding
@@ -36,7 +50,7 @@ module PaddedCell
36
50
  @on_result = on_result
37
51
  @sockets = []
38
52
  Hooks.run_before_fork
39
- @slots = Array.new([@jobs, batches.sum(&:size)].min) { spawn(Slot.new(it, nil, nil, nil, nil, [])) }
53
+ @slots = Array.new([@jobs, batches.sum(&:size)].min) { spawn(Slot.new(it, nil, nil, nil, nil, [], nil)) }
40
54
  @slots.each { feed(it) }
41
55
  loop do
42
56
  busy = @slots.select(&:test)
@@ -53,6 +67,7 @@ module PaddedCell
53
67
 
54
68
  # Dispatch nothing more; tests already running still report.
55
69
  def stop!
70
+ @undispatched += @queue.sum(&:size) + @slots.sum { it.batch.size }
56
71
  @queue.clear
57
72
  @slots.each { it.batch.clear }
58
73
  end
@@ -67,7 +82,7 @@ module PaddedCell
67
82
  # A worker holding another worker's socket would keep it from ever
68
83
  # seeing EOF: keep only its own end.
69
84
  [parent, *@sockets].each(&:close)
70
- Worker.new(@tests, isolation: @isolation, seed: @seed, timeout: @timeout, probe: @coverage&.probe)
85
+ Worker.new(@tests, isolation: @isolation, seed: @seed, limits: @limits, probe: @coverage&.probe)
71
86
  .run(slot.worker, child)
72
87
  end
73
88
  child.close
@@ -77,18 +92,25 @@ module PaddedCell
77
92
  end
78
93
 
79
94
  def feed(slot)
95
+ return stop! if @limits.spent?
96
+
80
97
  slot.batch = @queue.shift || steal if slot.batch.empty?
81
98
  slot.test = slot.batch.shift
82
99
  return unless slot.test
83
100
 
84
101
  slot.started = Minitest.clock_time
102
+ slot.deadline = @limits.for_test
85
103
  begin
86
104
  slot.socket.puts(slot.test)
87
105
  rescue Errno::EPIPE, Errno::ECONNRESET
88
- # The worker died between tests: its replacement gets this one.
106
+ # The worker died between tests: its replacement gets this one, unless
107
+ # it dies too. Restarts bounds the retries.
89
108
  reap(slot)
90
109
  @coverage&.lost_worker
91
- spawn(slot).socket.puts(slot.test)
110
+ return abandon(slot) unless @restarts.died(Limits.now)
111
+
112
+ spawn(slot)
113
+ retry
92
114
  end
93
115
  end
94
116
 
@@ -99,17 +121,24 @@ module PaddedCell
99
121
  end
100
122
 
101
123
  def receive(slot)
102
- header = slot.socket.read(4)
124
+ header = read_frame(slot, 4)
103
125
  return died(slot) unless header&.bytesize == 4
104
126
 
105
127
  size = header.unpack1('N')
106
- payload = slot.socket.read(size)
128
+ payload = read_frame(slot, size)
107
129
  return died(slot) unless payload&.bytesize == size
108
130
 
109
131
  report(slot, Results.load(payload, *@tests.fetch(slot.test)))
110
132
  feed(slot)
111
133
  end
112
134
 
135
+ # nil when the worker died: EOF, or a reset when it left data unread.
136
+ def read_frame(slot, size)
137
+ slot.socket.read(size)
138
+ rescue Errno::ECONNRESET
139
+ nil
140
+ end
141
+
113
142
  def report(slot, result)
114
143
  index = slot.test
115
144
  slot.test = nil
@@ -118,25 +147,42 @@ module PaddedCell
118
147
 
119
148
  def died(slot)
120
149
  status = reap(slot)
150
+ give_up unless @restarts.died(Limits.now)
121
151
  replace(slot, Results.describe(status, 'worker'), Minitest.clock_time - slot.started)
122
152
  end
123
153
 
124
- # Cells time out inside their worker; with :worker isolation the runner
125
- # kills the worker itself.
154
+ # Stops replacing workers: whatever was not dispatched is not run.
155
+ def give_up
156
+ window = PaddedCellNative::Restarts.window_ns / Limits::NS
157
+ @gave_up = "workers died more than #{@restarts.limit} times in #{window}s"
158
+ stop!
159
+ end
160
+
161
+ # A test taken for a worker that died before receiving it, and is not
162
+ # replaced.
163
+ def abandon(slot)
164
+ slot.test = nil
165
+ @undispatched += 1
166
+ give_up
167
+ end
168
+
169
+ # Cells meet their deadline inside their worker; with :worker isolation
170
+ # the runner kills the worker itself.
126
171
  def wait_time(busy)
127
- return unless @timeout && @isolation == :worker
172
+ return unless @isolation == :worker
128
173
 
129
- deadline = busy.map { it.started + @timeout }.min
130
- [deadline - Minitest.clock_time, 0].max
174
+ now = Limits.now
175
+ busy.filter_map { Limits.remaining(it.deadline, now) }.min
131
176
  end
132
177
 
133
178
  def expire(busy)
179
+ now = Limits.now
134
180
  busy.each do |slot|
135
- next if Minitest.clock_time - slot.started < @timeout
181
+ next unless slot.deadline.expired?(now)
136
182
 
137
183
  Process.kill(:KILL, slot.pid)
138
184
  reap(slot)
139
- replace(slot, "timed out after #{@timeout}s", @timeout)
185
+ replace(slot, @limits.message(slot.deadline), Minitest.clock_time - slot.started)
140
186
  end
141
187
  end
142
188
 
@@ -145,6 +191,7 @@ module PaddedCell
145
191
  @coverage&.lost_worker
146
192
  klass, name = @tests.fetch(slot.test)
147
193
  report(slot, Results.crashed(klass, name, message, time:))
194
+ stop! if @limits.spent?
148
195
  return if @queue.empty? && @slots.all? { it.batch.empty? }
149
196
 
150
197
  spawn(slot)
@@ -103,6 +103,52 @@ module PaddedCell
103
103
  def escape(text) = text.to_s.scrub.gsub(INVALID, '').gsub(/[&<>"']/, ESCAPES)
104
104
  end
105
105
 
106
+ # --coverage-map: per test, the lines of the project it ran, one JSON
107
+ # object per line, in id order:
108
+ #
109
+ # {"id":"SignTest#test_zero","file":"test/calc_test.rb","line":28,
110
+ # "covers":{"lib/calc.rb":[[7,8],10,13]}}
111
+ #
112
+ # Line numbers ascend; [first, last] stands for a run of consecutive
113
+ # ones. Files are those the coverage report would show. A test that was
114
+ # not measured (its cell or worker died) is left out.
115
+ class CoverageMap < FileReporter
116
+ # coverage: the run's Chart::Accumulator
117
+ def initialize(path, coverage:)
118
+ super(path)
119
+ @coverage = coverage
120
+ end
121
+
122
+ # A first attempt, as it arrives: what it ran comes off its metadata.
123
+ def record(result)
124
+ covers = result.metadata? && result.metadata.delete(:covers)
125
+ @results << entry(result, covers) if covers
126
+ end
127
+
128
+ private
129
+
130
+ def render(entries) = entries.sort_by { it[:id] }.map { "#{JSON.generate(it)}\n" }.join
131
+
132
+ def entry(result, covers)
133
+ file, line = file_and_line(result)
134
+ { id: "#{result.klass}##{result.name}", file:, line:, covers: files(covers) }
135
+ end
136
+
137
+ # Two paths can name one file (a symlink): their lines are merged.
138
+ def files(covers)
139
+ files = Hash.new { |hash, name| hash[name] = [] }
140
+ covers.each do |path, lines|
141
+ name = @coverage.project_file(path)
142
+ files[name].concat(lines) if name
143
+ end
144
+ files.sort.to_h { |name, lines| [name, ranges(lines.uniq.sort)] }
145
+ end
146
+
147
+ def ranges(lines)
148
+ lines.slice_when { |previous, line| line != previous + 1 }.map { it.size == 1 ? it[0] : [it[0], it[-1]] }
149
+ end
150
+ end
151
+
106
152
  # One JSON object per test, one per line.
107
153
  class JSONLines < FileReporter
108
154
  private
@@ -88,12 +88,13 @@ module PaddedCell
88
88
  end
89
89
 
90
90
  # Marshal.dump, after replacing failures that cannot cross a pipe (an
91
- # exception holding a Proc, an IO...) with plain copies.
91
+ # exception holding a Proc, an IO...) with plain copies. Of the metadata,
92
+ # only the coverage map's plain data survives.
92
93
  def dump(result)
93
94
  Marshal.dump(result)
94
95
  rescue TypeError, ArgumentError
95
96
  result.failures = result.failures.map { portable(it) }
96
- result.metadata = {} if result.metadata?
97
+ result.metadata = result.metadata.slice(:covers) if result.metadata?
97
98
  Marshal.dump(result)
98
99
  end
99
100
 
@@ -4,6 +4,7 @@ require 'etc'
4
4
  require 'minitest'
5
5
  require_relative '../padded_cell'
6
6
  require_relative 'results'
7
+ require_relative 'limits'
7
8
  require_relative 'cell'
8
9
  require_relative 'worker'
9
10
  require_relative 'pool'
@@ -20,9 +21,9 @@ module PaddedCell
20
21
  class Runner
21
22
  DEFAULTS = {
22
23
  paths: [], jobs: Etc.nprocessors, seed: nil, include: nil, exclude: nil, shard: [0, 1],
23
- isolation: nil, timeout: nil, asylum: nil, fail_fast: false, verbose: false, show_skips: false,
24
+ isolation: nil, timeout: nil, budget: nil, asylum: nil, fail_fast: false, verbose: false, show_skips: false,
24
25
  list: false, junit: nil, json: nil, timings: 'tmp/padded_cell/timings.tsv', coverage: nil,
25
- coverage_dir: nil, io: $stdout
26
+ coverage_dir: nil, coverage_map: nil, io: $stdout
26
27
  }.freeze
27
28
 
28
29
  attr_reader :options
@@ -30,11 +31,16 @@ module PaddedCell
30
31
  def initialize(**options)
31
32
  @options = DEFAULTS.merge(options)
32
33
  @options[:seed] ||= (ENV['SEED'] || Random.new_seed).to_i % 0xFFFF
34
+ # The map is made of lines, and of methods: a call to a one-line
35
+ # method runs no line Ruby sees.
36
+ @options[:coverage] ||= %i[lines methods] if @options[:coverage_map]
33
37
  end
34
38
 
35
39
  # Exit status: 0 when everything passed, 1 otherwise, 3 when only
36
40
  # coverage is below a minimum, 130 on Ctrl-C.
37
41
  def run
42
+ # The budget covers the whole run, loading included.
43
+ @limits = Limits.new(timeout: options[:timeout], budget: options[:budget])
38
44
  selection = Selection.parse(options[:paths])
39
45
  refs = Discovery.call(selection.files)
40
46
  filter = Filter.new(selection, refs, include: options[:include], exclude: options[:exclude])
@@ -59,7 +65,7 @@ module PaddedCell
59
65
  # Before the suite loads: nothing loaded earlier is measured.
60
66
  def start_coverage
61
67
  require_relative 'chart'
62
- Chart::Accumulator.new(options[:coverage]).start
68
+ Chart::Accumulator.new(options[:coverage], map: !options[:coverage_map].nil?).start
63
69
  end
64
70
 
65
71
  # Two tools cannot share Ruby's Coverage.
@@ -94,10 +100,16 @@ module PaddedCell
94
100
  nothing_ran = batches.empty?
95
101
  reporter = build_reporter
96
102
  reporter.start
103
+ # First attempts only, as with the coverage it is made of.
104
+ map = Reporters::CoverageMap.new(options[:coverage_map], coverage: @coverage) if options[:coverage_map]
97
105
  retried = []
98
106
  @coverage&.snapshot
99
- status = dispatch(tests, batches, reporter, retried) { |index, result| timings[ids[index]] = result.time }
107
+ status = dispatch(tests, batches, reporter, retried) do |index, result|
108
+ timings[ids[index]] = result.time
109
+ map&.record(result)
110
+ end
100
111
  reporter.report
112
+ map&.report
101
113
  report_asylum(retried)
102
114
  covered = @coverage ? report_coverage(status, reporter) : true
103
115
  Timings.save(options[:timings], timings)
@@ -121,7 +133,8 @@ module PaddedCell
121
133
 
122
134
  # Yields each result as it arrives. With --asylum a failure is held back:
123
135
  # only its final result, after the retries, is reported. Returns 1 when a
124
- # worker failed (its cleanup hook), 130 when interrupted, 0 otherwise.
136
+ # worker failed (its cleanup hook) or tests were left out (the budget ran
137
+ # out, workers kept dying), 130 when interrupted, 0 otherwise.
125
138
  def dispatch(tests, batches, reporter, retried)
126
139
  held = {}
127
140
  record = lambda do |index, result|
@@ -130,15 +143,16 @@ module PaddedCell
130
143
  retried << result if result.metadata? && (result.metadata[:flaky] || result.metadata[:asylum])
131
144
  end
132
145
  pool = Pool.new(tests, jobs: options[:jobs], isolation: options[:isolation], seed: options[:seed],
133
- timeout: options[:timeout], coverage: @coverage)
146
+ limits: @limits, coverage: @coverage)
134
147
  pool.run(batches) do |index, result|
135
148
  yield index, result
136
149
  failed = failed?(result)
137
150
  options[:asylum] && failed ? held[index] = result : record.call(index, result)
138
151
  pool.stop! if options[:fail_fast] && failed
139
152
  end
153
+ complete = report_left_out(pool)
140
154
  retries_ok = retry_held(tests, held, record)
141
- pool.success? && retries_ok ? 0 : 1
155
+ pool.success? && retries_ok && complete ? 0 : 1
142
156
  rescue Interrupt
143
157
  warn 'Interrupted. Exiting...'
144
158
  # Failures still waiting for a retry are failures.
@@ -146,11 +160,31 @@ module PaddedCell
146
160
  130
147
161
  end
148
162
 
163
+ # False when tests never ran because the budget ran out or workers kept
164
+ # dying. --fail-fast leaving them out is what it asked for.
165
+ def report_left_out(pool)
166
+ left_out = pool.undispatched
167
+ if pool.gave_up
168
+ warn "padded_cell: #{pool.gave_up}; gave up, #{left_out} tests not run"
169
+ elsif @limits.spent? && left_out.positive?
170
+ warn "padded_cell: run budget of #{@limits.budget}s spent, #{left_out} tests not run"
171
+ else
172
+ return true
173
+ end
174
+ false
175
+ end
176
+
149
177
  # False when a retry's worker failed.
150
178
  def retry_held(tests, held, record)
151
179
  return true if held.empty?
152
180
 
153
- asylum = Asylum.new(tests, attempts: options[:asylum], seed: options[:seed], timeout: options[:timeout])
181
+ # No budget left to retry in: failures stay failures.
182
+ if @limits.spent?
183
+ held.each { |index, result| record.call(index, result) }
184
+ return true
185
+ end
186
+
187
+ asylum = Asylum.new(tests, attempts: options[:asylum], seed: options[:seed], limits: @limits)
154
188
  asylum.call(held) do |index, result|
155
189
  held.delete(index)
156
190
  record.call(index, result)
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module PaddedCell
4
- VERSION = '0.2.0'
4
+ VERSION = '0.4.0'
5
5
  end
@@ -6,12 +6,12 @@ module PaddedCell
6
6
  # Minitest::Result as a length-prefixed Marshal frame. Exits once the
7
7
  # socket closes.
8
8
  class Worker
9
- # probe: a Chart::Probe when measuring coverage
10
- def initialize(tests, isolation:, seed:, timeout:, probe:)
9
+ # limits: the run's Limits; probe: a Chart::Probe when measuring coverage
10
+ def initialize(tests, isolation:, seed:, limits:, probe:)
11
11
  @tests = tests
12
12
  @isolation = isolation
13
13
  @seed = seed
14
- @timeout = timeout
14
+ @limits = limits
15
15
  @probe = probe
16
16
  end
17
17
 
@@ -54,7 +54,9 @@ module PaddedCell
54
54
  if setup_error
55
55
  Results.crashed(klass, name, "after_fork hook failed: #{setup_error.class}: #{setup_error.message}")
56
56
  elsif @isolation == :test
57
- Cell.run(klass, name, seed: @seed, timeout: @timeout, close: [socket], probe: @probe)
57
+ Cell.run(klass, name, seed: @seed, limits: @limits, close: [socket], probe: @probe)
58
+ elsif @probe
59
+ @probe.measure { Cell.execute(klass, name) }
58
60
  else
59
61
  Cell.execute(klass, name)
60
62
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: padded_cell
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.0
4
+ version: 0.4.0
5
5
  platform: x86_64-linux-gnu
6
6
  authors:
7
7
  - Abdelkader Boudih
@@ -56,6 +56,7 @@ files:
56
56
  - lib/padded_cell/cli.rb
57
57
  - lib/padded_cell/discovery.rb
58
58
  - lib/padded_cell/hooks.rb
59
+ - lib/padded_cell/limits.rb
59
60
  - lib/padded_cell/loader.rb
60
61
  - lib/padded_cell/native.rb
61
62
  - lib/padded_cell/pool.rb