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
//! **WHAT A NODE DECLARED** — the facts an emission states about one node, and the join that turns
//! a list of them into an arrangement.
//!
//! A root derive can see a FIELD's type path and nothing else: what that node subscribes to is
//! written in the node's own declaration, and two derives cannot read each other's tokens. That
//! wall is real and it is not moved here. What crosses it is the other road — a node's expansion
//! STATES its facts as a trait impl, and the root's expansion NAMES them through the projection
//! `<Field as Declared>::…`. Nobody reads anybody's tokens; the compiler resolves the meeting.
//!
//! ```ignore
//! impl Declared for Scene {
//!   const EFFECT: Effect = Effect::Lands;
//!   const HOLDS_LANE: bool = true;
//!   const UPSTREAMS: &'static [Upstream] = &[Upstream::of::<Shot>("media::Shot")];
//!   type Attribution<O> = RootProjection<O>;
//!   type Mode = Block;
//!   type Options = SceneOptions;
//!   type Pair = Buffered;
//!   type Wires<O> = Downstream<O>;
//! }
//! ```
//!
//! # The join is by TYPE IDENTITY, because that is the only name both ends have
//!
//! A upstream states its upstream as a PATH — `media::Shot` — and a root states its catalog as
//! FIELDS. The two spellings need never agree: an alias, a re-export or a `use` makes one path two,
//! and a mount name is the deployment's word rather than the type's. What both ends hold without
//! agreeing about anything is the TYPE, so [`Upstream::of`] records
//! [`TypeId`](core::any::TypeId)`::of::<Upstream>()` and [`Blueprint::node`] records the same for
//! each declared field. The edge join is a lookup between them — the arrangement's own registry,
//! built once at launch, exactly as the v2 router built its own.
//!
//! # What is a HEAD, and what is an interior node
//!
//! A node whose [`Declared::UPSTREAMS`] is empty is a dataflow head: nothing inside the graph feeds
//! it, so the deployment does. That is [`GraphBuilder::source`] and not a word anybody writes —
//! having no upstream IS the fact, and a second spelling of it would be a fact that could disagree
//! with the first.
//!
//! # It is a PUBLIC seam and not the derive's private channel
//!
//! Every item here is hand-writable, and the crate's own arrangements hand-write them. A node is
//! not obliged to be generated to be launched, and a trait only one emitter could satisfy would
//! make the framework's own door a closed one.

use core::any::TypeId;

use smol_bytes::Utf8Bytes;

use crate::{
  arrange::{DriverKind, FanoutKind, GraphBuilder, NodeId},
  drive::{AckMode, ChannelOptions, Effect, Listen, Streams, TracingLevel},
  operator::Driven,
  resource::ResourceDemand,
};

use super::{
  ArrangementError, ChannelShelf, Goodbye, GrantsNoStoreError, LaunchError, NodeWiring, Plan,
  Refusal, UnknownGrantError, UnknownUpstreamError, UpstreamWiring,
};

#[cfg(test)]
mod tests;

/// ONE inbound edge, as the declaration wrote it.
///
/// The per-upstream words of the subscribe grammar, in the shape the launch floor spends them:
/// which upstream, how this node listens to it, when it releases that input's ack, and the depth
/// its author shipped the edge at. Every one of them is `const`-constructible, because the whole
/// table is an associated constant — a node's edges are a fact about its declaration and not a
/// value anybody computes.
#[derive(Debug, Clone, Copy)]
pub struct Upstream {
  /// The UPSTREAM's identity — the join key, and the one name both ends of an edge hold.
  upstream: TypeId,
  /// The path the declaration wrote, kept for the sentence a refusal makes.
  named: &'static str,
  /// How this node is fed by that upstream.
  listen: Listen,
  /// When it releases the input's ack.
  ack: AckMode,
  /// The depth its AUTHOR shipped this edge at — `None` where the declaration wrote no `channel`
  /// word, and the deployment's document overrides either way.
  channel: Option<ChannelOptions>,
}

impl Upstream {
  /// An edge from `U`, listened to the default way: real messages over a channel, released on this
  /// node's own completion, at whatever depth the deployment and the framework settle on.
  ///
  /// `named` is the path the declaration wrote. It is carried for DIAGNOSTICS only — the join runs
  /// on `U`'s identity, so an alias, a re-export or a rename changes the sentence and never the
  /// edge.
  #[inline]
  #[must_use]
  pub const fn of<U: 'static>(named: &'static str) -> Self {
    Self {
      upstream: TypeId::of::<U>(),
      named,
      listen: Listen::Channel,
      ack: AckMode::Local,
      channel: None,
    }
  }

  /// The same edge, listened to another way — the `changes(<db>)` word's road, and the poll one.
  #[inline]
  #[must_use]
  pub const fn listening(mut self, listen: Listen) -> Self {
    self.listen = listen;
    self
  }

  /// The same edge, releasing its ack the other way.
  #[inline]
  #[must_use]
  pub const fn acking(mut self, ack: AckMode) -> Self {
    self.ack = ack;
    self
  }

  /// The same edge, at the depth this upstream's author shipped it — the `channel = …` word.
  #[inline]
  #[must_use]
  pub const fn channelled(mut self, channel: ChannelOptions) -> Self {
    self.channel = Some(channel);
    self
  }

  /// The upstream's identity.
  #[inline]
  #[must_use]
  pub const fn upstream(&self) -> TypeId {
    self.upstream
  }

  /// The path the declaration wrote — what a refusal names this edge by.
  #[inline]
  #[must_use]
  pub const fn named(&self) -> &'static str {
    self.named
  }

  /// How this node is fed by that upstream.
  #[inline]
  #[must_use]
  pub const fn listen(&self) -> Listen {
    self.listen
  }

  /// When it releases the input's ack.
  #[inline]
  #[must_use]
  pub const fn ack(&self) -> AckMode {
    self.ack
  }

  /// The depth its author shipped, or `None` where the declaration wrote no `channel` word.
  #[inline]
  #[must_use]
  pub const fn channel(&self) -> Option<ChannelOptions> {
    self.channel
  }

  /// This edge as the launch floor's own row.
  #[inline]
  fn wiring(&self) -> UpstreamWiring {
    let wiring = UpstreamWiring::new(self.listen, self.ack);
    match self.channel {
      Some(channel) => wiring.with_channel(channel),
      None => wiring,
    }
  }
}

