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
//! **THE DRIVER**: the one long-lived body that owns [`Debounce`] and [`Batcher`] on a family's
//! behalf, and the only writer of the head node's keyed feed.
//!
//! [`crate::batch`]'s module note names the contract this file is the other half of — *nothing here
//! happens on its own; a loop that owns one of these machines runs three lines forever* — and this
//! is that loop. Everything else in this module is what the three lines need: where a key comes
//! from, what a ripe key becomes, and who is told when the head has taken it.
//!
//! # ONE BODY PER FAMILY, and it is a TASK wherever there is a runtime to put one on
//!
//! The engine fork is the one this crate already takes for its cadences, read one seat over. An
//! ignition that named a runtime ([`Assembly::ignite_on`](crate::Assembly::ignite_on)) gets a
//! long-lived TASK on it, timed by that runtime's own sleep — the [`AfterClock`](crate::AfterClock)
//! road. An ignition that named none gets ONE THREAD parked in a select with a deadline — the
//! [`Sweeper`](crate::Sweeper) road, and the same fallback, spelled the same way, for the same
//! reason: a task needs a runtime to be spawned onto, and a world that named no runtime has none to
//! ask.
//!
//! **A thread is never spawned on the async road.** [`RegistryDriver::engine`] is the word that says
//! which road a running driver took, and it is a fact about the value rather than a claim in prose —
//! see [`DriverEngine`].
//!
//! # THE INTAKE ROAD: a LOOSE feed, drained by the driver
//!
//! A key reaches the driver through [`Yielded<Root>`](crate::Yielded) — the far end of a LOOSE
//! [`Feed`](crate::Feed), whose own note says what it is for: *somebody outside the framework drains
//! it*. The registry driver is that somebody, and the two roads onto it are one door:
//!
//! * **THE ORIGIN ROAD.** A mounted origin is handed the loose feed and writes `feed.give(key)`,
//!   exactly as it writes it today — the origin learns nothing, declares nothing and changes not at
//!   all. What differs is where its edge lands: at the driver rather than at the head.
//! * **THE HAND ROAD**, for a deployment with no origin at all. [`crate::feed`] mints the pair, the
//!   deployment keeps the [`Feed`](crate::Feed) and pushes through it — from a command face, a test,
//!   or beside a door taken from [`App::feeder`](crate::App::feeder).
//!
//! A BRIDGED feed is deliberately not the road, and the reason is the bridge's own argument: a
//! bridged feed IS its consumer's edge, so a driver behind one would be a second queue in a place
//! built to have none. The loose line already is the queue, bounded by the depth its minter named.
//!
//! # WHAT AN "END" IS HERE, since this layer has no punctuation
//!
//! [`Wake`](crate::Wake) carries `Delivered`, `Sweep` and `Tick` and nothing else, and *shutdown is
//! the receive failing because every sender is gone*. So the END this driver honours is the loose
//! line's own ending: the last [`Feed`](crate::Feed) clone dropped, which is what a finite origin's
//! `run` returning does. It BEATS BOTH TIMERS — every pending key ripens at once however far its
//! quiet window had to run, and the batch drains however few items it holds — which is
//! [`Batcher::drain`](crate::batch::Batcher::drain)'s own sentence about the punctuation door, said
//! by the one party that can see the punctuation.
//!
//! # THE COUNT: `+1` AT THE GIVE, `-1` AT THE HEAD'S ACK
//!
//! An intake alone leaves a key `Analyzing` with NOTHING in flight
//! ([`RootState::Analyzing`](super::RootState::Analyzing) at zero), and the head node's own `+1`
//! does not exist until the head has actually fanned something out. Between those two instants a
//! key would answer *idle* to anybody looking. So the driver holds one dispatch of its own across
//! exactly that gap: `dispatched` beside the give, and `observed` when the head ACKS — which, by the
//! ack discipline the counting knife was accepted under, is after the head has dispatched its own
//! outputs. The count therefore never touches zero in the middle of a chain that has only started.
//!
//! # THE REGISTRY IS TOUCHED AT THE GIVE AND NOT BEFORE
//!
//! A key sitting in the quiet window or in an open batch is `Idle`, and that is the honest reading:
//! nothing has been asked of the graph for it yet. Taking it in earlier would buy nothing and cost
//! the one thing that matters at shutdown — a dropped batch would leave keys `Analyzing` over work
//! that was never sent. See [`RegistryDriver`] for what a stop does with a pending batch, and why.

