ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
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
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
use crate::Context;
use core::{convert::Infallible, error::Error, time::Duration};

use std::{
  sync::{Arc, Mutex},
  thread,
  time::Instant,
};

use crate::{
  AckMode, AsyncResource, ChannelGraph, Delivery, DriverKind, EdgeId, EdgeTypeError, Effect,
  Emitter, Enablement, FanoutKind, Feeder, GraphBuilder, Item, ItemId, LaunchError, Listen, NodeId,
  NodeWiring, Operator, Party, Payload, Plan, PollUpstream, RecordingTap, Resources, Shared,
  TakenInboxError, Taps, UpstreamWiring, Wired, Wiring, ack_channel,
};

use crate::drive::Drives;

struct Shout;

/// The facts a hand-wired node states — the mount predicate is `O: Declared + Driven<O::Mode>`, so
/// a node that is not emitted says what it is too, in the mode a bare declaration has.
macro_rules! declared {
  ($name:ident) => {
    impl crate::Declared for $name {
      const EFFECT: crate::Effect = crate::Effect::Pure;

      type Channels = crate::Unchanneled;
      type Mode = crate::Block;
      type Options = ();
      type Pair = crate::Buffered;
      type Wires<O> = crate::Downstream<O>;
      type Attribution<O> = ();
    }
  };
}

declared!(Shout);

impl Operator for Shout {
  type Error = Infallible;
  type In = String;
  type Out = String;

  fn accept(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    emitter: &mut Emitter<String>,
  ) -> Result<(), Self::Error> {
    for item in delivery.into_items() {
      let item = item.into_value();
      emitter.emit(item.to_uppercase());
    }
    Ok(())
  }
}

/// A leaf that keeps what reached it, so a walk can be checked by what came out the far end.
struct Keeping {
  seen: Arc<Mutex<Vec<String>>>,
}

declared!(Keeping);

impl Operator for Keeping {
  type Error = Infallible;
  type In = String;
  type Out = String;

  fn accept(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    _emitter: &mut Emitter<String>,
  ) -> Result<(), Self::Error> {
    for item in delivery.into_items() {
      let item = item.into_value();
      self.seen.lock().expect("the walk's record").push(item);
    }
    Ok(())
  }
}

struct Counting;

declared!(Counting);

impl Operator for Counting {
  type Error = Infallible;
  type In = u8;
  type Out = u8;

  fn accept(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    emitter: &mut Emitter<u8>,
  ) -> Result<(), Self::Error> {
    for item in delivery.into_items() {
      let item = item.into_value();
      emitter.emit(item);
    }
    Ok(())
  }
}

/// `shout → titles`, one edge, both nodes on `driver`.
fn pair(driver: DriverKind) -> ChannelGraph {
  let mut builder = GraphBuilder::new();
  let shout = builder.source::<Shout>("shout", driver);
  let titles = builder.node::<Shout>("titles", driver);
  builder.edge(&shout, &titles, FanoutKind::Broadcast);
  builder.validate().expect("one edge validates")
}

/// The pair, launched whole, with the leaf landing through a lane of its own.
fn pair_plan(driver: DriverKind) -> Plan {
  Plan::new(pair(driver))
    .with_enablement(Enablement::new().launching("shout").launching("titles"))
    .wiring(NodeId::new(1), NodeWiring::new(Effect::Lands).landing())
}

/// The fast hand and the slow one, far enough apart to be told apart in a list.
const REAP: Duration = Duration::from_millis(10);
const COMPACT: Duration = Duration::from_secs(3600);

/// `scenes → reaper` and `media → reaper`, both POLL — one node, two clocks.
fn reaper_plan(driver: DriverKind) -> Plan {
  let mut builder = GraphBuilder::new();
  let scenes = builder.source::<Shout>("scenes", driver);
  let media = builder.source::<Shout>("media", driver);
  let reaper = builder.node::<Shout>("reaper", driver);
  builder.edge(&scenes, &reaper, FanoutKind::Broadcast);
  builder.edge(&media, &reaper, FanoutKind::Broadcast);
  let graph = builder.validate().expect("two edges validate");

  Plan::new(graph)
    .with_enablement(
      Enablement::new()
        .launching("scenes")
        .launching("media")
        .launching("reaper"),
    )
    .upstream(
      EdgeId::new(0),
      UpstreamWiring::new(Listen::Poll(REAP), AckMode::Local),
    )
    .upstream(
      EdgeId::new(1),
      UpstreamWiring::new(Listen::Poll(COMPACT), AckMode::Local),
    )
}

fn wired(plan: Plan) -> Wired {
  plan.validate().expect("the deployment checks out")
}

/// The mount a refusal names, and the typed error under its erasure.
fn refused<E>(error: &LaunchError) -> (&str, &E)
where
  E: core::error::Error + 'static,
{
  let LaunchError::Wiring { node, error } = error else {
    panic!("a wiring refusal was expected: {error}")
  };
  (
    node.as_str(),
    error
      .source()
      .and_then(|source| source.downcast_ref::<E>())
      .expect("the typed refusal survives its erasure"),
  )
}

#[test]
fn each_node_gets_one_inbox_and_a_second_ask_is_refused_by_name() {
  let wired = wired(pair_plan(DriverKind::Thread));
  let mut wiring = wired.create().wire();

  assert!(
    wiring
      .inbox::<String>(NodeId::new(1))
      .expect("nothing to refuse")
      .is_some()
  );
  let twice = wiring
    .inbox::<String>(NodeId::new(1))
    .expect_err("one inbox per node");
  let (node, taken) = refused::<TakenInboxError>(&twice);
  assert_eq!(node, "titles");
  assert!(taken.inbox().contains("Inbox"), "{}", taken.inbox());
}

