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
use crate::Context;
use core::time::Duration;

use super::super::{
  AckMode, Effect, Enablement, Feeder, LaunchError, Listen, NodeWiring, Plan, Refusal,
  UpstreamWiring,
};
use crate::{
  ChannelGraph, Delivery, DriverKind, Emitter, FanoutKind, GraphBuilder, NodeId, Operator,
};

macro_rules! node {
  ($name:ident) => {
    struct $name;

    impl Operator for $name {
      type Error = core::convert::Infallible;
      type In = u8;
      type Out = u8;

      fn accept(
        &mut self,
        _ctx: &Context,
        _delivery: Delivery<Self::In>,
        _emitter: &mut Emitter<u8>,
      ) -> Result<(), Self::Error> {
        Ok(())
      }
    }

    /// 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.
    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> = ();
    }
  };
}

node!(Scenes);
node!(Keyframes);
node!(Captions);

/// `scenes → keyframes → captions`, a chain of three.
fn chain() -> ChannelGraph {
  let mut builder = GraphBuilder::new();
  let scenes = builder.source::<Scenes>("scenes", DriverKind::Thread);
  let keyframes = builder.node::<Keyframes>("keyframes", DriverKind::Async);
  let captions = builder.node::<Captions>("captions", DriverKind::Async);
  builder.edge(&scenes, &keyframes, FanoutKind::Broadcast);
  builder.edge(&keyframes, &captions, FanoutKind::Broadcast);
  builder.validate().expect("a chain of three validates")
}

/// The deployment that names EVERY node `graph` declares.
///
/// PRESENCE IS ENABLEMENT, so a test that is not about enablement has to say this out loud: a plan
/// nobody named a node in launches nothing, and a check that is never asked about a node cannot
/// refuse one.
fn everything(graph: &ChannelGraph) -> Enablement {
  graph
    .nodes()
    .iter()
    .fold(Enablement::new(), |enablement, node| {
      enablement.launching(node.name())
    })
}

/// [`everything`], minus the nodes `dark` names — written with no section at all, which is the
/// shape presence-is-enablement gives to "not launched".
fn everything_but(graph: &ChannelGraph, dark: &[&str]) -> Enablement {
  graph
    .nodes()
    .iter()
    .filter(|node| !dark.contains(&node.name()))
    .fold(Enablement::new(), |enablement, node| {
      enablement.launching(node.name())
    })
}

/// The ONE row a plan with a single problem collected.
///
/// The walk collects, so every claim about WHICH refusal a plan earned is also a claim that it
/// earned no other — which is what this reads, and what makes a test that grows a second problem
/// say so instead of quietly passing on the first.
fn only(refused: &LaunchError) -> &Refusal {
  match refused.refusals() {
    [refusal] => refusal,
    rows => panic!(
      "one refusal was expected, and {} came back: {refused}",
      rows.len()
    ),
  }
}

/// A plan over `graph` whose deployment launches the whole catalog.
fn plan(graph: ChannelGraph) -> Plan {
  let enablement = everything(&graph);
  Plan::new(graph).with_enablement(enablement)
}

/// The chain with every node declared as a storing one — each holding its OWN write lane, which is
/// what makes the leaf's landing real and the plan one that passes.
fn landing(graph: ChannelGraph) -> Plan {
  let mut plan = plan(graph);
  for index in 0..3 {
    plan = plan.wiring(NodeId::new(index), NodeWiring::default().landing());
  }
  plan
}

#[test]
fn a_chain_whose_leaf_stores_is_launchable() {
  let wired = landing(chain()).validate().expect("every node lands");
  assert_eq!(wired.running().count(), 3);
  assert!(wired.is_enabled(NodeId::new(0)));
  assert_eq!(
    wired.node(NodeId::new(2)).expect("declared").effect(),
    Effect::Lands
  );
  assert_eq!(wired.graph().nodes().len(), 3);
}

#[test]
fn a_plan_nobody_named_a_node_in_is_the_empty_deployment() {
  // THE CATALOG PRINCIPLE at the plan's own door. The chain's leaf is pure, so under the inverted
  // law — absence meaning enabled — this plan was a pure-leaf refusal. Under the ruled one it is a
  // deployment that runs nothing, which is a legal thing to deploy and has nothing to refuse.
  let wired = Plan::new(chain())
    .validate()
    .expect("a deployment that names nothing launches nothing");
  assert_eq!(wired.running().count(), 0);
  assert!(!wired.is_enabled(NodeId::new(0)));
}

