croft-software 0.2.82

VSCode-style TUI written in Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
//! Deadlines for tests that wait on a spawned process (#307).
//!
//! A test that spawns a real process and waits a fixed wall-clock budget will
//! flake on a loaded machine, and the budget looks generous right up until it
//! isn't. The reason per-test tuning keeps looking reasonable is that each
//! number is chosen against the operation it names - a shell printing a line,
//! a PTY delivering a byte - while what actually blows the budget is
//! CONTENTION, which is not a property of any test. It is a property of how
//! many other tests, and other builds, are spawning in the same moment. The
//! right number is therefore not knowable from inside a single test, which is
//! why raising individual caps has already been tried twice on one of them.
//!
//! So the budget stops being a guess and becomes
//! `base x BASE_CALIBRATION x scale`, where `base` is what the operation
//! costs on a quiet machine (the number a test author can actually reason
//! about), `scale` is measured from the load the suite is running under, and
//! the calibration is the one constant that keeps the wall clock where it was
//! when these budgets were derived (#422). The widest any budget stretches is
//! `BASE_CALIBRATION x MAX_SCALE`, deliberately unchanged at 8x, because a
//! broken test must still fail in a time a developer will wait.

use std::sync::OnceLock;
use std::time::{Duration, Instant};

/// Widest a budget may stretch. A failing test must still fail: past this the
/// wait is no longer distinguishing "loaded" from "broken", and every extra
/// second is paid by the developer whose change genuinely broke the thing.
///
/// Halved with the #422 rule change, so the CEILING is unchanged. The total
/// stretch is `BASE_CALIBRATION * MAX_SCALE`, and leaving this at 8 while
/// introducing a x2 calibration would have doubled the worst case with it —
/// a broken test on a 10s base going from 80s to 160s, which is exactly the
/// cost this constant exists to bound. 2 x 4 is the 8 it always was.
const MAX_SCALE: u32 = 4;

/// Narrowest it may shrink. Never below the budgets these tests already had,
/// since every one of them was observed failing at 1x.
const MIN_SCALE: u32 = 2;

/// Recalibration for the #422 rule change, applied once here rather than at
/// sixteen call sites.
///
/// The old scale tracked machine SIZE, so on any box with four or more cores
/// it read at least 4 and a `base` was effectively `base * 4`. Measuring
/// PRESSURE instead correctly reads 2 on a quiet machine — which would have
/// halved every budget in the suite, and the module's own note warned that
/// every one of these waits was observed failing at 1x. Doubling the base
/// holds the wall clock where it was calibrated while the scale goes back to
/// meaning what it says.
///
/// Deliberately central. Doubling sixteen literals by hand invites missing
/// one, and a missed one is a flake that looks like the change under test —
/// the exact failure this module exists to remove. It also keeps `base` the
/// number a test author reasons about ("a shell printing a line costs about
/// a second") rather than a number pre-multiplied for a rule they would have
/// to know about.
const BASE_CALIBRATION: u32 = 2;

/// One-minute load average, where the platform reports one.
fn load_average() -> Option<f64> {
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    {
        let mut avg = [0f64; 1];
        // SAFETY: getloadavg writes at most `nelem` doubles into the buffer;
        // it is given a one-element buffer and asked for one sample.
        let n = unsafe { libc::getloadavg(avg.as_mut_ptr(), 1) };
        return (n == 1).then_some(avg[0]);
    }
    #[allow(unreachable_code)]
    None
}

/// How much slack this machine needs, resolved once per test binary.
///
/// Two signals, and their SUM, because each is blind where the other sees
/// and both contend for the same cores (#422). The suite's own thread count
/// is known before anything runs and covers the self-inflicted case (dozens
/// of test shells at once), where
/// a load average would still be reading the quiet minute before the suite
/// started. The load average covers what no test can know: a second cargo
/// build, another suite, whatever else owns the machine.
pub fn load_scale() -> u32 {
    static SCALE: OnceLock<u32> = OnceLock::new();
    *SCALE.get_or_init(|| {
        let cpus = std::thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(1) as f64;
        let threads = configured_threads().unwrap_or(cpus);
        // The RAW load average, not a ratio: `scale_from` divides once, by
        // the same `cpus`, after summing. Dividing here too was the unit
        // error (#422).
        let load = load_average().unwrap_or(0.0);
        scale_from(threads, load, cpus)
    })
}