use core::future::Future;

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

use agnostic_lite::RuntimeLite;

use crate::{
  batch::{Batcher, Debounce, Push},
  conduit::{Arm, select},
  drive::{ItemId, channel::Outbox, lane::block_until},
  source::{Feed, ShutdownSignal, Stopper, Yielded, shutdown_signal},
};

use super::{Registry, RootAdvance, RootKey, Stamp};

#[cfg(test)]
mod tests;

/// The name the THREAD road's own thread runs under — [`Sweeper`](crate::Sweeper)'s
/// `ingraph-sweep` one seat over, so a stack dump names the body rather than a number.
const THREAD_NAME: &str = "ingraph-registry";

/// WHICH ROAD a running driver took.
///
/// It is a fact about the VALUE and not a claim in prose, which is what makes *no thread on the
/// async engine* an assertion a test can make: a driver that answers [`Task`](Self::Task) holds no
/// [`JoinHandle`] and never asked the operating system for a thread, because the only line in this
/// module that does is on the other road.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DriverEngine {
  /// A long-lived TASK on the runtime the ignition named, timed by that runtime's own sleep.
  Task,
  /// ONE THREAD parked in a select with a deadline — the road a world that named no runtime takes.
  Thread,
}

impl DriverEngine {
  /// A stable name for a report and for logs.
  #[inline]
  #[must_use]
  pub const fn as_str(&self) -> &'static str {
    match self {
      Self::Task => "task",
      Self::Thread => "thread",
    }
  }
}

/// **A RUNNING REGISTRY DRIVER** — dropping it stops the body and, on the thread road, waits for it.
///
/// # It belongs in the SOURCES, and that is where the shutdown order comes from
///
/// [`Ignition::registry_driver`](crate::Ignition::registry_driver) registers one through
/// [`Ignition::source`](crate::Ignition::source), so the handle lands in the running world's source
/// list and is released at STEP 2 of [`App::shutdown`](crate::App::shutdown) — after every mounted
/// origin has been told to wind down (steps 1b and 1c) and before the framework lets go of the edges
/// (step 3) and the nodes drain (step 4). *Origins stop → the driver stops → the nodes drain* is
/// therefore the sequence the existing steps already spell, with the driver at the one place in it
/// that is neither racing the origins nor racing the drain.
///
/// # A STOP DROPS THE PENDING BATCH, and the reason is what a batch IS
///
/// Whatever is in the quiet window or in the open batch when the stop is heard is DROPPED, and
/// nothing about it is written down. Four reasons, and the first is the ruling the tables were built
/// under:
///
/// 1. **The registry is a coordination cache and a timer is not the truth.** A restart rebuilds the
///    states from the ledgers with every count back at zero and no debounce timer surviving. Landing
///    a window at shutdown would be the one act that made a timer outlive the process.
/// 2. **A drain would push NEW work into a graph that is winding down.** The head node is about to
///    be left to drain; giving it a batch at that moment either fails on a closing edge or extends
///    the very wait the shutdown deadline bounds.
/// 3. **Nothing is lost, because the key was never the work.** A key in the window is a key whose
///    CONTENT is still there; the next run's origin says so again. What would be lost by draining is
///    the ordering — see 2.
/// 4. **The registry is untouched by the drop**, which is only true because the intake is taken at
///    the give (see the module note). A driver that had taken its keys in earlier would have to undo
///    them here, and there is no un-intake to call.
///
/// The END of the intake line is the OPPOSITE case and is not this one: a line that ended has no
/// wind-down behind it and nothing more to say, so everything pending flushes at once. See the
/// module note.
///
/// # The stop is heard BETWEEN passes, which is what makes the drop a clean line
///
/// It is one arm of the select, so a driver parked is a driver that hears it at once — the whole
/// reason the stop is a channel rather than a flag looked at on a timer. A driver already inside a
/// pass finishes THAT pass first: the batch it is holding has been given to the head and its acks
/// are owed, and abandoning a give half-made would be the one thing that could leave a key
/// `Analyzing` over an item nobody is going to answer for. So *drop the pending batch* is exactly
/// what it says — the batch that has not been sent — and never a batch already on the wire.
pub struct RegistryDriver {
  /// Said as this goes — [`Stopper`]'s own [`Drop`]. Held in an [`Option`] so the announcement can
  /// be made BEFORE the join below rather than after it, which is the order that makes the join
  /// finite.
  stop: Option<Stopper>,
  /// The thread road's engine. `None` on the async road, which is the whole of what
  /// [`engine`](Self::engine) reports.
  body: Option<JoinHandle<()>>,
}