#[test]
fn the_defaults_are_the_records_own() {
  // Pure, channel, local — and the first of those is a default that gets CHECKED.
  let refused = plan(chain()).validate().expect_err("the leaf is pure");
  assert!(only(&refused).is_pure_leaf());

  let wired = landing(chain()).validate().expect("lands");
  let upstream = wired.upstream(crate::EdgeId::new(0)).expect("declared");
  assert_eq!(upstream.listen(), Listen::Channel);
  assert_eq!(upstream.ack(), AckMode::Local);
}

#[test]
fn a_pure_unit_with_nobody_to_publish_to_is_refused_by_name() {
  // THE MUTATION this pins, now that there is an exemption to over-widen: exempt every node — or
  // exempt on the wrong end of the poll edge — and this schedule-less leaf walks through the floor.
  // The exemption is the SCHEDULE, so a node that declared none has nothing to claim it by.
  let mut plan = plan(chain());
  for index in 0..2 {
    plan = plan.wiring(NodeId::new(index), NodeWiring::new(Effect::Lands));
  }
  // `captions` is the leaf and stays pure.
  let refused = plan.validate().expect_err("a pure leaf");
  let payload = only(&refused)
    .try_unwrap_pure_leaf_ref()
    .expect("the pure-leaf arm");
  assert_eq!(payload.name(), "captions");
  assert_eq!(payload.node(), NodeId::new(2));
  let rendered = refused.to_string();
  assert!(rendered.contains("lands nothing"), "{rendered}");
  assert!(rendered.contains("publishes to nobody"), "{rendered}");
  assert!(rendered.contains("polls nothing"), "{rendered}");
}

#[test]
fn a_pure_leaf_with_a_poll_source_is_exempt_because_its_schedule_is_its_observability() {
  // The reaper's own shape: it lands nothing of its own, publishes to nobody, and is perfectly
  // observable — its declared schedule and grants say what it touches, and what it did with them
  // reaches the same taps every other node's work does. Refusing it would refuse the whole
  // maintenance mode.
  let wired = plan(chain())
    .wiring(NodeId::new(0), NodeWiring::new(Effect::Lands))
    .wiring(NodeId::new(1), NodeWiring::new(Effect::Lands))
    .upstream(
      crate::EdgeId::new(1),
      UpstreamWiring::new(Listen::Poll(Duration::from_secs(600)), AckMode::Local),
    )
    .validate()
    .expect("a poll node is observable through its schedule");
  assert!(wired.is_enabled(NodeId::new(2)));
  assert_eq!(
    wired
      .upstream(crate::EdgeId::new(1))
      .expect("declared")
      .listen(),
    Listen::Poll(Duration::from_secs(600))
  );
}

#[test]
fn the_exemption_follows_the_edge_to_the_unit_that_polls_and_not_to_the_one_polled() {
  // `scenes → keyframes` wired as a poll upstream exempts KEYFRAMES, which is the consumer. Wiring
  // the exemption on the producer instead would leave `captions` — the actual pure leaf, whose
  // inbound edge is a plain channel — walking through.
  let refused = plan(chain())
    .wiring(NodeId::new(0), NodeWiring::new(Effect::Lands))
    .upstream(
      crate::EdgeId::new(0),
      UpstreamWiring::new(Listen::Poll(Duration::from_secs(60)), AckMode::Local),
    )
    .validate()
    .expect_err("captions still has no way to be observed");
  assert_eq!(
    only(&refused)
      .try_unwrap_pure_leaf_ref()
      .expect("the pure-leaf arm")
      .name(),
    "captions"
  );
}

#[test]
fn a_poll_source_over_an_unlaunched_upstream_starts_and_runs() {
  // The changes precedent, and the reaper's own reason for existing: collecting a dead node's
  // garbage is exactly the work that outlives the node, so a schedule over something nobody
  // launched is the intended case rather than an oversight.
  let graph = chain();
  let enablement = everything_but(&graph, &["keyframes"]);
  let wired = landing(graph)
    .upstream(
      crate::EdgeId::new(1),
      UpstreamWiring::new(Listen::Poll(Duration::from_secs(600)), AckMode::Local),
    )
    .with_enablement(enablement)
    .validate()
    .expect("reaping does not need the dead alive");
  assert!(wired.is_enabled(NodeId::new(2)));
  assert!(!wired.is_enabled(NodeId::new(1)));
}

