brrrty-node 0.1.20

Runs an Eleventy site's JavaScript data files in the site's own Node, for Brrrty, an Eleventy-compatible static site generator.
Documentation
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
//! The replay check: whether any call a build made to a function in the
//! JavaScript data gave a result that depended on the calls made before it.
//!
//! 11ty makes the calls one page after another, in an order of its own;
//! Brrrty makes them as its render threads reach them. When a function
//! keeps state between calls (a registry, a counter, a "seen" set), the two
//! orders give different pages, and Brrrty's order isn't even the same from
//! one build to the next. So every request made since the data files
//! loaded is run again in two more workers: the renders (each a unit whose
//! own calls keep their order) in the reverse of the order they first
//! called in, and in the order of their names (page and kind), which is the
//! same every build. Every reply must be the same as the first time. A
//! cache that only remembers what it would compute anyway gives the same
//! replies in any order and passes; a function whose results follow the
//! order of calls gives a different reply in one of the orders: whichever
//! order puts a write before a read the first run didn't, or the reverse.
//!
//! The data files load again first, in their own order, handed the clock
//! and random values they read the first time, so state they set up from
//! the time is the same.
//!
//! The two workers start as soon as the first run has something for them
//! to check, and load the data while it goes on. They are sent each value
//! the first run defines as it defines it (see [`crate::wire`]), so when
//! the first run ends they hold what it held, and a request is replayed by
//! sending its text again: it refers to the same values by the same ids.
//! Requests go ahead of their replies, so a replay takes the time the
//! site's own code takes, not a round trip per call.

use std::collections::{HashMap, HashSet, VecDeque};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use brrrty_js::runtime::RuntimeFailure;
use serde_json::{Value as Json, json};

use crate::client::{Frame, LoadKind, LoadRecord, Record, RunMode, Worker, parse_reply};
use crate::find::NodeInfo;
use crate::wire::DynamicDef;

/// How the first run loaded the data.
pub(crate) struct Loads {
    pub node: NodeInfo,
    pub root: PathBuf,
    pub run_mode: RunMode,
    pub loads: Vec<LoadRecord>,
    /// How many of `loads` loaded global data.
    pub global_end: usize,
    pub load_handles: u64,
    /// Why the build's own worker walks, when Brrrty asked it to: the
    /// replays' workers do the same.
    pub walk: Option<String>,
    /// How long the first run's loads took, all of them.
    pub took: Duration,
}

/// The requests the first run made once the data had loaded.
pub(crate) struct Calls {
    pub records: Vec<Record>,
    pub load_handles: u64,
    /// The longest any request took the first time.
    pub slowest: Duration,
    /// Definitions holding functions calls made, by root.
    pub dynamic: HashMap<u32, DynamicDef>,
    /// Every definition, in order, and whether it is dynamic.
    pub lines: Vec<(Arc<str>, bool)>,
    /// A call changed a value the worker kept.
    pub dropped: bool,
}

pub(crate) enum Failure {
    /// A reply differed: why, for the build's problem, and the first run's
    /// handle of the function called, when it was a call, to name it.
    Differs(String, Option<u64>),
    /// A replay's Node couldn't run.
    Runtime(RuntimeFailure),
    /// A replay's worker asks for the build to be run again, walking (see
    /// the worker's "Freezing"): why.
    Again(String),
}

/// The reply, unless the worker asks for the build again.
fn heard(frame: Frame) -> Result<Frame, Failure> {
    match frame.head.get("again") {
        Some(why) => Err(Failure::Again(why.as_str().unwrap_or("").to_string())),
        None => Ok(frame),
    }
}

enum Msg {
    /// A value the first run defined.
    Line(Arc<str>),
    /// The first run is over: replay its calls.
    Run(Arc<Calls>),
}

/// One of the replay check's workers, on a thread of its own.
pub(crate) struct Handle {
    tx: Sender<Msg>,
    result: Receiver<Result<(), Failure>>,
    /// Its Node's process id while it runs, so a build that ends without
    /// the check stops it at once.
    live: Arc<Mutex<Option<u32>>>,
    cancelled: Arc<AtomicBool>,
}

impl Drop for Handle {
    fn drop(&mut self) {
        self.cancelled.store(true, Ordering::SeqCst);
        let live = self.live.lock().unwrap_or_else(|e| e.into_inner());
        if let Some(pid) = *live {
            crate::client::stop_pid(pid);
        }
    }
}