impl core::fmt::Debug for RegistryDriver {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("RegistryDriver")
      .field("engine", &self.engine())
      .finish()
  }
}

impl RegistryDriver {
  /// **THE THREAD ROAD**: one thread, parked in a select with a deadline.
  ///
  /// [`Sweeper::ticking`](crate::Sweeper::ticking)'s shape at a different question — a stop line
  /// rather than a timer wheel, and a deadline the machines compute rather than a recurrence — and
  /// the same two promises: the stop is observed AT ONCE rather than one window late, and dropping
  /// the handle means the body has actually stopped rather than merely been told to.
  ///
  /// `keys` is the loose feed's far end and `head` is the head node's own inbox, which this takes as
  /// an [`Outbox`] rather than as a [`Feed`](crate::Feed) so that the bridging is made HERE: an
  /// acked give on a loose line has no window to keep, and a driver handed one would refuse every
  /// give it ever made. The one shape that works is therefore the only one that can be passed.
  ///
  /// # Panics
  ///
  /// Where the operating system refuses the thread, which is
  /// [`Sweeper::ticking`](crate::Sweeper::ticking)'s own posture at the same failure: a clock that
  /// could not start is a deployment that will not coordinate, and there is no honest half-running
  /// state to hand back.
  #[must_use]
  pub fn spawn<Root>(
    registry: Arc<Registry<Root>>,
    keys: Yielded<Root>,
    head: Outbox<ItemId, Root>,
  ) -> Self
  where
    Root: RootKey,
  {
    let (stop, halt) = shutdown_signal();
    let machine = Machine::new(registry, head);
    let body = std::thread::Builder::new()
      .name(THREAD_NAME.to_owned())
      .spawn(move || run_parked(machine, &keys, &halt))
      .expect("the registry driver thread");
    Self {
      stop: Some(stop),
      body: Some(body),
    }
  }

  /// **THE ASYNC ROAD**: one long-lived task on `R`, timed by `R`'s own sleep.
  ///
  /// [`spawn`](Self::spawn)'s twin over the runtime a deployment named, and the contract is that
  /// one's verbatim but for what a drop MEANS: a detached task cannot be joined, so dropping this
  /// handle says the stop and returns. What makes that enough is the head's own edge — the driver
  /// holds a sending half of it, so a head node cannot settle until this body has returned and let
  /// go, and the settlement the shutdown already waits for is therefore the driver's ending
  /// observed from the one place it matters.
  ///
  /// [`Ignition::registry_driver`](crate::Ignition::registry_driver) takes the ignition's own
  /// [`spawn`](crate::Ignition::spawn) instead, which HOLDS the join; this is the door for a
  /// deployment building a driver from a running [`App`](crate::App).
  #[must_use]
  pub fn spawn_on<R, Root>(
    registry: Arc<Registry<Root>>,
    keys: Yielded<Root>,
    head: Outbox<ItemId, Root>,
  ) -> Self
  where
    R: RuntimeLite,
    Root: RootKey,
  {
    let (stop, halt) = shutdown_signal();
    R::spawn_detach(run_task::<R, Root>(
      Machine::new(registry, head),
      keys,
      halt,
    ));
    Self::stopping(stop)
  }

