plexus-ui-engine 0.2.0

The plexus-ui engine — signals, live() over Plexus streams, the view tree over a renderer, Rhai folds, sections, hot-swap
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
//! UI-6's testing surface: `live()` — the folds and the shared cache.

use super::*;
use crate::transport::{FakeWire, WireItem};
use serde_json::json;

/// The hello page's collection: every ticket's summary, folded from
/// `tickets.watch`. `deleted` carries `ids` (a list) on the wire.
fn spec(params: Value) -> LiveSpec {
    LiveSpec::new(
        "tickets.list",
        params,
        Some("tickets.watch"),
        json!({}),
        "id",
        &[("created", "upsert:ticket"), ("amended", "upsert:ticket"), ("deleted", "remove:ids")],
    )
    .expect("a spec")
}

fn summary(id: &str, title: &str) -> Value {
    json!({ "type": "summary", "summary": { "id": id, "title": title } })
}

fn ids(live: &Live) -> Vec<String> {
    live.rows.iter().map(|r| r["id"].as_str().unwrap_or("?").to_string()).collect()
}

fn setup() -> (FakeWire, ManualClock, Rc<LiveCache<FakeWire, ManualClock>>) {
    let rt = Runtime::new();
    let (wire, clock) = (FakeWire::new(), ManualClock::new());
    let cache = LiveCache::new(&rt, wire.clone(), clock.clone());
    (wire, clock, cache)
}

/// A snapshot of three rows, then `created` (upsert), `amended` (replace in
/// place), `deleted` (remove), then `lagged`: `resyncing`, the snapshot
/// asked again, `live` on its rows. And a dropped socket: `resyncing`, then
/// both calls opened again on the reconnect, `live`.
#[test]
fn live_folds_a_snapshot_and_its_changes() {
    assert_eq!("upsert:ticket".parse::<FoldRule>(), Ok(FoldRule::Upsert("ticket".into())));
    assert_eq!("remove:ids".parse::<FoldRule>(), Ok(FoldRule::Remove("ids".into())));
    assert!("replace:ticket".parse::<FoldRule>().is_err(), "only upsert: and remove:");

    let (wire, _clock, cache) = setup();
    let params = json!({ "summary": true, "limit": 200 });
    let reader = cache.acquire(&spec(params.clone()));
    assert_eq!(wire.opened_of("tickets.list").len(), 1, "the snapshot asked once");
    assert_eq!(wire.opened_of("tickets.list")[0].params, params, "with the declared params");
    assert_eq!(wire.opened_of("tickets.watch").len(), 1, "the changes opened once");
    assert_eq!(reader.live().status, Status::Pending);
    assert!(reader.live().rows.is_empty());

    let snap = wire.last_of("tickets.list");
    wire.answer(snap, [summary("T-1", "a"), summary("T-2", "b"), summary("T-3", "c"), json!({ "type": "page", "next": null, "remaining": 0 })]);
    let live = reader.live();
    assert_eq!(live.status, Status::Live);
    assert_eq!(ids(&live), ["T-1", "T-2", "T-3"], "each summary a row; the page none");
    assert_eq!(live.rows[1]["title"], "b");
    assert_eq!(live.to_value()["status"], "live", "an expression reads status as text");

    let watch = wire.last_of("tickets.watch");
    wire.feed(watch, WireItem::Data(json!({ "type": "created", "ticket": { "id": "T-4", "title": "d" } })));
    assert_eq!(ids(&reader.live()), ["T-1", "T-2", "T-3", "T-4"], "created: upserted");
    wire.feed(watch, WireItem::Data(json!({ "type": "amended", "ticket": { "id": "T-2", "title": "b2" }, "changed": ["title"] })));
    let live = reader.live();
    assert_eq!(ids(&live), ["T-1", "T-2", "T-3", "T-4"], "amended: replaced in place");
    assert_eq!(live.rows[1]["title"], "b2");
    wire.feed(watch, WireItem::Data(json!({ "type": "deleted", "ids": ["T-3"], "tombstones": [] })));
    assert_eq!(ids(&reader.live()), ["T-1", "T-2", "T-4"], "deleted: removed");
    wire.feed(watch, WireItem::Data(json!({ "type": "created", "ticket": { "id": "T-9", "title": "z" } })));
    wire.feed(watch, WireItem::Data(json!({ "type": "deleted", "ids": "T-9", "tombstones": [] })));
    assert_eq!(ids(&reader.live()), ["T-1", "T-2", "T-4"], "deleted with a single id: removed");
    wire.feed(watch, WireItem::Data(json!({ "type": "linked", "id": "T-1", "added": [] })));
    assert_eq!(ids(&reader.live()), ["T-1", "T-2", "T-4"], "an event no rule names: nothing");

    wire.feed(watch, WireItem::Data(json!({ "type": "lagged", "missed": 3 })));
    assert_eq!(reader.live().status, Status::Resyncing, "lagged: resyncing");
    assert_eq!(wire.opened_of("tickets.list").len(), 2, "the snapshot asked again");
    assert_eq!(wire.opened_of("tickets.watch").len(), 1, "the changes stream kept");
    wire.answer(wire.last_of("tickets.list"), [summary("T-1", "a"), summary("T-5", "e")]);
    let live = reader.live();
    assert_eq!(live.status, Status::Live);
    assert_eq!(ids(&live), ["T-1", "T-5"], "the new snapshot's rows");

    wire.drop_socket();
    assert_eq!(reader.live().status, Status::Resyncing, "the socket dropped: resyncing");
    cache.reconnected();
    assert_eq!(wire.opened_of("tickets.watch").len(), 2, "the changes re-opened on the new socket");
    assert_eq!(wire.opened_of("tickets.list").len(), 3, "the snapshot asked again");
    wire.answer(wire.last_of("tickets.list"), [summary("T-5", "e")]);
    assert_eq!(reader.live().status, Status::Live);
    assert_eq!(ids(&reader.live()), ["T-5"]);
}