#[test]
fn a_node_this_deployment_does_not_launch_has_no_edge_at_all() {
  // The CONSUMER is dark, which is the legal direction: a launched consumer listening to a dark
  // producer is what the validate walk already refused.
  let plan = Plan::new(pair(DriverKind::Thread))
    .with_enablement(Enablement::new().launching("shout"))
    .wiring(NodeId::new(0), NodeWiring::new(Effect::Lands).landing());
  let wired = wired(plan);
  let mut wiring = wired.create().wire();

  assert!(
    wiring
      .inbox::<String>(NodeId::new(1))
      .expect("nothing to refuse")
      .is_none()
  );
  assert!(
    wiring
      .outbox::<String>(NodeId::new(1))
      .expect("nothing to refuse")
      .is_none()
  );
  assert_eq!(wiring.into_assembly().senders(), 0);
}

#[test]
fn the_edge_is_minted_by_whichever_end_reaches_it_first() {
  let wired = wired(pair_plan(DriverKind::Thread));
  let mut wiring = wired.create().wire();

  // The PRODUCER's side first, which is the order a walk that wires an upstream before its
  // downstream takes.
  let outbox = wiring
    .outbox::<String>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let inbox = wiring
    .inbox::<String>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  let (ack, _answers) = ack_channel();
  outbox
    .deliver(Delivery::new(
      Payload::One(Item::new(ItemId::new(0), "one".to_owned())),
      ack,
    ))
    .expect("the consumer is listening");
  assert_eq!(inbox.len(), 1, "the two halves are one edge");
}

#[test]
fn an_edge_asked_for_under_the_wrong_type_names_both_of_them() {
  let wired = wired(pair_plan(DriverKind::Thread));
  let mut wiring = wired.create().wire();

  wiring
    .inbox::<String>(NodeId::new(1))
    .expect("nothing to refuse");
  let mismatch = wiring
    .outbox::<u8>(NodeId::new(1))
    .expect_err("the edge carries strings");
  let (node, error) = refused::<EdgeTypeError>(&mismatch);
  assert_eq!(node, "titles");
  assert!(error.carries().contains("String"), "{}", error.carries());
  assert!(error.wanted().contains("u8"), "{}", error.wanted());
}

#[test]
fn a_data_edge_is_opened_at_the_shipped_capacity_and_backpressures_past_it() {
  let wired = wired(pair_plan(DriverKind::Thread));
  let mut wiring = wired.create().wire();
  let outbox = wiring
    .outbox::<String>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let inbox = wiring
    .inbox::<String>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  // One more than the edge holds, so the last send is the one that has to wait — a bounded edge is
  // backpressure and never a drop.
  let producer = thread::spawn(move || {
    for seq in 0..=Wiring::CAPACITY {
      // The answer half goes nowhere: what this measures is the EDGE's room, and an ack channel
      // with no reader neither takes any nor gives any back.
      let (ack, _answers) = ack_channel();
      if outbox
        .deliver(Delivery::new(
          Payload::One(Item::new(ItemId::new(seq as u64), "one".to_owned())),
          ack,
        ))
        .is_err()
      {
        return;
      }
    }
  });

  let deadline = Instant::now() + Duration::from_secs(10);
  while inbox.len() < Wiring::CAPACITY {
    assert!(
      Instant::now() < deadline,
      "the edge filled to {}",
      inbox.len()
    );
    thread::yield_now();
  }
  assert_eq!(inbox.len(), Wiring::CAPACITY);
  assert!(
    !producer.is_finished(),
    "the delivery past the capacity waits for room"
  );

  drop(inbox);
  producer.join().expect("the producer thread");
}

#[test]
fn a_resident_comes_back_publishing_over_its_declared_channel_edges() {
  let wired = wired(pair_plan(DriverKind::Thread));
  let mut wiring = wired.create().wire();
  let inbox = wiring
    .inbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  let (resident, _enrolled) = wiring
    .resident(NodeId::new(0), Shout, inbox)
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  assert_eq!(resident.name().as_str(), "shout");
  assert_eq!(resident.nudges().len(), 1, "one declared consumer");
  assert!(resident.effect().is_pure(), "what the declaration says");
  assert!(resident.ack().is_local());
}

#[test]
fn the_effect_a_resident_declares_is_the_one_the_plan_wired() {
  let wired = wired(pair_plan(DriverKind::Thread));
  let mut wiring = wired.create().wire();
  let inbox = wiring
    .inbox::<String>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  let (resident, _enrolled) = wiring
    .resident(NodeId::new(1), Shout, inbox)
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  // The leaf lands, and it says so BEFORE a lane is attached — a node whose durability comes from a
  // storage co-subscriber never attaches one at all.
  assert!(resident.effect().is_lands());
  assert_eq!(resident.nudges().len(), 0, "nothing declared downstream");
}

#[test]
fn a_resident_does_not_publish_to_a_consumer_this_deployment_leaves_dark() {
  let plan = Plan::new(pair(DriverKind::Thread))
    .with_enablement(Enablement::new().launching("shout"))
    .wiring(NodeId::new(0), NodeWiring::new(Effect::Lands).landing());
  let wired = wired(plan);
  let mut wiring = wired.create().wire();
  let inbox = wiring
    .inbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  let (resident, _enrolled) = wiring
    .resident(NodeId::new(0), Shout, inbox)
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  assert_eq!(
    resident.nudges().len(),
    0,
    "an enabled producer with a dark consumer has one edge fewer"
  );
}