  /// The handle for a body somebody ELSE spawned — what
  /// [`Ignition::registry_driver`](crate::Ignition::registry_driver) registers once it has handed
  /// the body to [`Ignition::spawn`](crate::Ignition::spawn), which holds the join this cannot.
  #[inline]
  #[must_use]
  pub(crate) const fn stopping(stop: Stopper) -> Self {
    Self {
      stop: Some(stop),
      body: None,
    }
  }

  /// Which road this driver took — see [`DriverEngine`].
  #[inline]
  #[must_use]
  pub const fn engine(&self) -> DriverEngine {
    match self.body {
      Some(_) => DriverEngine::Thread,
      None => DriverEngine::Task,
    }
  }
}

/// **THE ASYNC ROAD's BODY, COMPOSED**, for the walk that holds a runtime and wants to hold the join
/// too — [`Ignition::registry_driver`](crate::Ignition::registry_driver)'s own line.
///
/// The R-less fallback's shape one seat over ([`Ignition::task`](crate::Ignition::task)): the body is
/// handed back rather than spawned, so the party that has both a runtime AND somewhere to put a join
/// can use both. [`RegistryDriver::spawn_on`] is the same body detached, for a caller with nowhere to
/// put one.
pub(crate) fn body<R, Root>(
  registry: Arc<Registry<Root>>,
  keys: Yielded<Root>,
  head: Outbox<ItemId, Root>,
  halt: ShutdownSignal,
) -> impl Future<Output = ()> + Send + 'static
where
  R: RuntimeLite,
  Root: RootKey,
{
  run_task::<R, Root>(Machine::new(registry, head), keys, halt)
}

impl Drop for RegistryDriver {
  /// Say the stop, THEN wait for the body where there is one to wait for.
  ///
  /// The order is what makes the wait finite: the announcement is what ends the select the body is
  /// parked in, so joining first would be joining a body nothing had told to go.
  fn drop(&mut self) {
    drop(self.stop.take());
    if let Some(body) = self.body.take() {
      let _ = body.join();
    }
  }
}

/// WHAT ONE TURN OF THE LOOP HEARD.
///
/// Four, and they are the four things that can happen to a coalescer: a key arrived, the line
/// ended, a deadline came due, or the world said stop. The two engines differ in how they WAIT for
/// one and in nothing else — which is the whole reason this enum exists rather than each loop
/// branching on its own channel.
enum Turn<Root> {
  /// A key was pushed.
  Key(Root),
  /// The intake line ENDED — every [`Feed`](crate::Feed) onto it is gone, so no key can arrive
  /// again. The punctuation, in the only vocabulary this layer has one in.
  Ended,
  /// A deadline the machines named has come due. It carries nothing: what is due is read off the
  /// machines afterwards, by the same code that reads it after every other turn.
  Due,
  /// The world said stop.
  Halt,
}

/// THE COALESCER AND WHAT IT WRITES INTO — everything a turn needs, and no engine anywhere in it.
///
/// It reads no clock of its own for the same reason [`Batcher`] and [`Debounce`] do not: `now`
/// arrives from the loop that woke at it. What it does hold that they do not is the two ends the
/// coalescing exists to join — the family's table, and the head node's feed.
struct Machine<Root: 'static> {
  registry: Arc<Registry<Root>>,
  /// The head node's own edge, bridged. The driver is its ONLY writer, which is what makes the
  /// order the head sees the order this loop decided.
  head: Feed<Root>,
  debounce: Debounce<Root>,
  batcher: Batcher<Root>,
}

impl<Root: RootKey> Machine<Root> {
  /// A machine tuned by whatever this family's table is holding RIGHT NOW — the `[registry]`
  /// section's own values, resolved for the family when it was opened.
  fn new(registry: Arc<Registry<Root>>, head: Outbox<ItemId, Root>) -> Self {
    let options = registry.options();
    Self {
      registry,
      head: Feed::bridging(head),
      debounce: Debounce::new(options.debounce()),
      batcher: Batcher::new(options.batch_max_items(), options.batch_max_wait()),
    }
  }