/// Two readers of one method and params open one stream; other params
/// another; both readers gone, a third within 5 s reuses the first; past
/// 5 s it is closed and a new reader opens anew.
#[test]
fn a_subscription_is_shared_and_kept_five_seconds() {
    let (wire, clock, cache) = setup();
    let params = json!({ "summary": true, "limit": 200 });
    let one = cache.acquire(&spec(params.clone()));
    let two = cache.acquire(&spec(params.clone()));
    assert_eq!(wire.opened_of("tickets.list").len(), 1, "one snapshot for two readers");
    assert_eq!(wire.opened_of("tickets.watch").len(), 1, "one changes stream for two readers");
    wire.answer(wire.last_of("tickets.list"), [summary("T-1", "a"), summary("T-2", "b"), summary("T-3", "c")]);
    assert_eq!(ids(&two.live()), ["T-1", "T-2", "T-3"], "both read the one collection");

    let other = cache.acquire(&spec(json!({ "parent": "T-1", "summary": true })));
    assert_eq!(wire.opened_of("tickets.list").len(), 2, "other params: another subscription");
    assert_eq!(cache.kept(), 2);
    drop(other);

    let first_watch = wire.opened_of("tickets.watch")[0].id;
    let other_watch = wire.opened_of("tickets.watch")[1].id;
    drop(one);
    drop(two);
    // First leg: 4,999 ms after the last reader went, kept; a reader then
    // reuses it.
    clock.advance(4_999);
    cache.sweep();
    assert!(!wire.closed().contains(&first_watch), "4,999 ms after its last reader: kept");
    assert!(!wire.closed().contains(&other_watch), "the other params' too");
    let three = cache.acquire(&spec(params.clone()));
    assert_eq!(wire.opened_of("tickets.list").len(), 2, "reused: no snapshot asked");
    assert_eq!(ids(&three.live()), ["T-1", "T-2", "T-3"], "the kept rows at once");
    assert_eq!(three.live().status, Status::Live);
    clock.advance(2);
    cache.sweep();
    assert!(wire.closed().contains(&other_watch), "the other params' subscription, 5,001 ms without a reader: closed");
    assert!(!wire.closed().contains(&first_watch), "the one with a reader stays");

    // Second leg: the third reader goes; kept at 4,999 ms, closed at 5,001.
    drop(three);
    clock.advance(4_999);
    cache.sweep();
    assert!(!wire.closed().contains(&first_watch), "4,999 ms after its last reader: kept");
    clock.advance(2);
    cache.sweep();
    assert!(wire.closed().contains(&first_watch), "5,001 ms: its changes stream closed");
    assert_eq!(cache.kept(), 0);
    let four = cache.acquire(&spec(params));
    assert_eq!(wire.opened_of("tickets.list").len(), 3, "a new reader: a new snapshot");
    assert_eq!(wire.opened_of("tickets.watch").len(), 3, "and a new changes stream");
    assert_eq!(four.live().status, Status::Pending);
}

/// A filtered collection keeps only what is its own: with params
/// `{ parent: "T-1", summary, limit }` a created ticket under T-2 is
/// ignored, one under T-1 upserted (`summary` and `limit` name no field of
/// a ticket, so they filter nothing); an amended item that leaves the
/// filter is removed. The changes stream opens with its own params.
#[test]
fn live_keeps_only_what_matches_its_filter() {
    let (wire, _clock, cache) = setup();
    let params = json!({ "parent": "T-1", "summary": true, "limit": 200 });
    let spec = LiveSpec::new(
        "tickets.list",
        params.clone(),
        Some("tickets.watch"),
        json!({ "epic": "KILN" }),
        "id",
        &[("created", "upsert:ticket"), ("amended", "upsert:ticket"), ("deleted", "remove:ids")],
    )
    .expect("a spec");
    let reader = cache.acquire(&spec);
    assert_eq!(wire.opened_of("tickets.watch")[0].params, json!({ "epic": "KILN" }), "the changes stream's own params");
    assert_eq!(wire.opened_of("tickets.list")[0].params, params);
    wire.answer(wire.last_of("tickets.list"), [json!({ "type": "summary", "summary": { "id": "T-2", "parent": "T-1", "title": "a" } })]);

    let watch = wire.last_of("tickets.watch");
    wire.feed(watch, WireItem::Data(json!({ "type": "created", "ticket": { "id": "T-7", "parent": "T-2", "title": "elsewhere" } })));
    assert_eq!(ids(&reader.live()), ["T-2"], "a created ticket under another parent: ignored");
    wire.feed(watch, WireItem::Data(json!({ "type": "created", "ticket": { "id": "T-8", "parent": "T-1", "title": "mine" } })));
    assert_eq!(ids(&reader.live()), ["T-2", "T-8"], "one under T-1: upserted");
    wire.feed(watch, WireItem::Data(json!({ "type": "amended", "ticket": { "id": "T-8", "parent": "T-2", "title": "moved" }, "changed": ["parent"] })));
    assert_eq!(ids(&reader.live()), ["T-2"], "amended out of the filter: removed");
    wire.feed(watch, WireItem::Data(json!({ "type": "amended", "ticket": { "id": "T-7", "parent": "T-2", "title": "still elsewhere" }, "changed": ["title"] })));
    assert_eq!(ids(&reader.live()), ["T-2"], "amended, never its own: nothing");
}

// ── UI-10: the second cut ─────────────────────────────────────────────────

fn query(changes: Option<&str>, debounce_ms: Option<u64>) -> LiveQuery {
    LiveQuery {
        snapshot: "tickets.list".into(),
        changes: changes.map(str::to_string),
        key: "id".into(),
        on: vec![("created".into(), "upsert:ticket".into())],
        debounce_ms,
    }
}

/// A `live` without `changes` is a one-shot read: the snapshot alone, no
/// watch opened; `pending → live`.
#[test]
fn a_live_without_changes_opens_no_watch() {
    let (wire, _clock, cache) = setup();
    let spec = LiveSpec::new("tickets.list", json!({ "limit": 5 }), None, json!({}), "id", &[]).expect("a spec");
    let reader = cache.acquire(&spec);
    assert_eq!(wire.opened_of("tickets.list").len(), 1, "one snapshot call");
    assert!(wire.opened_of("tickets.watch").is_empty(), "no watch");
    assert_eq!(wire.opened().len(), 1, "nothing else opened");
    assert_eq!(reader.live().status, Status::Pending);
    wire.answer(wire.last_of("tickets.list"), [summary("T-1", "a")]);
    assert_eq!(reader.live().status, Status::Live);
    assert_eq!(ids(&reader.live()), ["T-1"]);

    // Followed the same way: one snapshot, no watch.
    let rt = Runtime::new();
    let (wire, clock) = (FakeWire::new(), ManualClock::new());
    let cache = LiveCache::new(&rt, wire.clone(), clock);
    let follow = cache.follow(query(None, None), || (json!({ "limit": 5 }), json!({})));
    assert_eq!(wire.opened_of("tickets.list").len(), 1);
    assert!(wire.opened_of("tickets.watch").is_empty(), "a followed live without changes opens no watch either");
    wire.answer(wire.last_of("tickets.list"), [summary("T-1", "a")]);
    assert_eq!(follow.live().status, Status::Live);
}

