mds-cli 0.7.0

MDS (Markdown Script) compiler — command-line interface
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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
//! `mds watch` never publishes the empty intermediate of a truncating save (#380).
//!
//! An editor that saves by truncate-then-write leaves the source empty for a moment.
//! A watcher that compiles in that moment publishes an empty output and announces a
//! rebuild of content nobody wrote. The watcher instead holds any rebuild while a
//! watched file — the entry, an imported partial, the `--vars` file, any source of a
//! watched directory — has gone from non-empty to empty, and compiles whatever is there
//! at a FIXED deadline from the first empty observation, so a file that really was
//! emptied is still published, and a stream of events cannot postpone that forever.
//!
//! Every hold here is `File::create` — `O_TRUNC` with the handle kept open — and the
//! output is polled DURING the hold, so an empty output that existed only briefly is
//! still seen.
//!
//! The claims are cadence-independent. The watcher's first empty observation cannot
//! precede the truncation, so an empty output read before [`EMPTY_HOLD_DEADLINE`] has
//! passed since the truncation is a violation whatever the scheduler did. The stricter
//! claims — never empty, exactly one rebuild — hold only when the hold measurably ended
//! before that deadline; a test thread descheduled past it leaves the watcher entitled
//! to publish, and the test then checks the deadline claim alone. Every run of a test
//! with stricter claims reports which it was in one line (`common::record_run_flag`):
//! conclusive when they were judged, inconclusive when only the deadline claim was. The
//! watch soak counts them, so a binary whose runs stop judging is seen, not passed.
//!
//! Counts and absences are read behind an ordered anchor (`common::ORDER_MARKER_SOURCE`)
//! with `finish_text`, never from a snapshot of a live pipe.

mod common;
use common::{
    count_occurrences, mds_bin, record_run_flag, spawn_watch_ready, wait_for_tap, write_atomic,
    ChildGuard, RunFlag, StderrTap, ORDER_MARKER_LINE, ORDER_MARKER_SOURCE,
};

use std::fs::File;
use std::io::Write as _;
use std::path::Path;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

// ── Constants ───────────────────────────────────────────────────────────────

/// How long a test holds a watched file truncated before it writes the content — a
/// slow editor save. Deliberately half of [`EMPTY_HOLD_DEADLINE`], so a hold that ends
/// on time ends well inside it.
const TRUNCATE_HOLD: Duration = Duration::from_millis(500);

/// The fixed deadline, from its first empty observation, after which the watcher
/// compiles a watched file that is still empty. The product's own constant of the
/// same name carries this value.
const EMPTY_HOLD_DEADLINE: Duration = Duration::from_secs(1);

/// Upper bound on an inotify-delivered effect — the same failure bound, not a
/// synchroniser, as `TIMEOUT` in `cli_watch.rs`.
const TIMEOUT: Duration = Duration::from_secs(2);

/// How often the output file is read while a hold lasts.
const OUTPUT_POLL: Duration = Duration::from_millis(5);

/// How often the repeated-truncation test truncates the already-empty entry, and how
/// many times: every 100ms for five seconds.
const REPEAT_EVERY: Duration = Duration::from_millis(100);
const REPEAT_ROUNDS: u32 = 50;

/// At most this many distinct output states are kept for a failure message.
const MAX_STATES: usize = 32;

/// The one line `mds watch` prints when it publishes an empty output over a non-empty
/// one — suppressed by `--quiet`, like every other watch status line. The output's
/// label follows it after a space: `<this text> <output>`.
const EMPTY_OUTPUT_NOTICE: &str = "Wrote an empty output:";

// ── Harness ─────────────────────────────────────────────────────────────────

/// Spawn a watcher, block until it reports readiness, and wrap it in a `ChildGuard`.
fn spawn_ready(cmd: &mut Command) -> (ChildGuard, StderrTap) {
    let (child, tap, stdout_tap) = spawn_watch_ready(cmd);
    assert!(stdout_tap.is_none(), "these tests never pipe stdout");
    (ChildGuard(child), tap)
}

/// What the test read from one output file, in order.
#[derive(Default)]
struct OutputLog {
    /// Distinct successive contents with the instant each was FIRST read (at most
    /// [`MAX_STATES`]).
    states: Vec<(String, Instant)>,
    /// When the output was first read empty.
    first_empty: Option<Instant>,
}

impl OutputLog {
    /// Read `path` once and record what it holds. A missing file records nothing.
    fn record(&mut self, path: &Path) -> Option<String> {
        let content = std::fs::read_to_string(path).ok()?;
        let now = Instant::now();
        if content.is_empty() && self.first_empty.is_none() {
            self.first_empty = Some(now);
        }
        let changed = self.states.last().is_none_or(|(last, _)| *last != content);
        if changed && self.states.len() < MAX_STATES {
            self.states.push((content.clone(), now));
        }
        Some(content)
    }

    /// When a state holding `needle` was first read.
    fn first_holding(&self, needle: &str) -> Option<Instant> {
        self.states
            .iter()
            .find(|(content, _)| content.contains(needle))
            .map(|&(_, at)| at)
    }

    /// The contents read, in order, for a failure message.
    fn contents(&self) -> Vec<&str> {
        self.states.iter().map(|(c, _)| c.as_str()).collect()
    }

    /// Keep reading `path` for `span`.
    fn poll_for(&mut self, path: &Path, span: Duration) {
        let until = Instant::now() + span;
        // Bounded by `span`: at most span / OUTPUT_POLL iterations.
        while Instant::now() < until {
            self.record(path);
            std::thread::sleep(OUTPUT_POLL);
        }
    }

    /// Keep reading `path` until it holds `needle`. PANICS after `timeout`, naming the
    /// caller and every state read.
    #[track_caller]
    fn wait_for(&mut self, path: &Path, needle: &str, timeout: Duration) {
        let deadline = Instant::now() + timeout;
        // Bounded by `timeout`: at most timeout / OUTPUT_POLL iterations.
        loop {
            if self.record(path).is_some_and(|c| c.contains(needle)) {
                return;
            }
            assert!(
                Instant::now() < deadline,
                "{}: {} never held {needle:?} within {timeout:?}; states read: {:?}",
                std::panic::Location::caller(),
                path.display(),
                self.contents()
            );
            std::thread::sleep(OUTPUT_POLL);
        }
    }
}

/// A watched file held truncated: `File::create` emptied it and the handle stays open.
struct Hold {
    file: File,
    started: Instant,
}

/// When a hold began, and when its content was written.
#[derive(Clone, Copy)]
struct HoldTiming {
    started: Instant,
    written: Instant,
}

impl Hold {
    /// Truncate `path` and keep it open. `started` is taken BEFORE the truncation, so
    /// every observation of the empty file is at or after it.
    fn start(path: &Path) -> Hold {
        let started = Instant::now();
        let file = File::create(path)
            .unwrap_or_else(|e| panic!("cannot truncate {}: {e}", path.display()));
        Hold { file, started }
    }

    /// Write `content` through the held handle, then close it.
    fn write_and_close(mut self, content: &str) -> HoldTiming {
        self.file
            .write_all(content.as_bytes())
            .expect("write through the held handle");
        let written = Instant::now();
        drop(self.file);
        HoldTiming {
            started: self.started,
            written,
        }
    }
}

impl HoldTiming {
    /// Whether the content was written before the watcher's deadline could fire: its
    /// first empty observation is at or after `started`, so its deadline is too.
    fn ended_before_deadline(&self) -> bool {
        self.written.duration_since(self.started) < EMPTY_HOLD_DEADLINE
    }

    fn held(&self) -> Duration {
        self.written.duration_since(self.started)
    }
}

/// The deadline claim, which holds under ANY scheduling: an empty output read before
/// [`EMPTY_HOLD_DEADLINE`] had passed since the truncation was published by a watcher
/// that did not hold.
#[track_caller]
fn assert_no_empty_before_the_deadline(log: &OutputLog, started: Instant, what: &str) {
    if let Some(empty_at) = log.first_empty {
        let after = empty_at.duration_since(started);
        assert!(
            after >= EMPTY_HOLD_DEADLINE,
            "{what}: an empty output was published {after:?} after the truncation, before \
             the {EMPTY_HOLD_DEADLINE:?} deadline could have passed; states read: {:?}",
            log.contents()
        );
    }
}

/// Whether the stricter claims apply to this hold of `test`: only when it measurably
/// ended before the deadline. Either way the run is flagged ([`flag_strict_claims`]).
fn strict_claims_apply(test: &str, timing: &HoldTiming, what: &str) -> bool {
    flag_strict_claims(
        test,
        timing.ended_before_deadline(),
        &format!("{what}: {}", hold_against_the_deadline(timing)),
    )
}

/// How long a hold lasted, against the deadline, for a run's flag.
fn hold_against_the_deadline(timing: &HoldTiming) -> String {
    format!(
        "hold {:?} vs deadline {EMPTY_HOLD_DEADLINE:?}",
        timing.held()
    )
}