#[test]
fn a_poll_source_mixes_with_the_other_two_words_in_one_fan_in() {
  let mut builder = GraphBuilder::new();
  let scenes = builder.source::<Scenes>("scenes", DriverKind::Thread);
  let ocr = builder.source::<Keyframes>("ocr", DriverKind::Thread);
  let expiry = builder.source::<Keyframes>("expiry", DriverKind::Thread);
  let reaper = builder.node::<Captions>("reaper", DriverKind::Async);
  builder.edge(&scenes, &reaper, FanoutKind::Broadcast);
  builder.edge(&ocr, &reaper, FanoutKind::Broadcast);
  builder.edge(&expiry, &reaper, FanoutKind::Broadcast);
  let graph = builder.validate().expect("a fan-in of three validates");

  let wired = plan(graph)
    .wiring(NodeId::new(0), NodeWiring::new(Effect::Lands))
    .wiring(NodeId::new(1), NodeWiring::new(Effect::Lands))
    .wiring(NodeId::new(2), NodeWiring::new(Effect::Lands))
    .upstream(
      crate::EdgeId::new(1),
      UpstreamWiring::new(Listen::Changes(Feeder::InGraph), AckMode::Local),
    )
    .upstream(
      crate::EdgeId::new(2),
      UpstreamWiring::new(Listen::Poll(Duration::from_secs(10)), AckMode::Local),
    )
    .validate()
    .expect("three words, one fan-in");
  let words: Vec<&'static str> = (0..3)
    .map(|edge| {
      wired
        .upstream(crate::EdgeId::new(edge))
        .expect("declared")
        .listen()
        .as_str()
    })
    .collect();
  assert_eq!(words, ["channel", "changes", "poll"]);
}

#[test]
fn a_pure_unit_that_publishes_is_fine() {
  // The refusal is about a LEAF, not about purity: `keyframes` is pure and has a consumer.
  let plan = plan(chain())
    .wiring(NodeId::new(0), NodeWiring::new(Effect::Lands))
    .wiring(NodeId::new(2), NodeWiring::default().landing());
  assert!(plan.validate().is_ok());
}

#[test]
fn a_section_naming_a_unit_that_does_not_exist_refuses_at_start_up() {
  let graph = chain();
  let enablement = everything(&graph).launching("keyfrmaes");
  let refused = landing(graph)
    .with_enablement(enablement)
    .validate()
    .expect_err("a misspelling");
  assert_eq!(
    only(&refused)
      .try_unwrap_unknown_node_ref()
      .expect("the unknown-node arm")
      .name(),
    "keyfrmaes"
  );
  assert!(refused.to_string().contains("does not declare"));
}

#[test]
fn the_unknown_key_is_reported_before_anything_else_is_judged() {
  // A misspelled key is the first thing a reader has to know about: everything after it describes
  // the deployment as literally written, in which the node the typo meant to name is absent.
  let refused = plan(chain())
    .with_enablement(Enablement::new().launching("nope"))
    .validate()
    .expect_err("the key");
  // FIRST, and beside whatever else the deployment as written has wrong.
  assert!(refused.refusals()[0].is_unknown_node(), "{refused}");
}

#[test]
fn a_unit_that_says_it_lands_with_no_lane_and_no_consumer_is_refused_by_name() {
  // THE RULED ROW. `captions` is the leaf: it declares that it lands, holds no write lane of its
  // own, and has nobody to publish to — so its ack would answer *persisted* over a write that
  // happens nowhere.
  let refused = plan(chain())
    .wiring(NodeId::new(0), NodeWiring::new(Effect::Lands))
    .wiring(NodeId::new(1), NodeWiring::new(Effect::Lands))
    .wiring(NodeId::new(2), NodeWiring::new(Effect::Lands))
    .validate()
    .expect_err("the leaf lands nowhere");
  let payload = only(&refused)
    .try_unwrap_lands_nowhere_ref()
    .expect("the lands-nowhere arm");
  assert_eq!(payload.name(), "captions");
  assert_eq!(payload.node(), NodeId::new(2));
  let rendered = refused.to_string();
  assert!(rendered.contains("declares that it lands"), "{rendered}");
  assert!(rendered.contains("give it a lane of its own"), "{rendered}");
  assert!(
    rendered.contains("a consumer that lands what it emits"),
    "{rendered}"
  );
}