impl Handle {
    /// Start a worker that loads the data again with the template and
    /// directory data modules in the reverse of the build's order
    /// (`reverse`) or rotated by one, then waits for the calls.
    pub fn start(loads: Arc<Loads>, reverse: bool) -> Handle {
        let (tx, rx) = mpsc::channel();
        let (done, result) = mpsc::channel();
        let live = Arc::new(Mutex::new(None));
        let cancelled = Arc::new(AtomicBool::new(false));
        // Requests are parsed again here, and data may nest deep: a roomy
        // stack, as for replies.
        let spawned = std::thread::Builder::new()
            .name("brrrty-node-replay".into())
            .stack_size(crate::client::REPLY_STACK)
            .spawn({
                let done = done.clone();
                let (live, cancelled) = (live.clone(), cancelled.clone());
                move || {
                    let _ = done.send(work(&loads, reverse, rx, &live, &cancelled));
                }
            });
        if let Err(e) = spawned {
            let _ = done.send(Err(runtime(format!(
                "the replay check couldn't start: {e}"
            ))));
        }
        Handle {
            tx,
            result,
            live,
            cancelled,
        }
    }

    pub fn line(&self, line: Arc<str>) {
        let _ = self.tx.send(Msg::Line(line));
    }

    pub fn run(&self, calls: Arc<Calls>) {
        let _ = self.tx.send(Msg::Run(calls));
    }

    pub fn finish(self) -> Result<(), Failure> {
        self.result.recv().unwrap_or_else(|_| {
            Err(Failure::Runtime(RuntimeFailure {
                message: "the replay check stopped".into(),
                stderr_tail: Vec::new(),
                stopped: false,
                again: false,
            }))
        })
    }
}

fn runtime(why: impl Into<String>) -> Failure {
    Failure::Runtime(RuntimeFailure {
        message: why.into(),
        stderr_tail: Vec::new(),
        stopped: false,
        again: false,
    })
}

/// A request of the replay check, and what a failure of it means.
fn send(w: &mut Worker, text: &str, feed: Option<&str>) -> Result<Frame, Failure> {
    w.exchange(text, feed, "a request of the replay check")
        .map_err(failed)
        .and_then(heard)
}

fn failed(f: RuntimeFailure) -> Failure {
    if f.message.contains("longer than the first run allows") {
        Failure::Differs(
            format!(
                "the replay check ran the JavaScript data again, and {}: the data or a function behaves differently when it runs again, so Brrrty can't check the pages' calls",
                f.message
            ),
            None,
        )
    } else {
        Failure::Runtime(f)
    }
}

/// A request may take a while again, but not without end: the first run
/// finished.
fn deadline(slowest: Duration) -> Duration {
    (slowest * 4).max(floor())
}

/// The least a replay's request is allowed: 10 s, or `BRRRTY_JS_REPLAY_FLOOR_MS`
/// (for the tests, which can't wait that long to see a slow load pass).
fn floor() -> Duration {
    static FLOOR: std::sync::LazyLock<Duration> = std::sync::LazyLock::new(|| {
        std::env::var("BRRRTY_JS_REPLAY_FLOOR_MS")
            .ok()
            .and_then(|v| v.parse().ok())
            .map(Duration::from_millis)
            .unwrap_or(Duration::from_secs(10))
    });
    *FLOOR
}

fn work(
    loads: &Loads,
    reverse: bool,
    rx: Receiver<Msg>,
    live: &Mutex<Option<u32>>,
    cancelled: &AtomicBool,
) -> Result<(), Failure> {
    if cancelled.load(Ordering::SeqCst) {
        return Ok(());
    }
    let mut w = Worker::start_as(&loads.node, &loads.root, loads.run_mode, Some(loads))
        .map_err(|e| runtime(format!("the replay check couldn't start Node: {e}")))?;
    *live.lock().unwrap_or_else(|e| e.into_inner()) = Some(w.pid());
    let out = work_with(&mut w, loads, reverse, rx, cancelled);
    // Its process id is no longer this worker's once it is dropped.
    *live.lock().unwrap_or_else(|e| e.into_inner()) = None;
    // Nothing of it is needed any more: no waiting for Node to wind down.
    w.stop();
    out
}