/// ONE `write` grant, as the declaration wrote it — the PERMISSION half of a node's declaration.
///
/// A maintenance node reaches into another node's store, and the word that says so is the granting
/// node's own: `write = "media::Media"` INSIDE the `poll(…)` entry whose ticks spend it. This is
/// that word as the launch floor spends it, and it is [`Upstream`]'s sibling on a different axis — a
/// upstream is an EDGE (something arrives), a grant is a PERMISSION (something may be reached).
///
/// It carries the CLOCK that holds it, because the ruling seated the word there: two clocks granting
/// one store are two grants and two rows, and a refusal that could not say which entry to fix would
/// be sending an author to look at a list that no longer exists.
///
/// `const`-constructible for [`Upstream`]'s reason: the whole table is an associated constant, because
/// a node's grants are a fact about its declaration and not a value anybody computes.
///
/// # TWO ROADS to somebody else's handle, and they are deliberately separate
///
/// This one is PER-CLOCK, NAMED and LEAST-PRIVILEGE: the entry that wrote the word is handed
/// exactly what it asked for, the set is knowable from the declaration alone, and reaching for a
/// handle nobody granted is a START-UP refusal naming the clock and the store — an audit a reader
/// can run without running the deployment.
///
/// The other is [`Context::shared`](crate::Context::shared): DEPLOYMENT-WIDE, reached BY TYPE, and
/// answered at the moment of asking. It is the door for the need a declaration cannot enumerate —
/// a resource one branch in a thousand reaches for — and its refusal is a runtime `Err` rather than
/// a launch-time one, which is the price of not having to say the set in advance.
///
/// NEITHER SUBSUMES THE OTHER, and neither is a fallback for the other. A grant that could be
/// widened by a runtime lookup would not be least-privilege any more; a window narrowed to a
/// declared list would not serve the case it exists for. Take the grant where the set is knowable
/// and the audit is worth having; take the window where it is not.
#[derive(Debug, Clone, Copy)]
pub struct Grant {
  /// The GRANTED node's identity — the join key, and the one name both ends of a grant hold.
  node: TypeId,
  /// The `poll(…)` entry that wrote it, by the bare word that entry minted.
  clock: &'static str,
  /// The path the declaration wrote, kept for the sentence a refusal makes.
  named: &'static str,
}

impl Grant {
  /// The right, held by the `clock` entry's ticks, to write into `N`'s store.
  ///
  /// `named` is the path the declaration wrote. It is carried for DIAGNOSTICS only — the join runs
  /// on `N`'s identity, so an alias, a re-export or a rename changes the sentence and never the
  /// grant. [`Upstream::of`]'s own arrangement, one axis over. `clock` is carried for the same reason
  /// and nothing else reads it: the emitted contexts already are per clock, so this is the sentence's
  /// half of a fact the types alone would state without a word for it.
  #[inline]
  #[must_use]
  pub const fn of<N: 'static>(clock: &'static str, named: &'static str) -> Self {
    Self {
      node: TypeId::of::<N>(),
      clock,
      named,
    }
  }

  /// The granted node's identity.
  #[inline]
  #[must_use]
  pub const fn node(&self) -> TypeId {
    self.node
  }

  /// The clock whose entry wrote this grant — the word a refusal sends an author to.
  #[inline]
  #[must_use]
  pub const fn clock(&self) -> &'static str {
    self.clock
  }

  /// The path the declaration wrote — what a refusal names this grant by.
  #[inline]
  #[must_use]
  pub const fn named(&self) -> &'static str {
    self.named
  }
}

