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

use std::{
  convert::Infallible,
  sync::{Arc, Mutex},
  thread,
  time::SystemTime,
};

use super::{
  super::{
    AsyncLands, Attributes, Commit, Delivery, Item, ItemId, JournalRow, Ledger, Payload,
    RecordingTap, Resident, Station, Taps, ack_channel, channel,
  },
  Answers, AsyncAnswers, Invoke, QueryArm, QueryError, door, reply,
};
use crate::{Arrival, Emitter, NodeName, Operator, drive::Drives};

/// How long a proof waits before deciding an answer is never coming.
///
/// A DEADLINE and not a sleep: every walk here is driven by real threads, so the alternative to a
/// bounded wait is a regression that hangs a run rather than reddening it. Generous enough that a
/// loaded machine does not trip it, short enough that a broken read path is reported while somebody
/// is still looking.
const DEADLINE: Duration = Duration::from_secs(10);

// ─── the toy tower and the toy index ────────────────────────────────────────────────────────────

/// What a tower produces and an index searches by.
type Vector = Vec<f32>;

/// What a search answers with — a pointer back into the system of record, never a payload.
type Hits = Vec<u64>;

/// One image, as the indexing side's upstream hands it over.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Keyframe {
  id: u64,
}

/// One INDEXED entry: the key it is addressed by, and the coordinates it is found by.
#[derive(Debug, Clone, PartialEq)]
struct Entry {
  key: u64,
  vector: Vector,
}

/// The index itself — the one thing the write arm and the read arm SHARE.
///
/// It stands in for what a real engine gives: tantivy's `Searcher` beside its `IndexWriter`,
/// lancedb's equivalent. The lock is held for the length of a write and for the length of a read
/// and never across a park, which is exactly the property that makes a read-during-write possible;
/// an engine that could not do this is one the framework was never asked to support.
#[derive(Debug, Clone, Default)]
struct Index(Arc<Mutex<Vec<Entry>>>);

impl Index {
  /// Keyed replace, last write wins — the write arm's half.
  fn write(&self, entries: &[Entry]) {
    let mut held = self.0.lock().expect("the index");
    for entry in entries {
      match held.iter_mut().find(|held| held.key == entry.key) {
        Some(existing) => existing.vector.clone_from(&entry.vector),
        None => held.push(entry.clone()),
      }
    }
  }

  /// Nearest neighbours by squared distance — the read arm's half.
  fn nearest(&self, query: &[f32], k: usize) -> Hits {
    let held = self.0.lock().expect("the index");
    let mut scored: Vec<(u64, f32)> = held
      .iter()
      .map(|entry| {
        let distance = entry
          .vector
          .iter()
          .zip(query)
          .map(|(a, b)| (a - b) * (a - b))
          .sum::<f32>();
        (entry.key, distance)
      })
      .collect();
    scored.sort_by(|a, b| a.1.partial_cmp(&b.1).expect("no NaN in a toy vector"));
    scored.into_iter().take(k).map(|(key, _)| key).collect()
  }

  fn len(&self) -> usize {
    self.0.lock().expect("the index").len()
  }
}

/// The INDEXING node: an image goes in, an entry comes out.
struct ImageTower;

impl Operator for ImageTower {
  type Error = Infallible;
  type In = Keyframe;
  type Out = Entry;

  fn accept(
    &mut self,
    _ctx: &Context,
    delivery: Delivery<Self::In>,
    emitter: &mut Emitter<Entry>,
  ) -> Result<(), Self::Error> {
    for item in delivery.into_items() {
      let item = item.into_value();
      #[expect(
        clippy::cast_precision_loss,
        reason = "a toy id is small by construction"
      )]
      let coordinate = item.id as f32;
      emitter.emit(Entry {
        key: item.id,
        vector: vec![coordinate, 0.0],
      });
    }
    Ok(())
  }
}

/// The index node's WRITE arm: it stages what it saw, and the lane commits it.
struct Indexer;