/// Flag this run of `test` (`common::record_run_flag`) and return `strict`: conclusive
/// when the stricter claims are judged, inconclusive when the test thread was descheduled
/// past what they rest on and only the deadline claim is. `details` says what they rest
/// on, as measured.
fn flag_strict_claims(test: &str, strict: bool, details: &str) -> bool {
    let (flag, judged) = if strict {
        (RunFlag::Conclusive, "strict claims judged")
    } else {
        (RunFlag::Inconclusive, "only the deadline claim judged")
    };
    record_run_flag(test, flag, &format!("{details}; {judged}"));
    strict
}

/// Write the order marker to `src` and return everything the watcher wrote to stderr
/// through its diagnostic — every earlier rebuild's lines included.
#[track_caller]
fn stderr_through_the_marker(src: &Path, tap: StderrTap, child: &mut ChildGuard) -> String {
    // Keep the source identity for a rebuild that has not finished its reads.
    // The marker uses the same truncate-then-write save as these fixtures.
    std::fs::write(src, ORDER_MARKER_SOURCE).expect("write the order marker in place");
    wait_for_tap(&tap, ORDER_MARKER_LINE, TIMEOUT);
    tap.finish_text(child)
}

/// Everything stderr held before the order marker's first diagnostic began.
///
/// Only the start of the marker is a boundary: one edit can reach the watcher as more
/// than one event, and a failed compile is reported every time, so the marker's
/// diagnostic may repeat after it.
fn before_the_marker(stderr: &str) -> &str {
    let at = stderr
        .find(ORDER_MARKER_LINE)
        .expect("the order marker's diagnostic is on stderr");
    // A diagnostic opens with its code line (`mds::undefined_var`) above the message.
    let head = &stderr[..at];
    head.rfind("mds::").map_or(head, |code| &head[..code])
}

/// While a rebuild is held nothing is printed: before the order marker, stderr holds
/// no diagnostic, only startup lines and exactly `rebuilds` `Recompiled` lines.
#[track_caller]
fn assert_holding_printed_nothing(stderr: &str, rebuilds: usize, what: &str) {
    let before = before_the_marker(stderr);
    assert_eq!(
        count_occurrences(before, "mds::"),
        0,
        "{what}: no diagnostic may be printed while the file is held empty; \
         stderr:\n{stderr}"
    );
    let lines: Vec<&str> = before.lines().filter(|l| !l.trim().is_empty()).collect();
    let unexpected: Vec<&&str> = lines
        .iter()
        .filter(|l| {
            !(l.starts_with("Watching ")
                || l.starts_with("Compiled to ")
                || l.starts_with("Recompiled "))
        })
        .collect();
    assert!(
        unexpected.is_empty(),
        "{what}: holding a rebuild prints nothing; unexpected lines {unexpected:?}; \
         stderr:\n{stderr}"
    );
    assert_eq!(
        lines
            .iter()
            .filter(|l| l.starts_with("Recompiled "))
            .count(),
        rebuilds,
        "{what}: exactly {rebuilds} rebuild(s) for the content finally written; \
         stderr:\n{stderr}"
    );
}

// ── The entry held truncated ────────────────────────────────────────────────

/// Hold the entry truncated for [`TRUNCATE_HOLD`], then write: the output never goes
/// empty, and exactly one `Recompiled` line is printed, for the final content. `test`
/// names the run's flag.
fn held_truncate_of_the_entry(test: &str, extra: &[&str], what: &str) {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("t.mds");
    std::fs::write(&src, "version 1\n").unwrap();
    let out = dir.path().join("t.md");

    let (mut child, tap) = spawn_ready(
        mds_bin()
            .arg("watch")
            .arg(&src)
            .args(extra)
            .stdout(Stdio::null()),
    );
    let mut log = OutputLog::default();
    log.wait_for(&out, "version 1", TIMEOUT);

    let hold = Hold::start(&src);
    log.poll_for(&out, TRUNCATE_HOLD);
    let timing = hold.write_and_close("version 2\n");
    log.wait_for(&out, "version 2", TIMEOUT);
    // A little longer: an empty output published late would still be seen.
    log.poll_for(&out, TRUNCATE_HOLD);

    let stderr = stderr_through_the_marker(&src, tap, &mut child);
    assert_no_empty_before_the_deadline(&log, timing.started, what);
    assert_eq!(
        std::fs::read_to_string(&out).unwrap(),
        "version 2\n",
        "{what}: the output holds the content finally written"
    );
    if strict_claims_apply(test, &timing, what) {
        assert!(
            log.first_empty.is_none(),
            "{what}: the output must never be empty while the entry is held truncated; \
             states read: {:?}; stderr:\n{stderr}",
            log.contents()
        );
        assert_holding_printed_nothing(&stderr, 1, what);
    }
}

#[test]
fn held_truncate_of_the_entry_at_debounce_0_never_publishes_an_empty_output() {
    held_truncate_of_the_entry(
        "held_truncate_of_the_entry_at_debounce_0_never_publishes_an_empty_output",
        &["--debounce", "0"],
        "--debounce 0",
    );
}

#[test]
fn held_truncate_of_the_entry_at_the_default_debounce_never_publishes_an_empty_output() {
    held_truncate_of_the_entry(
        "held_truncate_of_the_entry_at_the_default_debounce_never_publishes_an_empty_output",
        &[],
        "default debounce",
    );
}

#[test]
fn held_truncate_of_the_entry_with_poll_interval_0_never_publishes_an_empty_output() {
    held_truncate_of_the_entry(
        "held_truncate_of_the_entry_with_poll_interval_0_never_publishes_an_empty_output",
        &["--debounce", "0", "--poll-interval", "0"],
        "--debounce 0 --poll-interval 0",
    );
}

// ── A dependency held truncated ─────────────────────────────────────────────

/// A dependency of a source to hold truncated.
struct DependencyCase<'a> {
    /// The test, by name, for its run's flag.
    test: &'a str,
    what: &'a str,
    /// The path `mds watch` is given: the source, or the directory it is in.
    watched: &'a Path,
    /// The source that reads the dependency; the order marker is written to it.
    source: &'a Path,
    /// The source's output.
    output: &'a Path,
    /// The file held truncated: a dependency of the source, or the source itself.
    dependency: &'a Path,
    /// What is written through the held handle.
    rewrite: &'a str,
    /// Extra `mds watch` arguments.
    extra: &'a [&'a str],
    /// A needle the output holds before the hold, and one it holds after the rewrite.
    before: &'a str,
    after: &'a str,
}

/// Hold a dependency of a source truncated, then write it: no compile runs while it is
/// empty — no diagnostic, no `Recompiled`, the output untouched — and one rebuild
/// follows the write.
fn held_truncate_of_a_dependency(case: &DependencyCase<'_>) {
    let what = case.what;
    let out = case.output;
    let (mut child, tap) = spawn_ready(
        mds_bin()
            .arg("watch")
            .arg(case.watched)
            .args(case.extra)
            .args(["--debounce", "0"])
            .stdout(Stdio::null()),
    );
    let mut log = OutputLog::default();
    log.wait_for(out, case.before, TIMEOUT);

    let hold = Hold::start(case.dependency);
    log.poll_for(out, TRUNCATE_HOLD);
    let timing = hold.write_and_close(case.rewrite);
    log.wait_for(out, case.after, TIMEOUT);

    let stderr = stderr_through_the_marker(case.source, tap, &mut child);
    assert_no_empty_before_the_deadline(&log, timing.started, what);
    if strict_claims_apply(case.test, &timing, what) {
        assert_eq!(
            log.states.len(),
            2,
            "{what}: the output changes once, from the old content straight to the new; \
             states read: {:?}",
            log.contents()
        );
        assert_holding_printed_nothing(&stderr, 1, what);
    }
}

#[test]
fn held_truncate_of_an_imported_partial_triggers_nothing_until_written() {
    let dir = tempfile::tempdir().unwrap();
    let partial = dir.path().join("_p.mds");
    std::fs::write(
        &partial,
        "@define val():\nPartial one\n@end\n\n@export val\n",
    )
    .unwrap();
    let entry = dir.path().join("t.mds");
    std::fs::write(&entry, "@import \"./_p.mds\" as p\n{{p.val()}}\n").unwrap();

    held_truncate_of_a_dependency(&DependencyCase {
        test: "held_truncate_of_an_imported_partial_triggers_nothing_until_written",
        what: "an imported partial",
        watched: &entry,
        source: &entry,
        output: &dir.path().join("t.md"),
        dependency: &partial,
        rewrite: "@define val():\nPartial two\n@end\n\n@export val\n",
        extra: &[],
        before: "Partial one",
        after: "Partial two",
    });
}