/// **THE FACTS ONE NODE STATES ABOUT ITSELF** — everything the launch walk needs and the root's
/// own declaration cannot see.
///
/// Emitted by the five node macros and hand-writable by anybody: see the module note for why the
/// seam is open.
///
/// # `In`/`Out` are the OPERATOR's, and this trait does NOT bind one
///
/// A node's input and output types are what [`Operator`](crate::Operator) already declares, and a
/// second pair beside them would be a second authority for one fact. So they are not restated —
/// and `Operator` is not a supertrait either, which is bound-minimization applied and MEASURED: a
/// declaration states its facts whether or not its author has written the body yet, and a
/// supertrait here would make every declared record in a corpus owe an `accept` before its key type
/// could be emitted. The walks that SPEND `In` and `Out` — [`Blueprint::node`], the wiring — bind
/// `Operator` themselves, at the sites that use it, and a node that cannot run is refused where it
/// is mounted rather than where it is declared.
#[diagnostic::on_unimplemented(
  note = "a node the graph root launches states its facts through `Declared` — the five node \
          macros emit one, and a hand-written node writes one",
  note = "if `{Self}` is a resource rather than a node, mark its field `#[ingraph(resource)]`"
)]
pub trait Declared: Sized + 'static {
  /// What this node's outputs BECOME — durable, or computed and gone.
  const EFFECT: Effect;

  /// Whether it holds a WRITE LANE of its own.
  ///
  /// A separate fact from [`EFFECT`](Self::EFFECT) because the two answer different questions and a
  /// node can say the first without the second: a store node lands through a lane it owns, and a
  /// pure node whose emissions reach a storage co-subscriber lands through somebody else's. The
  /// launch floor refuses the pair that claims durability and performs none — see
  /// [`Refusal::LandsNowhere`](super::Refusal::LandsNowhere) — and this is the half of that check
  /// only the declaration can answer.
  const HOLDS_LANE: bool = false;

  /// Which engine runs it.
  ///
  /// Defaulted rather than declared, because no word states it yet: the engine follows the
  /// operator's mobility (a `!Send` body rides a thread), and the grammar for saying so is a later
  /// round's. The default is the engine the ignition starts today.
  const DRIVER: DriverKind = DriverKind::Thread;

  /// **WHICH PAIR THIS NODE'S BODY WEARS** — [`Buffered`](crate::Buffered) for the compute seam
  /// ([`Operator`](crate::Operator) / [`AsyncOperator`](crate::AsyncOperator)),
  /// [`Streaming`](crate::Streaming) for the streamed one
  /// ([`StreamOperator`](crate::StreamOperator) / [`AsyncStreamOperator`](crate::AsyncStreamOperator)).
  ///
  /// The `stream` word's whole runtime half, and a DIFFERENT AXIS from [`Mode`](Self::Mode): a pair
  /// is which two traits a body may wear and a mode is which half it wore — so the two questions
  /// multiply rather than compete, and a streaming node states `Block` or `Async` exactly as a
  /// buffered one does. [`StreamOperator`](crate::StreamOperator)'s own face-selection law is what a
  /// declaration answers by writing the word or leaving it off.
  ///
  /// # It is a TYPE for [`Mode`](Self::Mode)'s reason, and it used to be a CONST
  ///
  /// It shipped as `const STREAMS: bool = false` — a defaulted const, lifted back into the type
  /// system by a `Pair<STREAMS>` carrier so a bound could select on it. The design-law audit refused
  /// that shape by name: *no const ever states a mode*, and a defaulted const on a
  /// directly-implemented trait is the one member an author can leave WRONG — the default silently
  /// stands, the impl looks complete, and nothing checks it against the body. A hand-written
  /// streaming node that forgot the line was a BUFFERED node as far as every walk could see.
  ///
  /// As a type there is no default to leave: the seat is stated or the impl is incomplete, and what
  /// it is stated to is cashed at the mount — `Worn<Self::Pair, Self::Mode>: Mount<Self>` — where a
  /// pair the body does not wear is `E0277` naming the face it does not implement.
  ///
  /// # It has NO DEFAULT, and that is the language rather than a choice
  ///
  /// Associated-type defaults are not stable, so a hand-written node states `type Pair = Buffered;`
  /// in as many words — [`Mode`](Self::Mode)'s tax exactly, and the same escape hatch with it. The
  /// node macros write whichever pair the declaration's word chose.
  type Pair;

  /// **THE DOWNSTREAM SET THIS NODE PUBLISHES THROUGH**, at the product `O` its face states —
  /// [`Downstream<O>`](crate::Downstream) for a node that emits ONE thing, and the node's own
  /// emitted `<Node>Downstream` where its declaration wrote `emits = […]`.
  ///
  /// The THIRD seat beside [`Pair`](Self::Pair) and [`Mode`](Self::Mode), and it is here for their
  /// reason exactly: a node's own set is an emitted TYPE, a graph root's expansion writes one line
  /// per field and cannot see the word that minted it, and what crosses that wall is a member of the
  /// facts trait. [`Wiring::lane_parts`](super::Wiring) reads this projection and builds what it
  /// names, so a declared demultiplexer finally mounts — each product to the edge its own consumer
  /// opened, rather than the whole `<Node>Out` sum offered to every one of them and refused by
  /// [`EdgeTypeError`](crate::EdgeTypeError) at the first.
  ///
  /// # It takes the PRODUCT as a parameter, and that is the two-derive wall rather than a flourish
  ///
  /// The set a one-product node publishes through is `Downstream<Out>`, and `Out` is the OPERATOR's
  /// — a type this trait deliberately does not bind, because a declaration states its facts whether
  /// or not its author has written the body yet (see the trait note above). A seat spelled
  /// `type Wires = Downstream<<Self as Operator>::Out>` would undo that in one line: every declared
  /// record in a corpus would owe an `accept` before its facts could be emitted, and a STORE record
  /// — which wears no face at all — could not state the seat.
  ///
  /// So the seat is a set CONSTRUCTOR and the product arrives where it is spent: the walk knows the
  /// face it is mounting and writes `<N as Declared>::Wires<<N as Streams<M>>::Out>`, while a
  /// declaration that emits one thing answers `Downstream<O>` without naming its own output at all.
  /// A node that emits SEVERAL ignores the parameter — its set is one concrete emitted type whose
  /// slots are typed at the products the `emits` word named.
  ///
  /// # A LYING SEAT IS REFUSED AT THE MOUNT, which is [`Mode`](Self::Mode)'s own device
  ///
  /// Nothing here checks that the set matches the products, because nothing has to. What
  /// [`Mount`](super::Mount)'s streaming cell binds is [`Sink<Out>`](crate::Sink) on this
  /// projection, so a hand-written node naming a set that does not carry its output is `E0277` at
  /// the mount, naming the routing capability the set does not implement — and a set carrying
  /// ANOTHER node's products is the same refusal with the mismatch spelled in `Sink`'s own note.
  ///
  /// # It has NO DEFAULT, and that is the language rather than a choice
  ///
  /// Associated-type defaults are not stable, so a hand-written node states
  /// `type Wires<O> = Downstream<O>;` in as many words — [`Pair`](Self::Pair)'s tax exactly, one
  /// line, and the same escape hatch with it: a hand-written demultiplexer writes its own set's name
  /// and needs no macro to say so.
  type Wires<O>;

  /// **WHAT THIS NODE ATTRIBUTES ITS OUTPUTS TO** — [`RootProjection<O>`](crate::RootProjection)
  /// where the declaration wrote `attributed`, and `()` where it did not.
  ///
  /// The FOURTH seat beside [`Pair`](Self::Pair), [`Wires`](Self::Wires) and [`Mode`](Self::Mode),
  /// and it is here for their reason exactly: whether a node's output is a DECLARED RECORD — a type
  /// with a root to project — is a fact only that node's own declaration holds, a graph root's
  /// expansion writes one line per field and sees the output as a type it can name and cannot
  /// TEST, and what crosses that wall is a member of the facts trait.
  /// [`Wiring::resident`](super::Wiring::resident) reads this projection and installs what it
  /// names, so the root projection every emitted record has carried since it was emitted finally
  /// reaches the node that emits one. See [`RootProjection`](crate::RootProjection)'s own module
  /// note, which is where the wall was recorded and where this seat is the answer to it.
  ///
  /// # It takes the PRODUCT as a parameter, and that is [`Wires`](Self::Wires)'s wall rather than a
  /// flourish
  ///
  /// The projection for a node that emits `Out` is `RootProjection<Out>`, and `Out` is the
  /// OPERATOR's — a type this trait deliberately does not bind (see the trait note above). A seat
  /// spelled `type Attribution = RootProjection<<Self as Operator>::Out>` would put an `accept` in
  /// front of every declared record's facts, exactly as the same spelling would at
  /// [`Wires`](Self::Wires). So the seat is a projection CONSTRUCTOR and the product arrives where
  /// it is spent: the walk knows the face it is mounting and writes
  /// [`NodeAttribution<N, M>`](super::NodeAttribution), while a declaration that attributes nothing
  /// answers `()` and never reads the parameter at all.
  ///
  /// # A LYING SEAT IS REFUSED AT THE MOUNT, which is [`Wires`](Self::Wires)'s own device
  ///
  /// Nothing here checks that the seat can really project this node's output, because nothing has
  /// to. What [`Mount`](super::Mount)'s buffered cell binds is
  /// [`Attributes<Out>`](crate::Attributes) on this projection, so a declaration wearing
  /// `attributed` over an output that is a `String` or a `u64` — a type no record declaration
  /// emitted an impl for — is `E0277` at the mount, naming the projection and the payload it cannot
  /// take a root out of.
  ///
  /// # [`Default`] is the ONE bound the seat carries, because the WALK builds the value
  ///
  /// An install is unconditional, so the value cannot come from the deployment: the walk that wires
  /// a node has the seat's type and nothing else, and what it needs from it is a way to mint one.
  /// Both inhabitants supply it for free — a projection carries nothing and `()` is nothing — and
  /// the bound sits HERE rather than at the wiring because it is the one obligation that does not
  /// depend on the operator's own types. The [`Attributes`](crate::Attributes) half cannot sit here
  /// and does not: `for<T> Attribution<T>: Attributes<T>` is a claim `RootProjection<T>` does not
  /// make, since only a declared record has an impl.
  ///
  /// A node whose attribution carries STATE — a handle, a queue, a journal writer — is not this
  /// seat's road at all: it seats `()` and reaches
  /// [`Resident::attributing`](crate::Resident::attributing) by hand, which stays public for
  /// exactly that.
  ///
  /// # The seat is STATED and not defaulted, which is the language rather than a choice
  ///
  /// Associated-type defaults are not stable, so a hand-written node writes
  /// `type Attribution<O> = ();` in as many words — [`Wires`](Self::Wires)'s tax exactly, one line,
  /// and the same escape hatch with it. The node macros write whichever the declaration's word
  /// chose.
  type Attribution<O>: Default;

  /// **WHICH MODE THIS NODE'S BODY IS IN** — [`Block`](crate::Block) for an `accept` that answers,
  /// [`Async`](crate::Async) for one that has to be awaited.
  ///
  /// The mode word as a TYPE, which is what makes it spendable: [`GraphBuilder::node`] and
  /// [`GraphBuilder::source`] and the feeder door bind `Driven<<N as Declared>::Mode>`, so a
  /// declaration's own word is what decides which of the two faces a mount demands.
  ///
  /// # It is the ONE seat, and the const-shaped half is DERIVED from it
  ///
  /// A root's emitted `ALL_SYNC` needs this fact as a const, and it reads one:
  /// `<N as Driven<<N as Declared>::Mode>>::SYNC` — this seat picking the row, and that row's own
  /// const answering. A second seat here stating the same thing would be one fact with two
  /// accounts, and the two could be written to disagree — a declaration wearing the awaited face
  /// beside a const left at the blocking default would make a fold call a deployment all-blocking
  /// while one of its mounts awaits. There is no such const to leave, so the disagreement has
  /// nowhere to live; and the const that IS read cannot be forged either, because
  /// [`Driven::SYNC`](crate::Driven::SYNC) is set by the two blanket rows and by nothing an author
  /// can write.
  ///
  /// # A LYING WORD CORRECTS ITSELF, which is the whole reason the seat is a type
  ///
  /// Nothing here checks that the word matches the body, because nothing has to. A declaration
  /// saying `async` over a body with only a blocking `accept` states `type Mode = Async`, and the
  /// blanket row for `Async` is the one [`AsyncOperator`](crate::AsyncOperator) fills — so
  /// `Driven<Async>` goes unsatisfied and the mount is `E0277` naming the trait the type does not
  /// implement. The other direction is the same fact mirrored: a bare declaration over an awaited
  /// body asks for `Driven<Block>` and is refused where it is mounted.
  ///
  /// # It has NO DEFAULT, and that is the language rather than a choice
  ///
  /// Associated-type defaults are not stable, so a hand-written node states `type Mode = Block;` in
  /// as many words — [`Channels`](Self::Channels)'s tax exactly, and the same escape hatch with it:
  /// a hand-written node whose body wears the awaited face writes `type Mode = Async;` and needs no
  /// macro to say so. The node macros write whichever the declaration's word chose.
  type Mode;

  /// Every inbound edge, in declaration order — EMPTY for a dataflow head.
  ///
  /// Declaration order is the contract, exactly as it is for the channels shelf and for the poll
  /// clocks: the wiring walk numbers a node's upstreams by position, so an entry's place in this
  /// table is the slot its channel is opened at.
  const UPSTREAMS: &'static [Upstream] = &[];

  /// Every `write` grant this node's declaration wrote, clock by clock and in the order it wrote
  /// them — EMPTY for the node that reaches into nobody's store, which is most of them.
  ///
  /// A SEPARATE axis from [`UPSTREAMS`](Self::UPSTREAMS): a upstream is one arm of a fan-in, and a grant
  /// is one clock's permission. The ruling seated the word inside the `poll(…)` entry, so a reaper
  /// that reaps on one cadence and compacts on another states each clock's stores in that clock's
  /// own entry — and this table flattens them, each row naming the clock it came from.
  ///
  /// What it buys the launch is the only thing a grant can be checked against: the CATALOG. The
  /// emitted context is where a grant becomes a BOUND — one `AsyncLands<Granted>` impl per grant and
  /// none for anything else, so an ungranted store is a bound nothing satisfies and that half needs
  /// no runtime. This half is the other one: a grant naming a node the root does not mount, or
  /// naming a node whose declaration keeps no store, is a promise with nothing behind it, and
  /// [`Blueprint::into_plan`] says so by name.
  ///
  /// Defaulted, so every hand-written [`Declared`] already in existence keeps compiling.
  const GRANTS: &'static [Grant] = &[];

  /// The RESOURCES this node's construction reaches for, as thunks.
  ///
  /// A table of `fn` items rather than of values because a demand is minted by a generic call that
  /// is not `const`; the table is the constant and [`demands`](Self::demands) is the reading, which
  /// is the shape `<Node>Channels::DECLARED` and `ChannelShelf::tuning` already keep one organ over.
  const DEMANDS: &'static [fn() -> ResourceDemand] = &[];

  /// The level this node's FRAMEWORK SPANS open at — the `tracing(level = …)` word.
  ///
  /// Defaulted, so a declaration that wrote no word states nothing and every hand-written node
  /// already in existence keeps compiling. It is also what makes the emission gateable: an
  /// expansion writes this const inside `if_tracing!`, so a build with no observation emits no
  /// const at all and the default is what the spans would have read if anything read them.
  ///
  /// UNGATED, alone among the things this word touches. The others — the const an expansion writes,
  /// the spans that spend it — ride the feature; the TYPE cannot, because a trait item that existed
  /// in one build and not another would make this trait two different traits and a hand-written node
  /// compile against one of them.
  const TRACING: TracingLevel = TracingLevel::Info;

  /// The `[node.channels]` SHELF this node's section carries —
  /// [`Unchanneled`](super::Unchanneled) where the declaration has no container to tune.
  ///
  /// The root's options spine reaches the shelf's type through this projection, which is the whole
  /// of why it is here: a shelf is emitted beside the node that declared the upstreams, and a root
  /// sees a field's type path. Without it the spine holds the default shelf for every node and a
  /// deployment's `channels` block has nowhere to be written — the config layer of the precedence
  /// would be a rule with no road.
  ///
  /// It has no default, and that is the language rather than a choice: associated-type defaults are
  /// not stable, so a hand-written node states `type Channels = Unchanneled;` in as many words. The
  /// derive writes whichever of the two applies.
  type Channels: ChannelShelf;

  /// The type this node is CONFIGURED by — the `options = "path"` word, or `()` where the
  /// declaration wrote none.
  ///
  /// It is stated here rather than projected from
  /// [`AsyncConstructor::Options`](super::AsyncConstructor::Options) so that a root's options spine can name
  /// the path a declaration wrote WITHOUT demanding that every node in the catalog be constructible
  /// at the moment the spine is written. The two are pinned equal where the door is consumed — an
  /// emitted equation, `E0271` at the declaration that let them drift.
  type Options;

  /// Whether this declaration wrote `teardown` — the goodbye opt-in.
  ///
  /// The one fact the ignition reads to decide whether a node's value has anything to say before the
  /// process leaves it. `false` is the shipped posture and costs nothing: the value drops on its own
  /// engine as the body returns, exactly as it always did, and no channel carries anything extra.
  ///
  /// It is a CONST rather than a question asked of the type, because whether a type happens to
  /// implement [`AsyncTeardown`](super::AsyncTeardown) is not the same question as whether its declaration
  /// enrolled it. A library type that says goodbye for its own reasons does not join a graph's
  /// shutdown chain by accident; the word is what joins it.
  const TEARDOWN: bool = false;

  /// Say this node's goodbye, ON THE ENGINE THAT OWNS THE VALUE.
  ///
  /// The `teardown` word's whole runtime effect, and the reason it is a method on THIS trait: the
  /// root that mounts a node cannot see the word, and the node's own derive can. So the emission
  /// writes the override where the impl is nameable and the ignition calls it without ever
  /// mentioning [`AsyncTeardown`](super::AsyncTeardown) — a walk over the whole catalog stays one call, and a
  /// node that enrolled nothing pays no bound.
  ///
  /// The default DROPS, which is the shipped teardown for every value that enrols in no other. It is
  /// what [`TEARDOWN`](Self::TEARDOWN) being `false` means, and it is written here so that a
  /// hand-written [`Declared`] gets the ordinary posture for free.
  ///
  /// # It hands back a future, and that future is not `Send`
  ///
  /// The goodbye is created where the type is known and driven where the value lives — those are the
  /// same place — so nothing here has to cross a thread. That is what makes the thread engine the
  /// `!Send` home it was ruled to be: a model context or an FFI session says goodbye on its own
  /// thread, and only the outcome travels.
  ///
  /// The chain does NOT call this directly. It is called by the engine, at settle, and what reaches
  /// the chain is a turn signal — see [`Enrolled::settle_parked`](super::Enrolled::settle_parked).
  #[inline]
  fn goodbye(self) -> Goodbye {
    drop(self);
    Box::pin(core::future::ready(Ok(())))
  }

  /// What this node demands, read off [`DEMANDS`](Self::DEMANDS).
  #[inline]
  fn demands() -> impl Iterator<Item = ResourceDemand> {
    Self::DEMANDS.iter().map(|mint| mint())
  }
}