fn work_with(
    w: &mut Worker,
    loads: &Loads,
    reverse: bool,
    rx: Receiver<Msg>,
    cancelled: &AtomicBool,
) -> Result<(), Failure> {
    if cancelled.load(Ordering::SeqCst) {
        return Ok(());
    }
    // Replies are compared as text.
    w.decode.store(false, std::sync::atomic::Ordering::Relaxed);
    // A replay's loads run in another order, several modules in one
    // request, so each request is allowed what all of the first run's
    // loads took together, four times over.
    w.deadline = Some(deadline(loads.took));
    // The template and template/directory data modules run in the
    // reverse of the build's order in one worker, and rotated by one
    // (the first last) in the other: a rotation moves every module's
    // place, which the reverse leaves alone for the middle one.
    let mut early = loads_reordered(w, loads, reverse, cancelled).and_then(|()| {
        let begun = send(w, r#"{"op":"callsBegin"}"#, None)?;
        if begun.head.get("handles").and_then(Json::as_u64) != Some(loads.load_handles) {
            return Err(Failure::Differs(
                "the JavaScript data gave different functions when it loaded again, so Brrrty can't check that the functions' results don't depend on the order pages call them".into(),
                None,
            ));
        }
        Ok(())
    });
    loop {
        match rx.recv() {
            Ok(Msg::Line(line)) => {
                if early.is_ok()
                    && let Err(f) = w.write_line(&line)
                {
                    early = Err(Failure::Runtime(f));
                }
            }
            Ok(Msg::Run(calls)) => {
                early?;
                return replay(w, &calls, reverse);
            }
            // The build ended without the check.
            Err(_) => return Ok(()),
        }
    }
}

/// Load the data again with the template and directory data files and
/// the templates evaluated in another order (`reverse`, or the first
/// run's rotated by one), as 11ty evaluates each when its file finishes
/// loading, in an order of its own; then their loads in the first run's
/// order, each compared with the first run's reply. Each load gets the
/// clock and random values it read the first time.
///
/// Between the two orders every module's place changes (the rotation
/// moves each one), so a page that shows its own module's place (a
/// shared counter it read at load) differs in one of them. A
/// dependence that comes out the same in the build's order, its reverse
/// and its rotation is not seen.
fn loads_reordered(
    w: &mut Worker,
    log: &Loads,
    reverse: bool,
    cancelled: &AtomicBool,
) -> Result<(), Failure> {
    let feed = |r: &LoadRecord| r.clock.as_deref().unwrap_or("[]").to_string();
    // The build ended without the check (it failed, or was sent back):
    // nothing more is loaded for it.
    let send = |w: &mut Worker, text: &str, feed: Option<&str>| {
        if cancelled.load(Ordering::SeqCst) {
            return Err(runtime("the replay check was stopped".to_string()));
        }
        send(w, text, feed)
    };
    // A replay worker, handed no clock of its own: each load brings its own.
    send(w, r#"{"op":"feedClock","values":[]}"#, None)?;
    let split = log.global_end.min(log.loads.len());
    for r in &log.loads[..split] {
        send(w, &r.text, Some(&feed(r)))?;
    }
    let tail = &log.loads[split..];
    let mut items: Vec<(usize, Json)> = Vec::new();
    let mut seen: HashSet<&str> = HashSet::new();
    for (i, r) in tail.iter().enumerate() {
        let kind = match r.kind {
            LoadKind::Template => "template",
            // A data file's module runs once, on its first load.
            LoadKind::Data if seen.insert(r.path.as_str()) => "data",
            _ => continue,
        };
        let clock: Json = parse_reply(feed(r).as_bytes()).unwrap_or(json!([]));
        items.push((i, json!({"kind": kind, "path": r.path, "feed": clock})));
    }
    if reverse {
        items.reverse();
    } else if !items.is_empty() {
        items.rotate_left(1);
    }
    let got = send(
        w,
        &json!({"op": "preload", "items": items.iter().map(|(_, j)| j.clone()).collect::<Vec<_>>()})
            .to_string(),
        None,
    )?;
    let consumed: Vec<usize> = got
        .head
        .get("consumed")
        .and_then(Json::as_array)
        .map(|a| a.iter().map(|n| n.as_u64().unwrap_or(0) as usize).collect())
        .unwrap_or_default();
    let mut used: HashMap<usize, usize> = HashMap::new();
    for ((i, _), n) in items.iter().zip(consumed) {
        used.insert(*i, n);
    }
    for (i, r) in tail.iter().enumerate() {
        // What its module code read ran already.
        let skip = used.get(&i).copied().unwrap_or(0);
        let rest = if skip == 0 {
            feed(r)
        } else {
            let all: Json = parse_reply(feed(r).as_bytes()).unwrap_or(json!([]));
            Json::Array(
                all.as_array()
                    .map(|a| a.iter().skip(skip).cloned().collect())
                    .unwrap_or_default(),
            )
            .to_string()
        };
        let got = send(w, &r.text, Some(&rest))?;
        if got.body != r.body {
            let shown = Path::new(&r.path)
                .strip_prefix(&log.root)
                .map(|p| p.display().to_string())
                .unwrap_or_else(|_| {
                    if r.path.is_empty() {
                        "a file".to_string()
                    } else {
                        r.path.clone()
                    }
                });
            return Err(Failure::Differs(
                format!(
                    "{shown} gives different data when the templates and template and directory data files load in another order: 11ty runs each one's module code as its file finishes loading, in an order of its own, so module state they share (a counter, a registry) follows that order, which Brrrty can't know"
                ),
                None,
            ));
        }
    }
    Ok(())
}

/// One render's requests, in order.
struct Unit {
    label: Arc<str>,
    records: Vec<usize>,
    /// Handles of functions made by calls that its requests use before its
    /// own replies made them: another unit must have made them.
    needs: HashSet<u64>,
}

/// Every function handle in `j`: `{"$f": n}` forms, and with `fields`, a
/// request's `handle`.
fn handles_in(j: &Json, out: &mut Vec<u64>, fields: bool) {
    match j {
        Json::Array(a) => a.iter().for_each(|x| handles_in(x, out, false)),
        Json::Object(o) => {
            if let Some(("$f", Json::Number(n))) = tagged(j) {
                out.extend(n.as_u64());
                return;
            }
            for (k, v) in o {
                if fields && k == "handle" {
                    out.extend(v.as_u64());
                } else {
                    handles_in(v, out, false);
                }
            }
        }
        _ => {}
    }
}

/// A wire form with one key: `{"$f": 3}` gives `("$f", 3)`.
fn tagged(j: &Json) -> Option<(&str, &Json)> {
    let o = j.as_object()?;
    if o.len() != 1 {
        return None;
    }
    o.iter().next().map(|(k, v)| (k.as_str(), v))
}

fn parse(text: &str) -> Json {
    parse_reply(text.as_bytes()).unwrap_or(Json::Null)
}

impl Calls {
    /// Whether no request or reply names a function a call made, and no
    /// call changed a kept value: every request can be sent again as it
    /// is, ahead of the replies.
    fn plain(&self) -> bool {
        !self.dropped
            && self.dynamic.is_empty()
            && self
                .records
                .iter()
                .all(|r| !r.made && !r.names_made && r.dynamic.is_empty())
    }

    /// The functions calls made that request `i` names: in itself, and in
    /// the dynamic definitions it needs.
    fn uses(&self, i: usize) -> Vec<u64> {
        let r = &self.records[i];
        let mut used = Vec::new();
        if r.names_made {
            handles_in(&parse(&r.text), &mut used, true);
        }
        for root in &r.dynamic {
            if let Some(d) = self.dynamic.get(root) {
                handles_in(&parse(&d.line), &mut used, false);
            }
        }
        used.retain(|h| *h >= self.load_handles);
        used
    }

    fn units(&self, with_needs: bool) -> Vec<Unit> {
        let mut index: HashMap<u64, usize> = HashMap::new();
        let mut units: Vec<Unit> = Vec::new();
        for (i, r) in self.records.iter().enumerate() {
            let u = *index.entry(r.unit).or_insert_with(|| {
                units.push(Unit {
                    label: r.label.clone(),
                    records: Vec::new(),
                    needs: HashSet::new(),
                });
                units.len() - 1
            });
            units[u].records.push(i);
        }
        if !with_needs {
            return units;
        }
        for unit in &mut units {
            let mut made: HashSet<u64> = HashSet::new();
            for &i in &unit.records {
                for h in self.uses(i) {
                    if !made.contains(&h) {
                        unit.needs.insert(h);
                    }
                }
                let r = &self.records[i];
                if r.made {
                    let mut out = Vec::new();
                    handles_in(&parse(&r.body), &mut out, false);
                    made.extend(out.into_iter().filter(|h| *h >= self.load_handles));
                }
            }
        }
        units
    }
}

fn replay(w: &mut Worker, calls: &Calls, interleave: bool) -> Result<(), Failure> {
    w.deadline = Some(deadline(calls.slowest));
    // The clock and random values the first run's calls read, by kind,
    // in the order it read them.
    let mut by_kind = serde_json::Map::new();
    for r in &calls.records {
        let Some(clock) = &r.clock else { continue };
        if let Json::Array(reads) = parse(clock) {
            for read in reads {
                if let Some([Json::String(kind), v]) = read.as_array().map(Vec::as_slice)
                    && let Json::Array(list) = by_kind
                        .entry(kind.clone())
                        .or_insert_with(|| Json::Array(Vec::new()))
                {
                    list.push(v.clone());
                }
            }
        }
    }
    send(
        w,
        &json!({"op": "feedCalls", "values": Json::Object(by_kind)}).to_string(),
        None,
    )?;
    let plain = calls.plain();
    let units = calls.units(!plain);
    let order: Vec<usize> = if interleave {
        (0..units.len()).rev().collect()
    } else {
        let mut named: Vec<usize> = (0..units.len()).collect();
        named.sort_by(|a, b| units[*a].label.cmp(&units[*b].label).then(a.cmp(b)));
        named
    };
    if plain {
        let mut sequence = Vec::with_capacity(calls.records.len());
        if interleave {
            // One request from each render in turn: renders that call
            // functions at the same time, as Brrrty's threads may, and as
            // 11ty never does.
            let mut active: Vec<(usize, usize)> = order.iter().map(|&u| (u, 0)).collect();
            while !active.is_empty() {
                for slot in active.iter_mut() {
                    sequence.push(units[slot.0].records[slot.1]);
                    slot.1 += 1;
                }
                active.retain(|(u, at)| *at < units[*u].records.len());
            }
        } else {
            for &u in &order {
                sequence.extend(units[u].records.iter().copied());
            }
        }
        return ahead(w, calls, &sequence);
    }
    stepped(w, calls, &units, &order, interleave)
}

/// How many requests may be on their way before their replies are read.
const AHEAD: usize = 512;

/// Send the first run's requests again in the order of `sequence`, ahead
/// of their replies, and compare each reply as it comes.
fn ahead(w: &mut Worker, calls: &Calls, sequence: &[usize]) -> Result<(), Failure> {
    let Some(mut stdin) = w.take_stdin() else {
        return Err(runtime("the replay check's Node stopped reading requests"));
    };
    let (tx, rx) = mpsc::channel::<String>();
    std::thread::scope(|s| {
        // The requests go from a thread of their own: Node may stop
        // reading them while it waits for an answer to a question of its
        // own, and this thread must be free to answer.
        s.spawn(move || {
            for line in rx {
                if stdin
                    .write_all(line.as_bytes())
                    .and_then(|()| stdin.write_all(b"\n"))
                    .is_err()
                {
                    break;
                }
            }
            // Dropping stdin here tells Node it is done.
        });
        let mut ids: VecDeque<u64> = VecDeque::new();
        let mut sent = 0;
        let out = 'all: {
            for (done, &i) in sequence.iter().enumerate() {
                while sent < sequence.len() && sent - done < AHEAD {
                    let r = &calls.records[sequence[sent]];
                    let (id, line) = w.line_for(&r.text, r.clock.as_deref());
                    if !r.one_way {
                        ids.push_back(id);
                    }
                    if tx.send(line).is_err() {
                        break 'all Err(runtime(
                            "the replay check's Node stopped reading requests",
                        ));
                    }
                    sent += 1;
                }
                let r = &calls.records[i];
                if r.one_way {
                    continue;
                }
                // The filters a JavaScript template asked for, answered as
                // the first time.
                w.answers_feed = Some(r.answers.iter().cloned().collect());
                let mut wait = w.wait();
                let got = loop {
                    match w.next_frame("a request of the replay check", &mut wait) {
                        Ok(f) if f.question => {
                            if let Err(why) =
                                w.answer(&f, &mut |_: &str, _: &[brrrty_js::Value]| {
                                    Err("asks for a filter in the replay check".to_string())
                                })
                            {
                                break 'all Err(runtime(why));
                            }
                        }
                        Ok(f) => break f,
                        Err(f) => break 'all Err(failed(f)),
                    }
                };
                if ids.pop_front() != Some(got.id) {
                    break 'all Err(runtime("the replay check got a reply out of order"));
                }
                let got = match heard(got) {
                    Ok(got) => got,
                    Err(e) => break 'all Err(e),
                };
                if got.body != r.body {
                    break 'all Err(Failure::Differs(
                        difference(r, &got.body),
                        r.handle.map(u64::from),
                    ));
                }
            }
            Ok(())
        };
        w.answers_feed = None;
        drop(tx);
        if out.is_err() {
            // The writer may be blocked on a Node that no longer reads.
            w.stop();
        }
        out
    })
}