#[test]
fn held_truncate_of_the_vars_file_triggers_nothing_until_written() {
    let dir = tempfile::tempdir().unwrap();
    let vars = dir.path().join("vars.json");
    std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
    let entry = dir.path().join("t.mds");
    std::fs::write(&entry, "Vars {{v}}\n").unwrap();

    held_truncate_of_a_dependency(&DependencyCase {
        test: "held_truncate_of_the_vars_file_triggers_nothing_until_written",
        what: "the vars file",
        watched: &entry,
        source: &entry,
        output: &dir.path().join("t.md"),
        dependency: &vars,
        rewrite: r#"{"v": "two"}"#,
        extra: &["--vars", vars.to_str().unwrap()],
        before: "Vars one",
        after: "Vars two",
    });
}

/// In directory mode the `--vars` file, which no source of the directory is, holds the
/// batch back while it is empty as a source would: no compile, no error, no rebuild until
/// it is written (#380).
#[test]
fn dir_mode_held_truncate_of_the_vars_file_triggers_nothing_until_written() {
    let dir = tempfile::tempdir().unwrap();
    let vars = dir.path().join("vars.json");
    std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
    let root = dir.path().join("src");
    std::fs::create_dir(&root).unwrap();
    let source = root.join("t.mds");
    std::fs::write(&source, "Vars {{v}}\n").unwrap();
    let out = dir.path().join("out");

    held_truncate_of_a_dependency(&DependencyCase {
        test: "dir_mode_held_truncate_of_the_vars_file_triggers_nothing_until_written",
        what: "directory mode, the vars file",
        watched: &root,
        source: &source,
        output: &out.join("t.md"),
        dependency: &vars,
        rewrite: r#"{"v": "two"}"#,
        extra: &[
            "--out-dir",
            out.to_str().unwrap(),
            "--vars",
            vars.to_str().unwrap(),
        ],
        before: "Vars one",
        after: "Vars two",
    });
}

// ── A dependency truncated after its rebuild looked ─────────────────────────

/// Hold a dependency of a source truncated while a rebuild is under way — after it looked
/// and found every file full, before it read any — then write it. The debug build's pause
/// between a rebuild's look and its reads (`MDS_TEST_PAUSE_AFTER_LOOK`) makes the window
/// certain; outside a test, a save that lands while an earlier event's rebuild runs opens
/// it. The rebuild reads the file empty and fails — the `--vars` file cannot be loaded, or
/// the import no longer defines what the source uses — and is held as a rebuild whose look
/// found the file empty is: no diagnostic, no `Recompiled`, the output untouched, and one
/// rebuild follows the write.
#[cfg(debug_assertions)]
fn held_truncate_after_the_look(case: &DependencyCase<'_>) {
    held_truncate_in_a_pause(case, case.source, "MDS_TEST_PAUSE_AFTER_LOOK");
}

/// Save `saved` as it is, truncate the dependency while the rebuild that save starts is
/// stopped at the debug build's `pause` — the variable of the pause after a rebuild's look,
/// of the one after a directory batch's split, or of the one after a file rebuild's reads —
/// then write it: no diagnostic, no `Recompiled`, the output untouched, and one rebuild
/// follows the write.
#[cfg(debug_assertions)]
fn held_truncate_in_a_pause(case: &DependencyCase<'_>, saved: &Path, pause: &str) {
    let what = case.what;
    let out = case.output;
    // Outside every watched directory, so the pause's files raise no event.
    let gate = tempfile::tempdir().unwrap();
    let (go, paused) = (gate.path().join("go"), gate.path().join("go.paused"));
    let (mut child, tap) = spawn_ready(
        mds_bin()
            .arg("watch")
            .arg(case.watched)
            .args(case.extra)
            .args(["--debounce", "0", "--poll-interval", "0"])
            .env(pause, &go)
            .stdout(Stdio::null()),
    );
    let mut log = OutputLog::default();
    log.wait_for(out, case.before, TIMEOUT);

    // The file saved as it is: its rebuild looks, finds every file full, and pauses.
    let content = std::fs::read_to_string(saved).unwrap();
    write_atomic(saved, &content);
    let paused_by = Instant::now() + TIMEOUT;
    // Bounded by TIMEOUT: at most TIMEOUT / OUTPUT_POLL iterations.
    while !paused.exists() {
        assert!(
            Instant::now() < paused_by,
            "{what}: setup: no rebuild paused after its look; stderr: {}",
            tap.text()
        );
        std::thread::sleep(OUTPUT_POLL);
    }
    let hold = Hold::start(case.dependency);
    std::fs::write(&go, "").unwrap();
    log.poll_for(out, TRUNCATE_HOLD);
    let timing = hold.write_and_close(case.rewrite);
    log.wait_for(out, case.after, TIMEOUT);

    let stderr = stderr_through_the_marker(case.source, tap, &mut child);
    assert_no_empty_before_the_deadline(&log, timing.started, what);
    if strict_claims_apply(case.test, &timing, what) {
        assert_eq!(
            log.states.len(),
            2,
            "{what}: the output changes once, from the old content straight to the new; \
             states read: {:?}",
            log.contents()
        );
        assert_holding_printed_nothing(&stderr, 1, what);
    }
}

#[cfg(debug_assertions)]
#[test]
fn an_imported_partial_truncated_after_the_look_triggers_nothing_until_written() {
    let dir = tempfile::tempdir().unwrap();
    let partial = dir.path().join("_p.mds");
    std::fs::write(
        &partial,
        "@define val():\nPartial one\n@end\n\n@export val\n",
    )
    .unwrap();
    let entry = dir.path().join("t.mds");
    std::fs::write(&entry, "@import \"./_p.mds\" as p\n{{p.val()}}\n").unwrap();

    held_truncate_after_the_look(&DependencyCase {
        test: "an_imported_partial_truncated_after_the_look_triggers_nothing_until_written",
        what: "an imported partial, truncated after the look",
        watched: &entry,
        source: &entry,
        output: &dir.path().join("t.md"),
        dependency: &partial,
        rewrite: "@define val():\nPartial two\n@end\n\n@export val\n",
        extra: &[],
        before: "Partial one",
        after: "Partial two",
    });
}

#[cfg(debug_assertions)]
#[test]
fn the_vars_file_truncated_after_the_look_triggers_nothing_until_written() {
    let dir = tempfile::tempdir().unwrap();
    let vars = dir.path().join("vars.json");
    std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
    let entry = dir.path().join("t.mds");
    std::fs::write(&entry, "Vars {{v}}\n").unwrap();

    held_truncate_after_the_look(&DependencyCase {
        test: "the_vars_file_truncated_after_the_look_triggers_nothing_until_written",
        what: "the vars file, truncated after the look",
        watched: &entry,
        source: &entry,
        output: &dir.path().join("t.md"),
        dependency: &vars,
        rewrite: r#"{"v": "two"}"#,
        extra: &["--vars", vars.to_str().unwrap()],
        before: "Vars one",
        after: "Vars two",
    });
}

#[cfg(debug_assertions)]
#[test]
fn dir_mode_the_vars_file_truncated_after_the_look_triggers_nothing_until_written() {
    let dir = tempfile::tempdir().unwrap();
    let vars = dir.path().join("vars.json");
    std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
    let root = dir.path().join("src");
    std::fs::create_dir(&root).unwrap();
    let source = root.join("t.mds");
    std::fs::write(&source, "Vars {{v}}\n").unwrap();
    let out = dir.path().join("out");

    held_truncate_after_the_look(&DependencyCase {
        test: "dir_mode_the_vars_file_truncated_after_the_look_triggers_nothing_until_written",
        what: "directory mode, the vars file, truncated after the look",
        watched: &root,
        source: &source,
        output: &out.join("t.md"),
        dependency: &vars,
        rewrite: r#"{"v": "two"}"#,
        extra: &[
            "--out-dir",
            out.to_str().unwrap(),
            "--vars",
            vars.to_str().unwrap(),
        ],
        before: "Vars one",
        after: "Vars two",
    });
}

#[cfg(debug_assertions)]
#[test]
fn dir_mode_an_imported_partial_truncated_after_the_look_triggers_nothing_until_written() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("src");
    std::fs::create_dir(&root).unwrap();
    let partial = root.join("_p.mds");
    std::fs::write(
        &partial,
        "@define val():\nPartial one\n@end\n\n@export val\n",
    )
    .unwrap();
    let source = root.join("t.mds");
    std::fs::write(&source, "@import \"./_p.mds\" as p\n{{p.val()}}\n").unwrap();
    let out = dir.path().join("out");

    held_truncate_after_the_look(&DependencyCase {
        test:
            "dir_mode_an_imported_partial_truncated_after_the_look_triggers_nothing_until_written",
        what: "directory mode, an imported partial, truncated after the look",
        watched: &root,
        source: &source,
        output: &out.join("t.md"),
        dependency: &partial,
        rewrite: "@define val():\nPartial two\n@end\n\n@export val\n",
        extra: &["--out-dir", out.to_str().unwrap()],
        before: "Partial one",
        after: "Partial two",
    });
}

// ── A file truncated after its file rebuild read it ─────────────────────────