/// **THE ARRANGEMENT, JOINED** — declared facts in, a [`Plan`] out.
///
/// One call per declared mount, in the root's own order, and the edges appear by themselves: each
/// node's [`Declared::UPSTREAMS`] names its upstreams by type identity, and the registry this builds
/// as it walks is what turns those identities into [`NodeId`]s. Nothing is wired by hand and
/// nothing is named twice.
///
/// # Why the edges are joined at the END and not as each node arrives
///
/// A declaration may name an upstream the root mounts LATER — the catalog is a set and not a
/// sequence, and forcing a topological order on the root's fields would make a declaration's
/// position load-bearing. So the walk collects, and the join runs once every identity is known.
#[derive(Default)]
pub struct Blueprint {
  builder: GraphBuilder,
  nodes: Vec<Declaration>,
}

/// Written rather than derived, for the reason the node bag's own is: what a reader wants from a
/// half-built arrangement is HOW MUCH of the catalog has entered it, and the builder underneath
/// prints nothing at all.
impl core::fmt::Debug for Blueprint {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("Blueprint")
      .field("nodes", &self.nodes.len())
      .field(
        "upstreams",
        &self
          .nodes
          .iter()
          .map(|node| node.upstreams.len())
          .sum::<usize>(),
      )
      .finish()
  }
}