#[test]
fn a_lane_and_a_consumer_are_each_enough_on_their_own() {
  // The two postures the effect is reached by, and the difference is WHOSE write. THE MUTATION
  // this pins: demand a lane of every landing node and the co-subscriber posture — `keyframes`
  // here, whose storage neighbour does the writing — is refused, which is the arrangement
  // mediagraph actually runs.
  let wired = plan(chain())
    .wiring(NodeId::new(0), NodeWiring::new(Effect::Lands))
    .wiring(NodeId::new(1), NodeWiring::new(Effect::Lands))
    .wiring(NodeId::new(2), NodeWiring::default().landing())
    .validate()
    .expect("a lane at the leaf, a consumer at the hop before it");
  assert!(!wired.node(NodeId::new(1)).expect("declared").holds_lane());
  assert!(wired.node(NodeId::new(2)).expect("declared").holds_lane());
}

#[test]
fn holding_a_lane_declares_the_effect_rather_than_asking_for_it() {
  // One fact, one place: a node holding a write lane lands by construction, so the builder sets
  // the effect and a wiring that says it holds a lane cannot also say it is pure.
  let wiring = NodeWiring::default().landing();
  assert_eq!(wiring.effect(), Effect::Lands);
  assert!(wiring.holds_lane());
  assert!(!wiring.answers());
  // And it composes: a node that stores may answer questions too.
  let both = NodeWiring::answering(Effect::Pure).landing();
  assert_eq!(both.effect(), Effect::Lands);
  assert!(both.holds_lane() && both.answers());
  // A plain wiring holds none.
  assert!(!NodeWiring::new(Effect::Lands).holds_lane());
}

#[test]
fn the_walk_collects_every_refusal_before_it_reports_one() {
  // THE RULED LAW, and the mutation it pins: return at the first check that fails and this
  // deployment is fixed one restart at a time. Three independent things are wrong here — a key
  // naming nothing, a leaf nobody can observe, and a listener whose upstream is not launched — and
  // the operator is told all three at once.
  let graph = chain();
  let enablement = everything_but(&graph, &["keyframes"]).launching("keyfrmaes");
  let refused = Plan::new(graph)
    .wiring(NodeId::new(0), NodeWiring::new(Effect::Lands))
    .wiring(NodeId::new(1), NodeWiring::new(Effect::Lands))
    .with_enablement(enablement)
    .validate()
    .expect_err("three things at once");

  let rows = refused.refusals();
  assert_eq!(rows.len(), 3, "{refused}");
  // The walk's order is a reading order: the name that names nothing first, because every row
  // after it describes the deployment as literally written.
  assert!(rows[0].is_unknown_node(), "{refused}");
  assert!(rows[1].is_pure_leaf(), "{refused}");
  assert!(rows[2].is_disabled_upstream(), "{refused}");

  let rendered = refused.to_string();
  assert!(rendered.contains("3 thing(s) to fix"), "{rendered}");
  assert!(rendered.contains("keyfrmaes"), "{rendered}");
  assert!(rendered.contains("lands nothing"), "{rendered}");
  assert!(rendered.contains("listen to its changes"), "{rendered}");
}

#[test]
fn the_names_that_name_nothing_come_out_in_a_stable_order() {
  // A report is read by a human and diffed by a machine, and neither is served by a list whose
  // order is a hash map's. THE MUTATION: drop the sort and this passes about half the time.
  let graph = chain();
  let enablement = everything(&graph)
    .launching("zebra")
    .launching("aardvark")
    .launching("mongoose");
  let refused = landing(graph)
    .with_enablement(enablement)
    .validate()
    .expect_err("three names name nothing");
  let named: Vec<&str> = refused
    .refusals()
    .iter()
    .filter_map(|refusal| refusal.try_unwrap_unknown_node_ref().ok())
    .map(super::UnknownNodeError::name)
    .collect();
  assert_eq!(named, ["aardvark", "mongoose", "zebra"]);
}

#[test]
fn a_unit_the_options_do_not_name_simply_does_not_run() {
  let graph = chain();
  let enablement = everything_but(&graph, &["captions"]);
  let wired = landing(graph)
    .with_enablement(enablement)
    .validate()
    .expect("nothing listens to captions");
  assert_eq!(
    wired.running().collect::<Vec<_>>(),
    [NodeId::new(0), NodeId::new(1)]
  );
  assert!(!wired.is_enabled(NodeId::new(2)));
}