/// The first run's handles of functions calls made, to the replay's, and
/// what the replay's worker has been sent.
struct State<'c> {
    calls: &'c Calls,
    functions: HashMap<u64, u64>,
    /// The dynamic definitions the worker has.
    defined: HashSet<u32>,
}

/// Replay one request at a time: for a build where requests name functions
/// that calls made (each worker numbers them as it makes them), or where a
/// call changed a kept value (the worker is then sent every value again).
fn stepped(
    w: &mut Worker,
    calls: &Calls,
    units: &[Unit],
    order: &[usize],
    interleave: bool,
) -> Result<(), Failure> {
    let mut st = State {
        calls,
        functions: HashMap::new(),
        defined: HashSet::new(),
    };
    let unready = || {
        Failure::Differs(
            "a function made by one page's call is used by another in a way Brrrty can't check"
                .into(),
            None,
        )
    };
    if interleave {
        let mut active: Vec<(usize, usize)> = order.iter().map(|&u| (u, 0)).collect();
        while !active.is_empty() {
            let mut progressed = false;
            for slot in active.iter_mut() {
                let (u, at) = *slot;
                let i = units[u].records[at];
                if !calls.uses(i).iter().all(|h| st.functions.contains_key(h)) {
                    continue;
                }
                st.step(w, i)?;
                slot.1 += 1;
                progressed = true;
            }
            active.retain(|(u, at)| *at < units[*u].records.len());
            if !progressed && !active.is_empty() {
                return Err(unready());
            }
        }
    } else {
        let mut pending: Vec<usize> = order.to_vec();
        while !pending.is_empty() {
            let Some(pos) = pending
                .iter()
                .position(|&u| units[u].needs.iter().all(|h| st.functions.contains_key(h)))
            else {
                return Err(unready());
            };
            let u = pending.remove(pos);
            for &i in &units[u].records {
                st.step(w, i)?;
            }
        }
    }
    Ok(())
}