  /// WHEN THE LOOP MUST COME BACK — the earlier of the two machines' own deadlines, or [`None`]
  /// where neither is holding anything.
  ///
  /// `None` is *park on arrivals alone*, which both machines already spell for themselves; taking
  /// the minimum is the whole of what a loop owning two of them adds.
  fn deadline(&self) -> Option<Instant> {
    match (self.debounce.deadline(), self.batcher.deadline()) {
      (Some(quiet), Some(batch)) => Some(quiet.min(batch)),
      (deadline, None) | (None, deadline) => deadline,
    }
  }

  /// A key was pushed at `now` — its quiet window RESTARTS.
  #[inline]
  fn touched(&mut self, key: Root, now: Instant) {
    self.debounce.touch(key, now);
  }

  /// Move every key that has fallen quiet by `now` into the batch, handing back whatever batches
  /// CLOSED on the way.
  ///
  /// More than one is reachable and is not an edge case: a burst of thirty keys ripening in one
  /// window fills three batches of ten, and a driver that answered only the first would leave two
  /// full batches waiting on a timer that has nothing to do with them.
  ///
  /// A [`Push::Refused`] cannot happen on this path — the batch is drained the moment it answers
  /// [`Push::Full`] — but it is spelled rather than unwrapped, because the refusal exists exactly so
  /// that a driver cannot grow a batch past its ceiling by accident.
  fn ripened(&mut self, now: Instant) -> Vec<Vec<Root>> {
    let mut closed = Vec::new();
    for key in self.debounce.ripe(now) {
      let mut offered = key;
      loop {
        match self.batcher.push(offered, now) {
          Push::Queued => break,
          Push::Full => {
            closed.push(self.batcher.drain());
            break;
          }
          Push::Refused(back) => {
            closed.push(self.batcher.drain());
            offered = back;
          }
        }
      }
    }
    closed
  }

  /// The open batch where its WAIT has run out at `now`, and nothing otherwise.
  fn due(&mut self, now: Instant) -> Option<Vec<Root>> {
    self.batcher.ready(now).then(|| self.batcher.drain())
  }

  /// **THE PUNCTUATION DOOR**: everything pending, at once, whatever the two timers say.
  ///
  /// Every key still in its quiet window ripens — the line has ended, so no further touch can arrive
  /// to extend one — and the batch drains however few items it holds. See the module note for why
  /// the line's own ending is what an END means here.
  fn ended(&mut self, now: Instant) -> Vec<Vec<Root>> {
    // `now + quiet` is the instant every key touched at or before `now` has ripened by, which is
    // every key there can be: nothing can touch this debounce again.
    let all = now.checked_add(self.debounce.quiet()).unwrap_or(now);
    let mut closed = self.ripened(all);
    let last = self.batcher.drain();
    if !last.is_empty() {
      closed.push(last);
    }
    closed
  }

  /// **RE-READ THE DIAL** where there is nothing to carry over.
  ///
  /// The options layer's third tier — [`Registry::apply_knobs`](super::Registry::apply_knobs), which
  /// a GraphQL mutation turns at request time — reaches a RUNNING driver here, and only here: a
  /// window half-elapsed under one quiet and a batch half-filled under one ceiling have no honest
  /// reading under different ones, so the machines are rebuilt at the one moment they hold nothing.
  /// A driver with work in hand keeps the dial it started the work under and takes the new one at
  /// its next quiet moment, which for every knob these three are is the next moment that matters.
  ///
  /// Both loops call it at the TOP of a turn rather than at the bottom, and the difference is the
  /// only one that matters: a driver parked with nothing pending is a driver that will not turn
  /// again until a key arrives, and a dial re-read after that key had already been touched into the
  /// old window would take effect one key late.
  fn retune(&mut self) {
    if !self.debounce.is_empty() || !self.batcher.is_empty() {
      return;
    }
    let options = self.registry.options();
    if options.debounce() != self.debounce.quiet() {
      self.debounce = Debounce::new(options.debounce());
    }
    if options.batch_max_items() != self.batcher.max_items()
      || options.batch_max_wait() != self.batcher.max_wait()
    {
      self.batcher = Batcher::new(options.batch_max_items(), options.batch_max_wait());
    }
  }