/// A param's signal changes: the snapshot runs again, once, with the new
/// params (the changes stream reopened with the new changes params); the
/// old rows stay, `resyncing`, until the new snapshot lands; the follow's
/// signal is the same one throughout.
#[test]
fn a_live_re_runs_when_a_param_signal_changes() {
    let rt = Runtime::new();
    let (wire, clock) = (FakeWire::new(), ManualClock::new());
    let cache = LiveCache::new(&rt, wire.clone(), clock);
    let parent = rt.signal("T-1".to_string());
    let p = parent.clone();
    let follow = cache.follow(query(Some("tickets.watch"), None), move || (json!({ "parent": p.get() }), json!({ "parent": p.get() })));
    let signal = follow.signal();
    assert_eq!(wire.opened_of("tickets.list")[0].params, json!({ "parent": "T-1" }));
    assert_eq!(wire.opened_of("tickets.watch")[0].params, json!({ "parent": "T-1" }));
    wire.answer(wire.last_of("tickets.list"), [summary("T-2", "a")]);
    assert_eq!(ids(&follow.live()), ["T-2"]);

    parent.set("T-9".into());
    assert_eq!(wire.opened_of("tickets.list").len(), 2, "the snapshot ran again, once");
    assert_eq!(wire.opened_of("tickets.list")[1].params, json!({ "parent": "T-9" }), "with the new params");
    assert_eq!(wire.opened_of("tickets.watch").last().map(|o| o.params.clone()), Some(json!({ "parent": "T-9" })), "the changes reopened with the new changes params");
    let mid = follow.live();
    assert_eq!((ids(&mid), mid.status), (vec!["T-2".to_string()], Status::Resyncing), "the old rows kept, resyncing");
    wire.answer(wire.last_of("tickets.list"), [summary("T-10", "b"), summary("T-11", "c")]);
    let now = follow.live();
    assert_eq!((ids(&now), now.status), (vec!["T-10".to_string(), "T-11".to_string()], Status::Live), "the new snapshot's rows");
    assert_eq!(Live::from_value(&signal.peek()).map(|l| l.rows.len()), Some(2), "the same signal carries them");

    parent.set("T-9".into());
    assert_eq!(wire.opened_of("tickets.list").len(), 2, "the same value: nothing ran");
    drop(follow);
}

/// With `debounce_ms: 80`, two changes 30 ms apart run the snapshot once,
/// 80 ms after the second, with the last params.
#[test]
fn a_live_re_runs_when_a_param_signal_changes_and_waits_debounce_ms() {
    let rt = Runtime::new();
    let (wire, clock) = (FakeWire::new(), ManualClock::new());
    let cache = LiveCache::new(&rt, wire.clone(), clock.clone());
    let q = rt.signal("a".to_string());
    let p = q.clone();
    let follow = cache.follow(query(None, Some(80)), move || (json!({ "query": p.get() }), json!({})));
    assert_eq!(wire.opened_of("tickets.list").len(), 1, "the first snapshot at once");
    wire.answer(wire.last_of("tickets.list"), [summary("T-1", "a")]);

    q.set("ab".into());
    clock.advance(30);
    q.set("abc".into());
    clock.advance(79);
    assert_eq!(wire.opened_of("tickets.list").len(), 1, "79 ms after the second change: not yet");
    assert_eq!(follow.live().status, Status::Live, "nothing asked yet: the rows as they are");
    clock.advance(1);
    assert_eq!(wire.opened_of("tickets.list").len(), 2, "80 ms after the second change: once");
    assert_eq!(wire.opened_of("tickets.list")[1].params, json!({ "query": "abc" }), "with the last params");
    assert!(wire.opened_of("tickets.watch").is_empty(), "one-shot stays one-shot across a param change: no watch");
    clock.advance(500);
    assert_eq!(wire.opened_of("tickets.list").len(), 2, "and only once");
}

/// `upsert:.` takes the event itself, less `type`, as the row: `extent`
/// events, from the snapshot and the changes, keyed by `epic`.
#[test]
fn a_flat_event_is_its_own_row() {
    let (wire, _clock, cache) = setup();
    let spec = LiveSpec::new("tickets.nav.extents", json!({}), Some("tickets.watch"), json!({}), "epic", &[("extent", "upsert:.")]).expect("a spec");
    let reader = cache.acquire(&spec);
    wire.answer(
        wire.last_of("tickets.nav.extents"),
        [
            json!({ "type": "extent", "epic": "KILN", "first": 1, "last": 9 }),
            json!({ "type": "extent", "epic": "GLAZE", "first": 1, "last": 4 }),
        ],
    );
    let live = reader.live();
    assert_eq!(live.rows, vec![json!({ "epic": "KILN", "first": 1, "last": 9 }), json!({ "epic": "GLAZE", "first": 1, "last": 4 })], "the events, less type");
    wire.feed(wire.last_of("tickets.watch"), WireItem::Data(json!({ "type": "extent", "epic": "KILN", "first": 1, "last": 12 })));
    wire.feed(wire.last_of("tickets.watch"), WireItem::Data(json!({ "type": "extent", "epic": "SLIP", "first": 1, "last": 1 })));
    let live = reader.live();
    let epics: Vec<&str> = live.rows.iter().map(|r| r["epic"].as_str().unwrap()).collect();
    assert_eq!(epics, ["KILN", "GLAZE", "SLIP"], "replaced by epic in place; a new one appended");
    assert_eq!(live.rows[0]["last"], 12);
    assert!(live.rows.iter().all(|r| r.get("type").is_none()), "no row keeps its type");
}

/// FRAME-48: a change heard while the snapshot runs is folded again over
/// its answer — the answer lands whole and took it back before (a `shown`
/// said as a studio's watch opens was lost to the `ui.versions` page); one
/// the answer has already moves nothing. FRAME-48b: a remove heard
/// meanwhile takes away only what an upsert heard meanwhile put there,
/// never a row of the answer — a stream's opening word folded as a remove
/// (menger's releases: the watch's `live { version }` as
/// `remove:version`) took the live version out of the list. The same over
/// a resync's snapshot.
#[test]
fn a_change_heard_while_the_snapshot_runs_survives_its_answer() {
    let (wire, _clock, cache) = setup();
    let reader = cache.acquire(&spec(json!({})));
    let watch = wire.last_of("tickets.watch");
    wire.feed(watch, WireItem::Data(json!({ "type": "created", "ticket": { "id": "T-9", "title": "said as it opened" } })));
    wire.feed(watch, WireItem::Data(json!({ "type": "amended", "ticket": { "id": "T-1", "title": "a2" } })));
    wire.feed(watch, WireItem::Data(json!({ "type": "deleted", "ids": ["T-2"] })));
    wire.feed(watch, WireItem::Data(json!({ "type": "created", "ticket": { "id": "T-8", "title": "made and gone meanwhile" } })));
    wire.feed(watch, WireItem::Data(json!({ "type": "deleted", "ids": ["T-8", "T-3"] })));
    wire.answer(wire.last_of("tickets.list"), [summary("T-1", "a"), summary("T-2", "b"), summary("T-3", "c")]);
    let live = reader.live();
    assert_eq!(live.status, Status::Live);
    assert_eq!(ids(&live), ["T-1", "T-2", "T-3", "T-9"], "the answer's rows, kept; what came meanwhile over them; T-8 made and gone");
    assert_eq!(live.rows[0]["title"], "a2", "an amend heard meanwhile is the row");

    // After the answer a change is folded once, as ever; a resync's
    // snapshot keeps what came while it ran, and nothing from before.
    wire.feed(watch, WireItem::Data(json!({ "type": "lagged", "missed": 1 })));
    wire.feed(watch, WireItem::Data(json!({ "type": "created", "ticket": { "id": "T-10", "title": "meanwhile" } })));
    wire.answer(wire.last_of("tickets.list"), [summary("T-1", "a2"), summary("T-10", "meanwhile")]);
    assert_eq!(ids(&reader.live()), ["T-1", "T-10"], "the resync's rows, T-10 once");

    // The review's case: a `lagged` while a snapshot runs asks again, and
    // what was heard before that ask is never folded over the newer answer
    // (T-1 amended to a4, then lagged: the resync's a5 is the row).
    wire.feed(watch, WireItem::Data(json!({ "type": "lagged", "missed": 1 })));
    let first = wire.last_of("tickets.list");
    wire.feed(watch, WireItem::Data(json!({ "type": "amended", "ticket": { "id": "T-1", "title": "a4" } })));
    wire.feed(watch, WireItem::Data(json!({ "type": "lagged", "missed": 1 })));
    let second = wire.last_of("tickets.list");
    assert_ne!(first, second, "asked again");
    // Two snapshots at once: the earlier one's answer is not heard — it
    // takes neither the buffer nor what the running one heard meanwhile.
    wire.feed(watch, WireItem::Data(json!({ "type": "created", "ticket": { "id": "T-11", "title": "during the second" } })));
    wire.answer(first, [summary("T-1", "a4"), summary("T-10", "meanwhile"), summary("T-99", "stale")]);
    assert_eq!(reader.live().status, Status::Resyncing, "the earlier answer ends nothing");
    wire.answer(second, [summary("T-1", "a5"), summary("T-10", "meanwhile")]);
    let live = reader.live();
    assert_eq!(live.status, Status::Live);
    assert_eq!(ids(&live), ["T-1", "T-10", "T-11"], "the second's rows and what it heard; nothing of the first's");
    assert_eq!(live.rows[0]["title"], "a5", "the amend heard before the ask is not folded over the newer answer");
}