#[test]
fn only_a_channel_out_edge_is_something_a_resident_sends_over() {
  // The same topology under each of the three non-channel words: a changes listener reads this
  // node's STORE, a poll edge carries no messages, and a transient edge is a door.
  for listen in [
    Listen::Changes(Feeder::InGraph),
    Listen::Poll(Duration::from_millis(5)),
    Listen::Transient,
  ] {
    let plan = pair_plan(DriverKind::Thread)
      .upstream(EdgeId::new(0), UpstreamWiring::new(listen, AckMode::Local))
      .wiring(NodeId::new(0), NodeWiring::new(Effect::Lands).landing());
    let wired = wired(plan);
    let mut wiring = wired.create().wire();
    let inbox = wiring
      .inbox::<String>(NodeId::new(0))
      .expect("nothing to refuse")
      .expect("the deployment launches it");

    let (resident, _enrolled) = wiring
      .resident(NodeId::new(0), Shout, inbox)
      .expect("nothing to refuse")
      .expect("the deployment launches it");
    assert_eq!(resident.nudges().len(), 0, "{listen} is not a send");
  }
}

#[test]
fn the_ack_mode_folds_toward_the_source_that_asked_to_be_chained() {
  let plan = pair_plan(DriverKind::Thread).upstream(
    EdgeId::new(0),
    UpstreamWiring::new(Listen::Channel, AckMode::Chained),
  );
  let wired = wired(plan);
  let mut wiring = wired.create().wire();
  let inbox = wiring
    .inbox::<String>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  let (resident, _enrolled) = wiring
    .resident(NodeId::new(1), Shout, inbox)
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  assert!(
    resident.ack().is_chained(),
    "releasing early would break what the upstream was promised"
  );
}

#[test]
fn a_poll_source_carries_an_ack_word_nothing_reads() {
  // The poll edge's `Chained` is not folded in: a tick moves no items, so there is no window for it
  // to be a claim about.
  let plan = pair_plan(DriverKind::Thread)
    .upstream(
      EdgeId::new(0),
      UpstreamWiring::new(Listen::Poll(Duration::from_millis(5)), AckMode::Chained),
    )
    .wiring(NodeId::new(0), NodeWiring::new(Effect::Lands).landing());
  let wired = wired(plan);
  let mut wiring = wired.create().wire();
  let inbox = wiring
    .inbox::<String>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  let (resident, _enrolled) = wiring
    .resident(NodeId::new(1), Shout, inbox)
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  assert!(resident.ack().is_local());
}

#[test]
fn every_resident_the_walk_builds_observes_through_the_taps_it_was_assembled_with() {
  let wired = wired(pair_plan(DriverKind::Thread));
  let mut wiring = wired.create().wire().with_taps(
    Taps::new()
      .with(Arc::new(RecordingTap::new()))
      .with(Arc::new(RecordingTap::new())),
  );
  assert_eq!(wiring.taps().len(), 2);
  let inbox = wiring
    .inbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  let (resident, _enrolled) = wiring
    .resident(NodeId::new(0), Shout, inbox)
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  assert_eq!(resident.taps().len(), 2);
}

#[test]
fn a_body_that_will_be_running_is_a_party_the_shutdown_waits_for() {
  let wired = wired(pair_plan(DriverKind::Thread));
  let mut wiring = wired.create().wire();
  for index in [0, 1] {
    let inbox = wiring
      .inbox::<String>(NodeId::new(index))
      .expect("nothing to refuse")
      .expect("the deployment launches it");
    wiring
      .resident(NodeId::new(index), Shout, inbox)
      .expect("nothing to refuse")
      .expect("the deployment launches it");
  }

  let assembly = wiring.into_assembly();
  assert_eq!(assembly.shutdown().len(), 2, "N is exact at wiring");
  let named: Vec<&str> = assembly
    .shutdown()
    .parties()
    .iter()
    .map(|party| party.name().as_str())
    .collect();
  assert_eq!(named, ["shout", "titles"]);
}

#[test]
fn the_schedule_a_node_runs_on_is_read_off_its_declared_poll_sources() {
  let wired = wired(reaper_plan(DriverKind::Async));
  let wiring = wired.create().wire();

  let schedule = wiring.schedule(NodeId::new(2));
  assert_eq!(schedule.len(), 2, "one entry per declared poll upstream");
  assert_eq!(
    schedule.interval(PollUpstream::new(0)),
    Some(REAP),
    "declaration order is what a poll upstream's position means"
  );
  assert_eq!(schedule.interval(PollUpstream::new(1)), Some(COMPACT));
  assert!(
    wiring.schedule(NodeId::new(0)).is_empty(),
    "a node that declared none has none"
  );
}

#[test]
fn a_channel_source_is_not_a_clock() {
  let wired = wired(pair_plan(DriverKind::Async));
  let wiring = wired.create().wire();
  assert!(wiring.schedule(NodeId::new(1)).is_empty());
}

#[test]
fn a_thread_node_needs_no_cadence_because_it_times_itself() {
  let wired = wired(reaper_plan(DriverKind::Thread));
  let mut wiring = wired.create().wire();
  assert_eq!(
    wiring.schedule(NodeId::new(2)).len(),
    2,
    "it declared the upstreams all the same"
  );
  let clocks = wiring
    .clock::<String>(NodeId::new(2), Duration::from_secs(1))
    .expect("nothing to refuse");
  assert_eq!(clocks, 0);
  assert!(wiring.into_assembly().cadences().is_empty());
}