/// One node's row in the walk: who it is, and what it said.
#[derive(Debug)]
struct Declaration {
  /// The mount the root wrote it under — what a refusal calls it.
  mount: Utf8Bytes,
  /// Its own identity, which is what a downstream's `Upstream` names it by.
  identity: TypeId,
  /// The launch floor's row for the node itself.
  wiring: NodeWiring,
  /// Its inbound edges, in declaration order.
  upstreams: &'static [Upstream],
  /// The stores it was granted the right to write, in declaration order.
  grants: &'static [Grant],
  /// What its construction reaches for.
  demands: Vec<ResourceDemand>,
}

impl Blueprint {
  /// An empty arrangement.
  #[inline]
  #[must_use]
  pub fn new() -> Self {
    Self {
      builder: GraphBuilder::new(),
      nodes: Vec::new(),
    }
  }

  /// Declare `N` at `mount`, from the facts `N` itself states.
  ///
  /// A node with no [`UPSTREAMS`](Declared::UPSTREAMS) enters as a dataflow HEAD and every other as an
  /// interior node; a node drawing from more than one upstream takes an intake of its own, so its
  /// edges get a channel each rather than sharing one inbox — the fan-in shape the pairing runtime
  /// reads.
  ///
  /// The [`NodeId`] comes back so a caller that also has to WIRE the node — the emitted entry does
  /// — holds the same handle the plan was built under.
  ///
  /// The `Driven` half of the bound is [`GraphBuilder::node`]'s, carried through: a mount states
  /// facts AND runs a body, so the declaration that reaches this door has to have the body its own
  /// mode word names.
  #[inline]
  pub fn node<N>(&mut self, mount: impl Into<Utf8Bytes>) -> NodeId
  where
    N: Declared + Driven<<N as Declared>::Mode>,
  {
    let mount = mount.into();
    let handle = if N::UPSTREAMS.is_empty() {
      self.builder.source::<N>(mount.clone(), N::DRIVER)
    } else {
      self.builder.node::<N>(mount.clone(), N::DRIVER)
    };
    self.entered::<N>(mount);
    handle.id()
  }