impl Operator for Indexer {
  type Error = Infallible;
  type In = Entry;
  type Out = Entry;

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

/// A handshake a write batch can be PARKED on, so a proof can hold one open and ask a question
/// while it is in flight.
#[derive(Debug, Clone)]
struct Latch {
  entered: flume::Sender<()>,
  release: flume::Receiver<()>,
}

/// The index's write lane. Where the barrier lives, when there is one.
struct IndexLane {
  index: Index,
  latch: Option<Latch>,
}

impl AsyncLands<Entry> for IndexLane {
  type Error = Infallible;

  async fn land(&mut self, items: &[Entry]) -> Commit<Self::Error> {
    if let Some(latch) = &self.latch {
      // Announce that the batch is IN FLIGHT, then hold it there. Nothing about the index is locked
      // while this waits, which is the whole point: the write is occupying the node, not the store.
      let _ = latch.entered.send(());
      let _ = latch.release.recv();
    }
    self.index.write(items);
    Commit::all()
  }
}

/// The TEXT tower: a query node whose input is the raw modality and whose output is the next hop's.
///
/// It is its own typed node and never the indexing tower re-used, which is the ruling's own
/// correction: an indexing node's input is the source ENTITY and a query's is a `String`, so a
/// query edge could never point at one even inside a same-network family.
struct TextTower;

/// A query with nothing in it — a responder's own refusal, in its own currency.
#[derive(Debug, derive_more::Display)]
#[display("a query needs something to search for")]
struct EmptyQuery;

impl core::error::Error for EmptyQuery {}

impl Answers<String> for TextTower {
  type Error = EmptyQuery;
  type Output = Vector;

  fn on_invoke(&mut self, input: String) -> Result<Vector, Self::Error> {
    if input.is_empty() {
      return Err(EmptyQuery);
    }
    // The toy "embedding": the number of words, which is enough to be asked for and found.
    #[expect(
      clippy::cast_precision_loss,
      reason = "a toy corpus is small by construction"
    )]
    let coordinate = input.split_whitespace().count() as f32;
    Ok(vec![coordinate, 0.0])
  }
}

/// A ONE-HOP query node: text in, hits out.
///
/// The terminal shape, which is what most chains are — the two-hop walk below is what proves the
/// chain can be longer, and this is what proves it does not have to be.
struct Lookup {
  index: Index,
  k: usize,
}

impl Answers<String> for Lookup {
  type Error = EmptyQuery;
  type Output = Hits;

  fn on_invoke(&mut self, input: String) -> Result<Hits, Self::Error> {
    let mut tower = TextTower;
    // A blocking hop calling a blocking hop: the `.await` this line carried was unwrapping a future
    // that had never waited for anything, which is the whole of what the face pair deleted.
    let vector = tower.on_invoke(input)?;
    Ok(self.index.nearest(&vector, self.k))
  }
}

/// The index node's READ arm — the second, lightweight arm beside its resident.
struct VectorSearch {
  index: Index,
  k: usize,
}

impl Answers<Vector> for VectorSearch {
  type Error = Infallible;
  type Output = Hits;

  fn on_invoke(&mut self, input: Vector) -> Result<Hits, Self::Error> {
    Ok(self.index.nearest(&input, self.k))
  }
}

/// The SAME responder on the OTHER face, so one type is driven through BOTH cells of the arm's
/// matrix and the two are compared on the same corpus.
///
/// A responder wearing both faces is legal and says nothing about which one drives it — that is the
/// arm's verb's business, exactly as a unit wearing both `Operator` faces leaves the choice to the
/// resident it was built on. Here it is what lets
/// [`the_async_engine_serves_the_same_chain_as_the_thread_one`] be a claim about the ENGINES rather
/// than about two different responders.
impl AsyncAnswers<Vector> for VectorSearch {
  type Error = Infallible;
  type Output = Hits;