#[test]
fn a_channel_listener_on_an_unlaunched_upstream_is_refused_by_both_names() {
  let graph = chain();
  let enablement = everything_but(&graph, &["keyframes"]);
  let refused = landing(graph)
    .with_enablement(enablement)
    .validate()
    .expect_err("captions would starve");
  let payload = only(&refused)
    .try_unwrap_disabled_upstream_ref()
    .expect("the disabled-upstream arm");
  assert_eq!(payload.consumer_name(), "captions");
  assert_eq!(payload.producer_name(), "keyframes");
  assert_eq!(payload.edge(), crate::EdgeId::new(1));
  let rendered = refused.to_string();
  assert!(rendered.contains("captions"), "{rendered}");
  assert!(rendered.contains("keyframes"), "{rendered}");
  assert!(rendered.contains("no section names it"), "{rendered}");
  assert!(
    rendered.contains("listen to its changes instead"),
    "{rendered}"
  );
}

#[test]
fn a_changes_listener_on_an_unlaunched_upstream_is_legal_and_drains_the_store() {
  // The reindex posture: the upstream writes nothing, and the rows it already wrote are still
  // there. This is the one case the two-mode design exists for, so it must not be a refusal.
  let graph = chain();
  let enablement = everything_but(&graph, &["keyframes"]);
  let wired = landing(graph)
    .upstream(
      crate::EdgeId::new(1),
      UpstreamWiring::new(Listen::Changes(Feeder::InGraph), AckMode::Local),
    )
    .with_enablement(enablement)
    .validate()
    .expect("a changes listener may consume an unlaunched upstream's store");
  assert!(wired.is_enabled(NodeId::new(2)));
  assert!(!wired.is_enabled(NodeId::new(1)));
  assert_eq!(
    wired
      .upstream(crate::EdgeId::new(1))
      .expect("declared")
      .listen(),
    Listen::Changes(Feeder::InGraph)
  );
}

#[test]
fn an_unlaunched_consumer_is_not_asked_about_its_upstream() {
  // Both ends dark: there is nobody to starve, so there is nothing to refuse.
  let graph = chain();
  let enablement = everything_but(&graph, &["keyframes", "captions"]);
  let wired = landing(graph)
    .with_enablement(enablement)
    .validate()
    .expect("nothing is listening");
  assert_eq!(wired.running().collect::<Vec<_>>(), [NodeId::new(0)]);
}

#[test]
fn an_unlaunched_leaf_is_not_asked_whether_it_is_pure() {
  let graph = chain();
  let enablement = everything_but(&graph, &["captions"]);
  let wired = plan(graph)
    .wiring(NodeId::new(0), NodeWiring::new(Effect::Lands))
    .wiring(NodeId::new(1), NodeWiring::new(Effect::Lands))
    .with_enablement(enablement)
    .validate()
    .expect("a node that does not run cannot compute into nothing");
  assert!(!wired.is_enabled(NodeId::new(2)));
}

#[test]
fn a_handle_from_another_graph_wires_nothing() {
  // A `NodeId` carries no builder identity, so the only honest answer to one that is out of range
  // is that there is nothing to wire — the same posture `ChannelGraph::node` takes.
  let wired = landing(chain())
    .wiring(NodeId::new(99), NodeWiring::new(Effect::Pure))
    .upstream(
      crate::EdgeId::new(99),
      UpstreamWiring::new(Listen::Changes(Feeder::InGraph), AckMode::Chained),
    )
    .validate()
    .expect("out-of-range handles were ignored");
  assert!(wired.node(NodeId::new(99)).is_none());
  assert!(wired.upstream(crate::EdgeId::new(99)).is_none());
  assert!(!wired.is_enabled(NodeId::new(99)));
}

#[test]
fn a_source_can_be_wired_per_edge_within_one_fan_in() {
  // Two upstreams into one consumer, one listened to as a channel and one as changes — the
  // per-upstream words, mixed.
  let mut builder = GraphBuilder::new();
  let scenes = builder.source::<Scenes>("scenes", DriverKind::Thread);
  let ocr = builder.source::<Keyframes>("ocr", DriverKind::Thread);
  let captions = builder.node::<Captions>("captions", DriverKind::Async);
  builder.edge(&scenes, &captions, FanoutKind::Broadcast);
  builder.edge(&ocr, &captions, FanoutKind::Broadcast);
  let graph = builder.validate().expect("a fan-in validates");

  let wired = landing(graph)
    .upstream(
      crate::EdgeId::new(0),
      UpstreamWiring::new(Listen::Changes(Feeder::InGraph), AckMode::Chained),
    )
    .validate()
    .expect("mixed modes in one fan-in");
  let first = wired.upstream(crate::EdgeId::new(0)).expect("declared");
  let second = wired.upstream(crate::EdgeId::new(1)).expect("declared");
  assert_eq!(first.listen(), Listen::Changes(Feeder::InGraph));
  assert_eq!(first.ack(), AckMode::Chained);
  assert_eq!(second.listen(), Listen::Channel);
  assert_eq!(second.ack(), AckMode::Local);
}