/// UI-8: an in-band `error` (a filter `nav counts` does not take) makes the
/// collection `error` with the server's `message`, and no rows; the next
/// answer that is not one clears it. A call refused is `refused`, its words
/// the `message`.
#[test]
fn an_in_band_error_is_the_collections_message() {
    let (wire, _clock, cache) = setup();
    let spec = LiveSpec::new("tickets.nav.counts", json!({ "filter": "text foo" }), None, json!({}), "shortcode", &[("count", "upsert:.")]).expect("a spec");
    let reader = cache.acquire(&spec);
    wire.answer(wire.last_of("tickets.nav.counts"), [json!({ "type": "error", "message": "`text foo`: text is not taken here" })]);
    let v = reader.signal().peek();
    assert_eq!(v["status"], "error");
    assert_eq!(v["message"], "`text foo`: text is not taken here");
    assert_eq!(v["rows"], json!([]));

    let ok = LiveSpec::new("tickets.nav.counts", json!({ "filter": "status Ready" }), None, json!({}), "shortcode", &[("count", "upsert:.")]).expect("a spec");
    let r2 = cache.acquire(&ok);
    wire.answer(wire.last_of("tickets.nav.counts"), [json!({ "type": "count", "epic": "K", "shortcode": "K", "held": 3 })]);
    let v = r2.signal().peek();
    assert_eq!(v["status"], "live");
    assert!(v.get("message").is_none(), "no message on an answer: {v}");
    assert_eq!(v["rows"][0]["held"], 3);

    let refused = LiveSpec::new("tickets.nav.counts", json!({ "filter": "" }), None, json!({}), "shortcode", &[]).expect("a spec");
    let r3 = cache.acquire(&refused);
    wire.feed(wire.last_of("tickets.nav.counts"), WireItem::Refused("filter: a blank value".into()));
    let v = r3.signal().peek();
    assert_eq!((v["status"].as_str(), v["message"].as_str()), (Some("refused"), Some("filter: a blank value")));
}

/// After a param change, a late answer to the old snapshot changes nothing
/// the follow shows; the old subscription's watch is closed once its keep
/// window has passed and a sweep runs.
#[test]
fn a_late_answer_to_the_old_snapshot_is_ignored_and_the_old_watch_closes() {
    let rt = Runtime::new();
    let (wire, clock) = (FakeWire::new(), ManualClock::new());
    let cache = LiveCache::new(&rt, wire.clone(), clock.clone());
    let parent = rt.signal("T-1".to_string());
    let p = parent.clone();
    let follow = cache.follow(query(Some("tickets.watch"), None), move || (json!({ "parent": p.get() }), json!({ "parent": p.get() })));
    let (old_list, old_watch) = (wire.last_of("tickets.list"), wire.last_of("tickets.watch"));

    parent.set("T-9".into());
    let new_list = wire.last_of("tickets.list");
    assert_ne!(new_list, old_list);
    wire.answer(old_list, [summary("T-OLD", "late")]);
    let now = follow.live();
    assert!(!ids(&now).contains(&"T-OLD".to_string()), "the old snapshot's late rows are not shown: {:?}", ids(&now));
    assert_ne!(now.status, Status::Live, "still waiting on the new snapshot");
    wire.answer(new_list, [summary("T-10", "new")]);
    assert_eq!(ids(&follow.live()), ["T-10"]);

    clock.advance(4_999);
    cache.sweep();
    assert!(!wire.closed().contains(&old_watch), "within the keep window: the old watch kept");
    clock.advance(2);
    cache.sweep();
    assert!(wire.closed().contains(&old_watch), "past it: the old watch closed");
    assert!(!wire.closed().contains(&wire.last_of("tickets.watch")), "the new one stays");
}

/// Dropping a follow while a debounced run waits runs nothing; with
/// `changes` and a debounce, the watch is reopened only when the timer
/// fires.
#[test]
fn dropping_a_follow_mid_debounce_runs_nothing_and_a_watch_reopens_only_when_the_timer_fires() {
    let rt = Runtime::new();
    let (wire, clock) = (FakeWire::new(), ManualClock::new());
    let cache = LiveCache::new(&rt, wire.clone(), clock.clone());
    let q = rt.signal("a".to_string());
    let p = q.clone();
    let follow = cache.follow(query(Some("tickets.watch"), Some(80)), move || (json!({ "query": p.get() }), json!({ "query": p.get() })));
    assert_eq!((wire.opened_of("tickets.list").len(), wire.opened_of("tickets.watch").len()), (1, 1));
    q.set("ab".into());
    clock.advance(79);
    assert_eq!(wire.opened_of("tickets.watch").len(), 1, "the watch not reopened before the timer");
    assert_eq!(wire.opened_of("tickets.list").len(), 1);
    clock.advance(1);
    assert_eq!(wire.opened_of("tickets.watch").len(), 2, "reopened when the timer fired");
    assert_eq!(wire.opened_of("tickets.watch")[1].params, json!({ "query": "ab" }));

    q.set("abc".into());
    clock.advance(40);
    drop(follow);
    clock.advance(1_000);
    assert_eq!(wire.opened_of("tickets.list").len(), 2, "dropped mid-debounce: nothing ran");
    assert_eq!(wire.opened_of("tickets.watch").len(), 2);
}