#[test]
fn an_async_node_gets_one_cadence_per_poll_source_and_one_for_the_sweep() {
  let wired = wired(reaper_plan(DriverKind::Async));
  let mut wiring = wired.create().wire();
  let clocks = wiring
    .clock::<String>(NodeId::new(2), Duration::from_secs(1))
    .expect("nothing to refuse");
  assert_eq!(clocks, 3, "two declared upstreams plus the liveness floor");

  let mut assembly = wiring.into_assembly();
  let cadences = assembly.take_cadences();
  let intervals: Vec<Duration> = cadences
    .iter()
    .map(|cadence| {
      cadence
        .until_next()
        .expect("an interval is always due again")
    })
    .collect();
  assert_eq!(intervals, [REAP, COMPACT, Duration::from_secs(1)]);
  assert!(assembly.cadences().is_empty(), "taken, not copied");
}

#[test]
fn an_async_node_this_deployment_leaves_dark_gets_no_clock() {
  let plan = Plan::new(pair(DriverKind::Async))
    .with_enablement(Enablement::new().launching("shout"))
    .wiring(NodeId::new(0), NodeWiring::new(Effect::Lands).landing());
  let wired = wired(plan);
  let mut wiring = wired.create().wire();
  assert_eq!(
    wiring
      .clock::<String>(NodeId::new(1), Duration::from_secs(1))
      .expect("nothing to refuse"),
    0
  );
}

#[test]
fn the_assembly_holds_the_edges_open_until_it_closes_them() {
  let wired = wired(pair_plan(DriverKind::Thread));
  let mut wiring = wired.create().wire();
  let inbox = wiring
    .inbox::<String>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let mut assembly = wiring.into_assembly();

  assert_eq!(assembly.senders(), 1);
  assert!(
    !inbox.is_disconnected(),
    "a body with no producer must not stop before it starts"
  );

  assembly.close();
  assert_eq!(assembly.senders(), 0);
  assert!(
    inbox.is_disconnected(),
    "closing the framework's own halves is the wave's first domino"
  );
}

#[test]
fn an_edge_nobody_took_a_reader_from_is_an_edge_this_deployment_does_not_have() {
  let wired = wired(pair_plan(DriverKind::Thread));
  let mut wiring = wired.create().wire();
  // A producer's side, and no consumer body ever built: the wire is dropped whole rather than kept
  // as a sender into nothing.
  let outbox = wiring
    .outbox::<String>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let assembly = wiring.into_assembly();

  assert_eq!(assembly.senders(), 0);
  assert!(outbox.is_disconnected());
}

#[test]
fn a_query_door_is_the_same_two_halves_over_a_transient_edge() {
  let plan = pair_plan(DriverKind::Thread)
    .upstream(
      EdgeId::new(0),
      UpstreamWiring::new(Listen::Transient, AckMode::Local),
    )
    .wiring(NodeId::new(0), NodeWiring::new(Effect::Lands).landing());
  let wired = wired(plan);
  let mut wiring = wired.create().wire();

  let door = wiring
    .door::<String, u8>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let invokes = wiring
    .invokes::<String, u8>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  let _awaiting = door.invoke("ask".to_owned()).expect("the arm is listening");
  assert_eq!(invokes.len(), 1);

  let twice = wiring
    .invokes::<String, u8>(NodeId::new(1))
    .expect_err("one transient inbox per node");
  let (node, taken) = refused::<TakenInboxError>(&twice);
  assert_eq!(node, "titles");
  assert!(taken.inbox().contains("Invokes"), "{}", taken.inbox());
}

#[test]
fn a_door_asked_for_under_the_wrong_pair_of_types_names_both() {
  let plan = pair_plan(DriverKind::Thread)
    .upstream(
      EdgeId::new(0),
      UpstreamWiring::new(Listen::Transient, AckMode::Local),
    )
    .wiring(NodeId::new(0), NodeWiring::new(Effect::Lands).landing());
  let wired = wired(plan);
  let mut wiring = wired.create().wire();

  wiring
    .door::<String, u8>(NodeId::new(1))
    .expect("nothing to refuse");
  let mismatch = wiring
    .invokes::<String, u16>(NodeId::new(1))
    .expect_err("the door answers with a u8");
  let (_node, error) = refused::<EdgeTypeError>(&mismatch);
  assert!(error.carries().contains("u8"), "{}", error.carries());
  assert!(error.wanted().contains("u16"), "{}", error.wanted());
}

#[test]
fn a_door_and_a_data_edge_on_one_node_are_two_edges() {
  let wired = wired(pair_plan(DriverKind::Thread));
  let mut wiring = wired.create().wire();
  let _inbox = wiring
    .inbox::<String>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let _invokes = wiring
    .invokes::<String, u8>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  // The read-path law as arithmetic: an indexing batch has no way to be queued in front of a query,
  // because the two are not the same channel.
  assert_eq!(wiring.into_assembly().senders(), 2);
}

#[test]
fn a_party_that_is_not_a_node_enrols_through_the_same_door() {
  let wired = wired(pair_plan(DriverKind::Thread));
  let mut wiring = wired.create().wire();
  let intake = wiring.enrol("shout/intake");
  assert_eq!(wiring.shutdown().len(), 1);

  let assembly = wiring.into_assembly();
  assert!(!assembly.shutdown().parties()[0].settled());
  intake.settle();
  assert!(assembly.shutdown().parties()[0].settled());
}