#[test]
fn the_launch_refusals_are_errors() {
  fn is_error<E: core::error::Error>(_: &E) {}
  let refused: LaunchError = plan(chain()).validate().expect_err("a pure leaf");
  is_error(&refused);
}

/// The query lane's own half of this floor: the two exemptions the transient edge earns, the
/// refusal it earns, and the resource cross-check that runs before either.
mod query {
  use super::{
    super::super::{AckMode, Effect, Listen, NodeWiring, Plan, UpstreamWiring},
    Captions, Keyframes, Scenes, chain, everything_but, landing, only, plan,
  };
  use crate::{
    AsyncResource, ChannelGraph, DeclaredResource, DriverKind, EdgeId, FanoutKind, GraphBuilder,
    NodeId, ResourceCatalog, ResourceDemand, ResourceName, ResourceSource, Resources,
  };

  /// A resource that is DECLARED — the macro's citizenship, written out.
  struct Egemma;

  impl AsyncResource for Egemma {
    type Options = ();
    type Error = core::convert::Infallible;

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

  impl DeclaredResource for Egemma {}

  /// A resource that satisfies the CONTRACT and never joined the walk — the gap the start-up
  /// cross-check exists to close, and it is reachable exactly because `AsyncResource` is hand-written.
  struct Whisper;

  impl AsyncResource for Whisper {
    type Options = ();
    type Error = core::convert::Infallible;

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

  /// `tower → index`, where the query edge is the tower's and the index is the fan-in.
  fn tower_and_index() -> ChannelGraph {
    let mut builder = GraphBuilder::new();
    let images = builder.source::<Scenes>("images", DriverKind::Thread);
    let tower = builder.source::<Keyframes>("tower", DriverKind::Thread);
    let index = builder.node::<Captions>("index", DriverKind::Thread);
    builder.edge(&images, &index, FanoutKind::Broadcast);
    builder.edge(&tower, &index, FanoutKind::Broadcast);
    builder.validate().expect("a fan-in of two validates")
  }

  /// The index node's TRUE FAN-IN, as a plan states it: one durable inbound and one transient.
  fn fan_in() -> Plan {
    plan(tower_and_index())
      .wiring(NodeId::new(0), NodeWiring::new(Effect::Lands))
      .wiring(NodeId::new(1), NodeWiring::answering(Effect::Pure))
      .wiring(NodeId::new(2), NodeWiring::default().landing())
      .upstream(
        EdgeId::new(1),
        UpstreamWiring::new(Listen::Transient, AckMode::Local),
      )
  }

  #[test]
  fn the_fourth_word_names_itself_and_mixes_with_the_other_three() {
    let wired = fan_in().validate().expect("two edge kinds, one fan-in");
    let words: Vec<&'static str> = (0..2)
      .map(|edge| {
        wired
          .upstream(EdgeId::new(edge))
          .expect("declared")
          .listen()
          .as_str()
      })
      .collect();
    assert_eq!(words, ["channel", "transient"]);
    assert!(Listen::Transient.is_transient());
    assert_eq!(Listen::Transient.to_string(), "transient");
  }

  #[test]
  fn a_query_only_unit_is_legal_because_somebody_is_holding_its_answer() {
    // THE RECONCILIATION with the pure-leaf refusal, at its narrowest. `tower` lands nothing,
    // polls nothing, and its ONE outbound edge is transient — so under the pre-query rule it was
    // only saved by publishing at all. Take that edge away and the door is the whole of its
    // observability.
    fn lone_tower() -> ChannelGraph {
      let mut builder = GraphBuilder::new();
      builder.source::<Keyframes>("tower", DriverKind::Thread);
      builder.node::<Captions>("index", DriverKind::Thread);
      builder.validate().expect("two unconnected nodes validate")
    }

    let refused = plan(lone_tower())
      .wiring(NodeId::new(1), NodeWiring::default().landing())
      .validate()
      .expect_err("a pure leaf with no arm at all");
    assert_eq!(
      only(&refused)
        .try_unwrap_pure_leaf_ref()
        .expect("the pure-leaf arm")
        .name(),
      "tower"
    );

    let wired = plan(lone_tower())
      .wiring(NodeId::new(0), NodeWiring::answering(Effect::Pure))
      .wiring(NodeId::new(1), NodeWiring::default().landing())
      .validate()
      .expect("a door is observability: somebody holds the other half of the oneshot");
    assert!(wired.is_enabled(NodeId::new(0)));
    assert!(wired.node(NodeId::new(0)).expect("declared").answers());
  }