/// A flat event that also holds an object-valued field is the same row
/// from the snapshot as from the changes: `upsert:.` decides, not a guess
/// at which field is the row.
#[test]
fn a_flat_event_with_an_object_field_is_the_same_row_from_snapshot_and_changes() {
    let (wire, _clock, cache) = setup();
    let spec = LiveSpec::new("tickets.nav.groups", json!({}), Some("tickets.watch"), json!({}), "epic", &[("group", "upsert:.")]).expect("a spec");
    let reader = cache.acquire(&spec);
    let event = json!({ "type": "group", "epic": "KILN", "counts": { "open": 3, "done": 1 } });
    wire.answer(wire.last_of("tickets.nav.groups"), [event.clone()]);
    let from_snapshot = reader.live().rows;
    assert_eq!(from_snapshot, vec![json!({ "epic": "KILN", "counts": { "open": 3, "done": 1 } })], "the event less type, not its counts");
    let mut changed = event;
    changed["counts"]["open"] = json!(4);
    wire.feed(wire.last_of("tickets.watch"), WireItem::Data(changed));
    assert_eq!(reader.live().rows, vec![json!({ "epic": "KILN", "counts": { "open": 4, "done": 1 } })], "the same row from the changes, replaced");
}

/// FRAME-17: a snapshot asked before its component mounts — the host's
/// early call is a subscription with no reader yet. Its answer is kept, and
/// the subscriber that comes (the same spec) reads it at once: no second
/// snapshot, no second changes stream. Nobody coming, it is swept past
/// `KEEP_MS` and both calls closed.
#[test]
fn an_answer_waits_for_its_subscriber() {
    let (wire, clock, cache) = setup();
    let params = json!({ "summary": true, "limit": 200, "filter": null, "after": null });
    drop(cache.acquire(&spec(params.clone())));
    wire.answer(wire.last_of("tickets.list"), [summary("T-1", "a"), summary("T-2", "b")]);
    clock.advance(KEEP_MS / 2);
    let reader = cache.acquire(&spec(params.clone()));
    assert_eq!(reader.live().status, Status::Live, "the kept answer, at once");
    assert_eq!(ids(&reader.live()), ["T-1", "T-2"]);
    assert_eq!(wire.opened_of("tickets.list").len(), 1, "the subscriber shares the early snapshot");
    assert_eq!(wire.opened_of("tickets.watch").len(), 1, "and its changes stream");
    drop(reader);

    let other = json!({ "summary": true, "limit": 99 });
    drop(cache.acquire(&spec(other)));
    let early = wire.last_of("tickets.list");
    clock.advance(KEEP_MS + 1);
    cache.sweep();
    assert!(wire.closed().contains(&early), "an early call nobody subscribed to is closed once its keep is out");
}

/// FRAME-19: a module's spec as it crosses the bus, `when` and
/// `debounce_ms` with it.
fn module_spec(v: Value) -> ModuleSpec {
    ModuleSpec::from_value(&v).unwrap_or_else(|e| panic!("a module's spec takes when and debounce_ms: {e}"))
}

/// FRAME-19: a module's `live` held by `when: false` asks nothing; its
/// `update({ params, when: true })` asks — after `debounce_ms` when it has
/// one (the palette's first key is one call, not one per key), at once when
/// it has none; `when: false` again lets its reader go (the rows stay as
/// they were, the subscription swept past `KEEP_MS`). A `when` that is no
/// boolean, a `debounce_ms` that is no count, and an `update` of anything
/// but `params`, `changes_params` and `when` are refused, naming them.
#[test]
fn a_modules_spec_waits_for_when() {
    let (wire, clock, cache) = setup();
    let pal = cache.follow_module(module_spec(json!({ "snapshot": "tickets.find", "params": { "q": "" }, "key": "id", "when": false, "debounce_ms": 80 })));
    clock.advance(1_000);
    assert!(wire.opened_of("tickets.find").is_empty(), "held by when: nothing asked");
    assert_eq!(pal.live().status, Status::Pending, "held: pending, no rows");
    assert!(pal.live().rows.is_empty());

    pal.update(&json!({ "params": { "q": "a" }, "when": true })).expect("update takes params and when");
    clock.advance(79);
    assert!(wire.opened_of("tickets.find").is_empty(), "79 ms after the key: not yet");
    clock.advance(1);
    assert_eq!(wire.opened_of("tickets.find").len(), 1, "80 ms after the key: once");
    assert_eq!(wire.opened_of("tickets.find")[0].params, json!({ "q": "a" }), "with the params of that moment");
    wire.answer(wire.last_of("tickets.find"), [summary("T-1", "a")]);
    assert_eq!(pal.live().status, Status::Live);
    assert_eq!(ids(&pal.live()), ["T-1"]);

    pal.update(&json!({ "params": { "q": "" }, "when": false })).expect("held again");
    clock.advance(500);
    assert_eq!(wire.opened_of("tickets.find").len(), 1, "held again: nothing asked");
    assert_eq!(ids(&pal.live()), ["T-1"], "the rows stay as they were");
    // Kept for another reader: a sweep before KEEP_MS closes nothing. (Its
    // snapshot is answered, so there is no call left to close: the kept
    // subscription is what says it.)
    cache.sweep();
    assert_eq!(cache.kept(), 1, "let go, kept KEEP_MS for another reader");
    clock.advance(KEEP_MS + 1);
    cache.sweep();
    assert_eq!(cache.kept(), 0, "its reader let go: the subscription swept past KEEP_MS");

    // No debounce_ms: asked the moment it turns true.
    let now = cache.follow_module(module_spec(json!({ "snapshot": "tickets.find", "params": { "q": "" }, "key": "id", "when": false })));
    assert_eq!(wire.opened_of("tickets.find").len(), 1, "a second held spec asks nothing");
    now.update(&json!({ "params": { "q": "b" }, "when": true })).unwrap();
    assert_eq!(wire.opened_of("tickets.find").len(), 2, "no debounce_ms: at once");
    assert_eq!(wire.opened_of("tickets.find")[1].params, json!({ "q": "b" }));

    // Refusals, naming what.
    for (bad, word) in [
        (json!({ "snapshot": "tickets.find", "key": "id", "when": "yes" }), "when"),
        (json!({ "snapshot": "tickets.find", "key": "id", "debounce_ms": -1 }), "debounce_ms"),
        (json!({ "snapshot": "tickets.find", "key": "id", "debounce_ms": "80" }), "debounce_ms"),
        (json!({ "snapshot": "tickets.find", "key": "id", "params": "q" }), "params"),
    ] {
        let e = ModuleSpec::from_value(&bad).expect_err(&format!("refused: {bad}"));
        assert!(e.contains(word), "{bad} refused naming {word}: {e}");
    }
    for (bad, word) in [(json!({ "snapshot": "tickets.list" }), "snapshot"), (json!({ "when": 1 }), "when"), (json!({ "params": 3 }), "params")] {
        let e = now.update(&bad).expect_err(&format!("update refused: {bad}"));
        assert!(e.contains(word), "update {bad} refused naming {word}: {e}");
    }
}