  /// Declare the STREAMING node `N` at `mount`, from the facts `N` itself states.
  ///
  /// [`node`](Self::node)'s walk verbatim — the same head rule, the same intake rule, the same
  /// registry row, the same edges appearing by themselves — with one difference, and it is the only
  /// one there is: the BOUND. A streaming body wears [`StreamOperator`](crate::StreamOperator) or
  /// [`AsyncStreamOperator`](crate::AsyncStreamOperator), so what its mount demands is the
  /// [`Streams`](crate::Streams) row its own [`Mode`](Declared::Mode) picks rather than the
  /// [`Driven`] one — see [`GraphBuilder::streaming`], which carries the argument.
  ///
  /// # The two doors are the WORD, cashed
  ///
  /// [`Declared::Pair`] is the fact a declaration states and this is the door that fact belongs at.
  /// Nothing here reads the seat, and nothing needs to: an emission knows which word its own
  /// declaration wrote, so it writes the door — and a hand-written node's author knows the same
  /// thing. What the seat is for is the ROOT's emission, which writes one line per field and cannot
  /// see the word: it names [`Worn`](super::Worn) and the seat picks the door.
  #[inline]
  pub fn stream<N>(&mut self, mount: impl Into<Utf8Bytes>) -> NodeId
  where
    N: Declared + Streams<<N as Declared>::Mode>,
  {
    let mount = mount.into();
    let handle = if N::UPSTREAMS.is_empty() {
      self.builder.streaming_source::<N>(mount.clone(), N::DRIVER)
    } else {
      self.builder.streaming::<N>(mount.clone(), N::DRIVER)
    };
    self.entered::<N>(mount);
    handle.id()
  }