  async fn on_invoke(&mut self, input: Vector) -> Result<Hits, Self::Error> {
    Ok(self.index.nearest(&input, self.k))
  }
}

// ─── the journal, so a proof can see what the durable side did ───────────────────────────────

/// One `(root, node)` completion row, as a deployment declares one.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Row {
  root: u64,
  node: String,
  station: Station,
}

impl JournalRow<u64> for Row {
  fn of(root: &u64, node: &NodeName, arrival: &Arrival, _at: SystemTime) -> Self {
    Self {
      root: *root,
      node: node.as_str().to_owned(),
      station: arrival.station(),
    }
  }
}

/// The rows a run kept.
type Rows = Arc<Mutex<Vec<Row>>>;

/// A control store that keeps every row it is given.
struct Runs(Rows);

impl Ledger for Runs {
  type Error = Infallible;
  type Row = Row;

  fn record(&mut self, rows: &[Row]) -> Result<(), Self::Error> {
    self.0.lock().expect("the rows").extend_from_slice(rows);
    Ok(())
  }

  async fn record_async(&mut self, rows: &[Row]) -> Result<(), Self::Error> {
    self.record(rows)
  }
}

/// The projection an emitted wrapper would supply: which root an entry descends from.
struct Roots;

impl Attributes<Entry> for Roots {
  type Root = u64;

  fn root(&self, record: &Entry) -> u64 {
    record.key
  }

  fn observe(&self, _root: &u64, _worker: &NodeName, _arrival: &Arrival) {}
}

// ─── the primitives ─────────────────────────────────────────────────────────────────────────────

#[test]
fn a_reply_carries_the_result_and_a_dropped_one_is_a_typed_error() {
  let (answer, awaiting) = reply::<Hits>();
  assert!(answer.is_awaited());
  assert!(answer.answer(vec![7, 9]));
  assert_eq!(awaiting.take().expect("answered"), vec![7, 9]);

  // THE RULED SEMANTICS: a dropped reply is not a re-delivery. There is no window holding anything,
  // so the caller learns it here and the question ends.
  let (answer, awaiting) = reply::<Hits>();
  drop(answer);
  assert_eq!(awaiting.take().expect_err("dropped"), QueryError::Dropped);
}

#[test]
fn a_reply_nobody_is_waiting_for_is_dropped_rather_than_held() {
  let (answer, awaiting) = reply::<Hits>();
  drop(awaiting);
  assert!(!answer.is_awaited());
  assert!(
    !answer.answer(vec![1]),
    "a withdrawn question keeps nothing"
  );
}

#[test]
fn a_door_with_nobody_behind_it_is_unreachable() {
  let (front, invokes) = door::<String, Hits>(1);
  drop(invokes);
  assert!(front.is_closed());
  assert_eq!(
    front.invoke("red car".to_owned()).expect_err("nobody home"),
    QueryError::Unreachable
  );
}

#[test]
fn a_deadline_says_which_way_the_wait_ended() {
  // Two ways to stop waiting and they are different facts: `TimedOut` says nothing about the query,
  // which may still be running, while `Dropped` says the chain is gone.
  let (answer, awaiting) = reply::<Hits>();
  assert_eq!(
    awaiting
      .take_within(Duration::from_millis(20))
      .expect_err("nothing answered"),
    QueryError::TimedOut
  );
  drop(answer);

  let (answer, awaiting) = reply::<Hits>();
  drop(answer);
  assert_eq!(
    awaiting.take_within(DEADLINE).expect_err("dropped"),
    QueryError::Dropped
  );
}

#[test]
fn the_query_errors_read_as_what_they_are() {
  fn is_error<E: core::error::Error>(_: &E) {}
  is_error(&QueryError::Dropped);
  assert!(QueryError::Unreachable.is_unreachable());
  assert!(
    QueryError::Dropped
      .to_string()
      .contains("without an answer")
  );
  assert!(QueryError::TimedOut.to_string().contains("deadline"));
  assert!(
    QueryError::Unreachable
      .to_string()
      .contains("not listening")
  );
}