/// FRAME-19: a module's param changes coalesce by its `debounce_ms`, on
/// the registry's clock — the first snapshot at once, then two updates 30
/// ms apart run it once, 80 ms after the second, with the last params, the
/// old rows `resyncing` meanwhile kept; an update to the params it has
/// asks nothing; a patch keeps what it leaves out; dropped mid-debounce,
/// nothing runs.
#[test]
fn a_modules_params_coalesce_by_debounce() {
    let (wire, clock, cache) = setup();
    let m = cache.follow_module(module_spec(json!({
        "snapshot": "tickets.find", "params": { "q": "a", "limit": 12 }, "changes": "tickets.watch", "changes_params": { "epic": "KILN" },
        "key": "id", "on": { "created": "upsert:summary" }, "debounce_ms": 80
    })));
    assert_eq!(wire.opened_of("tickets.find").len(), 1, "the first snapshot at once");
    assert_eq!(wire.opened_of("tickets.find")[0].params, json!({ "q": "a", "limit": 12 }));
    wire.answer(wire.last_of("tickets.find"), [summary("T-1", "a")]);

    m.update(&json!({ "params": { "q": "ab", "limit": 12 } })).unwrap();
    clock.advance(30);
    m.update(&json!({ "params": { "q": "abc", "limit": 12 } })).unwrap();
    clock.advance(79);
    assert_eq!(wire.opened_of("tickets.find").len(), 1, "79 ms after the second update: not yet");
    assert_eq!(ids(&m.live()), ["T-1"], "nothing asked yet: the rows as they are");
    clock.advance(1);
    assert_eq!(wire.opened_of("tickets.find").len(), 2, "80 ms after the second update: once");
    assert_eq!(wire.opened_of("tickets.find")[1].params, json!({ "q": "abc", "limit": 12 }), "with the last params");
    assert_eq!(m.live().status, Status::Resyncing, "the old rows kept while the new snapshot runs");
    assert_eq!(ids(&m.live()), ["T-1"]);
    assert_eq!(wire.opened_of("tickets.watch").last().map(|o| o.params.clone()), Some(json!({ "epic": "KILN" })), "changes_params kept: the patch named params only");
    assert_eq!(wire.opened_of("tickets.watch").len(), 2, "one watch per run: the first and the debounced one");
    clock.advance(500);
    assert_eq!(wire.opened_of("tickets.find").len(), 2, "and only once");
    assert_eq!(wire.opened_of("tickets.watch").len(), 2);

    // changes_params moved: the watch's params move, after the debounce.
    m.update(&json!({ "changes_params": { "epic": "GLAZE" } })).unwrap();
    clock.advance(79);
    assert_eq!(wire.opened_of("tickets.watch").len(), 2, "not before the debounce");
    clock.advance(1);
    assert_eq!(wire.opened_of("tickets.watch").len(), 3, "the watch opened again");
    assert_eq!(wire.opened_of("tickets.watch")[2].params, json!({ "epic": "GLAZE" }));
    assert_eq!(wire.opened_of("tickets.find").len(), 3, "a new spec: its snapshot asked too");
    assert_eq!(wire.opened_of("tickets.find")[2].params, json!({ "q": "abc", "limit": 12 }), "params kept: the patch named changes_params only");

    m.update(&json!({ "params": { "q": "abc", "limit": 12 } })).unwrap();
    m.update(&json!({})).unwrap();
    clock.advance(500);
    assert_eq!(wire.opened_of("tickets.find").len(), 3, "the params it has, or none named: nothing asked");
    assert_eq!(wire.opened_of("tickets.watch").len(), 3);

    m.update(&json!({ "params": { "q": "abcd", "limit": 12 } })).unwrap();
    clock.advance(40);
    drop(m);
    clock.advance(1_000);
    assert_eq!(wire.opened_of("tickets.find").len(), 3, "dropped mid-debounce: nothing ran");
    assert_eq!(wire.opened_of("tickets.watch").len(), 3);
}

/// FRAME-20: the board's collection as a module reads it — 200 summaries,
/// `created` / `status_changed` upserted, `deleted` removed.
fn board_spec() -> ModuleSpec {
    module_spec(json!({
        "snapshot": "tickets.list", "params": { "summary": true, "limit": 200 }, "changes": "tickets.watch", "key": "id",
        "on": { "created": "upsert:ticket", "status_changed": "upsert:ticket", "deleted": "remove:ids" }
    }))
}

fn row(n: usize, status: &str) -> Value {
    json!({ "id": format!("T-{n}"), "title": format!("t{n}"), "status": status })
}

/// The board's 200 rows answered; the crossing of that first page.
fn board(wire: &FakeWire, m: &ModuleLive) -> Crossing {
    let page: Vec<Value> = (1..=200).map(|n| json!({ "type": "summary", "summary": row(n, "Ready") })).collect();
    wire.answer(wire.last_of("tickets.list"), page);
    assert_eq!(m.live().rows.len(), 200);
    m.since(0)
}

/// FRAME-20: a change crosses as the change. The first page is whole; then
/// a `created` is `{ upsert: [that row], remove: [] }` — one move, the
/// collection with the row added at its end; a `status_changed` of T-7 is
/// one upsert, T-7's new value, the row replaced in place; a `deleted` is
/// one remove, its key. Each the next move, read by a subscriber that saw
/// the one before.
#[test]
fn a_change_crosses_as_the_change() {
    let (wire, _clock, cache) = setup();
    let m = cache.follow_module(board_spec());
    let first = board(&wire, &m);
    assert_eq!(first.delta, Delta::Whole, "the first page crosses whole");
    assert!(first.seq > 0, "the first page is a move: seq {}", first.seq);
    assert_eq!(m.seq(), first.seq, "seq() is where since() stands");
    let watch = wire.last_of("tickets.watch");

    wire.feed(watch, WireItem::Data(json!({ "type": "created", "ticket": row(201, "Draft") })));
    let c = m.since(first.seq);
    assert_eq!(c.seq, first.seq + 1, "a created is one move");
    assert_eq!(c.delta, Delta::Change { upsert: vec![row(201, "Draft")], remove: vec![] }, "created: the row alone crosses");
    assert_eq!(m.live().rows.len(), 201);
    assert_eq!(m.live().rows[200], row(201, "Draft"), "upserted at the end, as the fold puts it");

    wire.feed(watch, WireItem::Data(json!({ "type": "status_changed", "ticket": row(7, "Coding"), "from": "Ready", "to": "Coding" })));
    let s = m.since(c.seq);
    assert_eq!(s.seq, c.seq + 1);
    assert_eq!(s.delta, Delta::Change { upsert: vec![row(7, "Coding")], remove: vec![] }, "status_changed: T-7's new value alone");
    assert_eq!(m.live().rows[6], row(7, "Coding"), "replaced in place");

    wire.feed(watch, WireItem::Data(json!({ "type": "deleted", "ids": ["T-3"], "tombstones": [] })));
    let d = m.since(s.seq);
    assert_eq!(d.seq, s.seq + 1);
    assert_eq!(d.delta, Delta::Change { upsert: vec![], remove: vec!["T-3".into()] }, "deleted: its key alone");
    assert_eq!(m.live().rows.len(), 200);
    assert!(m.live().rows.iter().all(|r| r["id"] != "T-3"));
}