  #[test]
  fn a_transient_inbound_exempts_the_hop_it_feeds_and_not_the_one_it_leaves() {
    // The poll exemption's own mutation, restated for the arm: wiring the exemption on the PRODUCER
    // would exempt `tower` — which is already exempt through its door — and leave a genuinely
    // unobservable consumer walking through. `index` is pure here, so it must be refused on the
    // strength of the edge alone.
    let refused = plan(tower_and_index())
      .wiring(NodeId::new(0), NodeWiring::new(Effect::Lands))
      .wiring(NodeId::new(1), NodeWiring::answering(Effect::Pure))
      .validate()
      .expect_err("`index` is a pure leaf while its inbound is a plain channel");
    assert_eq!(
      only(&refused)
        .try_unwrap_pure_leaf_ref()
        .expect("the pure-leaf arm")
        .name(),
      "index"
    );

    let wired = plan(tower_and_index())
      .wiring(NodeId::new(0), NodeWiring::new(Effect::Lands))
      .wiring(NodeId::new(1), NodeWiring::answering(Effect::Pure))
      .upstream(
        EdgeId::new(1),
        UpstreamWiring::new(Listen::Transient, AckMode::Local),
      )
      .validate()
      .expect("the transient inbound is `index`'s arm");
    assert!(wired.is_enabled(NodeId::new(2)));
  }

  #[test]
  fn the_refusal_still_names_every_way_out_it_has() {
    let refused = plan(chain())
      .wiring(NodeId::new(0), NodeWiring::new(Effect::Lands))
      .wiring(NodeId::new(1), NodeWiring::new(Effect::Lands))
      .validate()
      .expect_err("a pure leaf");
    let rendered = refused.to_string();
    for way in [
      "lands nothing",
      "publishes to nobody",
      "polls nothing",
      "answers nobody",
      "query arm",
    ] {
      assert!(rendered.contains(way), "{rendered}");
    }
  }

  #[test]
  fn an_unlaunched_embedder_under_a_running_index_is_refused_in_its_own_words() {
    // The ruled refusal, and the reason it is not `DisabledUpstream`'s sentence: a starved channel
    // listener is told to read the upstream's STORE, and a starved query edge has no store to be
    // told about — the dark node computes the query's own input, which nothing has asked for yet.
    let graph = tower_and_index();
    let enablement = everything_but(&graph, &["tower"]);
    let refused = plan(graph)
      .wiring(NodeId::new(0), NodeWiring::new(Effect::Lands))
      .wiring(NodeId::new(1), NodeWiring::answering(Effect::Pure))
      .wiring(NodeId::new(2), NodeWiring::default().landing())
      .upstream(
        EdgeId::new(1),
        UpstreamWiring::new(Listen::Transient, AckMode::Local),
      )
      .with_enablement(enablement)
      .validate()
      .expect_err("the index's query edge starves");
    let payload = only(&refused)
      .try_unwrap_disabled_query_upstream_ref()
      .expect("the disabled-query-upstream arm");
    assert_eq!(payload.consumer_name(), "index");
    assert_eq!(payload.producer_name(), "tower");
    assert_eq!(payload.edge(), EdgeId::new(1));
    let rendered = refused.to_string();
    assert!(rendered.contains("query edge"), "{rendered}");
    assert!(rendered.contains("no store to fall back on"), "{rendered}");
    assert!(
      !rendered.contains("listen to its changes"),
      "the channel listener's escape is not offered: {rendered}"
    );
  }

  #[test]
  fn a_demanded_resource_that_nothing_declared_refuses_by_name() {
    // `Whisper` implements `AsyncResource` — so `Shared<Whisper>` compiles — and never joined the walk.
    // That gap is exactly why the check is a start-up one.
    let refused = landing(chain())
      .with_resources(ResourceCatalog::new().with::<Egemma>("egemma", ResourceSource::Section))
      .demanding(NodeId::new(1), ResourceDemand::of::<Whisper>())
      .validate()
      .expect_err("nothing declared `Whisper`");
    let payload = only(&refused)
      .try_unwrap_undeclared_resource_ref()
      .expect("the undeclared-resource arm");
    assert_eq!(payload.name(), "keyframes");
    assert_eq!(payload.node(), NodeId::new(1));
    assert!(
      payload.resource().as_str().ends_with("Whisper"),
      "the refusal names the resource: {}",
      payload.resource().as_str()
    );
    let rendered = refused.to_string();
    assert!(rendered.contains("keyframes"), "{rendered}");
    assert!(rendered.contains("Whisper"), "{rendered}");
    assert!(rendered.contains("#[ingraph::resource]"), "{rendered}");
  }