  /// **SEND ONE BATCH**, and hold a dispatch of this driver's own until the head has acked each key.
  ///
  /// Two passes rather than one, and the split is what keeps the batch a batch: the whole of it
  /// reaches the head before any of its acks is waited for, so a head that batches internally sees
  /// the burst the driver assembled rather than a trickle it has to reassemble.
  ///
  /// The gate is the INTAKE, and the three answers it can give that are not *go* are all the same
  /// instruction: a `Declined` key is retired and is not wanted, and a `Queued` or `Coalesced` one
  /// is behind a retirement or a restore, which is where the intake will be applied when that act
  /// finishes. Dispatching either would be work the registry has already refused — and, on a
  /// draining key, a dispatch is the refusal that sets `late_tails`.
  async fn send(&mut self, batch: Vec<Root>) {
    let stamp = Stamp::now();
    let mut flying = Vec::with_capacity(batch.len());
    for key in batch {
      match self.registry.intake(&key, stamp) {
        RootAdvance::Moved | RootAdvance::Unchanged => {}
        RootAdvance::Queued | RootAdvance::Coalesced | RootAdvance::Declined => continue,
      }
      let _taken = self.registry.dispatched(&key, stamp);
      match self.head.give_acked_async(key.clone()).await {
        Ok(acked) => flying.push((key, acked)),
        // The graph hung up. The give never landed, so the `+1` above answers nothing and is
        // balanced here rather than left holding the key `Analyzing` over an item that does not
        // exist.
        Err(_unacked) => {
          let _balanced = self.registry.observed(&key, stamp);
        }
      }
    }
    for (key, acked) in flying {
      // A HUNG-UP ack counts exactly as an answer does, and for the counting knife's own reason: an
      // item whose consumer left is an item no answer is ever coming for, and leaving it uncounted
      // would hold the key `Analyzing` forever over work that no longer exists.
      let _answered = acked.settled_async().await;
      let _released = self.registry.observed(&key, Stamp::now());
    }
  }

  /// Everything one turn owes after whatever it heard: the ripe keys in, then the due batch out.
  async fn worked(&mut self, now: Instant) {
    for batch in self.ripened(now) {
      self.send(batch).await;
    }
    if let Some(batch) = self.due(now) {
      self.send(batch).await;
    }
  }
}

/// One arm: the intake line, wrapped into this loop's own turn.
///
/// [`conduit::arm`](crate::conduit::arm)'s shape over a [`Yielded`], which carries no `arm` of its
/// own: `None` from the take is the line's END rather than an absence, so the two outcomes are two
/// turns rather than an [`Option`] the select would have to unwrap.
async fn pushed<Root>(keys: &Yielded<Root>) -> Turn<Root> {
  keys.take_async().await.map_or(Turn::Ended, Turn::Key)
}

/// One arm: the stop.
///
/// [`ShutdownSignal::arm`] never answers `None` — its own note says why, and the fallback below is
/// that sentence written where a reader of this loop can see it rather than a case that can arise.
async fn halted<Root>(halt: &ShutdownSignal) -> Turn<Root> {
  halt.arm(true, || Turn::Halt).await.unwrap_or(Turn::Halt)
}