/// FRAME-20: an unchanged row does not cross. A `status_changed` of T-7
/// names T-7 alone (rows 1–6 and 8–200 are not in the change, so the face
/// keeps their objects: the smoke's `unchanged_rows_keep_their_identity`
/// sees it on the JS side); the same row sent again, equal to the one kept,
/// moves nothing — no move, nothing to cross.
#[test]
fn an_unchanged_row_does_not_cross() {
    let (wire, _clock, cache) = setup();
    let m = cache.follow_module(board_spec());
    let first = board(&wire, &m);
    let watch = wire.last_of("tickets.watch");
    wire.feed(watch, WireItem::Data(json!({ "type": "status_changed", "ticket": row(7, "Coding"), "from": "Ready", "to": "Coding" })));
    let c = m.since(first.seq);
    match &c.delta {
        Delta::Change { upsert, remove } => {
            assert_eq!(upsert.iter().map(|r| r["id"].clone()).collect::<Vec<_>>(), [json!("T-7")], "T-7 alone crosses");
            assert!(remove.is_empty());
        }
        Delta::Whole => panic!("a status_changed of T-7 crossed the whole collection (seq {} → {})", first.seq, c.seq),
    }
    wire.feed(watch, WireItem::Data(json!({ "type": "status_changed", "ticket": row(7, "Coding"), "from": "Coding", "to": "Coding" })));
    assert_eq!(m.seq(), c.seq, "the row sent again as it is kept: no move");
    assert_eq!(m.since(m.seq()), Crossing { seq: c.seq, delta: Delta::Change { upsert: vec![], remove: vec![] } }, "since(seq()): nothing to cross");
}

/// FRAME-20: a row that stops matching the snapshot's params crosses as a
/// remove — the board filtered to `status: "Ready"`, T-7 moved to Coding.
#[test]
fn a_row_that_stops_matching_crosses_as_a_remove() {
    let (wire, _clock, cache) = setup();
    let m = cache.follow_module(module_spec(json!({
        "snapshot": "tickets.list", "params": { "status": "Ready", "limit": 200 }, "changes": "tickets.watch", "key": "id",
        "on": { "created": "upsert:ticket", "status_changed": "upsert:ticket", "deleted": "remove:ids" }
    })));
    let first = board(&wire, &m);
    let watch = wire.last_of("tickets.watch");
    wire.feed(watch, WireItem::Data(json!({ "type": "status_changed", "ticket": row(7, "Coding"), "from": "Ready", "to": "Coding" })));
    let c = m.since(first.seq);
    assert_eq!(c.seq, first.seq + 1);
    assert_eq!(c.delta, Delta::Change { upsert: vec![], remove: vec!["T-7".into()] }, "no longer Ready: T-7's key removed");
    assert_eq!(m.live().rows.len(), 199);
    wire.feed(watch, WireItem::Data(json!({ "type": "created", "ticket": row(300, "Draft") })));
    assert_eq!(m.seq(), c.seq, "a created row not Ready: not this collection's, no move");
}

/// FRAME-20: a resync crosses whole, once. A `lagged` moves the status
/// (`resyncing`, the rows kept: a change of nothing); the snapshot asked
/// again lands as the whole collection; the next change is a change again.
/// A subscriber that missed a move gets the whole. Params moved by
/// `update` (a switch to another collection) cross whole.
#[test]
fn a_resync_crosses_whole() {
    let (wire, _clock, cache) = setup();
    let m = cache.follow_module(board_spec());
    let first = board(&wire, &m);
    let watch = wire.last_of("tickets.watch");

    wire.feed(watch, WireItem::Data(json!({ "type": "lagged", "missed": 3 })));
    assert_eq!(m.live().status, Status::Resyncing);
    let lag = m.since(first.seq);
    assert_eq!(lag.seq, first.seq + 1, "resyncing is a move");
    assert_eq!(lag.delta, Delta::Change { upsert: vec![], remove: vec![] }, "the status alone: no row crosses");
    let page: Vec<Value> = (1..=150).map(|n| json!({ "type": "summary", "summary": row(n, "Pending") })).collect();
    wire.answer(wire.last_of("tickets.list"), page);
    let whole = m.since(lag.seq);
    assert_eq!(whole.seq, lag.seq + 1, "the new snapshot is one move");
    assert_eq!(whole.delta, Delta::Whole, "a resync's snapshot crosses whole");
    assert_eq!(m.live().rows.len(), 150);

    wire.feed(watch, WireItem::Data(json!({ "type": "created", "ticket": row(151, "Draft") })));
    let next = m.since(whole.seq);
    assert_eq!(next.delta, Delta::Change { upsert: vec![row(151, "Draft")], remove: vec![] }, "after the resync a change is a change again");

    // Two moves unread: the subscriber that saw `whole` gets the whole.
    wire.feed(watch, WireItem::Data(json!({ "type": "created", "ticket": row(152, "Draft") })));
    let missed = m.since(whole.seq);
    assert_eq!(missed.seq, whole.seq + 2);
    assert_eq!(missed.delta, Delta::Whole, "a missed move: the whole collection");

    // Other params: another collection, whole.
    m.update(&json!({ "params": { "summary": true, "limit": 50 } })).unwrap();
    let page: Vec<Value> = (1..=50).map(|n| json!({ "type": "summary", "summary": row(n, "Ready") })).collect();
    wire.answer(wire.last_of("tickets.list"), page);
    let switched = m.since(missed.seq);
    assert!(switched.seq > missed.seq, "the switch moved it");
    assert_eq!(switched.delta, Delta::Whole, "a switch to other params crosses whole");
    assert_eq!(m.live().rows.len(), 50);
}

/// PERF-15: a page is one frame — `rows { items }`, each item the per-row
/// event it was (`summary`, `node`, `hit`, a flat `extent`), then `page`.
fn rows_event(items: Vec<Value>) -> Value {
    json!({ "type": "rows", "items": items })
}