/// The entry truncated while its rebuild finishes — after the compile read it whole and no
/// file was found emptied, before the rebuild took its baseline — holds the rebuilds its own
/// events start, as a look that found it empty does: the rebuild must not take the empty
/// file for the one it read, or those rebuilds publish it empty. The debug build's pause
/// after a file rebuild's reads (`MDS_TEST_PAUSE_AFTER_READ`) makes the window certain;
/// outside a test, a truncating save that lands as an earlier event's rebuild finishes
/// opens it.
#[cfg(debug_assertions)]
#[test]
fn the_entry_truncated_after_its_rebuild_read_it_never_publishes_an_empty_output() {
    let dir = tempfile::tempdir().unwrap();
    let entry = dir.path().join("t.mds");
    std::fs::write(&entry, "Entry one\n").unwrap();

    held_truncate_in_a_pause(
        &DependencyCase {
            test: "the_entry_truncated_after_its_rebuild_read_it_never_publishes_an_empty_output",
            what: "the entry, truncated after its rebuild read it",
            watched: &entry,
            source: &entry,
            output: &dir.path().join("t.md"),
            dependency: &entry,
            rewrite: "Entry two\n",
            extra: &[],
            before: "Entry one",
            after: "Entry two",
        },
        &entry,
        "MDS_TEST_PAUSE_AFTER_READ",
    );
}

/// The `--vars` file truncated after a file rebuild read it whole, before the rebuild took
/// its baseline, holds the rebuilds its own events start: they report nothing while it is
/// empty (`MDS_TEST_PAUSE_AFTER_READ`, as above).
#[cfg(debug_assertions)]
#[test]
fn the_vars_file_truncated_after_its_rebuild_read_it_triggers_nothing_until_written() {
    let dir = tempfile::tempdir().unwrap();
    let vars = dir.path().join("vars.json");
    std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
    let entry = dir.path().join("t.mds");
    std::fs::write(&entry, "Vars {{v}}\n").unwrap();

    held_truncate_in_a_pause(
        &DependencyCase {
            test:
                "the_vars_file_truncated_after_its_rebuild_read_it_triggers_nothing_until_written",
            what: "the vars file, truncated after its rebuild read it",
            watched: &entry,
            source: &entry,
            output: &dir.path().join("t.md"),
            dependency: &vars,
            rewrite: r#"{"v": "two"}"#,
            extra: &["--vars", vars.to_str().unwrap()],
            before: "Vars one",
            after: "Vars two",
        },
        &entry,
        "MDS_TEST_PAUSE_AFTER_READ",
    );
}

// ── A save that ends between a rebuild's read and its late look ─────────────

/// A save that truncates a file and writes it again, and ends between a rebuild's read and
/// its late look, never publishes the empty read (#380): the rebuild read the file empty,
/// so it is held, whatever the file holds when the late look runs, and the next rebuild
/// publishes what was written. A `stat` at the late look would find the bytes written and
/// let the empty read through. The debug build's pause after the look
/// (`MDS_TEST_PAUSE_AFTER_LOOK`) lets the test empty the file before the read, and its
/// pause before the late look (`MDS_TEST_PAUSE_BEFORE_LATE_LOOK`) lets it write the file
/// before the check; outside a test, an editor's truncate-then-write save that ends in
/// that window opens it.
#[cfg(debug_assertions)]
fn a_save_ending_between_the_read_and_the_late_look(case: &DependencyCase<'_>, saved: &Path) {
    let what = case.what;
    let out = case.output;
    // Outside every watched directory, so the pauses' files raise no event.
    let gate = tempfile::tempdir().unwrap();
    let (look_go, look_paused) = (gate.path().join("look"), gate.path().join("look.paused"));
    let (late_go, late_paused) = (gate.path().join("late"), gate.path().join("late.paused"));
    let (mut child, tap) = spawn_ready(
        mds_bin()
            .arg("watch")
            .arg(case.watched)
            .args(case.extra)
            .args(["--debounce", "0", "--poll-interval", "0"])
            .env("MDS_TEST_PAUSE_AFTER_LOOK", &look_go)
            .env("MDS_TEST_PAUSE_BEFORE_LATE_LOOK", &late_go)
            .stdout(Stdio::null()),
    );
    let mut log = OutputLog::default();
    log.wait_for(out, case.before, TIMEOUT);

    // The file saved as it is: its rebuild looks, finds every file full, and pauses.
    let content = std::fs::read_to_string(saved).unwrap();
    write_atomic(saved, &content);
    wait_for_the_pause(&look_paused, &tap, what);
    // The save begins: the file is emptied before the rebuild reads it.
    File::create(case.dependency).expect("truncate the file");
    std::fs::write(&look_go, "").unwrap();
    wait_for_the_pause(&late_paused, &tap, what);
    // The save ends after the read, before the late look.
    std::fs::write(case.dependency, case.rewrite).expect("write the file again");
    std::fs::write(&late_go, "").unwrap();
    log.wait_for(out, case.after, TIMEOUT);

    let stderr = stderr_through_the_marker(case.source, tap, &mut child);
    assert!(
        !log.contents().contains(&""),
        "{what}: the empty read is never published; states read: {:?}; stderr:\n{stderr}",
        log.contents()
    );
    assert!(
        !before_the_marker(&stderr).contains(EMPTY_OUTPUT_NOTICE),
        "{what}: no empty output is written; stderr:\n{stderr}"
    );
    assert_holding_printed_nothing(&stderr, 1, what);
}

#[cfg(debug_assertions)]
#[test]
fn the_entry_saved_between_its_rebuild_s_read_and_late_look_never_publishes_an_empty_output() {
    let dir = tempfile::tempdir().unwrap();
    let entry = dir.path().join("t.mds");
    std::fs::write(&entry, "Entry one\n").unwrap();

    a_save_ending_between_the_read_and_the_late_look(
        &DependencyCase {
            test: "the_entry_saved_between_its_rebuild_s_read_and_late_look_never_publishes_an_empty_output",
            what: "the entry, saved between its rebuild's read and late look",
            watched: &entry,
            source: &entry,
            output: &dir.path().join("t.md"),
            dependency: &entry,
            rewrite: "Entry two\n",
            extra: &[],
            before: "Entry one",
            after: "Entry two",
        },
        &entry,
    );
}

/// The `--vars` file read empty by a file rebuild's load, which refuses it, and written
/// again before the late look: the rebuild is held and reports nothing.
#[cfg(debug_assertions)]
#[test]
fn the_vars_file_saved_between_its_rebuild_s_read_and_late_look_reports_nothing() {
    let dir = tempfile::tempdir().unwrap();
    let vars = dir.path().join("vars.json");
    std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
    let entry = dir.path().join("t.mds");
    std::fs::write(&entry, "Vars {{v}}\n").unwrap();

    a_save_ending_between_the_read_and_the_late_look(
        &DependencyCase {
            test: "the_vars_file_saved_between_its_rebuild_s_read_and_late_look_reports_nothing",
            what: "the vars file, saved between its rebuild's read and late look",
            watched: &entry,
            source: &entry,
            output: &dir.path().join("t.md"),
            dependency: &vars,
            rewrite: r#"{"v": "two"}"#,
            extra: &["--vars", vars.to_str().unwrap()],
            before: "Vars one",
            after: "Vars two",
        },
        &entry,
    );
}

/// In directory mode, a source read empty by its batch's compile and written again before
/// the late look: the source is held, and the next batch publishes what was written.
#[cfg(debug_assertions)]
#[test]
fn dir_mode_a_source_saved_between_its_batch_s_read_and_late_look_never_publishes_an_empty_output()
{
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("src");
    std::fs::create_dir(&root).unwrap();
    let source = root.join("t.mds");
    std::fs::write(&source, "Source one\n").unwrap();
    let out = dir.path().join("out");

    a_save_ending_between_the_read_and_the_late_look(
        &DependencyCase {
            test: "dir_mode_a_source_saved_between_its_batch_s_read_and_late_look_never_publishes_an_empty_output",
            what: "directory mode, a source saved between its batch's read and late look",
            watched: &root,
            source: &source,
            output: &out.join("t.md"),
            dependency: &source,
            rewrite: "Source two\n",
            extra: &["--out-dir", out.to_str().unwrap()],
            before: "Source one",
            after: "Source two",
        },
        &source,
    );
}

// ── A file truncated while a directory batch runs ───────────────────────────