#[test]
fn the_walk_carries_the_context_the_create_walk_filled() {
  let wired = wired(pair_plan(DriverKind::Thread));
  let wiring = wired.create().wire();
  assert!(wiring.context().is_empty(), "this plan demands no resource");
  assert_eq!(wiring.into_assembly().context().len(), 0);
}

#[test]
fn the_two_capacities_are_shipped_constants_and_the_door_is_the_shallower_one() {
  // The values are v1's whole capacity story; the claim is about the RELATION, which is the fact
  // the two constants' notes state: a door's depth is a queue of callers who are all waiting.
  //
  // Pinned at COMPILE time, because both sides are `const` — a build that broke the relation would
  // not have to be run to be wrong.
  const {
    assert!(Wiring::CAPACITY > 0);
    assert!(Wiring::DOOR_CAPACITY > 0);
    assert!(Wiring::DOOR_CAPACITY < Wiring::CAPACITY);
  }
}

#[test]
fn an_operator_whose_types_are_not_the_edge_s_is_refused_at_the_wiring() {
  let wired = wired(pair_plan(DriverKind::Thread));
  let mut wiring = wired.create().wire();
  // `shout` publishes strings, and its consumer's edge was minted for bytes: the two ends of one
  // edge are one type, and an emission reading both off the same declarations cannot spell this.
  wiring
    .outbox::<u8>(NodeId::new(1))
    .expect("nothing to refuse");
  let inbox = wiring
    .inbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  let Err(mismatch) = wiring.resident(NodeId::new(0), Shout, inbox) else {
    panic!("its consumer's edge carries bytes")
  };
  let (node, error) = refused::<EdgeTypeError>(&mismatch);
  assert_eq!(node, "titles", "the edge that did not fit");
  assert!(error.carries().contains("u8"));
  assert!(error.wanted().contains("String"));
}

#[test]
fn the_walk_hands_back_an_assembly_that_runs() {
  // THE WHOLE STAGE, spent the way the ignition round will spend it: both edges minted by the walk,
  // both residents wired from the declaration, both bodies enrolled — and then started, fed, and
  // closed. Nothing here is hand-connected: the only handle this test holds is the head's own
  // sending half, which is what a upstream would deliver through.
  let seen = Arc::new(Mutex::new(Vec::new()));
  let wired = wired(pair_plan(DriverKind::Thread));
  let mut wiring = wired.create().wire();

  let head_inbox = wiring
    .inbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let leaf_inbox = wiring
    .inbox::<String>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let feed = wiring
    .outbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  let (mut head, head_party) = wiring
    .resident(NodeId::new(0), Shout, head_inbox)
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let (mut leaf, leaf_party) = wiring
    .resident(NodeId::new(1), Keeping { seen: seen.clone() }, leaf_inbox)
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let mut assembly = wiring.into_assembly();

  // The ignition's own shape: run the body, and fire its enrolment when the loop returns.
  let head_engine = thread::spawn(move || {
    let report = head.run();
    head_party.settle();
    report
  });
  let leaf_engine = thread::spawn(move || {
    let report = leaf.run();
    leaf_party.settle();
    report
  });

  let (ack, _answers) = ack_channel();
  feed
    .deliver(Delivery::new(
      Payload::One(Item::new(ItemId::new(0), "one".to_owned())),
      ack,
    ))
    .expect("the head is listening");

  // Closing the framework's halves is the whole of the shutdown this stage can perform: the head
  // drains what is queued, exits, and its own outbox goes with it — which is what the leaf sees.
  drop(feed);
  assembly.close();

  let head_report = head_engine.join().expect("the head's engine");
  let leaf_report = leaf_engine.join().expect("the leaf's engine");

  assert_eq!(head_report.items(), 1);
  assert_eq!(
    leaf_report.items(),
    1,
    "the edge the walk minted carried it"
  );
  assert_eq!(*seen.lock().expect("the walk's record"), ["ONE"]);
  assert!(
    assembly.shutdown().parties().iter().all(Party::settled),
    "every party the walk counted answered"
  );
}

#[test]
fn a_second_operator_type_is_wired_the_same_way() {
  // Nothing here is about strings: the walk is generic over what an edge carries, and this is the
  // claim that its steps do not quietly assume one item type.
  let mut builder = GraphBuilder::new();
  let counter = builder.source::<Counting>("counter", DriverKind::Thread);
  let sink = builder.node::<Counting>("sink", DriverKind::Thread);
  builder.edge(&counter, &sink, FanoutKind::Broadcast);
  let graph = builder.validate().expect("one edge validates");
  let wired = wired(
    Plan::new(graph)
      .with_enablement(Enablement::new().launching("counter").launching("sink"))
      .wiring(NodeId::new(1), NodeWiring::new(Effect::Lands).landing()),
  );

  let mut wiring = wired.create().wire();
  let inbox = wiring
    .inbox::<u8>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let (resident, _enrolled) = wiring
    .resident(NodeId::new(0), Counting, inbox)
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  assert_eq!(resident.nudges().len(), 1);
}

/// A resource nothing on the hot path would hold as a field — the runtime door's poster case.
struct Vocabulary {
  banner: String,
}

impl AsyncResource for Vocabulary {
  type Error = Infallible;
  type Options = String;

  async fn build(_ctx: &Resources, banner: String) -> Result<Self, Self::Error> {
    Ok(Self { banner })
  }
}

