padded_cell 0.2.0 → 0.4.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: 71107b6522d03ca5d3c7f11cb93cd0e6374f283b843a1b456699d69f2a131e11
4
- data.tar.gz: efd0654d4986a1fca13380f8a5abcea88ead77944e7e7a92b4cd6a58a69208de
3
+ metadata.gz: 8c460bc9c30d1aceca5e6e4dd764503b7871971c2da3c8aaa7e497581717f92f
4
+ data.tar.gz: f72d0d43ff6ba9fe4505bc2c1293fefc073c89c905b0ae8fa4f8fb27784d597d
5
5
  SHA512:
6
- metadata.gz: 64a6eca62591f0b9c6c887587ae7a00be9135f4b6addb9fb4e869fe9fae10b6be9145c9a3834d05e83a2e9e225319f846b91f85a92266038db1bf383b40d3c65
7
- data.tar.gz: 53049afc045f49d8a3e62504780babf42a7800988055c2075a961c57fb124085c868a31fff5356f4bf8ed5fd1db3c61e2c771ae151b2d243e62d92facb304c81
6
+ metadata.gz: c72c3a035714f8c70cb2a93461cde0c447e2417f954af98e23dc689e3b375bda3bd1132527fe0110b2e964ac33c45999e975146d214f7e71230e96e2eb383818
7
+ data.tar.gz: fb6a39de58a92cf0abb8fc3bedfb8f8d72fa3fa14179508e27d416c259e77c73fda818daee6d06ea7f83f95b72432776c1a63a8ba0d692cbb82df73454e28371
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/Cargo.lock CHANGED
@@ -73,6 +73,12 @@ dependencies = [
73
73
  "libloading",
74
74
  ]
75
75
 
76
+ [[package]]
77
+ name = "deadline-machines"
78
+ version = "0.4.0"
79
+ source = "registry+https://github.com/rust-lang/crates.io-index"
80
+ checksum = "805cba0e8981fd367f11a17886e0ad53b84365601f5d39d8b66819f9bd0ba463"
81
+
76
82
  [[package]]
77
83
  name = "either"
78
84
  version = "1.19.0"
@@ -220,17 +226,19 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
220
226
 
221
227
  [[package]]
222
228
  name = "padded_cell"
223
- version = "0.2.0"
229
+ version = "0.4.0"
224
230
  dependencies = [
225
231
  "ruby-prism",
232
+ "supervisor-machines",
226
233
  "tempfile",
227
234
  "thiserror",
228
235
  ]
229
236
 
230
237
  [[package]]
231
238
  name = "padded_cell_native"
232
- version = "0.2.0"
239
+ version = "0.4.0"
233
240
  dependencies = [
241
+ "deadline-machines",
234
242
  "magnus",
235
243
  "padded_cell",
236
244
  ]
@@ -435,6 +443,12 @@ version = "2.0.1"
435
443
  source = "registry+https://github.com/rust-lang/crates.io-index"
436
444
  checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
437
445
 
446
+ [[package]]
447
+ name = "supervisor-machines"
448
+ version = "0.4.0"
449
+ source = "registry+https://github.com/rust-lang/crates.io-index"
450
+ checksum = "89f7646079e8a1b802737bb514b9c68e8e0743c046c9fb3c570b50e38ba03121"
451
+
438
452
  [[package]]
439
453
  name = "syn"
440
454
  version = "2.0.119"
data/Cargo.toml CHANGED
@@ -13,6 +13,8 @@ repository = "https://github.com/seuros/padded_cell"
13
13
  padded_cell = { path = "ext/padded_cell_native/core" }
14
14
  magnus = { version = "0.9.2", default-features = false }
15
15
  ruby-prism = "1.9.0"
16
+ deadline_machines = { package = "deadline-machines", version = "0.4.0", default-features = false }
17
+ supervisor_machines = { package = "supervisor-machines", version = "0.4.0", default-features = false }
16
18
  tempfile = "3.27.0"
17
19
  thiserror = "2.0.21"
18
20
 
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
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "padded_cell"
3
- version = "0.2.0"
3
+ version = "0.4.0"
4
4
  description = "Static Minitest discovery and test scheduling for the padded_cell gem"
5
5
  publish = false