#[test]
fn an_invoke_splits_into_the_input_and_the_reply_that_travels_past_it() {
  let (answer, awaiting) = reply::<Hits>();
  let invoke = Invoke::new("red car".to_owned(), answer);
  assert_eq!(invoke.input(), "red car");
  let (input, answer) = invoke.into_parts();
  assert_eq!(input, "red car");
  // The whole of multi-hop: the input stops here and the reply goes on.
  let onward = Invoke::new(vec![1.0_f32], answer);
  let (_, answer) = onward.into_parts();
  assert!(answer.answer(vec![3]));
  assert_eq!(awaiting.take().expect("answered"), vec![3]);
}

#[test]
fn a_transient_inbox_carries_invokes_and_ends_when_every_door_is_gone() {
  let (front, invokes) = door::<String, Hits>(4);
  assert!(invokes.is_empty());
  let first = front.invoke("a".to_owned()).expect("listening");
  let second = front.invoke("b".to_owned()).expect("listening");
  assert_eq!(invokes.len(), 2);

  let taken = invokes.park().expect("queued");
  assert_eq!(taken.input(), "a");
  drop(taken);
  drop(second);
  drop(first);

  let taken = invokes.park().expect("queued");
  assert_eq!(taken.input(), "b");
  drop(taken);
  drop(front);
  assert!(invokes.is_disconnected());
  assert!(invokes.park().is_none(), "shutdown is every door gone");
}

// ─── the arm ────────────────────────────────────────────────────────────────────────────────────

#[test]
fn a_terminal_arm_answers_its_caller() {
  let index = Index::default();
  index.write(&[
    Entry {
      key: 1,
      vector: vec![1.0, 0.0],
    },
    Entry {
      key: 9,
      vector: vec![9.0, 0.0],
    },
  ]);
  let (front, invokes) = door::<Vector, Hits>(4);
  let mut arm = QueryArm::new("index", VectorSearch { index, k: 1 }, invokes);
  assert_eq!(arm.name().as_str(), "index");
  assert_eq!(arm.queued(), 0);

  let awaiting = front.invoke(vec![8.6, 0.0]).expect("listening");
  drop(front);
  let served = arm.run();

  assert_eq!(awaiting.take().expect("answered"), vec![9]);
  assert_eq!(served.invokes(), 1);
  assert_eq!(served.passed(), 1);
  assert_eq!(served.abandoned(), 0);
  assert_eq!(served.failed(), 0);
}

#[test]
fn a_refused_query_drops_the_reply_and_the_tap_keeps_the_error() {
  // The ruled contract, both halves: the CALLER gets a typed query error, and the ERROR keeps its
  // own type where a tap can still ask for it. Rendering it into the answer would have erased it at
  // exactly the layer that still knew what it was.
  let tap = Arc::new(RecordingTap::new());
  let (front, invokes) = door::<String, Hits>(4);
  let mut arm = QueryArm::new(
    "tower",
    Lookup {
      index: Index::default(),
      k: 1,
    },
    invokes,
  )
  .with_taps(Taps::new().with(tap.clone()));

  let awaiting = front.invoke(String::new()).expect("listening");
  drop(front);
  let served = arm.run();

  assert_eq!(awaiting.take().expect_err("refused"), QueryError::Dropped);
  assert_eq!(served.failed(), 1);
  assert_eq!(served.passed(), 0);
  assert_eq!(tap.seen(), vec![("tower".to_owned(), Station::Failed)]);
}

#[test]
fn an_answer_nobody_waited_for_is_abandoned_and_never_retried() {
  let (front, invokes) = door::<String, Hits>(4);
  let mut arm = QueryArm::new(
    "tower",
    Lookup {
      index: Index::default(),
      k: 1,
    },
    invokes,
  );
  let awaiting = front.invoke("red car".to_owned()).expect("listening");
  // The caller withdraws the question before the arm ever looks at it.
  drop(awaiting);
  drop(front);
  let served = arm.run();
  assert_eq!(served.invokes(), 1);
  assert_eq!(served.abandoned(), 1);
  assert_eq!(served.passed(), 0);
  assert_eq!(served.failed(), 0);
}