/// Reaches for a shared resource INSIDE `accept`, which is the door under test.
struct Announcing;

declared!(Announcing);

impl Operator for Announcing {
  type Error = Infallible;
  type In = String;
  type Out = String;

  fn accept(
    &mut self,
    ctx: &Context,
    delivery: Delivery<Self::In>,
    emitter: &mut Emitter<String>,
  ) -> Result<(), Self::Error> {
    // Not held as a field, which is the whole point: an occasional need reaches through the door
    // rather than making the declaration carry a demand for it.
    let banner = ctx
      .shared::<Vocabulary>()
      .expect("the launch built one")
      .banner
      .clone();
    for item in delivery.into_items() {
      emitter.emit(format!("{banner}{}", item.into_value()));
    }
    Ok(())
  }
}

#[test]
fn an_operator_reaches_the_launch_s_resources_from_inside_accept() {
  // THE RUNTIME DOOR, through the real walk: the map is the one the create walk filled, the wiring
  // hands every node the same one, and `ctx.shared::<R>()` inside `accept` finds it.
  let wired = wired(pair_plan(DriverKind::Thread));
  let ctx = Resources::new().with(Shared::new(Vocabulary {
    banner: ">> ".to_owned(),
  }));
  let mut wiring = Wiring::new(&wired, ctx, Taps::new());

  let head = wiring
    .inbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let leaf = wiring
    .inbox::<String>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let feed = wiring
    .outbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  let (head, _head_party) = wiring
    .resident(NodeId::new(0), Announcing, head)
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let seen: Arc<Mutex<Vec<String>>> = Arc::default();
  let (leaf, _leaf_party) = wiring
    .resident(NodeId::new(1), Keeping { seen: seen.clone() }, leaf)
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  assert!(
    head
      .resources()
      .expect("the walk wired its map")
      .holds::<Vocabulary>(),
    "every node gets the ONE map"
  );
  // The walk keeps a sender per edge, so it has to go before a shutdown-by-disconnect can finish.
  drop(wiring);

  let engines = [
    thread::spawn(move || {
      let mut head = head;
      head.run();
    }),
    thread::spawn(move || {
      let mut leaf = leaf;
      leaf.run();
    }),
  ];

  let (ack, _answers) = ack_channel();
  feed
    .deliver(Delivery::new(
      Payload::One(Item::new(ItemId::new(0), "one".to_owned())),
      ack,
    ))
    .expect("the head is listening");
  drop(feed);

  for engine in engines {
    engine.join().expect("the engine thread");
  }
  assert_eq!(
    seen.lock().expect("the walk's record").as_slice(),
    [">> one".to_owned()],
    "the banner came from the resource the operator asked for mid-call"
  );
}

#[test]
fn a_resident_with_no_map_refuses_by_name_rather_than_silently() {
  // The absence, from the operator's side: no `R` is reachable, and the refusal says which.
  let ctx = Resources::new();
  assert_eq!(
    ctx
      .shared::<Vocabulary>()
      .expect_err("nothing built one")
      .resource()
      .as_str(),
    core::any::type_name::<Vocabulary>()
  );
}

/// `left → sink` and `right → sink`, both CHANNEL — two producers at one consumer, which is either
/// a fan-in or a node drawing its upstreams apart, and only the declaration says which.
fn two_producers(apart: bool) -> Plan {
  let mut builder = GraphBuilder::new();
  let left = builder.source::<Shout>("left", DriverKind::Thread);
  let right = builder.source::<Shout>("right", DriverKind::Thread);
  let sink = builder.node::<Shout>("sink", DriverKind::Thread);
  builder.edge(&left, &sink, FanoutKind::Broadcast);
  builder.edge(&right, &sink, FanoutKind::Broadcast);
  let graph = builder.validate().expect("two edges validate");

  let declared = NodeWiring::new(Effect::Lands).landing();
  Plan::new(graph)
    .with_enablement(
      Enablement::new()
        .launching("left")
        .launching("right")
        .launching("sink"),
    )
    .wiring(
      NodeId::new(2),
      if apart { declared.drawing() } else { declared },
    )
}

/// Put `said` on `outbox` as one delivery, keeping nothing: these tests read the far end.
fn put(outbox: &crate::Outbox<ItemId, String>, said: &str) {
  let (ack, _answers) = ack_channel::<ItemId>();
  outbox
    .deliver(Delivery::new(
      Payload::One(Item::new(ItemId::new(0), said.to_owned())),
      ack,
    ))
    .map_err(|_| "the consumer is here")
    .expect("delivered");
}

/// What is queued on `inbox`, in arrival order.
fn queued(inbox: &crate::Inbox<ItemId, String>) -> Vec<String> {
  inbox
    .drain()
    .filter_map(|wake| match wake {
      crate::Wake::Delivered(delivery) => Some(delivery),
      crate::Wake::Sweep | crate::Wake::Tick(_) => None,
    })
    .flat_map(|delivery| delivery.into_items())
    .map(Item::into_value)
    .collect()
}

#[test]
fn a_source_position_is_the_place_among_the_consumer_s_channel_edges() {
  let wired = wired(two_producers(true));
  let wiring = wired.create().wire();
  let sink = NodeId::new(2);
  assert_eq!(wiring.source_of(sink, EdgeId::new(0)), Some(0));
  assert_eq!(wiring.source_of(sink, EdgeId::new(1)), Some(1));
  // An edge that is not this consumer's is not one of its upstreams.
  assert_eq!(wiring.source_of(NodeId::new(0), EdgeId::new(0)), None);
}