/// In directory mode, the `--vars` file truncated while a batch runs — after the batch read
/// it whole, before the batch ends — holds the rebuilds its own events start, as a look
/// that found it empty does: the batch compiled with what it read and ended with the file
/// empty, which it must not take for the file it read. The debug build's pause between a
/// batch's split and its compile (`MDS_TEST_PAUSE_AFTER_BATCH_SPLIT`), after the batch's
/// `--vars` load, makes the window certain; outside a test, a truncating save that lands
/// while an earlier event's batch compiles opens it.
#[cfg(debug_assertions)]
#[test]
fn dir_mode_the_vars_file_truncated_after_its_batch_read_it_triggers_nothing_until_written() {
    let dir = tempfile::tempdir().unwrap();
    let vars = dir.path().join("vars.json");
    std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
    let root = dir.path().join("src");
    std::fs::create_dir(&root).unwrap();
    let source = root.join("t.mds");
    std::fs::write(&source, "Vars {{v}}\n").unwrap();
    let out = dir.path().join("out");

    held_truncate_in_a_pause(
        &DependencyCase {
            test: "dir_mode_the_vars_file_truncated_after_its_batch_read_it_triggers_nothing_until_written",
            what: "directory mode, the vars file, truncated after its batch read it",
            watched: &root,
            source: &source,
            output: &out.join("t.md"),
            dependency: &vars,
            rewrite: r#"{"v": "two"}"#,
            extra: &[
                "--out-dir",
                out.to_str().unwrap(),
                "--vars",
                vars.to_str().unwrap(),
            ],
            before: "Vars one",
            after: "Vars two",
        },
        &source,
        "MDS_TEST_PAUSE_AFTER_BATCH_SPLIT",
    );
}

/// In directory mode, a source truncated while a batch that rebuilds another source runs —
/// after the batch looked, before it ends — is held when its own events come, as one a
/// look found empty is: the batch never read it and ended with it empty, which it must not
/// take for the file the session last saw. The debug build's pause after a batch's look
/// (`MDS_TEST_PAUSE_AFTER_LOOK`) makes the window certain; outside a test, a truncating
/// save that lands while an earlier event's batch rebuilds another source opens it.
#[cfg(debug_assertions)]
#[test]
fn dir_mode_a_source_truncated_while_a_batch_rebuilds_another_is_held() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("src");
    std::fs::create_dir(&root).unwrap();
    let a = root.join("a.mds");
    let b = root.join("b.mds");
    std::fs::write(&a, "A one\n").unwrap();
    std::fs::write(&b, "B one\n").unwrap();
    let out = dir.path().join("out");

    held_truncate_in_a_pause(
        &DependencyCase {
            test: "dir_mode_a_source_truncated_while_a_batch_rebuilds_another_is_held",
            what: "directory mode, a source truncated while another's batch runs",
            watched: &root,
            source: &a,
            output: &out.join("a.md"),
            dependency: &a,
            rewrite: "A two\n",
            extra: &["--out-dir", out.to_str().unwrap()],
            before: "A one",
            after: "A two",
        },
        &b,
        "MDS_TEST_PAUSE_AFTER_LOOK",
    );
}

// ── Directory mode defers the whole batch ───────────────────────────────────

/// In directory mode a source held truncated defers every rebuild, not only its own:
/// another source edited during the hold is published only after the held one is
/// written, and neither output is ever empty.
#[test]
fn dir_mode_held_truncate_defers_the_whole_batch() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("src");
    std::fs::create_dir(&root).unwrap();
    let a = root.join("a.mds");
    let b = root.join("b.mds");
    std::fs::write(&a, "A one\n").unwrap();
    std::fs::write(&b, "B one\n").unwrap();
    let out = dir.path().join("out");
    let (a_out, b_out) = (out.join("a.md"), out.join("b.md"));

    let (mut child, tap) = spawn_ready(
        mds_bin()
            .arg("watch")
            .arg(&root)
            .arg("--out-dir")
            .arg(&out)
            .args(["--debounce", "0"])
            .stdout(Stdio::null()),
    );
    let (mut a_log, mut b_log) = (OutputLog::default(), OutputLog::default());
    a_log.wait_for(&a_out, "A one", TIMEOUT);
    b_log.wait_for(&b_out, "B one", TIMEOUT);

    let hold = Hold::start(&a);
    // Into the hold, edit the other source, then keep reading both outputs. The edit is
    // always made, before a.mds is written, however late a descheduled thread comes back.
    let edit_after = TRUNCATE_HOLD / 5;
    let edit_at = hold.started + edit_after;
    let until = hold.started + TRUNCATE_HOLD;
    let mut edited_at: Option<Instant> = None;
    // Bounded by TRUNCATE_HOLD: at most TRUNCATE_HOLD / OUTPUT_POLL iterations, and one
    // more that edits when the thread came back after `until` without having edited.
    while edited_at.is_none() || Instant::now() < until {
        if edited_at.is_none() && Instant::now() >= edit_at {
            write_atomic(&b, "B two\n");
            edited_at = Some(Instant::now());
        }
        a_log.record(&a_out);
        b_log.record(&b_out);
        std::thread::sleep(OUTPUT_POLL);
    }
    let edited_at = edited_at.expect("the loop edits before it ends");
    let timing = hold.write_and_close("A two\n");
    a_log.wait_for(&a_out, "A two", TIMEOUT);
    b_log.wait_for(&b_out, "B two", TIMEOUT);

    let stderr = stderr_through_the_marker(&a, tap, &mut child);
    let what = "directory mode";
    assert_no_empty_before_the_deadline(&a_log, timing.started, what);
    // An edit made once the deadline could have passed may be published at once, as an
    // empty output then may: the strict claims need both in time.
    let edited = edited_at.duration_since(timing.started);
    let strict = timing.ended_before_deadline() && edited < EMPTY_HOLD_DEADLINE;
    if flag_strict_claims(
        "dir_mode_held_truncate_defers_the_whole_batch",
        strict,
        &format!(
            "{what}: {}, the other source edited {edited:?} into it",
            hold_against_the_deadline(&timing)
        ),
    ) {
        assert!(
            a_log.first_empty.is_none(),
            "{what}: a.md must never be empty while a.mds is held truncated; states: {:?}",
            a_log.contents()
        );
        let b_published = b_log
            .first_holding("B two")
            .expect("b.md reached its new content");
        assert!(
            b_published >= timing.written,
            "{what}: the other source's edit must wait for the held one — b.md held \
             `B two` {:?} before a.mds was written; stderr:\n{stderr}",
            timing.written.duration_since(b_published)
        );
        assert_holding_printed_nothing(&stderr, 2, what);
    }
}

/// A source created while another is held empty is compiled when the hold ends, though a
/// batch held with it changed the `--vars` file: the batch that ends the hold recompiles
/// every source, the ones created during the hold included.
#[test]
fn dir_mode_a_source_created_during_a_hold_is_compiled_with_a_vars_edit() {
    let dir = tempfile::tempdir().unwrap();
    let vars = dir.path().join("vars.json");
    std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
    let root = dir.path().join("src");
    std::fs::create_dir(&root).unwrap();
    let a = root.join("a.mds");
    std::fs::write(&a, "A {{v}}\n").unwrap();
    let out = dir.path().join("out");
    let (a_out, new_out) = (out.join("a.md"), out.join("new.md"));

    let (_child, _tap) = spawn_ready(
        mds_bin()
            .arg("watch")
            .arg(&root)
            .arg("--out-dir")
            .arg(&out)
            .arg("--vars")
            .arg(&vars)
            // No idle tick: its first full walk would find the new source whatever the
            // batch did.
            .args(["--debounce", "0", "--poll-interval", "0"])
            .stdout(Stdio::null()),
    );
    OutputLog::default().wait_for(&a_out, "A one", TIMEOUT);

    // a.mds emptied and left so: every batch is held until the deadline, which compiles
    // the files as they are.
    std::fs::write(&a, "").unwrap();
    std::fs::write(root.join("new.mds"), "New {{v}}\n").unwrap();
    write_atomic(&vars, r#"{"v": "two"}"#);

    OutputLog::default().wait_for(&new_out, "New two", EMPTY_HOLD_DEADLINE + TIMEOUT);
}

/// A source truncated while its rebuild is under way — after the rebuild looked and found
/// it full, before its compile read it — is held as one the look found empty is: the
/// empty read is never published, and the write that follows is. The debug build's pause
/// between a directory batch's look and its compile (`MDS_TEST_PAUSE_AFTER_BATCH_SPLIT`)
/// makes the window certain.
#[cfg(debug_assertions)]
#[test]
fn dir_mode_a_source_truncated_after_its_rebuild_looked_is_held() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("src");
    std::fs::create_dir(&root).unwrap();
    let a = root.join("a.mds");
    std::fs::write(&a, "A one\n").unwrap();
    let out = dir.path().join("out");
    let a_out = out.join("a.md");
    let (go, paused) = (dir.path().join("go"), dir.path().join("go.paused"));

    let (mut child, tap) = spawn_ready(
        mds_bin()
            .arg("watch")
            .arg(&root)
            .arg("--out-dir")
            .arg(&out)
            .args(["--debounce", "0", "--poll-interval", "0"])
            .env("MDS_TEST_PAUSE_AFTER_BATCH_SPLIT", &go)
            .stdout(Stdio::null()),
    );
    let mut log = OutputLog::default();
    log.wait_for(&a_out, "A one", TIMEOUT);

    // A save: its rebuild looks, finds a.mds full, and pauses before compiling it.
    write_atomic(&a, "A two\n");
    let paused_by = Instant::now() + TIMEOUT;
    // Bounded by TIMEOUT: at most TIMEOUT / OUTPUT_POLL iterations.
    while !paused.exists() {
        assert!(
            Instant::now() < paused_by,
            "setup: the rebuild never paused; stderr: {}",
            tap.text()
        );
        std::thread::sleep(OUTPUT_POLL);
    }
    let hold = Hold::start(&a);
    std::fs::write(&go, "").unwrap();
    log.poll_for(&a_out, TRUNCATE_HOLD);
    let timing = hold.write_and_close("A three\n");
    log.wait_for(&a_out, "A three", TIMEOUT);

    let stderr = stderr_through_the_marker(&a, tap, &mut child);
    let what = "directory mode, truncated after the look";
    assert_no_empty_before_the_deadline(&log, timing.started, what);
    if strict_claims_apply(
        "dir_mode_a_source_truncated_after_its_rebuild_looked_is_held",
        &timing,
        what,
    ) {
        assert!(
            log.first_empty.is_none(),
            "{what}: a.md must never be empty while a.mds is held truncated; states: {:?}",
            log.contents()
        );
        assert_holding_printed_nothing(&stderr, 1, what);
    }
}