  /// Declare the AUTONOMOUS node `N` at `mount`, from the facts `N` itself states.
  ///
  /// [`node`](Self::node)'s walk verbatim — the same head rule, the same intake rule, the same
  /// registry row, the same edges appearing by themselves — with one difference, and it is the only
  /// one there is: the BOUND. An autonomous body wears
  /// [`AutonomousOperator`](crate::AutonomousOperator) or
  /// [`AsyncAutonomousOperator`](crate::AsyncAutonomousOperator), so what its mount demands is the
  /// [`Runs`](crate::Runs) row its own [`Mode`](Declared::Mode) picks rather than the [`Driven`] one
  /// or the [`Streams`](crate::Streams) one.
  ///
  /// # THREE doors are the WORD, cashed
  ///
  /// [`stream`](Self::stream)'s note applies here unchanged: [`Declared::Pair`] is the fact a
  /// declaration states and this is the door that fact belongs at. Nothing here reads the seat — an
  /// emission knows which word its own declaration wrote, so it writes the door — and what the seat
  /// is for is the ROOT's emission, which writes one line per field and cannot see the word.
  #[inline]
  pub fn autonomous<N>(&mut self, mount: impl Into<Utf8Bytes>) -> NodeId
  where
    N: Declared + crate::Runs<<N as Declared>::Mode>,
  {
    let mount = mount.into();
    let handle = if N::UPSTREAMS.is_empty() {
      self
        .builder
        .autonomous_source::<N>(mount.clone(), N::DRIVER)
    } else {
      self.builder.autonomous::<N>(mount.clone(), N::DRIVER)
    };
    self.entered::<N>(mount);
    handle.id()
  }

  /// The REGISTRY ROW every mount door writes — everything a declaration states that is not the face
  /// it wears.
  ///
  /// Written once because the doors differ in exactly one thing, which is their bound: a row
  /// spelled at each would be as many chances for the effect, the lane, the intake rule or the
  /// demands to drift between one kind's mount and another's.
  fn entered<N>(&mut self, mount: Utf8Bytes)
  where
    N: Declared,
  {
    let upstreams = N::UPSTREAMS;
    let wiring = {
      let wiring = NodeWiring::new(N::EFFECT).tracing(N::TRACING);
      let wiring = if N::HOLDS_LANE {
        wiring.landing()
      } else {
        wiring
      };
      // An intake of its OWN is what makes a slow upstream backpressure on itself alone. One
      // upstream has nothing to keep apart from, so it takes the single-inbox shape every node has
      // had until now.
      if upstreams.len() > 1 {
        wiring.drawing()
      } else {
        wiring
      }
    };
    self.nodes.push(Declaration {
      mount,
      identity: TypeId::of::<N>(),
      wiring,
      upstreams,
      grants: N::GRANTS,
      demands: N::demands().collect(),
    });
  }