/// PERF-15: the board's 200 rows as one `rows` event, then `page`: the
/// collection is the 200 summaries in order, and it moved once — one
/// publish of the whole (a `replace` on the bus), so one render; the page
/// none. Then a change folds as ever.
#[test]
fn a_rows_event_is_one_replace() {
    let (wire, _clock, cache) = setup();
    let m = cache.follow_module(board_spec());
    let before = m.seq();
    let items: Vec<Value> = (1..=200).map(|n| json!({ "type": "summary", "summary": row(n, "Ready") })).collect();
    wire.answer(wire.last_of("tickets.list"), [rows_event(items), json!({ "type": "page", "next": "T-200", "remaining": 100 })]);
    let live = m.live();
    assert_eq!(live.status, Status::Live);
    assert_eq!(live.rows.len(), 200, "the rows event's 200 items are the page's 200 rows");
    assert_eq!(live.rows[0], row(1, "Ready"));
    assert_eq!(live.rows[199], row(200, "Ready"), "in order");
    let c = m.since(before);
    assert_eq!(c.seq, before + 1, "one move for the page: one render");
    assert_eq!(c.delta, Delta::Whole, "the page crosses whole: a replace");

    let watch = wire.last_of("tickets.watch");
    wire.feed(watch, WireItem::Data(json!({ "type": "status_changed", "ticket": row(7, "Coding"), "from": "Ready", "to": "Coding" })));
    let s = m.since(c.seq);
    assert_eq!(s.delta, Delta::Change { upsert: vec![row(7, "Coding")], remove: vec![] }, "after it a change is a change");

    // A resync answered by a rows of 50 is those 50 — the page replaces the
    // collection, never adds to it — crossing whole.
    wire.feed(watch, WireItem::Data(json!({ "type": "lagged", "missed": 3 })));
    let lag = m.since(s.seq);
    let items: Vec<Value> = (301..=350).map(|n| json!({ "type": "summary", "summary": row(n, "Pending") })).collect();
    wire.answer(wire.last_of("tickets.list"), [rows_event(items), json!({ "type": "page", "next": null, "remaining": 0 })]);
    let live = m.live();
    assert_eq!(live.rows.len(), 50, "the resync's 50, not 200 or 250");
    assert_eq!((live.rows[0]["id"].as_str(), live.rows[49]["id"].as_str()), (Some("T-301"), Some("T-350")));
    let whole = m.since(lag.seq);
    assert_eq!((whole.seq, whole.delta), (lag.seq + 1, Delta::Whole), "the resync's page: one move, whole");

    // A param switch answered by rows the same.
    m.update(&json!({ "params": { "summary": true, "limit": 50 } })).unwrap();
    let items: Vec<Value> = (1..=50).map(|n| json!({ "type": "summary", "summary": row(n, "Ready") })).collect();
    wire.answer(wire.last_of("tickets.list"), [rows_event(items), json!({ "type": "page", "next": "T-50", "remaining": 150 })]);
    assert_eq!(m.live().rows.len(), 50, "the switch's 50");
    assert_eq!(m.since(whole.seq).delta, Delta::Whole);
}

/// PERF-15: each item of a `rows` event is the row its event would have
/// been on its own — a `node`'s summary, a `hit`'s summary, a flat
/// `extent` under `upsert:.` the event less `type` — and a `rows` split
/// over two frames (a walk of whole tickets, a page of bodies at a time)
/// is still one page.
#[test]
fn a_rows_events_items_are_each_its_row() {
    let (wire, _clock, cache) = setup();
    let nodes = cache.acquire(&LiveSpec::new("tickets.nav.tree", json!({ "parent": "T-1" }), None, json!({}), "id", &[]).unwrap());
    wire.answer(wire.last_of("tickets.nav.tree"), [
        rows_event(vec![json!({ "type": "node", "summary": { "id": "T-2", "title": "b" }, "matched": true, "below": 0 }), json!({ "type": "node", "summary": { "id": "T-3", "title": "c" }, "matched": false, "below": 2 })]),
        json!({ "type": "page", "next": null, "remaining": 0 }),
    ]);
    assert_eq!(ids(&nodes.live()), ["T-2", "T-3"], "a node item: its summary, as a node event's row");

    let extents = cache.acquire(&LiveSpec::new("tickets.nav.extents", json!({}), None, json!({}), "shortcode", &[("extent", "upsert:.")]).unwrap());
    wire.answer(wire.last_of("tickets.nav.extents"), [rows_event(vec![
        json!({ "type": "extent", "epic": "A", "shortcode": "A", "last_seq": 3 }),
        json!({ "type": "extent", "epic": "B", "shortcode": "B", "last_seq": 9 }),
    ])]);
    let live = extents.live();
    assert_eq!(live.rows, [json!({ "epic": "A", "shortcode": "A", "last_seq": 3 }), json!({ "epic": "B", "shortcode": "B", "last_seq": 9 })], "a flat item under upsert:. — the event less type");

    let hits = cache.acquire(&LiveSpec::new("tickets.search", json!({ "query": "x" }), None, json!({}), "id", &[]).unwrap());
    wire.answer(wire.last_of("tickets.search"), [
        rows_event(vec![json!({ "type": "hit", "summary": { "id": "T-5", "title": "x" }, "title": "<b>x</b>", "snippet": "…", "corrected": false })]),
        json!({ "type": "searched", "matched": 1, "next": null, "words": [] }),
    ]);
    assert_eq!(ids(&hits.live()), ["T-5"], "a hit item: its summary; searched none");

    let whole = cache.acquire(&spec(json!({ "limit": 3 })));
    wire.answer(wire.last_of("tickets.list"), [
        rows_event(vec![json!({ "type": "ticket", "ticket": { "id": "T-1", "title": "a", "body": "" } }), json!({ "type": "ticket", "ticket": { "id": "T-2", "title": "b", "body": "" } })]),
        rows_event(vec![json!({ "type": "ticket", "ticket": { "id": "T-3", "title": "c", "body": "" } })]),
        json!({ "type": "page", "next": null, "remaining": 0 }),
    ]);
    assert_eq!(ids(&whole.live()), ["T-1", "T-2", "T-3"], "two rows frames, one page");
}

/// FRAME-50: `when_answered` waits for the snapshots running when it was
/// asked — answered, refused or failed — and not for one asked after: the
/// boot releases its held sections once what its mount asked is in.
#[test]
fn when_answered_waits_for_the_snapshots_running_then() {
    let (wire, _clock, cache) = setup();
    let ran = Rc::new(std::cell::Cell::new(0));
    let r = ran.clone();
    cache.when_answered(Box::new(move || r.set(r.get() + 1)));
    assert_eq!(ran.get(), 1, "none running: at once");

    let a = cache.acquire(&spec(json!({ "parent": "T-1" })));
    let b = cache.acquire(&spec(json!({ "parent": "T-2" })));
    assert_eq!(cache.running(), 2);
    let r = ran.clone();
    cache.when_answered(Box::new(move || r.set(r.get() + 1)));
    let late = cache.acquire(&spec(json!({ "parent": "T-3" })));
    assert_eq!(cache.running(), 3);
    let [ta, tb, tc] = [0, 1, 2].map(|i| wire.opened_of("tickets.list")[i].id);
    wire.answer(ta, [summary("T-4", "a")]);
    assert_eq!(ran.get(), 1, "one of the two still runs");
    wire.feed(tb, WireItem::Refused("forbidden".into()));
    assert_eq!(ran.get(), 2, "both in (a refusal is an answer); the one asked later is not waited for");
    assert_eq!(cache.running(), 1);
    wire.answer(tc, []);
    assert_eq!(ran.get(), 2, "once");
    drop((a, b, late));
}