#[test]
fn an_answered_query_is_observed_which_is_the_trace_the_exemption_claims() {
  // A query-only node is exempt from the pure-leaf refusal because its work leaves a trace by
  // construction. This is the trace, and the station is `Processed` and never `Persisted`: a query
  // READS, so the arm reached no durability and must not claim to have.
  //
  // MUTATION-CHECKED: answering `Persisted` here — a transient arm claiming the durability that an
  // ACK is what certifies — reds this, `[("tower", Persisted)]` against `[("tower", Processed)]`.
  // That is the observational half of *a transient edge does not ack*.
  let tap = Arc::new(RecordingTap::new());
  let (front, invokes) = door::<String, Hits>(4);
  let mut arm = QueryArm::new(
    "tower",
    Lookup {
      index: Index::default(),
      k: 1,
    },
    invokes,
  )
  .with_taps(Taps::new().with(tap.clone()));
  let awaiting = front.invoke("a red car".to_owned()).expect("listening");
  drop(front);
  arm.run();
  assert_eq!(awaiting.take().expect("answered").len(), 0);
  assert_eq!(tap.seen(), vec![("tower".to_owned(), Station::Processed)]);
}

#[test]
fn the_async_engine_serves_the_same_chain_as_the_thread_one() {
  let index = Index::default();
  index.write(&[Entry {
    key: 4,
    vector: vec![4.0, 0.0],
  }]);
  let (front, invokes) = door::<Vector, Hits>(4);
  let mut arm = QueryArm::new("index", VectorSearch { index, k: 1 }, invokes);
  let awaiting = front.invoke(vec![4.0, 0.0]).expect("listening");
  drop(front);

  let served = tokio::runtime::Builder::new_current_thread()
    .build()
    .expect("a current-thread runtime")
    .block_on(arm.run_async());

  assert_eq!(awaiting.take().expect("answered"), vec![4]);
  assert_eq!(served.passed(), 1);
}

// ─── the fan-in, end to end ─────────────────────────────────────────────────────────────────────