  /// Declare the ORIGIN `S` at `mount`, from the facts `S` itself states.
  ///
  /// An origin is always a dataflow HEAD — nothing inside the graph feeds it, which is what makes it
  /// an origin — so it takes no upstream, no grant and no demand, and there is no word for any of
  /// them to be written in.
  ///
  /// # ITS EFFECT IS PURE, and that is what refuses a source nobody listens to
  ///
  /// An origin lands nothing. What it produces becomes durable wherever its CONSUMERS land it, so
  /// the effect it declares is the pure one — and [`Plan::validate`](super::Plan)'s pure-leaf rule
  /// then does the whole of the work: an origin that publishes to nobody, polls nothing and answers
  /// nobody computes into nothing, and is refused BEFORE anything ignites, by name, with the fix in
  /// the sentence.
  ///
  /// That refusal is [`Refusal::PureLeaf`](super::Refusal::PureLeaf) and not a head-shaped one of
  /// its own. The vocabulary is named after WHAT IS WRONG rather than after WHO it happened to, so
  /// *this computes into nothing* is one word whether the node that computes into nothing has an
  /// upstream or is the head of the whole arrangement.
  ///
  /// # It rides the THREAD engine, whichever face it wears
  ///
  /// Both faces do — see [`origin`](super::origin)'s note on why the awaited one is pinned rather
  /// than spawned — so there is no driver word here and nothing for a declaration to choose.
  ///
  /// # THE EDGE IS RECORDED HERE AND OPENED AT THE MOUNT, and no word was added to say so
  ///
  /// The consumer that names this origin puts an edge in the plan, exactly as it would naming a
  /// node: the join runs on TYPE IDENTITY and this declaration is one of the identities it searches,
  /// so `subscribe(upstream(node = "…"))` reaches an origin with no vocabulary of its own. What
  /// opens it is [`Ignition::origin_bridged`](super::Ignition::origin_bridged), which hands the
  /// origin the consumer's own inbox as its feed — see [`origin`](super::origin) for that walk and
  /// for why the framework hands the edge over rather than pumping into it.
  ///
  /// A deployment may still be refused, and the two rows are about what a bridge cannot SERVE rather
  /// than about what it has not built: a consumer listening by `changes`, `poll` or `transient`
  /// ([`Refusal::UnbridgedOrigin`](super::Refusal::UnbridgedOrigin)) is asking an origin for a store
  /// or a door it has not got, and two launched consumers of one origin
  /// ([`Refusal::SplitOrigin`](super::Refusal::SplitOrigin)) are pulling at one feed.
  ///
  /// The edge itself stays declared and is not the mistake: it is what keeps this origin from being
  /// a leaf that computes into nothing, per the section above.
  #[inline]
  pub fn origin<S>(&mut self, mount: impl Into<Utf8Bytes>) -> NodeId
  where
    S: crate::DeclaredOrigin + crate::Lived<<S as crate::DeclaredOrigin>::Mode>,
  {
    let mount = mount.into();
    let handle = self.builder.origin::<S>(mount.clone(), DriverKind::Thread);
    self.nodes.push(Declaration {
      mount,
      identity: TypeId::of::<S>(),
      // `originating`, which is the one fact the graph text cannot show: an origin and an operator
      // subscribing to nothing are both HEADS, and which door mounted it is what tells them apart.
      // What reads it is the dead-edge row — see `NodeWiring::originating`.
      wiring: NodeWiring::new(Effect::Pure).originating(),
      upstreams: &[],
      grants: &[],
      demands: Vec::new(),
    });
    handle.id()
  }

  /// Join the edges and hand back the plan they make.
  ///
  /// # Errors
  ///
  /// [`LaunchError::Refused`], carrying one [`Refusal::UnknownUpstream`] row per upstream naming a
  /// node this root does not mount — collected rather than raised at the first, because the
  /// validate walk beside it collects and an operator fixing a catalog wants the whole list.
  ///
  /// The `write` GRANTS are checked in the same pass and land in the same list, because they are the
  /// same kind of fact: a grant names its store by TYPE and the root's fields are the whole set of
  /// types there are. Two rows answer the two ways a grant can have nothing behind it — the node is
  /// not mounted ([`Refusal::UnknownGrant`]), or it is mounted and keeps no store
  /// ([`Refusal::GrantsNoStore`]). Neither is about a deployment: a grant on a node this deployment
  /// does not LAUNCH stays legal, because collecting a dead node's garbage is exactly the work the
  /// poll mode exists for.
  pub fn into_plan(self) -> Result<Plan, LaunchError> {
    let Self { mut builder, nodes } = self;
    // The REGISTRY: one identity per mounted node, in the root's own order, which is the order the
    // builder numbered them in. A `Vec` scan rather than a map, because a catalog is tens of nodes
    // and the walk runs once — a hash of one `TypeId` per lookup would be the more expensive answer
    // at every size this ever has.
    let mut refusals = Vec::new();
    let mut edges = Vec::new();
    for (position, node) in nodes.iter().enumerate() {
      let consumer = NodeId::new(position);
      for upstream in node.upstreams {
        match nodes
          .iter()
          .position(|other| other.identity == upstream.upstream())
        {
          Some(producer) => edges.push((
            builder.join(NodeId::new(producer), consumer, FanoutKind::Broadcast),
            upstream.wiring(),
          )),
          None => refusals.push(Refusal::UnknownUpstream(UnknownUpstreamError::new(
            node.mount.clone(),
            upstream.named(),
          ))),
        }
      }
      // THE GRANTS, over the same registry and in the same list, and each row NAMES ITS CLOCK. A
      // grant opens no edge — nothing arrives over it and nothing acks — so it contributes no row to
      // the builder; what it contributes is the CHECK, which is the whole of what the graph text can
      // say about a permission. Two clocks granting one store are two rows, and both are wrong or
      // both are right together — the walk says nothing about that, because the entries are what an
      // author fixes and there are two of them.
      for grant in node.grants {
        match nodes.iter().find(|other| other.identity == grant.node()) {
          Some(granted) if granted.wiring.effect().is_pure() => {
            refusals.push(Refusal::GrantsNoStore(GrantsNoStoreError::new(
              node.mount.clone(),
              grant.clock(),
              granted.mount.clone(),
              grant.named(),
            )));
          }
          Some(_) => {}
          None => refusals.push(Refusal::UnknownGrant(UnknownGrantError::new(
            node.mount.clone(),
            grant.clock(),
            grant.named(),
          ))),
        }
      }
    }
    if !refusals.is_empty() {
      return Err(LaunchError::Refused(refusals));
    }

    let graph = builder.validate().map_err(|error| {
      LaunchError::Refused(vec![Refusal::Arrangement(ArrangementError::new(
        error.to_string(),
      ))])
    })?;
    let mut plan = Plan::new(graph);
    for (position, node) in nodes.iter().enumerate() {
      plan = plan.wiring(NodeId::new(position), node.wiring);
      for demand in &node.demands {
        plan = plan.demanding(NodeId::new(position), *demand);
      }
    }
    for (edge, wiring) in edges {
      plan = plan.upstream(edge, wiring);
    }
    Ok(plan)
  }
}