impl State<'_> {
    fn function(&self, h: u64) -> u64 {
        if h < self.calls.load_handles {
            h
        } else {
            self.functions.get(&h).copied().unwrap_or(h)
        }
    }

    /// The first run's text with its functions renamed to the replay's.
    fn rewrite(&self, j: &Json, top: bool) -> Json {
        match j {
            Json::Array(a) => Json::Array(a.iter().map(|x| self.rewrite(x, false)).collect()),
            Json::Object(o) => {
                if let Some(("$f", Json::Number(n))) = tagged(j)
                    && let Some(h) = n.as_u64()
                {
                    return json!({"$f": self.function(h)});
                }
                let mut out = serde_json::Map::with_capacity(o.len());
                for (k, v) in o {
                    let v = match (top, k.as_str(), v.as_u64()) {
                        (true, "handle", Some(h)) => json!(self.function(h)),
                        _ => self.rewrite(v, false),
                    };
                    out.insert(k.clone(), v);
                }
                Json::Object(out)
            }
            other => other.clone(),
        }
    }

    /// Send the first run's request `i` again, and compare the reply.
    fn step(&mut self, w: &mut Worker, i: usize) -> Result<(), Failure> {
        let r = &self.calls.records[i];
        for root in &r.dynamic {
            if self.defined.contains(root) {
                continue;
            }
            if let Some(d) = self.calls.dynamic.get(root) {
                let line = self.rewrite(&parse(&d.line), false).to_string();
                w.write_line(&line).map_err(Failure::Runtime)?;
                self.defined.insert(*root);
            }
        }
        let rewritten;
        let text: &str = if r.names_made {
            rewritten = self.rewrite(&parse(&r.text), true).to_string();
            &rewritten
        } else {
            &r.text
        };
        if r.one_way {
            let (_, line) = w.line_for(text, None);
            return w.write_line(&line).map_err(Failure::Runtime);
        }
        w.answers_feed = Some(r.answers.iter().cloned().collect());
        let got = send(w, text, r.clock.as_deref());
        w.answers_feed = None;
        let got = got?;
        // A function made by a call is matched up with the first run's as
        // it first appears.
        let same = if r.unchecked {
            // It ran on what a call sent with it had changed: the first
            // run made nothing of its reply.
            true
        } else if r.made || got.made {
            self.same(&parse(&r.body), &parse(&got.body))
        } else {
            got.body == r.body
        };
        if !same {
            return Err(Failure::Differs(
                difference(r, &got.body),
                r.handle.map(u64::from),
            ));
        }
        if got.head.get("dropShared").is_some() {
            // The worker forgot its values: every one again, made afresh.
            send(w, r#"{"op":"resetDefs"}"#, None)?;
            for (line, dynamic) in &self.calls.lines {
                if !dynamic {
                    w.write_line(line).map_err(Failure::Runtime)?;
                }
            }
            self.defined.clear();
        }
        Ok(())
    }

    /// Whether a replay's reply is the first run's, functions made by calls
    /// matched up as they first appear.
    fn same(&mut self, a: &Json, b: &Json) -> bool {
        match (a, b) {
            (Json::Array(x), Json::Array(y)) => {
                x.len() == y.len() && x.iter().zip(y).all(|(p, q)| self.same(p, q))
            }
            (Json::Object(x), Json::Object(y)) => {
                if let (Some(("$f", Json::Number(m))), Some(("$f", Json::Number(n)))) =
                    (tagged(a), tagged(b))
                {
                    let (Some(m), Some(n)) = (m.as_u64(), n.as_u64()) else {
                        return false;
                    };
                    if m < self.calls.load_handles {
                        return m == n;
                    }
                    return *self.functions.entry(m).or_insert(n) == n;
                }
                x.len() == y.len()
                    && x.iter()
                        .all(|(k, v)| y.get(k).is_some_and(|w| self.same(v, w)))
            }
            (x, y) => x == y,
        }
    }
}