#[test]
fn a_poll_edge_takes_no_source_position_because_it_delivers_nothing() {
  // The same rule the ack fold reads by: only a CHANNEL edge is a upstream anything arrives on, so a
  // poll edge is not a slot and does not shift a neighbour's.
  let wired = wired(reaper_plan(DriverKind::Thread));
  let wiring = wired.create().wire();
  let reaper = NodeId::new(2);
  assert_eq!(wiring.source_of(reaper, EdgeId::new(0)), None);
  assert_eq!(wiring.source_of(reaper, EdgeId::new(1)), None);
}

#[test]
fn a_node_that_draws_apart_takes_each_producer_on_its_own_edge() {
  let wired = wired(two_producers(true));
  let mut wiring = wired.create().wire();
  let sink = NodeId::new(2);

  let first = wiring
    .source_inbox::<String>(sink, 0)
    .expect("nothing to refuse")
    .expect("launched");
  let second = wiring
    .source_inbox::<String>(sink, 1)
    .expect("nothing to refuse")
    .expect("launched");
  assert!(
    wiring.source_inbox::<String>(sink, 0).is_err(),
    "one receiver per upstream, exactly as one per node"
  );

  let mut residents = Vec::new();
  let mut senders = Vec::new();
  for producer in [NodeId::new(0), NodeId::new(1)] {
    senders.push(
      wiring
        .outbox::<String>(producer)
        .expect("nothing to refuse")
        .expect("launched"),
    );
    let inbox = wiring
      .inbox::<String>(producer)
      .expect("nothing to refuse")
      .expect("launched");
    let (resident, _enrolled) = wiring
      .resident(producer, Shout, inbox)
      .expect("nothing to refuse")
      .expect("launched");
    residents.push(resident);
  }
  // The walk keeps a sender per edge, so nothing shuts down while it is alive.
  drop(wiring);

  for (resident, sender) in residents.into_iter().zip(senders) {
    let said = if resident.name().as_str() == "left" {
      "from-left"
    } else {
      "from-right"
    };
    put(&sender, said);
    drop(sender);
    let mut resident = resident;
    resident.run();
  }

  assert_eq!(queued(&first), ["FROM-LEFT"]);
  assert_eq!(
    queued(&second),
    ["FROM-RIGHT"],
    "and nothing of the other upstream's, which is the whole of what per-upstream channels buy"
  );
}

#[test]
fn a_fan_in_node_still_takes_every_producer_on_one_inbox() {
  // The zero-churn half: without the word, two producers of ONE message type meet on one edge, and
  // that is what nearly every node in an arrangement is.
  let wired = wired(two_producers(false));
  let mut wiring = wired.create().wire();
  let only = wiring
    .inbox::<String>(NodeId::new(2))
    .expect("nothing to refuse")
    .expect("launched");

  let mut residents = Vec::new();
  let mut senders = Vec::new();
  for producer in [NodeId::new(0), NodeId::new(1)] {
    senders.push(
      wiring
        .outbox::<String>(producer)
        .expect("nothing to refuse")
        .expect("launched"),
    );
    let inbox = wiring
      .inbox::<String>(producer)
      .expect("nothing to refuse")
      .expect("launched");
    let (resident, _enrolled) = wiring
      .resident(producer, Shout, inbox)
      .expect("nothing to refuse")
      .expect("launched");
    residents.push(resident);
  }
  drop(wiring);

  for (resident, sender) in residents.into_iter().zip(senders) {
    put(&sender, "said");
    drop(sender);
    let mut resident = resident;
    resident.run();
  }

  assert_eq!(
    queued(&only).len(),
    2,
    "both producers meet on the one inbox a fan-in node has always had"
  );
}

/// A root family's key, for the threading proof below — the shape an emitted root projection names.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct MediaId(u64);

/// **THE THREADING**, end to end: the walk hands its registries to every resident it builds, and
/// the running world hands out the SAME object — which is what makes a count a resident makes and a
/// retirement a command face asks for two views of one table.
///
/// The identity is proved by a family rather than by a pointer, because a family is what identity
/// MEANS here: one opened through the resident's handle and read back through the world's is one
/// table, and two `Registries` values could not answer that way.
#[test]
fn the_walk_hands_its_registries_to_the_residents_and_to_the_running_world() {
  let quiet = Duration::from_millis(7);
  let wired = wired(pair_plan(DriverKind::Thread));
  let registries = Arc::new(crate::Registries::new(
    crate::RegistryOptions::new().with_debounce(quiet),
  ));
  let mut wiring = wired
    .create()
    .wire()
    .with_registries(Arc::clone(&registries));
  assert!(Arc::ptr_eq(wiring.registries(), &registries));

  let upstream = wiring
    .inbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let (resident, _enrolled) = wiring
    .resident(NodeId::new(0), Shout, upstream)
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  // The resident is holding the DEPLOYMENT's tables, tuned by the document it was built from.
  let held = resident.registries().expect("the walk wired one");
  assert_eq!(held.options().debounce(), quiet);
  let opened = held.open::<MediaId>("media");
  assert_eq!(opened.options().debounce(), quiet);
  assert_eq!(
    opened.retire(&MediaId(1), crate::RetireOrigin::User, crate::Stamp::now()),
    crate::RootAdvance::Moved
  );

  let assembly = wiring.into_assembly();
  assert!(Arc::ptr_eq(assembly.registries(), &registries));
  let app = assembly.ignite().into_app::<()>();

  // And the running world hands out the very family the resident opened, holding what it wrote.
  let seen = app
    .registries()
    .of::<MediaId>()
    .expect("the world's tables are the resident's");
  assert!(Arc::ptr_eq(&opened, &seen));
  assert!(matches!(
    seen.state(&MediaId(1)),
    crate::RootState::Retired {
      origin: crate::RetireOrigin::User,
      ..
    }
  ));
  drop(app.abort());
}