/// THE SHAPE THE RULING DESCRIBES, wired by hand:
///
/// ```text
/// Keyframe ─→ ImageTower ── durable ──┐
///                                      ├→ KeyframeVectors   ← a TRUE fan-in, two edge kinds
/// resolver ─→ TextTower  ── transient ─┘
/// ```
///
/// The index node subscribes to both, and the two subscriptions are not two ways of being fed one
/// thing: the durable one carries an ack window, a write and a journal, and the transient one
/// carries a question somebody is holding the answer to.
///
/// What this proves, in one walk: a query travels TWO HOPS and comes back with the right hits; the
/// indexing side's own machinery counts only the indexing side's work; and no journal row was
/// ever written for a query.
#[test]
fn a_query_round_trips_through_two_hops_into_a_true_fan_in() {
  let index = Index::default();
  let rows: Rows = Rows::default();

  // The DURABLE lane: a source into the image tower, and the tower into the index node.
  let (images_out, images_in) = channel::<ItemId, Keyframe>(8);
  let (entries_out, entries_in) = channel::<ItemId, Entry>(8);

  // The TRANSIENT lane: a resolver's door into the text tower, and the text tower's door into the
  // index node. The second is an edge between two nodes; the first is the door, whose other end is
  // not a node at all.
  let (front, queries) = door::<String, Hits>(4);
  let (search_door, searches) = door::<Vector, Hits>(4);

  let mut tower = Resident::new("images", ImageTower, images_in).publish(entries_out);
  let mut writer = Resident::new("index", Indexer, entries_in)
    .land(IndexLane {
      index: index.clone(),
      latch: None,
    })
    .attributing(Roots)
    .recording_to(Runs(Arc::clone(&rows)));
  let mut text = QueryArm::new("text", TextTower, queries).forwarding_to(search_door);
  let mut reader = QueryArm::new(
    "index",
    VectorSearch {
      index: index.clone(),
      k: 2,
    },
    searches,
  );

  let tower_run = thread::Builder::new()
    .name("images".to_owned())
    .spawn(move || tower.run())
    .expect("the image tower's thread");
  let writer_run = thread::Builder::new()
    .name("index".to_owned())
    .spawn(move || writer.run())
    .expect("the index node's write arm");
  let text_run = thread::Builder::new()
    .name("text".to_owned())
    .spawn(move || text.run())
    .expect("the text tower's arm");
  let reader_run = thread::Builder::new()
    .name("search".to_owned())
    .spawn(move || reader.run())
    .expect("the index node's read arm");

  // Index three images, and wait for the effect to be durable in the index's own store.
  let (ack, answers) = ack_channel();
  images_out
    .deliver(Delivery::new(
      Payload::Batch(vec![
        Item::new(ItemId::new(1), Keyframe { id: 1 }),
        Item::new(ItemId::new(2), Keyframe { id: 2 }),
        Item::new(ItemId::new(3), Keyframe { id: 3 }),
      ]),
      ack,
    ))
    .expect("the image tower is listening");
  let indexed = crate::drive::invoke::tests::until(|| index.len() == 3);
  assert!(indexed, "the indexing lane wrote its three entries");
  drop(answers);

  // THE QUERY: one call, two hops, one answer.
  let hits = front
    .invoke("two words".to_owned())
    .expect("the text tower is listening")
    .take_within(DEADLINE)
    .expect("the chain answered");
  assert_eq!(
    hits,
    vec![2, 1],
    "nearest to the toy embedding of a 2-word query"
  );

  drop(front);
  drop(images_out);
  let tower_report = tower_run.join().expect("the image tower");
  let writer_report = writer_run.join().expect("the index node");
  let text_report = text_run.join().expect("the text tower");
  let reader_report = reader_run.join().expect("the read arm");

  // THE QUERY FLOW: two hops, one answer, and both arms counted it.
  assert_eq!(text_report.invokes(), 1);
  assert_eq!(
    text_report.passed(),
    1,
    "the text tower FORWARDED rather than answering"
  );
  assert_eq!(reader_report.invokes(), 1);
  assert_eq!(
    reader_report.passed(),
    1,
    "the read arm answered the caller"
  );

  // THE DURABLE SIDE, UNTOUCHED. Every one of these numbers is the indexing flow's and nothing
  // else's: two queries crossed this node and neither became a delivery, an item, or an emission.
  assert_eq!(tower_report.deliveries(), 1);
  assert_eq!(tower_report.items(), 3);
  assert_eq!(writer_report.deliveries(), 1);
  assert_eq!(writer_report.items(), 3);
  assert_eq!(writer_report.tally().processed(), 3);
  assert_eq!(writer_report.tally().failed(), 0);
  assert_eq!(writer_report.tally().refused(), 0);

  // AND NO JOURNAL FOR A QUERY. The rows are the index node's three completions and nothing
  // else — no row names a query node, and no row was written for the question that crossed the same
  // node.
  let rows = rows.lock().expect("the rows").clone();
  assert_eq!(rows.len(), 3, "one completion per indexed root: {rows:?}");
  let mut roots: Vec<u64> = rows.iter().map(|row| row.root).collect();
  roots.sort_unstable();
  assert_eq!(roots, [1, 2, 3]);
  assert!(
    rows
      .iter()
      .all(|row| row.node == "index" && row.station == Station::Persisted),
    "{rows:?}"
  );
  assert!(
    rows.iter().all(|row| row.station != Station::Processed),
    "a query's own station never reaches the journal: {rows:?}"
  );
}

// ─── the read-path invariant ────────────────────────────────────────────────────────────────────