/// The message for a reply that differs on the replay.
fn difference(r: &Record, got: &str) -> String {
    let shown = |body: &str| {
        let j = parse(body);
        let text = match (j.get("refused"), j.get("thrown"), j.get("ok")) {
            (Some(why), _, _) => format!("refused: {}", why.as_str().unwrap_or("")),
            (_, Some(t), _) => format!(
                "threw {}",
                t.get("message").and_then(Json::as_str).unwrap_or("")
            ),
            (_, _, Some(v)) => v.to_string(),
            _ => j.to_string(),
        };
        let mut t: String = text.chars().take(80).collect();
        if text.chars().count() > 80 {
            t.push('…');
        }
        t
    };
    let what = match r.op {
        "call" => "{fn}, which a template calls,",
        "pageCall" | "pageVars" => "{fn}, a computed or permalink function,",
        "render" => "a JavaScript template's render",
        _ => "a function from JavaScript data",
    };
    let place = match where_(&r.label) {
        Some(w) => format!(" ({w})"),
        None => String::new(),
    };
    format!(
        "{what}{place} gives a different result when the pages' calls, or the templates' and data files' module code, run in another order ({} the first time, {} the second): it shows state its module or the data share, which follows the order 11ty loads files and builds pages in, and that differs between 11ty and Brrrty",
        shown(&r.body),
        shown(got)
    )
}

/// A render's name as a message shows it: "in the content of src/a.njk".
fn where_(label: &str) -> Option<String> {
    let (kind, rest) = label.split_once(' ')?;
    let page = |rest: &str| match rest.rsplit_once(' ') {
        Some((file, n)) if n.parse::<usize>().is_ok() => format!("page {n} of {file}"),
        _ => rest.to_string(),
    };
    Some(match kind {
        "1" => format!("computing the data of {}", rest.strip_prefix("load ")?),
        "2" => format!("placing {}", page(rest.strip_prefix("place ")?)),
        "3" => format!(
            "computing the data of {}",
            page(rest.strip_prefix("page ")?)
        ),
        "5" => format!("in the content of {}", rest.strip_prefix("content ")?),
        "6" => format!("in the layouts of {}", rest.strip_prefix("layout ")?),
        _ => return None,
    })
}