6
6
  edition.workspace = true
@@ -14,6 +14,7 @@ workspace = true
14
14
 
15
15
  [dependencies]
16
16
  ruby-prism.workspace = true
17
+ supervisor_machines.workspace = true
17
18
  thiserror.workspace = true
18
19
 
19
20
  [dev-dependencies]
@@ -51,15 +51,24 @@ impl Source {
51
51
  /// The 1-based line and the 0-based byte column of `offset`.
52
52
  #[must_use]
53
53
  pub fn position(&self, offset: usize) -> (u32, u32) {
54
- let line = self.ends.partition_point(|&end| end <= offset);
54
+ let line = self.line_index(offset);
55
55
  let number = |value: usize| u32::try_from(value).unwrap_or(u32::MAX);
56
- (number(line.strict_add(1)), number(offset.strict_sub(self.line_start(offset))))
56
+ (number(line.strict_add(1)), number(offset.strict_sub(self.start_of(line))))
57
57
  }
58
58
 
59
59
  /// Where the line holding `offset` starts.
60
60
  #[must_use]
61
61
  pub fn line_start(&self, offset: usize) -> usize {
62
- let line = self.ends.partition_point(|&end| end <= offset);
62
+ self.start_of(self.line_index(offset))
63
+ }
64
+
65
+ /// The 0-based line holding `offset`.
66
+ fn line_index(&self, offset: usize) -> usize {
67
+ self.ends.partition_point(|&end| end <= offset)
68
+ }
69
+
70
+ /// Where the 0-based `line` starts.
71
+ fn start_of(&self, line: usize) -> usize {
63
72
  line.checked_sub(1).map_or(0, |previous| self.ends[previous])
64
73
  }
65
74
 
@@ -1,5 +1,6 @@
1
- //! Static Minitest discovery and deterministic test scheduling: the engine
2
- //! of the [padded_cell](https://github.com/seuros/padded_cell) test runner.
1
+ //! Static Minitest discovery, deterministic test scheduling and worker
2
+ //! supervision: the engine of the
3
+ //! [padded_cell](https://github.com/seuros/padded_cell) test runner.
3
4
  //!
4
5
  //! ```
5
6
  //! let source = b"class UserTest < Minitest::Test\n def test_valid\n end\nend\n";
@@ -19,6 +20,7 @@ mod error;
19
20
  mod hash;
20
21
  mod parallel;
21
22
  mod plan;
23
+ pub mod restarts;
22
24
  mod rng;
23
25
 
24
26
  pub use discover::{
@@ -27,6 +29,7 @@ pub use discover::{
27
29
  pub use error::FileError;
28
30
  pub use hash::fnv1a64;
29
31
  pub use plan::plan;
32
+ pub use restarts::Restarts;
30
33
  pub use rng::SplitMix64;
31
34
 
32
35
  #[cfg(doctest)]
@@ -0,0 +1,29 @@
1
+ use super::*;
2
+
3
+ const SECOND: u64 = 1_000_000_000;
4
+
5
+ #[test]
6
+ fn scales_with_jobs_above_a_floor() {
7
+ assert_eq!(Restarts::new(1).limit(), 16);
8
+ assert_eq!(Restarts::new(8).limit(), 32);
9
+ assert_eq!(Restarts::new(100_000).limit(), 1023);
10
+ }
11
+
12
+ #[test]
13
+ fn gives_up_past_the_limit_inside_the_window_and_stays_down() {
14
+ let mut restarts = Restarts::new(1);
15
+ for death in 0..16 {
16
+ assert!(restarts.died(death), "death {death}");
17
+ }
18
+ assert!(!restarts.died(16));
19
+ // A supervisor that gave up does not change its mind.
20
+ assert!(!restarts.died(WINDOW_NS * 10));
21
+ }
22
+
23
+ #[test]
24
+ fn deaths_spread_over_time_never_give_up() {
25
+ let mut restarts = Restarts::new(1);
26
+ for death in 0..1_000 {
27
+ assert!(restarts.died(death * SECOND), "death {death}");
28
+ }
29
+ }
@@ -0,0 +1,64 @@
1
+ //! When to stop replacing dead workers.
2
+ //!
3
+ //! A worker that dies takes its test with it and gets replaced; a worker
4
+ //! that keeps dying (a boot that segfaults, an `after_fork` hook that exits)
5
+ //! would otherwise turn every remaining test into a crash report, one fork
6
+ //! at a time.
7
+ //!
8
+ //! The decision is [`supervisor_machines`]'s: one-for-one, restart
9
+ //! intensity over a sliding window. Spawning, killing and reaping stay with
10
+ //! the caller.
11
+
12
+ use supervisor_machines::{Decision, Exit, Intensity, Policy, Strategy, Supervisor};
13
+
14
+ #[cfg(test)]
15
+ mod tests;
16
+
17
+ /// Restart timestamps kept: bounds [`Restarts::limit`].
18
+ const HISTORY: usize = 1024;
19
+
20
+ /// Deaths allowed per worker inside one window, before giving up.
21
+ const PER_WORKER: u32 = 4;
22
+
23
+ /// Deaths allowed inside one window whatever the worker count: a few tests
24
+ /// that kill their worker are what cells and workers exist to contain.
25
+ const FLOOR: u32 = 16;
26
+
27
+ /// The sliding window, in nanoseconds.
28
+ pub const WINDOW_NS: u64 = 10_000_000_000;
29
+
30
+ /// Worker deaths seen by one pool.
31
+ #[derive(Debug, Clone)]
32
+ pub struct Restarts {
33
+ supervisor: Supervisor<1, HISTORY>,
34
+ }
35
+
36
+ impl Restarts {
37
+ /// For a pool of `jobs` workers: `4 * jobs` deaths per 10 seconds, at
38
+ /// least 16.
39
+ #[must_use]
40
+ pub fn new(jobs: usize) -> Self {
41
+ let jobs = u32::try_from(jobs).unwrap_or(u32::MAX);
42
+ let limit = jobs.saturating_mul(PER_WORKER).clamp(FLOOR, HISTORY_LIMIT);
43
+ Self { supervisor: Supervisor::new(Strategy::OneForOne, Intensity::new(limit, WINDOW_NS)) }
44
+ }
45
+
46
+ /// A worker died at `now_ns` (monotonic): true to replace it, false to
47
+ /// give up. Once false, always false.
48
+ pub const fn died(&mut self, now_ns: u64) -> bool {
49
+ matches!(
50
+ self.supervisor.stopped(0, Policy::Permanent, Exit::Abnormal, now_ns),
51
+ Decision::Restart(_)
52
+ )
53
+ }
54
+
55
+ /// Deaths allowed inside [`WINDOW_NS`].
56
+ #[must_use]
57
+ pub const fn limit(&self) -> u32 {
58
+ self.supervisor.intensity().restarts
59
+ }
60
+ }
61
+
62
+ /// The history must hold one more death than the limit to see it exceeded.
63
+ #[expect(clippy::cast_possible_truncation, reason = "HISTORY is 1024")]
64
+ const HISTORY_LIMIT: u32 = HISTORY as u32 - 1;
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "padded_cell_native"
3
- version = "0.2.0"
3
+ version = "0.4.0"
4
4
  description = "Ruby bindings for the padded_cell crate"
5
5
  publish = false
6
6
  edition.workspace = true
@@ -15,5 +15,6 @@ crate-type = ["cdylib"]
15
15
  workspace = true
16
16
 
17
17
  [dependencies]
18
+ deadline_machines.workspace = true
18
19
  magnus.workspace = true
19
20
  padded_cell.workspace = true
@@ -19,6 +19,7 @@ use magnus::{Error, RArray, RString, Ruby, function};
19
19
  use padded_cell::{Discovery, FileError};
20
20
 
21
21
  mod chart;
22
+ mod limits;
22
23
 
23
24
  /// `Errno::*` for the path, as Ruby's own file reading raises.
24
25
  fn file_error(ruby: &Ruby, error: &FileError) -> Error {
@@ -119,5 +120,6 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
119
120
  module.define_module_function("discover_files", function!(discover_files, 1))?;
120
121
  module.define_module_function("plan", function!(plan, 5))?;
121
122
  module.define_module_function("chart_report", function!(chart::chart_report, 3))?;
123
+ limits::define(ruby, module)?;
122
124
  Ok(())
123
125
  }
@@ -0,0 +1,83 @@
1
+ //! What bounds a run: `PaddedCellNative::Deadline` (`--timeout` and
2
+ //! `--budget`) and `PaddedCellNative::Restarts` (dead workers). Times are
3
+ //! monotonic nanoseconds, the same clock in the runner, its workers and their
4
+ //! cells.
5
+
6
+ use std::cell::RefCell;
7
+
8
+ use deadline_machines::{Deadline, Instant};
9
+ use magnus::{Error, Module, Object, RModule, Ruby, function, method};
10
+ use padded_cell::Restarts;
11
+
12
+ /// A point in monotonic time past which a test (or the run) is cut short, or
13
+ /// never.
14
+ #[magnus::wrap(class = "PaddedCellNative::Deadline", free_immediately, size, frozen_shareable)]
15
+ struct RbDeadline(Deadline);
16
+
17
+ impl RbDeadline {
18
+ const fn after(now_ns: u64, ns: u64) -> Self {
19
+ Self(Deadline::after(Instant(now_ns), ns))
20
+ }
21
+
22
+ const fn never() -> Self {
23
+ Self(Deadline::never())
24
+ }
25
+
26
+ /// `timeout_ns` from `now_ns`, never past this deadline; nil: this one.
27
+ fn derive(&self, now_ns: u64, timeout_ns: Option<u64>) -> Self {
28
+ Self(timeout_ns.map_or(self.0, |ns| self.0.derive(Instant(now_ns), ns)))
29
+ }
30
+
31
+ /// Nanoseconds left (0 once expired), nil when never.
32
+ const fn remaining_ns(&self, now_ns: u64) -> Option<u64> {
33
+ self.0.remaining_ns(Instant(now_ns))
34
+ }
35
+
36
+ const fn is_expired(&self, now_ns: u64) -> bool {
37
+ self.0.is_expired(Instant(now_ns))
38
+ }
39
+
40
+ /// Monotonic nanoseconds, nil when never.
41
+ fn expires_at(&self) -> Option<u64> {
42
+ self.0.expires_at().map(|at| at.0)
43
+ }
44
+ }
45
+
46
+ #[magnus::wrap(class = "PaddedCellNative::Restarts", free_immediately, size)]
47
+ struct RbRestarts(RefCell<Restarts>);
48
+
49
+ impl RbRestarts {
50
+ fn new(jobs: usize) -> Self {
51
+ Self(RefCell::new(Restarts::new(jobs)))
52
+ }
53
+
54
+ /// True to replace the dead worker, false to give up.
55
+ fn died(&self, now_ns: u64) -> bool {
56
+ self.0.borrow_mut().died(now_ns)
57
+ }
58
+
59
+ fn limit(&self) -> u32 {
60
+ self.0.borrow().limit()
61
+ }
62
+
63
+ const fn window_ns() -> u64 {
64
+ padded_cell::restarts::WINDOW_NS
65
+ }
66
+ }
67
+
68
+ pub fn define(ruby: &Ruby, module: RModule) -> Result<(), Error> {
69
+ let deadline = module.define_class("Deadline", ruby.class_object())?;
70
+ deadline.define_singleton_method("after", function!(RbDeadline::after, 2))?;
71
+ deadline.define_singleton_method("never", function!(RbDeadline::never, 0))?;
72
+ deadline.define_method("derive", method!(RbDeadline::derive, 2))?;
73
+ deadline.define_method("remaining_ns", method!(RbDeadline::remaining_ns, 1))?;
74
+ deadline.define_method("expired?", method!(RbDeadline::is_expired, 1))?;
75
+ deadline.define_method("expires_at", method!(RbDeadline::expires_at, 0))?;
76
+
77
+ let restarts = module.define_class("Restarts", ruby.class_object())?;
78
+ restarts.define_singleton_method("new", function!(RbRestarts::new, 1))?;
79
+ restarts.define_singleton_method("window_ns", function!(RbRestarts::window_ns, 0))?;
80
+ restarts.define_method("died", method!(RbRestarts::died, 1))?;
81
+ restarts.define_method("limit", method!(RbRestarts::limit, 0))?;
82
+ Ok(())
83
+ }
@@ -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
  {