/// How many test threads the harness is actually running.
///
/// BOTH spellings, because they are the same instruction to the harness and
/// were not the same here. `cargo test -- --test-threads=8` does not set
/// `RUST_TEST_THREADS`, so reading only the variable reported this machine's
/// CORE COUNT while the suite ran twice that many threads. The signal meant
/// to cover the self-inflicted case went blind exactly when someone spelled
/// it with the flag, which is how #397's flake was reached: measured on a
/// 4-CPU box at `--test-threads=8` under six spinning hogs, the scale read
/// 4 where the visible count gives 8, so a wait budgeted at 4s should have
/// had 8s.
///
/// THE FLAG FIRST, because that is libtest's own precedence and reading it
/// the other way round would still undercount on the machine that matters
/// most. `library/test/src/lib.rs` resolves the count as
/// `opts.test_threads.unwrap_or_else(get_concurrency)`, and only
/// `get_concurrency` consults `RUST_TEST_THREADS`
/// (`library/test/src/helpers/concurrency.rs:7-16`). CI pins the variable to
/// 4 and CONTRIBUTING teaches the variable, so `RUST_TEST_THREADS=4 cargo
/// test -- --test-threads=8` is the natural way to reproduce #397: the
/// harness runs 8 and an env-first reading believes 4, which is the same
/// undercount this function exists to remove.
fn configured_threads() -> Option<f64> {
    threads_from_args(std::env::args()).or_else(|| {
        std::env::var("RUST_TEST_THREADS")
            .ok()
            .and_then(|v| v.parse::<f64>().ok())
    })
}

/// `--test-threads N` and `--test-threads=N`, the two spellings the harness
/// accepts, taken from an iterator so the parsing is testable without a
/// process in a particular state.
///
/// The whole argv is scanned and the LAST parseable value wins, rather than
/// returning at the first occurrence. A value that does not parse is not a
/// thread count, and stopping there would let it mask a real one later in
/// the line; libtest itself refuses such a run outright, so the only thing
/// this ordering changes is which answer a malformed argv produces on the
/// way to failing.
fn threads_from_args<I: IntoIterator<Item = String>>(args: I) -> Option<f64> {
    let mut found = None;
    let mut args = args.into_iter();
    while let Some(a) = args.next() {
        let value = if let Some(v) = a.strip_prefix("--test-threads=") {
            Some(v.to_string())
        } else if a == "--test-threads" {
            args.next()
        } else {
            None
        };
        if let Some(n) = value.and_then(|v| v.parse::<f64>().ok()) {
            found = Some(n);
        }
    }
    found
}

/// The rule itself, split out so it can be tested without a machine in a
/// particular state.
///
/// **Runnable work per CPU** (#422). The old rule was `max(threads, load /
/// cpus)`, which compared a COUNT against a RATIO: on a 64-core box running
/// 64 threads with no contention at all it returned the cap of 8, while a
/// genuinely crushed 4-core box returned 4. The scale was tracking machine
/// size rather than pressure, which is the one thing it exists to measure.
///
/// The two signals ADD rather than compete. The suite's own threads and
/// whatever else owns the machine are contending for the same cores, so the
/// runnable count is their sum, and dividing by `cpus` turns it into the
/// factor by which everything is slower than it would be alone. Both inputs
/// keep the property that made the old `max` attractive — each is blind
/// where the other sees, and summing preserves that without pretending a
/// count and a ratio are the same kind of number.
///
/// This deliberately reads LOWER than the old rule on a quiet machine (a
/// quiet 4-CPU box: 4 before, 2 now), which is why the bases moved with it
/// in the same change. See [`await_spawned`] for the ceiling that had to be
/// preserved: #397's measured flake — a 4-CPU box at `--test-threads=8`
/// under six spinning hogs — needed 8 seconds where the base was 4, and
/// with doubled bases it still gets them.
fn scale_from(threads: f64, load: f64, cpus: f64) -> u32 {
    if !(threads.is_finite() && load.is_finite() && cpus.is_finite()) || cpus < 1.0 {
        return MIN_SCALE;
    }
    // `load` is the machine-wide runnable average, `threads` this suite's own
    // contribution; the sum is what is competing for `cpus`.
    //
    // Those overlap once the suite has been running a minute — its own
    // threads then appear in the load average too, so the sum counts them
    // twice. Deliberately left alone. The overlap is bounded (it can only
    // raise the quotient by `threads / cpus`, one clamp step in practice)
    // and it errs toward MORE slack, which is the safe direction for a
    // deadline; subtracting an estimate of our own load would be a guess
    // about a number we cannot observe, and a wrong one shortens budgets.
    // `load_scale` memoises in a `OnceLock`, so in practice the reading is
    // taken at the first wait — early, while the average still describes
    // the machine the suite arrived on.
    let raw = ((threads + load) / cpus).ceil();
    // Belt and braces: the guard above already rules out every input that
    // could make this non-finite, so this branch is unreachable today. Kept
    // because the guard is the thing most likely to be relaxed later.
    if !raw.is_finite() {
        return MIN_SCALE;
    }
    (raw as u32).clamp(MIN_SCALE, MAX_SCALE)
}