// ── A source created and changed after its batch looked ─────────────────────

/// A directory watch of an empty `src/` whose rebuilds stop after their look
/// (`MDS_TEST_PAUSE_AFTER_LOOK`), with `src/n.mds` just created and the batch its creation
/// starts stopped there: a batch that names a source no compile has read yet.
#[cfg(debug_assertions)]
struct NewSourcePaused {
    child: ChildGuard,
    tap: StderrTap,
    source: std::path::PathBuf,
    output: std::path::PathBuf,
    /// The file whose creation ends the pause.
    go: std::path::PathBuf,
    _dir: tempfile::TempDir,
}

/// Watch an empty `src/`, create `src/n.mds` holding `content`, and return once the batch
/// that creation starts has looked and stopped. Nothing is below `src/` when the watch
/// starts, so no event of the startup can start a batch: the one that stops names `n.mds`.
#[cfg(debug_assertions)]
fn a_new_source_s_batch_stopped_after_its_look(content: &str) -> NewSourcePaused {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("src");
    std::fs::create_dir(&root).unwrap();
    let out = dir.path().join("out");
    std::fs::create_dir(&out).unwrap();
    // Outside the watched directory, so the pause's files raise no event.
    let (go, paused) = (dir.path().join("go"), dir.path().join("go.paused"));
    let (child, tap) = spawn_ready(
        mds_bin()
            .arg("watch")
            .arg(&root)
            .arg("--out-dir")
            .arg(&out)
            .args(["--debounce", "0", "--poll-interval", "0"])
            .env("MDS_TEST_PAUSE_AFTER_LOOK", &go)
            .stdout(Stdio::null()),
    );
    let source = root.join("n.mds");
    write_atomic(&source, content);
    let paused_by = Instant::now() + TIMEOUT;
    // Bounded by TIMEOUT: at most TIMEOUT / OUTPUT_POLL iterations.
    while !paused.exists() {
        assert!(
            Instant::now() < paused_by,
            "setup: the new source's batch never paused after its look; stderr: {}",
            tap.text()
        );
        std::thread::sleep(OUTPUT_POLL);
    }
    NewSourcePaused {
        child,
        tap,
        source,
        output: out.join("n.md"),
        go,
        _dir: dir,
    }
}

/// In directory mode, a source created and then truncated while the batch its creation
/// starts is under way — after the batch looked and found it full, before its compile read
/// it — is held as a source the session compiled before is: the empty read is never
/// published, and once the source is written one rebuild publishes what was written. The
/// look stamps every source its batch names, one no compile has read yet included, so the
/// look that follows the compile finds the source emptied. The debug build's pause after
/// a batch's look (`MDS_TEST_PAUSE_AFTER_LOOK`) makes the window certain; outside a test, an
/// editor that creates a file and saves it again by truncating it while the batch of its
/// creation runs opens it.
#[cfg(debug_assertions)]
#[test]
fn dir_mode_a_source_created_and_truncated_after_its_batch_looked_is_held() {
    let NewSourcePaused {
        mut child,
        tap,
        source,
        output,
        go,
        _dir,
    } = a_new_source_s_batch_stopped_after_its_look("N one\n");
    let hold = Hold::start(&source);
    std::fs::write(&go, "").unwrap();
    let mut log = OutputLog::default();
    log.poll_for(&output, TRUNCATE_HOLD);
    let timing = hold.write_and_close("N two\n");
    log.wait_for(&output, "N two", TIMEOUT);

    let stderr = stderr_through_the_marker(&source, tap, &mut child);
    let what = "directory mode, a source created and truncated after its batch looked";
    assert_no_empty_before_the_deadline(&log, timing.started, what);
    if strict_claims_apply(
        "dir_mode_a_source_created_and_truncated_after_its_batch_looked_is_held",
        &timing,
        what,
    ) {
        assert_eq!(
            log.contents(),
            ["N two\n"],
            "{what}: the output is published once, with the content finally written; \
             stderr:\n{stderr}"
        );
        assert_holding_printed_nothing(&stderr, 1, what);
    }
}

/// In directory mode, a source created and then saved again while the batch its creation
/// starts is under way — after the batch looked, before its compile read it — is published
/// as saved, once: the look stamped the source as it was then, and a change since that
/// leaves bytes in it holds nothing. The look's stamp, older than the read, is the one the
/// batch leaves, so the next look would see the save again were its event lost.
#[cfg(debug_assertions)]
#[test]
fn dir_mode_a_source_created_and_saved_after_its_batch_looked_publishes_the_save() {
    let NewSourcePaused {
        mut child,
        tap,
        source,
        output,
        go,
        _dir,
    } = a_new_source_s_batch_stopped_after_its_look("N one\n");
    write_atomic(&source, "N two, saved after the look\n");
    std::fs::write(&go, "").unwrap();
    let mut log = OutputLog::default();
    log.wait_for(&output, "N two, saved after the look", TIMEOUT);

    let stderr = stderr_through_the_marker(&source, tap, &mut child);
    let what = "directory mode, a source created and saved after its batch looked";
    assert_eq!(
        log.contents(),
        ["N two, saved after the look\n"],
        "{what}: the output is published once, with what was saved; stderr:\n{stderr}"
    );
    assert_holding_printed_nothing(&stderr, 1, what);
}

// ── A failing source truncated after a batch for another looked ─────────────

/// Wait until the watcher's pause has written `paused`. PANICS after [`TIMEOUT`], naming
/// `step`.
#[cfg(debug_assertions)]
#[track_caller]
fn wait_for_the_pause(paused: &Path, tap: &StderrTap, step: &str) {
    let paused_by = Instant::now() + TIMEOUT;
    // Bounded by TIMEOUT: at most TIMEOUT / OUTPUT_POLL iterations.
    while !paused.exists() {
        assert!(
            Instant::now() < paused_by,
            "setup: {step}: the batch never paused after its look; stderr: {}",
            tap.text()
        );
        std::thread::sleep(OUTPUT_POLL);
    }
}