/// A walk that was never told runs the SHIPPED defaults — today's behaviour for a hand-wired
/// arrangement, spelled out.
#[test]
fn a_walk_that_names_no_registries_runs_the_shipped_ones() {
  let wired = wired(pair_plan(DriverKind::Thread));
  let wiring = wired.create().wire();
  assert_eq!(
    wiring.registries().options(),
    &crate::RegistryOptions::new()
  );
  assert!(
    wiring.registries().is_empty(),
    "nothing is open until something opens it"
  );
}

// ---------------------------------------------------------------------------------------------
// the attribution seat, installed by the walk
// ---------------------------------------------------------------------------------------------

/// What the projection below wrote down — a static rather than a handle, because the seat is a TYPE
/// and a type cannot carry one.
///
/// That is the seat's own shape stated as a test fixture: a declaration names a projection the walk
/// builds from nothing, so an attribution that has to hold state is the OTHER road — `.attributing`
/// by hand, which every test above this one takes.
static PROJECTED: Mutex<Vec<String>> = Mutex::new(Vec::new());

/// A projection a DECLARATION can seat: zero-sized, `Default`, and loud enough to prove it ran.
#[derive(Default)]
struct Projecting;

impl crate::Attributes<String> for Projecting {
  type Root = String;

  fn root(&self, record: &String) -> Self::Root {
    PROJECTED
      .lock()
      .expect("the walk's record")
      .push(record.clone());
    record.clone()
  }

  fn observe(&self, _root: &Self::Root, _worker: &crate::NodeName, _arrival: &crate::Arrival) {}
}

/// A node that ATTRIBUTES — the `attributed` word's seat, hand-written, which is the same member the
/// node macros emit.
struct Attributed;

impl crate::Declared for Attributed {
  const EFFECT: crate::Effect = crate::Effect::Pure;

  type Attribution<O> = Projecting;
  type Channels = crate::Unchanneled;
  type Mode = crate::Block;
  type Options = ();
  type Pair = crate::Buffered;
  type Wires<O> = crate::Downstream<O>;
}

impl Operator for Attributed {
  type Error = Infallible;
  type In = String;
  type Out = String;

  fn accept(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    emitter: &mut Emitter<String>,
  ) -> Result<(), Self::Error> {
    for item in delivery.into_items() {
      emitter.emit(item.into_value());
    }
    Ok(())
  }
}

/// **THE SEAT IS INSTALLED BY THE WALK AND SPENT BY THE LOOP.**
///
/// Nothing here calls `attributing`. The node states `Declared::Attribution` and the wiring walk
/// installs what it names — unconditionally, for every node it wires — so what proves the install is
/// the projection being asked for a root as the running body fans an output out. Before the seat,
/// the same declaration produced a resident carrying `()` and this list stayed empty.
#[test]
fn a_declarations_own_projection_reaches_its_running_node() {
  PROJECTED.lock().expect("the walk's record").clear();
  let wired = wired(pair_plan(DriverKind::Thread));
  let mut wiring = wired.create().wire();

  let head = wiring
    .inbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let leaf = wiring
    .inbox::<String>(NodeId::new(1))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let feed = wiring
    .outbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");

  let (head, _head_party) = wiring
    .resident(NodeId::new(0), Attributed, head)
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let seen: Arc<Mutex<Vec<String>>> = Arc::default();
  let (leaf, _leaf_party) = wiring
    .resident(NodeId::new(1), Keeping { seen: seen.clone() }, leaf)
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  drop(wiring);

  let engines = [
    thread::spawn(move || {
      let mut head = head;
      head.run();
    }),
    thread::spawn(move || {
      let mut leaf = leaf;
      leaf.run();
    }),
  ];
  let (ack, _answers) = ack_channel();
  feed
    .deliver(Delivery::new(
      Payload::One(Item::new(ItemId::new(0), "keyframe".to_owned())),
      ack,
    ))
    .expect("the head is listening");
  drop(feed);
  for engine in engines {
    engine.join().expect("the engine thread");
  }

  assert_eq!(
    seen.lock().expect("the walk's record").as_slice(),
    ["keyframe".to_owned()],
    "the output reached the leaf"
  );
  assert_eq!(
    PROJECTED.lock().expect("the walk's record").as_slice(),
    ["keyframe".to_owned()],
    "and the DECLARED projection is what the node attributed it through"
  );
}

/// The other arm, and the reason the install needs no branch: a node that seats `()` is wired by the
/// same one line and carries the empty program, which is what every hand-wired node in this file
/// already does.
#[test]
fn a_declaration_that_seats_nothing_is_wired_by_the_same_line() {
  let wired = wired(pair_plan(DriverKind::Thread));
  let mut wiring = wired.create().wire();
  let inbox = wiring
    .inbox::<String>(NodeId::new(0))
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  let (resident, _party) = wiring
    .resident(NodeId::new(0), Shout, inbox)
    .expect("nothing to refuse")
    .expect("the deployment launches it");
  assert_eq!(resident.name().as_str(), "shout");
}