/// **A QUERY MUST NEVER QUEUE BEHIND AN INDEXING WRITE BATCH AT THE INDEX NODE.**
///
/// The engines already support read-during-write — tantivy's `Searcher` beside its `IndexWriter`,
/// lancedb's equivalent — and the framework must not un-support it. This pins the framework's half:
/// the query side is a SECOND ARM with its own receiver, so an indexing batch cannot be in front of
/// a query even in principle.
///
/// Deterministic rather than timing-based: the write batch is PARKED inside the lane, on a latch
/// this test holds, and the query has to complete while it is parked. Nothing here sleeps and
/// nothing races — the latch says the write is in flight, and the query's own answer says the read
/// path was open while it was.
///
/// # MUTATION-CHECKED
///
/// Route the query through the DURABLE inbox — send it as a `Delivery` on the channel the indexer
/// reads, or serve the transient inbox from the resident's own loop — and this reddens: the query
/// sits behind the parked batch and `take_within` returns `TimedOut`. That is the whole invariant,
/// and it is the one mutation that expresses it.
#[test]
fn a_query_never_queues_behind_an_indexing_write_batch() {
  let index = Index::default();
  // One entry already indexed, so the query has something true to find while the batch is held.
  index.write(&[Entry {
    key: 5,
    vector: vec![5.0, 0.0],
  }]);

  let (entered, arrived) = flume::bounded::<()>(1);
  let (release, held) = flume::bounded::<()>(1);

  let (entries_out, entries_in) = channel::<ItemId, Entry>(8);
  let (search_door, searches) = door::<Vector, Hits>(4);

  let mut writer = Resident::new("index", Indexer, entries_in).land(IndexLane {
    index: index.clone(),
    latch: Some(Latch {
      entered,
      release: held,
    }),
  });
  let mut reader = QueryArm::new(
    "index",
    VectorSearch {
      index: index.clone(),
      k: 1,
    },
    searches,
  );

  let writer_run = thread::Builder::new()
    .name("index-write".to_owned())
    .spawn(move || writer.run())
    .expect("the write arm");
  let reader_run = thread::Builder::new()
    .name("index-read".to_owned())
    .spawn(move || reader.run())
    .expect("the read arm");

  // A write batch, into the durable inbox.
  let (ack, answers) = ack_channel();
  entries_out
    .deliver(Delivery::new(
      Payload::Batch(vec![
        Item::new(
          ItemId::new(0),
          Entry {
            key: 7,
            vector: vec![7.0, 0.0],
          },
        ),
        Item::new(
          ItemId::new(1),
          Entry {
            key: 8,
            vector: vec![8.0, 0.0],
          },
        ),
      ]),
      ack,
    ))
    .expect("the index node is listening");

  // The batch is now IN FLIGHT and parked. Nothing about it has reached the store.
  arrived
    .recv_timeout(DEADLINE)
    .expect("the write batch entered the lane");
  assert_eq!(index.len(), 1, "the parked batch has written nothing");

  // THE INVARIANT: the query completes anyway.
  let hits = search_door
    .invoke(vec![5.0, 0.0])
    .expect("the read arm is listening")
    .take_within(DEADLINE)
    .expect("a query does not wait for a write batch");
  assert_eq!(hits, vec![5]);
  assert_eq!(index.len(), 1, "and the batch is STILL parked");

  release.send(()).expect("the write arm is still there");
  drop(entries_out);
  drop(search_door);
  let writer_report = writer_run.join().expect("the write arm");
  let reader_report = reader_run.join().expect("the read arm");
  drop(answers);

  assert_eq!(index.len(), 3, "the batch landed once it was released");
  assert_eq!(writer_report.items(), 2);
  assert_eq!(reader_report.passed(), 1);
}