/// In directory mode, a source whose every compile has failed is compiled again by each
/// batch that carries a change, though the batch does not name it. Truncated after such a
/// batch looked and before its compile read it, it is held as a source the session compiled
/// is: the empty read is never published, and once the source is written one rebuild
/// publishes what was written. The batch's look stamps the sources it will compile again
/// for a failure, so the look that follows the compile finds the source emptied.
///
/// The debug build's pause after a batch's look (`MDS_TEST_PAUSE_AFTER_LOOK`) makes the
/// window certain. It stops every batch until the file that ends it exists, so the test
/// moves that file aside to stop a later batch: the failing source's own batch is let go,
/// a second failing source's diagnostic proves every event of the first was handled, and
/// only then is the pause set again, for the batch of another source's creation. Outside a
/// test, an editor saving a fix to a broken file by truncating it, while a batch for another
/// file runs, opens the window.
#[cfg(debug_assertions)]
#[test]
fn dir_mode_a_failing_source_truncated_after_a_batch_for_another_looked_is_held() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("src");
    std::fs::create_dir(&root).unwrap();
    let out = dir.path().join("out");
    std::fs::create_dir(&out).unwrap();
    // Outside the watched directory, so the pause's files raise no event.
    let (go, paused) = (dir.path().join("go"), dir.path().join("go.paused"));
    let (mut child, tap) = spawn_ready(
        mds_bin()
            .arg("watch")
            .arg(&root)
            .arg("--out-dir")
            .arg(&out)
            .args(["--debounce", "0", "--poll-interval", "0"])
            .env("MDS_TEST_PAUSE_AFTER_LOOK", &go)
            .stdout(Stdio::null()),
    );
    let (failing, flush, other) = (root.join("e.mds"), root.join("f.mds"), root.join("a.mds"));
    let output = out.join("e.md");

    // e.mds is created failing: its batch stops after its look, and is let go.
    write_atomic(&failing, "E {{e_undefined}}\n");
    wait_for_the_pause(&paused, &tap, "the failing source's batch");
    std::fs::write(&go, "").unwrap();
    wait_for_tap(&tap, "undefined variable 'e_undefined'", TIMEOUT);
    // f.mds is created failing too, after every event of e.mds: once its diagnostic is
    // printed, no batch is left that names e.mds.
    write_atomic(&flush, "F {{f_undefined}}\n");
    wait_for_tap(&tap, "undefined variable 'f_undefined'", TIMEOUT);

    // The pause is set again: the batch a.mds's creation starts stops after its look.
    std::fs::rename(&go, dir.path().join("go.spent")).unwrap();
    std::fs::rename(&paused, dir.path().join("go.paused.spent")).unwrap();
    write_atomic(&other, "A one\n");
    wait_for_the_pause(&paused, &tap, "the batch of a.mds");
    let hold = Hold::start(&failing);
    std::fs::write(&go, "").unwrap();
    let mut log = OutputLog::default();
    log.poll_for(&output, TRUNCATE_HOLD);
    let timing = hold.write_and_close("E fixed\n");
    log.wait_for(&output, "E fixed", TIMEOUT);

    let stderr = stderr_through_the_marker(&failing, tap, &mut child);
    let what = "directory mode, a failing source truncated after a batch for another looked";
    assert_no_empty_before_the_deadline(&log, timing.started, what);
    if strict_claims_apply(
        "dir_mode_a_failing_source_truncated_after_a_batch_for_another_looked_is_held",
        &timing,
        what,
    ) {
        assert_eq!(
            log.contents(),
            ["E fixed\n"],
            "{what}: the output is published once, with the content finally written; \
             stderr:\n{stderr}"
        );
        let rebuilds = before_the_marker(&stderr)
            .lines()
            .filter(|line| line.starts_with("Recompiled ") && line.contains("e.md"))
            .count();
        assert_eq!(
            rebuilds, 1,
            "{what}: exactly one rebuild of e.md; stderr:\n{stderr}"
        );
    }
}

// ── A dependency outside the root, read empty by a compile that is held ─────

/// In directory mode, a dependency outside the watched directory that a source imports for
/// the first time, and that is truncated after the batch looked and before its compile read
/// it, holds the batch whose compile read it empty — and the batch its own truncation event
/// starts. That second batch names the dependency, which is no source and no dependency the
/// session tracks: the held compile recorded none. Until the hold ends, the file the held
/// compile read empty stays among the files the look stamps, so the second batch finds it
/// emptied and is held too, and the empty output is never published before the deadline.
///
/// The debug build's pause after a batch's look (`MDS_TEST_PAUSE_AFTER_LOOK`) makes the
/// window certain. It stops every batch until the file that ends it exists, so the test
/// moves that file aside to stop a later batch: the page is saved importing a missing
/// `_y.mds` and its batch is let go, the pause is set again, and `_y.mds` is created, which
/// starts the batch that stops after its look, with `_y.mds` full. Outside a test, an editor
/// that creates a file beside the root and saves it again by truncating it, while the batch
/// of its creation runs, opens the window.
#[cfg(debug_assertions)]
#[test]
fn dir_mode_a_dependency_a_held_compile_read_empty_holds_the_batch_its_truncation_starts() {
    let base = tempfile::tempdir().unwrap();
    let (root, shared) = (base.path().join("root"), base.path().join("shared"));
    std::fs::create_dir(&root).unwrap();
    std::fs::create_dir(&shared).unwrap();
    // The project's root marker, so the page may import from beside the root.
    std::fs::write(base.path().join(".git"), "").unwrap();
    std::fs::write(
        shared.join("_x.mds"),
        "@define greet():\nX one\n@end\n\n@export greet\n",
    )
    .unwrap();
    let page = root.join("page.mds");
    std::fs::write(&page, "@import \"../shared/_x.mds\" as x\n{{x.greet()}}\n").unwrap();
    let out = base.path().join("out");
    let output = out.join("page.md");
    // Outside every watched directory, so the pause's files raise no event.
    let (go, paused) = (base.path().join("go"), base.path().join("go.paused"));

    let (mut child, tap) = spawn_ready(
        mds_bin()
            .arg("watch")
            .arg(&root)
            .arg("--out-dir")
            .arg(&out)
            .args(["--debounce", "50", "--poll-interval", "0"])
            .env("MDS_TEST_PAUSE_AFTER_LOOK", &go)
            .stdout(Stdio::null()),
    );
    let mut log = OutputLog::default();
    log.wait_for(&output, "X one", TIMEOUT);

    // The page is saved importing a file that is not there: its batch stops after its look,
    // is let go, and the compile fails, which leaves the page errored.
    let missing = shared.join("_y.mds");
    write_atomic(&page, "@import \"../shared/_y.mds\" as y\n@include y\n");
    wait_for_the_pause(&paused, &tap, "the batch of the page's save");
    std::fs::write(&go, "").unwrap();
    wait_for_tap(&tap, "_y.mds", TIMEOUT);

    // The pause is set again: the batch the creation of `_y.mds` starts stops after its look,
    // with the file full, and the page is compiled again for its failure.
    std::fs::rename(&go, base.path().join("go.spent")).unwrap();
    std::fs::rename(&paused, base.path().join("go.paused.spent")).unwrap();
    write_atomic(&missing, "Y one\n");
    wait_for_the_pause(&paused, &tap, "the batch of the creation of _y.mds");
    let hold = Hold::start(&missing);
    std::fs::write(&go, "").unwrap();
    log.poll_for(&output, TRUNCATE_HOLD);
    let timing = hold.write_and_close("Y two\n");
    // The positive control: once `_y.mds` is written, the output is published with its
    // content, by the one rebuild that ends the hold.
    log.wait_for(&output, "Y two", TIMEOUT);

    let stderr = stderr_through_the_marker(&page, tap, &mut child);
    let what = "directory mode, a dependency beside the root truncated after its batch looked";
    assert_no_empty_before_the_deadline(&log, timing.started, what);
    if strict_claims_apply(
        "dir_mode_a_dependency_a_held_compile_read_empty_holds_the_batch_its_truncation_starts",
        &timing,
        what,
    ) {
        assert_eq!(
            log.contents(),
            ["X one\n", "Y two\n"],
            "{what}: the output goes from the first import to the content finally written, \
             never empty; stderr:\n{stderr}"
        );
        let before = before_the_marker(&stderr);
        assert_eq!(
            count_occurrences(before, EMPTY_OUTPUT_NOTICE),
            0,
            "{what}: no empty output is announced; stderr:\n{stderr}"
        );
        let rebuilds = before
            .lines()
            .filter(|line| line.starts_with("Recompiled ") && line.contains("page.md"))
            .count();
        assert_eq!(
            rebuilds, 1,
            "{what}: exactly one rebuild of page.md, for the content finally written; \
             stderr:\n{stderr}"
        );
    }
}