/// `base` stretched for the load this machine is under. For waits that hand a
/// timeout to something else (a `recv_timeout`, a probe's own deadline) rather
/// than polling.
pub fn spawn_budget(base: Duration) -> Duration {
    base * BASE_CALIBRATION * load_scale()
}

/// Poll `ready` until it answers true, within a load-scaled `base` budget.
/// Panics naming what was being waited for, the budget, and the scale, so a
/// failure says whether it ran out of time or never happened at all.
///
/// The teeth are unchanged: a genuinely broken behaviour never satisfies
/// `ready` and still fails here. It just takes longer to say so, which is the
/// trade this exists to make - a slow true failure over a fast false one.
#[track_caller]
pub fn await_spawned(base: Duration, what: &str, mut ready: impl FnMut() -> bool) {
    let scale = load_scale();
    let budget = base * BASE_CALIBRATION * scale;
    let started = Instant::now();
    while started.elapsed() < budget {
        if ready() {
            return;
        }
        std::thread::sleep(Duration::from_millis(20));
    }
    panic!(
        "timed out after {budget:?} ({base:?} x{BASE_CALIBRATION} calibration \
         x{scale} for load) waiting for {what}; \
         if this is a real failure it would also fail at 1x, so re-run the full suite \
         on the unmodified merge base under the same load before suspecting your diff"
    );
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;

    /// The base the two restored-shell waits use (#397).
    ///
    /// Shared rather than retyped at each call site, because the test that
    /// pins it has to be about THEM: an assertion over a literal written
    /// beside it stays green when a call site changes, which is the
    /// regression it exists to catch.
    ///
    /// 2s because `await_spawned` multiplies by
    /// `BASE_CALIBRATION * load_scale`, which is 4 at the floor: these two
    /// replaced a fixed 8000ms, and this keeps that as what they still get
    /// on a quiet machine. Deliberately NOT a repo-wide rule -
    /// `a_terminal_link_binding_is_not_refused_for_an_editor_side_reason`
    /// converts an 8s constant with a 1s base, and reconciling the two is a
    /// question about that test's operation rather than about these.
    ///
    /// Inside this module rather than beside it, because the release gate
    /// waives a `#[cfg(test)] mod` and nothing else: a `#[cfg(test)]` on a
    /// free item reads as shipped, which is the conservative direction that
    /// filter deliberately takes.
    pub(crate) const RESTORED_SHELL_BASE: Duration = Duration::from_secs(2);

    /// The base behind the app tests' `await_terminal_probe` (#397), which
    /// six end-to-end tests go through. It replaced a fixed 15s (#226 had
    /// raised that from 3s for the same reason). 3750ms because
    /// `BASE_CALIBRATION * MIN_SCALE` is 4 at the floor: a quiet machine
    /// keeps the 15s it had, and a loaded one gets up to twice that. The
    /// captured failure was a probe that had been ECHOED but not answered
    /// within the 15s during a full parallel suite, so the shell was alive
    /// and merely starved -- the case a load-scaled budget exists for.
    pub(crate) const TERMINAL_PROBE_BASE: Duration = Duration::from_millis(3750);

    /// The base for waiting on a real shell to PAINT something into a pane
    /// (#397): a grid line, a decoration or prompt mark, an inline image, an
    /// OSC-reported host or progress state.
    ///
    /// Separate from `TERMINAL_PROBE_BASE` because the two replaced
    /// different constants — 15s there, 8000ms here — and the house rule is
    /// that each base reproduces its own at the floor, which one number
    /// cannot do for both. The operation they wait on is the same.
    ///
    /// The rule, rather than a list that goes stale with every batch of
    /// conversions: every call site reproduces the 8000ms it replaced, and
    /// the rest are deliberate RAISES from a 4000ms bound. Each of those sat
    /// on a shell that other waits in the same suite already gave 8000ms, so
    /// the short bound was an accident of where it was written rather than a
    /// measured deadline — and one of them, the re-root test's foreground
    /// poll, never asserted on timeout at all, so its number could not fail
    /// a test in the first place.
    ///
    /// Nothing here is ever CUT: a raise cannot introduce a flake, and the
    /// floor assertion below guards the direction that can. That assertion
    /// checks the constant, not its call sites, so converting a wait whose
    /// old bound EXCEEDED 8000ms would need its own base rather than this
    /// one — no such call site exists among these, and this is the note
    /// that says why.
    ///
    /// 2s because `BASE_CALIBRATION * MIN_SCALE` is 4 at the floor, so the
    /// call sites keep the 8000ms they had on a quiet machine and get up to
    /// twice that under load. The hyperlink wait had already been raised
    /// once, 5s to 8s, and then re-expressed as a 1000ms base that gave it
    /// only 4s back; the marker loop was 8000ms from the day it was written
    /// and never scaled at all. Both still lost on a loaded box, which is
    /// the shape of a wait that needs to scale rather than to be guessed
    /// higher again.
    ///
    /// Equal in value to `RESTORED_SHELL_BASE` because both replaced the
    /// same 8000ms, not because either doc settled it: that doc defers a
    /// reconciliation, but the counterexample it names,
    /// `a_terminal_link_binding_is_not_refused_for_an_editor_side_reason`,
    /// no longer waits on anything — it feeds the grid bytes directly — so
    /// the deferral is stale rather than answered here. Still a SEPARATE
    /// constant: the name is what a call site's failure message and floor
    /// assertion read as, and should either operation's cost move, the
    /// other must not follow it silently.
    pub(crate) const SHELL_PAINT_BASE: Duration = Duration::from_secs(2);

    /// The base the three task-pane tests wait for the pane's shell to come
    /// back to its prompt (#397). They had a fixed 5000ms loop that `break`s
    /// on timeout, so under load the rerun met a pane still busy, opened a
    /// second one, and the count assertion reported "3 panes, expected 2"
    /// as if reuse were broken. 1250ms keeps the 5s at the floor, and the
    /// wait now fails loudly, naming what it waited for.
    pub(crate) const TASK_PANE_PROMPT_BASE: Duration = Duration::from_millis(1250);

    /// The four #362 view-socket waits, one constant per budget they replaced.
    ///
    /// Named rather than written inline at the call sites for the reason
    /// `RESTORED_SHELL_BASE` gives: the test that pins them has to be about
    /// THEM, and a literal retyped beside an assertion stays green when a
    /// call site drifts. The first version of these conversions used inline
    /// literals, and two of them overshot the rule below without anything
    /// noticing.
    ///
    /// Each is its old constant divided by `BASE_CALIBRATION * MIN_SCALE`
    /// (which is 4), so a quiet machine gets exactly what it had and a loaded
    /// one gets more. Overshooting is not free: the module bounds the worst
    /// case at `BASE_CALIBRATION * MAX_SCALE`, and a base twice what the rule
    /// asks doubles the time a genuinely broken test takes to say so.
    pub(crate) const VIEW_ACCEPT_BASE: Duration = Duration::from_millis(1250);
    /// Replaced a fixed 500ms server-side deadline in two tests.
    pub(crate) const VIEW_SERVER_DEADLINE_BASE: Duration = Duration::from_millis(125);
    /// Replaced two fixed 2000ms poll loops (200 iterations at 10ms).
    pub(crate) const VIEW_DRAIN_BASE: Duration = Duration::from_millis(500);
    /// Replaced a fixed 20s `recv_timeout` around a thread running `App::new`.
    pub(crate) const VIEW_FIFO_RECV_BASE: Duration = Duration::from_secs(5);

    // The floor matters more than it looks: every budget this replaces was
    // observed failing at 1x, so a quiet machine must still get more room
    // than the constant it replaced, not less.
    #[test]
    fn the_scale_is_clamped_at_both_ends() {
        assert_eq!(
            scale_from(1.0, 0.0, 4.0),
            MIN_SCALE,
            "a quiet machine still gets the floor"
        );
        assert_eq!(
            scale_from(64.0, 0.0, 4.0),
            MAX_SCALE,
            "far more threads than cores is capped"
        );
        assert_eq!(
            scale_from(1.0, 999.0, 4.0),
            MAX_SCALE,
            "a crushed machine is capped too"
        );
        for (t, l, c) in [
            (f64::NAN, f64::NAN, 4.0),
            (4.0, f64::INFINITY, 4.0),
            (4.0, 1.0, 0.0),
            (4.0, 1.0, f64::NAN),
        ] {
            assert_eq!(
                scale_from(t, l, c),
                MIN_SCALE,
                "a nonsense reading falls back: {t} {l} {c}"
            );
        }
    }

    /// #422: the scale measures PRESSURE, not machine size.
    ///
    /// The old rule took `max(threads, load / cpus)` — a count against a
    /// ratio — so it read the core count on any machine big enough, and a
    /// 64-core box idling at one thread per core got the same maximum
    /// stretch as a genuinely crushed one.
    #[test]
    fn a_big_quiet_machine_is_not_a_loaded_one() {
        assert_eq!(
            scale_from(64.0, 1.0, 64.0),
            MIN_SCALE,
            "64 threads on 64 cores with nothing else running is not \
             contention: the old rule returned the CAP here"
        );
        assert_eq!(
            scale_from(8.0, 0.5, 8.0),
            MIN_SCALE,
            "nor is a quiet developer machine at its default thread count"
        );
        assert!(
            scale_from(4.0, 14.0, 4.0) > MIN_SCALE,
            "while a 4-core box under a genuine 3.5x oversubscription is"
        );
    }

    /// Each signal is blind where the other sees, so both count — and they
    /// ADD, because the suite's threads and everything else on the machine
    /// contend for the same cores.
    #[test]
    fn both_signals_contribute_to_the_pressure() {
        let quiet = scale_from(4.0, 0.0, 4.0);
        assert!(
            scale_from(12.0, 0.0, 4.0) > quiet,
            "the suite's own parallelism counts"
        );
        assert!(
            scale_from(4.0, 12.0, 4.0) > quiet,
            "so does load from outside the suite"
        );
        // Strict, on inputs where summing genuinely separates from `max`:
        // (4 + 4) / 4 = 2 against max(4, 4) / 4 = 1. A `>=` here would pass
        // even if the sum were replaced by the old maximum.
        assert!(
            scale_from(6.0, 6.0, 4.0) > scale_from(6.0, 0.0, 4.0),
            "together they are worse than either alone"
        );
    }

    /// The total stretch is what a broken test pays, and it must not have
    /// grown. `BASE_CALIBRATION * MAX_SCALE` was 1 x 8 before #422 and is
    /// 2 x 4 after — the same 8. Pinned because the two constants are only
    /// safe as a PAIR: raising either alone doubles what a developer waits
    /// to be told their change broke something, which is the cost
    /// `MAX_SCALE` exists to bound.
    #[test]
    fn the_worst_case_stretch_is_unchanged() {
        assert_eq!(
            BASE_CALIBRATION * MAX_SCALE,
            8,
            "a broken test on a 10s base still fails in 80s, not 160s"
        );
        assert_eq!(
            BASE_CALIBRATION * MIN_SCALE,
            4,
            "and a quiet machine waits 4x, down from the old 8x"
        );
        // The property `MAX_SCALE`'s doc actually promises, asserted on the
        // OUTPUT rather than on the factors: a third multiplier entering the
        // expression would leave the constants above untouched.
        let base = Duration::from_secs(1);
        assert!(
            spawn_budget(base) <= base * 8,
            "no budget may exceed the 8x ceiling, however it is composed"
        );
    }

    /// The two restored-shell waits keep the 8000ms they replaced.
    ///
    /// Written against `RESTORED_SHELL_BASE`, which those call sites use, so
    /// lowering the base fails HERE. The first version asserted over a
    /// literal `Duration::from_secs(2)` retyped beside it, which left both
    /// call sites free to change underneath it, and reduced to
    /// `BASE_CALIBRATION * MIN_SCALE >= 4` - already asserted, more
    /// strongly, by `the_worst_case_stretch_is_unchanged` above.
    #[test]
    fn a_converted_wait_keeps_the_budget_it_replaced() {
        let floor = RESTORED_SHELL_BASE * BASE_CALIBRATION * MIN_SCALE;
        assert!(
            floor >= Duration::from_millis(8000),
            "the restored-shell base must reproduce the 8000ms it replaced at \
             the floor, got {floor:?}"
        );
    }

    /// Same rule for the two #397 bases added later: each must give back,
    /// at the floor, the constant it replaced. Against the constants the
    /// call sites use, so lowering either fails here.
    #[test]
    fn the_probe_and_task_pane_bases_keep_their_old_budgets() {
        let probe = TERMINAL_PROBE_BASE * BASE_CALIBRATION * MIN_SCALE;
        assert!(
            probe >= Duration::from_secs(15),
            "the terminal probe base must reproduce the 15s it replaced at the \
             floor, got {probe:?}"
        );
        let task = TASK_PANE_PROMPT_BASE * BASE_CALIBRATION * MIN_SCALE;
        assert!(
            task >= Duration::from_millis(5000),
            "the task-pane prompt base must reproduce the 5000ms it replaced at \
             the floor, got {task:?}"
        );
        let paint = SHELL_PAINT_BASE * BASE_CALIBRATION * MIN_SCALE;
        assert!(
            paint >= Duration::from_millis(8000),
            "the shell-paint base must reproduce 8000ms at the floor, the \
             constant its call sites replaced; the few that replaced 4000ms \
             are deliberate raises, named in the doc above - got {paint:?}"
        );
    }

    /// The same rule for the four #362 view-socket bases: each reproduces, at
    /// the floor, exactly the constant it replaced. Asserted as equality
    /// rather than `>=` because these were the ones that drifted: an
    /// overshoot is as much a defect here as an undershoot, since it doubles
    /// how long a broken test takes to fail while buying a quiet machine
    /// nothing.
    #[test]
    fn the_view_socket_bases_reproduce_the_constants_they_replaced() {
        let floor = |base: Duration| base * BASE_CALIBRATION * MIN_SCALE;
        for (got, want, what) in [
            (
                floor(VIEW_ACCEPT_BASE),
                Duration::from_secs(5),
                "the accept wait",
            ),
            (
                floor(VIEW_SERVER_DEADLINE_BASE),
                Duration::from_millis(500),
                "the server deadline",
            ),
            (
                floor(VIEW_DRAIN_BASE),
                Duration::from_millis(2000),
                "the drain poll",
            ),
            (
                floor(VIEW_FIFO_RECV_BASE),
                Duration::from_secs(20),
                "the FIFO recv",
            ),
        ] {
            assert_eq!(
                got, want,
                "{what} must give back exactly the budget it replaced at the \
                 floor: a quiet machine keeps what it had, and the worst case \
                 stays where this module bounds it"
            );
        }
    }

    /// #397's measured flake, which is the ceiling this rule may not lower:
    /// a 4-CPU box at `--test-threads=8` under six spinning hogs needed a
    /// wait budgeted at 4s to have 8s.
    ///
    /// The old rule reached 8 there by reading the thread count directly.
    /// This one reads 4 — (8 + 6) / 4 — so the bases doubled in the same
    /// change to hold the same wall clock. That trade is the whole point of
    /// doing both together, and this test is what stops the scale half
    /// being changed again without the base half.
    #[test]
    fn the_397_flake_still_gets_its_eight_seconds() {
        let scale = scale_from(8.0, 6.0, 4.0);
        assert_eq!(scale, 4, "runnable work per CPU: ceil((8 + 6) / 4)");
        // That value is also MAX_SCALE, so the assertion above passes via
        // the CLAMP whether or not the formula is right — it survives
        // reverting the sum to the old `max` rule, and survives dropping
        // the division. This companion sits clear of both clamps, so it
        // asserts the formula itself: ceil((6 + 2) / 4) = 2, where the old
        // max(6, 0.5) gave 6.
        assert_eq!(
            scale_from(6.0, 2.0, 4.0),
            MIN_SCALE,
            "away from the clamps, the rule is the sum over cpus"
        );
        // Through the real formula, not a hand-doubled literal: the base a
        // test author writes is 1s, and the module supplies the calibration.
        let base = std::time::Duration::from_secs(1);
        assert!(
            base * BASE_CALIBRATION * scale >= std::time::Duration::from_secs(8),
            "the 1s base a caller writes still clears the 8s that flake needed"
        );
    }

    /// `--test-threads` and `RUST_TEST_THREADS` are the same instruction to
    /// the harness, and only one of them used to reach this module.
    ///
    /// The flag is what `cargo test -- --test-threads=8` sets, and it never
    /// touches the environment, so the suite's own parallelism read as the
    /// machine's core count whenever it was spelled that way. On the box
    /// where #397 reproduces that is the difference between a 4s budget and
    /// an 8s one for the wait that timed out.
    #[test]
    fn both_spellings_of_the_thread_count_are_seen() {
        let argv = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        assert_eq!(
            threads_from_args(argv(&["croft", "--test-threads=8"])),
            Some(8.0),
            "the joined spelling"
        );
        assert_eq!(
            threads_from_args(argv(&["croft", "--test-threads", "8"])),
            Some(8.0),
            "and the separated one"
        );
        assert_eq!(
            threads_from_args(argv(&["croft", "--nocapture"])),
            None,
            "absent means absent, so the caller falls back to the CPU count"
        );
        assert_eq!(
            threads_from_args(argv(&["croft", "--test-threads"])),
            None,
            "a flag with no value is not a thread count"
        );
        assert_eq!(
            threads_from_args(argv(&["croft", "--test-threads=zero"])),
            None,
            "nor is one that does not parse"
        );
        assert_eq!(
            threads_from_args(argv(&["croft", "--test-threads=zero", "--test-threads=8"])),
            Some(8.0),
            "a value that does not parse must not mask a real one later on"
        );
    }

    /// The flag beats the variable, because that is libtest's own order.
    ///
    /// `library/test/src/lib.rs` resolves the count as
    /// `opts.test_threads.unwrap_or_else(get_concurrency)`, and only
    /// `get_concurrency` reads `RUST_TEST_THREADS`. Reading them the other
    /// way round undercounts exactly where it matters: CI pins the variable
    /// to 4 and `CONTRIBUTING.md` teaches the variable, so
    /// `RUST_TEST_THREADS=4 cargo test -- --test-threads=8` is the natural
    /// way to reproduce #397, and an env-first reading believes 4 while the
    /// harness runs 8.
    ///
    /// The rule is asserted on the resolver rather than by setting the
    /// variable: this suite shares one process, so mutating the environment
    /// here would change what every other thread reads.
    #[test]
    fn the_flag_outranks_the_environment_variable_as_libtest_does() {
        // The shape of `configured_threads`, with both sources supplied
        // explicitly instead of read from the process.
        fn resolve(flag: Option<f64>, env: Option<f64>) -> Option<f64> {
            flag.or(env)
        }
        assert_eq!(
            resolve(Some(8.0), Some(4.0)),
            Some(8.0),
            "the flag wins when both are given, as libtest resolves it"
        );
        assert_eq!(
            resolve(None, Some(4.0)),
            Some(4.0),
            "the variable is the fallback, not the override"
        );
        assert_eq!(resolve(None, None), None, "neither means fall back to CPUs");
    }

    #[test]
    fn a_budget_scales_by_exactly_the_scale() {
        let base = Duration::from_millis(500);
        assert_eq!(
            spawn_budget(base),
            base * BASE_CALIBRATION * load_scale(),
            "the calibration factor rides with the scale (#422)"
        );
    }

    // The helper must not become a way to pass by waiting: a condition that
    // never comes true still fails, and says so in terms the reader can act on.
    #[test]
    #[should_panic(expected = "waiting for a thing that never happens")]
    fn a_condition_that_never_holds_still_fails() {
        await_spawned(
            Duration::from_millis(1),
            "a thing that never happens",
            || false,
        );
    }

    #[test]
    fn a_condition_already_true_returns_at_once() {
        let started = Instant::now();
        await_spawned(Duration::from_secs(30), "an immediate condition", || true);
        assert!(started.elapsed() < Duration::from_secs(1));
    }
}