/// **THE ASYNC ROAD's LOOP**: one task, three arms, and the runtime's own sleep as the deadline.
///
/// The sleep arm is armed on EVERY turn rather than only where a deadline exists, and a turn with
/// none arms it at `pending` instead: an arm that never answers costs a poll and keeps the slice one
/// shape, where a conditional third arm would make the winner's index mean two different things.
async fn run_task<R, Root>(mut machine: Machine<Root>, keys: Yielded<Root>, halt: ShutdownSignal)
where
  R: RuntimeLite,
  Root: RootKey,
{
  let mut from = 0;
  loop {
    machine.retune();
    let deadline = machine.deadline();
    let turn = {
      let wait = deadline.map(|at| at.saturating_duration_since(Instant::now()));
      let mut pushing = core::pin::pin!(pushed(&keys));
      let mut stopping = core::pin::pin!(halted(&halt));
      let mut sleeping = core::pin::pin!(async move {
        match wait {
          Some(wait) => {
            // The answer is the runtime's own instant and is dropped: what a driver woke AT is read
            // off `Instant::now()` below, on the one clock the machines were touched under.
            let _woke = R::sleep(wait).await;
          }
          // Due NEVER — the honest arm for a turn with nothing pending, and what makes the slice
          // one shape whatever the machines are holding.
          None => core::future::pending().await,
        }
        Turn::Due
      });
      let mut arms: [Arm<'_, Turn<Root>>; 3] =
        [pushing.as_mut(), stopping.as_mut(), sleeping.as_mut()];
      select(from, &mut arms).await
    };
    let Some((index, turn)) = turn else {
      // Unreachable: the slice is never empty. Treated as a deadline rather than as an ending, so
      // that a fourth arm added later cannot turn a select this loop does not understand into a
      // silent stop.
      machine.worked(Instant::now()).await;
      continue;
    };
    // Past the winner, so a busy intake cannot starve the stop.
    from = index + 1;
    match turn {
      Turn::Key(key) => {
        let now = Instant::now();
        machine.touched(key, now);
        // One wake serves the whole burst, which is what makes ten keys pushed together one batch
        // rather than ten turns of the loop.
        for key in keys.drain() {
          machine.touched(key, now);
        }
      }
      Turn::Due => {}
      Turn::Ended => {
        let now = Instant::now();
        for batch in machine.ended(now) {
          machine.send(batch).await;
        }
        return;
      }
      // THE DROP. See `RegistryDriver`'s own note for the four reasons.
      Turn::Halt => return,
    }
    machine.worked(Instant::now()).await;
  }
}

/// **THE THREAD ROAD's LOOP**: the same turns, waited for on this thread.
///
/// [`block_until`] is what the async road's third arm is here — one future, no reactor, no runtime —
/// so the deadline is the PARK's rather than an arm of its own, and the two arms left are the two
/// channels. `None` from the park is the deadline, which is the same turn the sleep arm answers over
/// there.
fn run_parked<Root>(mut machine: Machine<Root>, keys: &Yielded<Root>, halt: &ShutdownSignal)
where
  Root: RootKey,
{
  let mut from = 0;
  loop {
    machine.retune();
    let deadline = machine.deadline();
    let parked = {
      let mut pushing = core::pin::pin!(pushed(keys));
      let mut stopping = core::pin::pin!(halted(halt));
      let mut arms: [Arm<'_, Turn<Root>>; 2] = [pushing.as_mut(), stopping.as_mut()];
      block_until(select(from, &mut arms), deadline)
    };
    let turn = match parked {
      Some(Some((index, turn))) => {
        from = index + 1;
        turn
      }
      // The deadline, or a select over nothing — the latter unreachable, and read as the former for
      // `run_task`'s own reason.
      None | Some(None) => Turn::Due,
    };
    match turn {
      Turn::Key(key) => {
        let now = Instant::now();
        machine.touched(key, now);
        for key in keys.drain() {
          machine.touched(key, now);
        }
      }
      Turn::Due => {}
      Turn::Ended => {
        let now = Instant::now();
        for batch in machine.ended(now) {
          block_on_batch(&mut machine, batch);
        }
        return;
      }
      // THE DROP. See `RegistryDriver`'s own note for the four reasons.
      Turn::Halt => return,
    }
    let now = Instant::now();
    for batch in machine.ripened(now) {
      block_on_batch(&mut machine, batch);
    }
    if let Some(batch) = machine.due(now) {
      block_on_batch(&mut machine, batch);
    }
  }
}

/// [`Machine::send`], driven on THIS thread — the one line the two roads differ in, spelled once.
///
/// It is the same posture the awaited origin face already takes: the body is written as a future
/// because a give and an ack are both waits, and the thread engine pins it here rather than the
/// framework writing the whole of it twice.
fn block_on_batch<Root>(machine: &mut Machine<Root>, batch: Vec<Root>)
where
  Root: RootKey,
{
  let sent = block_until(machine.send(batch), None);
  debug_assert!(
    sent.is_some(),
    "a park with no deadline runs the future to completion"
  );
}