/// Wait for `condition`, up to [`DEADLINE`]. `false` when it never came true.
///
/// A bounded poll rather than a sleep, for [`DEADLINE`]'s reason: what a walk of real threads owes a
/// reader is a red test rather than a hung run.
fn until(mut condition: impl FnMut() -> bool) -> bool {
  let deadline = std::time::Instant::now() + DEADLINE;
  while std::time::Instant::now() < deadline {
    if condition() {
      return true;
    }
    thread::yield_now();
  }
  condition()
}

/// The two `Onward` impls are the two shapes of hop, and the type is what picks between them.
#[test]
fn the_onward_destination_is_a_type_and_the_arm_body_is_one() {
  use super::Onward;

  // The TERMINAL shape: `()` answers the caller, and it can only be written where this hop's output
  // IS the chain's answer.
  let (answer, awaiting) = reply::<Hits>();
  assert!(Onward::<Hits, Hits>::pass(&(), vec![1, 2], answer));
  assert_eq!(awaiting.take().expect("answered"), vec![1, 2]);

  // The FORWARDING shape: a door passes the reply on with the next hop's input.
  let (next, invokes) = door::<Vector, Hits>(1);
  let (answer, awaiting) = reply::<Hits>();
  assert!(next.pass(vec![3.0], answer));
  let forwarded = invokes.park().expect("queued");
  assert_eq!(forwarded.input(), &vec![3.0]);
  let (_, answer) = forwarded.into_parts();
  answer.answer(vec![3]);
  assert_eq!(awaiting.take().expect("answered"), vec![3]);

  // A forward with nowhere to go DROPS the invocation, reply and all — so the caller learns
  // `Dropped` rather than waiting on a chain that no longer exists.
  drop(invokes);
  let (answer, awaiting) = reply::<Hits>();
  assert!(!next.pass(vec![4.0], answer));
  assert_eq!(awaiting.take().expect_err("gone"), QueryError::Dropped);
}

/// A reply that dies MID-CHAIN reaches the original caller as one typed error, however many hops it
/// had travelled — which is what makes a multi-hop query a single-shot question rather than a
/// pipeline the caller has to reason about.
///
/// MEASURED, and the shape is `flume`'s: a queued invocation is released when the transient edge
/// itself goes, which needs BOTH ends gone — the receiver alone marks the channel disconnected and
/// the queue is still reachable through the sender the forwarding arm holds. So the drop that ends
/// the chain is the arm's, and the caller waits until then. That is the honest behaviour rather than
/// a defect: a hop whose arm is still alive may still answer.
#[test]
fn a_failure_at_the_second_hop_reaches_the_first_hops_caller() {
  let (front, queries) = door::<String, Hits>(4);
  let (search_door, searches) = door::<Vector, Hits>(4);
  let mut text = QueryArm::new("text", TextTower, queries).forwarding_to(search_door);

  let awaiting = front.invoke("two words".to_owned()).expect("listening");
  drop(front);
  let served = text.run();
  assert_eq!(served.passed(), 1, "the first hop did its part");
  assert!(
    awaiting
      .take_within(Duration::from_millis(20))
      .is_err_and(|error| error == QueryError::TimedOut),
    "the query is queued at a hop that has not answered it"
  );

  // The second hop never runs, and its edge goes with it.
  drop(searches);
  drop(text);
  assert_eq!(
    front_awaiting_again(),
    QueryError::Dropped,
    "a dead chain answers once, and it answers with this"
  );
}

/// The second half of [`a_failure_at_the_second_hop_reaches_the_first_hops_caller`], written as its
/// own walk because [`Awaiting::take_within`](super::Awaiting::take_within) consumes the receiver.
fn front_awaiting_again() -> QueryError {
  let (front, queries) = door::<String, Hits>(4);
  let (search_door, searches) = door::<Vector, Hits>(4);
  let mut text = QueryArm::new("text", TextTower, queries).forwarding_to(search_door);
  let awaiting = front.invoke("two words".to_owned()).expect("listening");
  drop(front);
  text.run();
  drop(searches);
  drop(text);
  awaiting.take_within(DEADLINE).expect_err("nobody answered")
}