  #[test]
  fn a_declared_resource_satisfies_every_unit_that_demands_it() {
    let wired = landing(chain())
      .with_resources(ResourceCatalog::new().with::<Egemma>("egemma", ResourceSource::Section))
      .demanding(NodeId::new(0), ResourceDemand::of::<Egemma>())
      .demanding(NodeId::new(1), ResourceDemand::of::<Egemma>())
      .validate()
      .expect("one declaration serves every demand");
    assert_eq!(wired.running().count(), 3);
  }

  #[test]
  fn the_declared_set_and_the_demand_agree_because_one_call_makes_both() {
    // THE MUTATION this pins: give the citizenship its own name — the type's bare ident, a
    // hand-written label — and the cross-check refuses a resource that is really there. Both sides
    // reach `ResourceName::of`, so there is no second author for the key.
    assert_eq!(
      <Egemma as DeclaredResource>::resource(),
      ResourceDemand::of::<Egemma>().resource()
    );
    assert!(
      ResourceCatalog::new()
        .with::<Egemma>("egemma", ResourceSource::Section)
        .declares(ResourceDemand::of::<Egemma>().resource())
    );
  }

  #[test]
  fn an_unlaunched_unit_demands_nothing_because_it_is_not_there_to_hold_it() {
    // THE LAZY RULE: a resource is relevant iff at least one ENABLED node demands it. A deployment
    // that switched the ASR arm off owes no whisper model and no options section for one.
    let graph = chain();
    let enablement = everything_but(&graph, &["captions"]);
    let wired = landing(graph)
      .demanding(NodeId::new(2), ResourceDemand::of::<Whisper>())
      .with_enablement(enablement)
      .validate()
      .expect("a node that does not run demands nothing");
    assert!(!wired.is_enabled(NodeId::new(2)));
  }

  #[test]
  fn the_checked_plan_carries_the_lazy_rule_forward_rather_than_asking_it_twice() {
    // What the CREATE walk builds is what the ENABLED nodes demanded, which is the question this
    // walk has already answered — so the answer rides along instead of being derived a second time
    // from the same demands, where the two could disagree. `Whisper`'s demand is a dark node's:
    // checked against nothing here, and therefore nothing for the walk to load either.
    let graph = chain();
    let enablement = everything_but(&graph, &["captions"]);
    let wired = landing(graph)
      .with_resources(ResourceCatalog::new().with::<Egemma>("egemma", ResourceSource::Section))
      .demanding(NodeId::new(0), ResourceDemand::of::<Egemma>())
      .demanding(NodeId::new(2), ResourceDemand::of::<Whisper>())
      .with_enablement(enablement)
      .validate()
      .expect("a node that does not run demands nothing");

    assert!(wired.demands(<Egemma as DeclaredResource>::resource()));
    assert!(!wired.demands(ResourceDemand::of::<Whisper>().resource()));
    assert_eq!(wired.demanded().count(), 1);
  }

  #[test]
  fn the_resource_row_is_reported_before_the_observability_one_and_both_are_reported() {
    // A node that cannot get its resource cannot run at all, so a reader wants to be told that
    // before being told what its output would not have reached. The walk collects, so the ordering
    // is about READING and no longer hides the second row behind the first.
    let refused = plan(chain())
      .demanding(NodeId::new(2), ResourceDemand::of::<Whisper>())
      .validate()
      .expect_err("both a missing resource and a pure leaf");
    let rows = refused.refusals();
    assert_eq!(rows.len(), 2, "{refused}");
    assert!(rows[0].is_undeclared_resource(), "{refused}");
    assert!(rows[1].is_pure_leaf(), "{refused}");
  }

  #[test]
  fn a_plan_reports_the_resources_and_demands_it_was_wired_with() {
    let plan = landing(chain())
      .with_resources(ResourceCatalog::new().with::<Egemma>("egemma", ResourceSource::Section))
      .demanding(NodeId::new(1), ResourceDemand::of::<Egemma>());
    assert_eq!(plan.resources().len(), 1);
    assert_eq!(plan.demands().count(), 1);
    assert_eq!(
      plan.resources().names().next().map(ResourceName::as_str),
      Some(<Egemma as DeclaredResource>::resource().as_str())
    );
  }
}