/// The failing twin of the test above: the page calls a function of the dependency, so the
/// compile that reads the dependency empty fails. That compile is held, and the file it read
/// empty stays among the files the look stamps until the hold ends, as for a compile that
/// would write: the batch the truncation's own event starts finds it emptied and is held
/// too, so the failure on the empty file is never reported (#380).
#[cfg(debug_assertions)]
#[test]
fn dir_mode_a_dependency_a_failed_held_compile_read_empty_holds_the_batch_its_truncation_starts() {
    let base = tempfile::tempdir().unwrap();
    let (root, shared) = (base.path().join("root"), base.path().join("shared"));
    std::fs::create_dir(&root).unwrap();
    std::fs::create_dir(&shared).unwrap();
    // The project's root marker, so the page may import from beside the root.
    std::fs::write(base.path().join(".git"), "").unwrap();
    std::fs::write(
        shared.join("_x.mds"),
        "@define greet():\nX one\n@end\n\n@export greet\n",
    )
    .unwrap();
    let page = root.join("page.mds");
    std::fs::write(&page, "@import \"../shared/_x.mds\" as x\n{{x.greet()}}\n").unwrap();
    let out = base.path().join("out");
    let output = out.join("page.md");
    // Outside every watched directory, so the pause's files raise no event.
    let (go, paused) = (base.path().join("go"), base.path().join("go.paused"));

    let (mut child, tap) = spawn_ready(
        mds_bin()
            .arg("watch")
            .arg(&root)
            .arg("--out-dir")
            .arg(&out)
            .args(["--debounce", "50", "--poll-interval", "0"])
            .env("MDS_TEST_PAUSE_AFTER_LOOK", &go)
            .stdout(Stdio::null()),
    );
    let mut log = OutputLog::default();
    log.wait_for(&output, "X one", TIMEOUT);

    // The page is saved calling a function of a file that is not there: its batch stops
    // after its look, is let go, and the compile fails, which leaves the page errored.
    let missing = shared.join("_y.mds");
    write_atomic(&page, "@import \"../shared/_y.mds\" as y\n{{y.greet()}}\n");
    wait_for_the_pause(&paused, &tap, "the batch of the page's save");
    std::fs::write(&go, "").unwrap();
    wait_for_tap(&tap, "_y.mds", TIMEOUT);

    // The pause is set again: the batch the creation of `_y.mds` starts stops after its look,
    // with the file full, and the page is compiled again for its failure.
    std::fs::rename(&go, base.path().join("go.spent")).unwrap();
    std::fs::rename(&paused, base.path().join("go.paused.spent")).unwrap();
    write_atomic(&missing, "@define greet():\nY one\n@end\n\n@export greet\n");
    wait_for_the_pause(&paused, &tap, "the batch of the creation of _y.mds");
    let hold = Hold::start(&missing);
    std::fs::write(&go, "").unwrap();
    log.poll_for(&output, TRUNCATE_HOLD);
    let timing = hold.write_and_close("@define greet():\nY two\n@end\n\n@export greet\n");
    // The positive control: once `_y.mds` is written, the output is published with its
    // content, by the one rebuild that ends the hold.
    log.wait_for(&output, "Y two", TIMEOUT);

    let stderr = stderr_through_the_marker(&page, tap, &mut child);
    let what = "directory mode, a dependency beside the root truncated after its batch looked, \
                read empty by a compile that fails on it";
    assert_no_empty_before_the_deadline(&log, timing.started, what);
    if strict_claims_apply(
        "dir_mode_a_dependency_a_failed_held_compile_read_empty_holds_the_batch_its_truncation_starts",
        &timing,
        what,
    ) {
        assert_eq!(
            log.contents(),
            ["X one\n", "Y two\n"],
            "{what}: the output goes from the first import to the content finally written; \
             stderr:\n{stderr}"
        );
        let before = before_the_marker(&stderr);
        assert_eq!(
            (
                count_occurrences(before, "mds::"),
                count_occurrences(before, "mds::file_not_found"),
            ),
            (1, 1),
            "{what}: only the missing file of the first save is reported, never the failure \
             on the empty file; stderr:\n{stderr}"
        );
    }
}

// ── The deadline ────────────────────────────────────────────────────────────

/// Truncate the entry and close it without writing: the empty output IS published —
/// within the deadline plus the delivery bound — with one notice, which `--quiet`
/// suppresses.
fn truncate_and_close(extra: &[&str], quiet: bool, what: &str) {
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("t.mds");
    std::fs::write(&src, "version 1\n").unwrap();
    let out = dir.path().join("t.md");

    let mut cmd = mds_bin();
    cmd.arg("watch")
        .arg(&src)
        .args(["--debounce", "0"])
        .args(extra);
    if quiet {
        cmd.arg("--quiet");
    }
    let (mut child, tap) = spawn_ready(cmd.stdout(Stdio::null()));
    let mut log = OutputLog::default();
    log.wait_for(&out, "version 1", TIMEOUT);

    let started = Instant::now();
    drop(File::create(&src).expect("truncate the entry"));
    // Bounded: the deadline plus one inotify delivery.
    let bound = EMPTY_HOLD_DEADLINE + TIMEOUT;
    let until = started + bound;
    // Bounded by `bound`: at most bound / OUTPUT_POLL iterations.
    while log.first_empty.is_none() && Instant::now() < until {
        log.record(&out);
        std::thread::sleep(OUTPUT_POLL);
    }
    let empty_at = log.first_empty.unwrap_or_else(|| {
        panic!(
            "{what}: an emptied entry must be published within {bound:?}; states read: {:?}",
            log.contents()
        )
    });

    let stderr = stderr_through_the_marker(&src, tap, &mut child);
    let notices = if quiet { 0 } else { 1 };
    assert_eq!(
        count_occurrences(&stderr, EMPTY_OUTPUT_NOTICE),
        notices,
        "{what}: publishing the empty output prints {notices} notice(s) (published \
         {:?} after the truncation); stderr:\n{stderr}",
        empty_at.duration_since(started)
    );
}

#[test]
fn truncate_and_close_publishes_the_empty_output_within_the_deadline_with_one_notice() {
    truncate_and_close(&[], false, "default");
}

/// No idle tick, and no event arrives after the close: only a timer the deadline owns
/// can wake the watcher to publish.
#[test]
fn truncate_and_close_with_poll_interval_0_publishes_the_empty_output_on_its_own_deadline() {
    truncate_and_close(&["--poll-interval", "0"], false, "--poll-interval 0");
}

#[test]
fn truncate_and_close_under_quiet_publishes_the_empty_output_without_a_notice() {
    truncate_and_close(&[], true, "--quiet");
}

/// Truncate the already-empty entry every [`REPEAT_EVERY`], [`REPEAT_ROUNDS`] times: the
/// deadline runs from the FIRST empty observation and no later event extends it, so the
/// empty output is published while the stream is still running. Only a publish after the
/// stream ended — or none at all — fails; when inside the stream it happens is not
/// asserted.
fn repeated_truncation(poll_interval: &str) {
    let what = format!("--poll-interval {poll_interval}");
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("t.mds");
    std::fs::write(&src, "version 1\n").unwrap();
    let out = dir.path().join("t.md");

    let (mut child, tap) = spawn_ready(
        mds_bin()
            .arg("watch")
            .arg(&src)
            .args(["--debounce", "0", "--poll-interval", poll_interval])
            .stdout(Stdio::null()),
    );
    let mut log = OutputLog::default();
    log.wait_for(&out, "version 1", TIMEOUT);

    let stream_started = Instant::now();
    for _ in 0..REPEAT_ROUNDS {
        drop(File::create(&src).expect("truncate the entry"));
        log.poll_for(&out, REPEAT_EVERY);
    }
    let stream_ended = Instant::now();

    if log.first_empty.is_none() {
        // Classify the failure: late, or never.
        log.poll_for(&out, EMPTY_HOLD_DEADLINE + TIMEOUT);
    }
    let stderr = stderr_through_the_marker(&src, tap, &mut child);
    match log.first_empty {
        Some(at) => assert!(
            at < stream_ended,
            "{what}: the empty output was published {:?} AFTER the stream of truncations \
             ended — later events extended the deadline; stderr:\n{stderr}",
            at.duration_since(stream_ended)
        ),
        None => panic!(
            "{what}: the empty output was never published, during the {:?} stream or after \
             it; states read: {:?}; stderr:\n{stderr}",
            stream_ended.duration_since(stream_started),
            log.contents()
        ),
    }
}

#[test]
fn repeated_truncation_publishes_the_empty_output_before_the_stream_ends_poll_0() {
    repeated_truncation("0");
}

#[test]
fn repeated_truncation_publishes_the_empty_output_before_the_stream_ends_poll_1000() {
    repeated_truncation("1000");
}

// ── Empty from the start ────────────────────────────────────────────────────

/// A source that is already empty at startup is not a truncation in progress: the
/// startup compile publishes its empty output at once — before readiness — and no
/// notice is printed, since no non-empty output was replaced. Both watch modes.
#[test]
fn a_source_empty_at_startup_compiles_to_empty_immediately() {
    // File mode.
    let dir = tempfile::tempdir().unwrap();
    let src = dir.path().join("t.mds");
    File::create(&src).unwrap();
    let out = dir.path().join("t.md");
    let (mut child, tap) = spawn_ready(
        mds_bin()
            .arg("watch")
            .arg(&src)
            .args(["--debounce", "0"])
            .stdout(Stdio::null()),
    );
    assert_eq!(
        std::fs::read_to_string(&out).ok().as_deref(),
        Some(""),
        "file mode: the empty output exists as soon as the watcher is ready"
    );
    let stderr = stderr_through_the_marker(&src, tap, &mut child);
    assert_eq!(
        count_occurrences(&stderr, EMPTY_OUTPUT_NOTICE),
        0,
        "file mode: no notice for a source that was empty from the start; stderr:\n{stderr}"
    );

    // Directory mode.
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("src");
    std::fs::create_dir(&root).unwrap();
    let src = root.join("e.mds");
    File::create(&src).unwrap();
    let out = dir.path().join("out");
    let (mut child, tap) = spawn_ready(
        mds_bin()
            .arg("watch")
            .arg(&root)
            .arg("--out-dir")
            .arg(&out)
            .args(["--debounce", "0"])
            .stdout(Stdio::null()),
    );
    assert_eq!(
        std::fs::read_to_string(out.join("e.md")).ok().as_deref(),
        Some(""),
        "directory mode: the empty output exists as soon as the watcher is ready"
    );
    let stderr = stderr_through_the_marker(&src, tap, &mut child);
    assert_eq!(
        count_occurrences(&stderr, EMPTY_OUTPUT_NOTICE),
        0,
        "directory mode: no notice for a source that was empty from the start; \
         stderr:\n{stderr}"
    );
}