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

use std::collections::HashSet;

use super::super::{Ack, AsyncChanges, Lifecycle, Positions, Rings, Rung, Wake, doorbell};

#[test]
fn a_doorbell_coalesces_and_a_sweep_stands_in_for_a_ring_that_never_came() {
  let (hint, bell) = doorbell();
  // A thousand writes between two looks cost one wake: the capacity IS the coalescing.
  for _ in 0..1_000 {
    assert!(hint.ring());
  }
  assert_eq!(bell.wait(Duration::from_millis(10)), Rung::Rung);
  // Nothing queued now, so the wait expires — and looking anyway is what makes a hint optional.
  assert_eq!(bell.wait(Duration::from_millis(10)), Rung::Swept);
  assert_eq!(bell.take(), Rung::Swept);
}

#[test]
fn a_doorbell_with_no_writers_left_goes_silent() {
  let (hint, bell) = doorbell();
  drop(hint);
  assert_eq!(bell.wait(Duration::from_millis(10)), Rung::Silent);
  assert_eq!(bell.take(), Rung::Silent);
}

#[test]
fn ringing_a_doorbell_nobody_listens_to_reports_that() {
  let (hint, bell) = doorbell();
  drop(bell);
  assert!(!Rings::ring(&hint));
}

#[tokio::test]
async fn the_async_wait_takes_a_ring_and_ends_on_silence() {
  let (hint, bell) = doorbell();
  assert!(hint.ring());
  assert_eq!(bell.rung().await, Rung::Rung);
  drop(hint);
  assert_eq!(bell.rung().await, Rung::Silent);
}

/// A feed that has no store behind it: a fixed, ordered corpus. It is what the intake's ORDERING is
/// asserted against, since the ordering is the intake's and not the engine's — the SQLite floor
/// below then proves the same trait is answerable by a real database.
mod corpus {
  use super::super::super::{AsyncChanges, Doorbell, Item, Page};

  pub(super) struct Rows {
    pub(super) rows: Vec<(i64, &'static str)>,
    pub(super) doorbell: Doorbell,
    pub(super) pulls: usize,
  }

  /// The marker a hand-written backend supplies for itself, standing where a real one names its
  /// database — the parameter is what keeps one store listenable on several.
  pub(super) struct InMemory;

  impl AsyncChanges<InMemory> for Rows {
    type Error = core::convert::Infallible;
    type Item = &'static str;
    type Key = i64;
    type Message = ();

    fn doorbell(&self) -> &Doorbell {
      &self.doorbell
    }

    async fn pull(
      &mut self,
      after: Option<&i64>,
      limit: usize,
    ) -> Result<Page<&'static str, i64>, Self::Error> {
      self.pulls += 1;
      Ok(
        self
          .rows
          .iter()
          .filter(|(key, _)| after.is_none_or(|after| key > after))
          .take(limit)
          .map(|&(key, row)| Item::new(key, row))
          .collect(),
      )
    }
  }
}

use corpus::{InMemory, Rows};

use super::super::{ChangeIntake, Item, ItemId, Payload, RecordedPositions, Track, channel};

fn feed(rows: &[(i64, &'static str)]) -> (super::super::Hint, Rows) {
  let (hint, bell) = doorbell();
  (
    hint,
    Rows {
      rows: rows.to_vec(),
      doorbell: bell,
      pulls: 0,
    },
  )
}

/// Take every queued delivery, answering each in full.
fn take_and_release(inbox: &super::super::Inbox<ItemId, &'static str>) -> Vec<&'static str> {
  let mut seen = Vec::new();
  for wake in inbox.drain() {
    let Wake::Delivered(delivery) = wake else {
      continue;
    };
    let (payload, ack) = delivery.into_parts();
    let ack = ack.expect("a delivery off the wire carries its custody token");
    let released: HashSet<ItemId> = payload.keys().copied().collect();
    for item in payload {
      seen.push(*item.value());
    }
    ack.send(Ack::new(released, "consumer", Lifecycle::Persisted(())));
  }
  seen
}

#[tokio::test]
async fn a_backlog_is_drained_with_no_replay_path_of_its_own() {
  // This is also the DISABLED-UPSTREAM case: nobody is writing, so nobody rings, and the listener
  // still walks everything the store already holds.
  let (_hint, rows) = feed(&[(1, "a"), (2, "b"), (3, "c")]);
  let (out, inbox) = channel(8);
  let mut intake = ChangeIntake::<InMemory, _, _>::new(
    Track::new("keyframes", "scene"),
    rows,
    RecordedPositions::new(),
    out,
  )
  .with_page(2);

  let report = intake.drain().await.expect("the walk");
  assert_eq!(report.pulled(), 3);
  assert_eq!(report.delivered(), 2, "a page of two, then the remainder");
  assert_eq!(take_and_release(&inbox), ["a", "b", "c"]);
}

#[tokio::test]
async fn the_position_advances_only_after_the_consumer_answers() {
  // The ordering the whole layer rests on. The rows are SENT, the read head has moved past them,
  // and the durable position is still nothing — because nothing has been answered.
  let (_hint, rows) = feed(&[(1, "a"), (2, "b")]);
  let (out, inbox) = channel(8);
  let mut intake = ChangeIntake::<InMemory, _, _>::new(
    Track::new("keyframes", "scene"),
    rows,
    RecordedPositions::new(),
    out,
  );

  let report = intake.drain().await.expect("the walk");
  assert_eq!(report.pulled(), 2);
  assert!(!report.advanced());
  assert_eq!(intake.position(), None, "sent is not settled");

  assert_eq!(take_and_release(&inbox), ["a", "b"]);
  let report = intake.drain().await.expect("the second pass");
  assert!(report.advanced());
  assert_eq!(intake.position(), Some(&2));
}

#[tokio::test]
async fn a_partial_answer_stops_the_position_at_the_gap() {
  let (_hint, rows) = feed(&[(1, "a"), (2, "b"), (3, "c")]);
  let (out, inbox) = channel(8);
  let mut intake = ChangeIntake::<InMemory, _, _>::new(
    Track::new("keyframes", "scene"),
    rows,
    RecordedPositions::new(),
    out,
  );
  intake.drain().await.expect("the walk");

  // Release the first and the third, holding the second: the position may only reach key 1.
  for wake in inbox.drain() {
    let Wake::Delivered(delivery) = wake else {
      continue;
    };
    let (payload, ack) = delivery.into_parts();
    let ack = ack.expect("a delivery off the wire carries its custody token");
    let keys: Vec<ItemId> = payload.keys().copied().collect();
    ack.send(Ack::new(
      [keys[0], keys[2]].into_iter().collect(),
      "consumer",
      Lifecycle::Persisted(()),
    ));
  }
  intake.drain().await.expect("the second pass");
  assert_eq!(intake.position(), Some(&1));
}

#[tokio::test]
async fn a_dropped_answer_rewinds_the_read_head_and_the_rows_come_back() {
  // The crash matrix's first row, simulated exactly: the consumer takes the page and dies without
  // answering. The position never moved, so the re-pull starts where it did and the rows are
  // delivered again — at-least-once, made harmless by keyed replace.
  let (_hint, rows) = feed(&[(1, "a"), (2, "b"), (3, "c")]);
  let (out, inbox) = channel(8);
  let mut intake = ChangeIntake::<InMemory, _, _>::new(
    Track::new("keyframes", "scene"),
    rows,
    RecordedPositions::new(),
    out,
  );
  intake.drain().await.expect("the walk");

  // Take the delivery and DROP its oneshot.
  let mut dropped = 0usize;
  for wake in inbox.drain() {
    if let Wake::Delivered(delivery) = wake {
      let (payload, ack) = delivery.into_parts();
      let ack = ack.expect("a delivery off the wire carries its custody token");
      dropped += payload.len();
      drop(ack);
    }
  }
  assert_eq!(dropped, 3);

  let report = intake.drain().await.expect("the sweep");
  assert_eq!(report.retracted(), 3, "the whole tail came back");
  assert_eq!(report.pulled(), 3, "and was re-read from the position");
  assert_eq!(intake.position(), None);
  assert_eq!(take_and_release(&inbox), ["a", "b", "c"]);
}

#[tokio::test]
async fn a_position_read_at_start_up_resumes_past_it() {
  let mut positions = RecordedPositions::new();
  let track = Track::new("keyframes", "scene");
  positions
    .advance_async(&track, 2i64, &[])
    .await
    .expect("in memory");

  let (_hint, rows) = feed(&[(1, "a"), (2, "b"), (3, "c")]);
  let (out, inbox) = channel(8);
  let mut intake = ChangeIntake::<InMemory, _, _>::new(track, rows, positions, out);
  intake.drain().await.expect("the walk");
  assert_eq!(
    take_and_release(&inbox),
    ["c"],
    "the first two are behind it"
  );
}

#[tokio::test]
async fn an_intake_stops_when_the_consumer_is_gone() {
  let (_hint, rows) = feed(&[(1, "a")]);
  let (out, inbox) = channel::<ItemId, &'static str>(1);
  drop(inbox);
  let mut intake = ChangeIntake::<InMemory, _, _>::new(
    Track::new("keyframes", "scene"),
    rows,
    RecordedPositions::new(),
    out,
  );
  assert!(
    intake
      .drain()
      .await
      .expect_err("nowhere to send")
      .is_disconnected()
  );
}

#[tokio::test]
async fn a_change_intake_is_one_more_producer_on_a_shared_inbox() {
  // Which is what makes the two delivery modes mixable in one fan-in: the consumer's loop never
  // learns which producer a delivery came from.
  let (_hint, rows) = feed(&[(1, "a")]);
  let (out, inbox) = channel(8);
  let channel_side = out.clone();
  let mut intake = ChangeIntake::<InMemory, _, _>::new(
    Track::new("keyframes", "scene"),
    rows,
    RecordedPositions::new(),
    out,
  );
  intake.drain().await.expect("the walk");

  let (ack, _answers) = super::super::ack_channel();
  channel_side
    .deliver(super::super::Delivery::new(
      Payload::One(Item::new(ItemId::new(999), "direct")),
      ack,
    ))
    .expect("the inbox is open");

  let mut seen = Vec::new();
  for wake in inbox.drain() {
    if let Wake::Delivered(delivery) = wake {
      for item in delivery.into_parts().0 {
        seen.push(*item.value());
      }
    }
  }
  assert_eq!(seen, ["a", "direct"]);
}

#[cfg(feature = "sqlite")]
mod floor {
  use std::collections::HashSet;

  use sqlx::Connection as _;

  use super::super::super::{
    Ack, AsyncChanges, ChangeIntake, ItemId, Lifecycle, RecordedPositions, SqliteFeed,
    SqliteFeedError, Track, Wake, channel, doorbell,
  };

  #[derive(Debug, PartialEq, Eq)]
  struct Scene {
    id: i64,
    title: String,
  }

  // Written rather than derived, exactly as the emitter writes one: sqlx's derive rides a feature
  // this crate declines, and the row form is the emitter's to spell in any case.
  impl<'r> sqlx::FromRow<'r, sqlx::sqlite::SqliteRow> for Scene {
    fn from_row(row: &'r sqlx::sqlite::SqliteRow) -> sqlx::Result<Self> {
      use sqlx::Row as _;

      Ok(Self {
        id: row.try_get("id")?,
        title: row.try_get("title")?,
      })
    }
  }

  async fn corpus(rows: &[(i64, &str)]) -> sqlx::sqlite::SqliteConnection {
    let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
      .await
      .expect("an in-memory database");
    sqlx::query("CREATE TABLE scene (id INTEGER PRIMARY KEY, title TEXT NOT NULL)")
      .execute(&mut db)
      .await
      .expect("the table");
    for (id, title) in rows {
      sqlx::query("INSERT INTO scene (id, title) VALUES (?, ?)")
        .bind(id)
        .bind(title)
        .execute(&mut db)
        .await
        .expect("the row");
    }
    db
  }

  #[tokio::test]
  async fn the_pull_is_ordered_bounded_and_strictly_past_the_cursor() {
    let db = corpus(&[(1, "one"), (2, "two"), (3, "three"), (4, "four")]).await;
    let (_hint, bell) = doorbell();
    let mut feed: SqliteFeed<Scene> = SqliteFeed::new(db, "scene", "id", bell).expect("the feed");

    let page = AsyncChanges::<sqlx::Sqlite>::pull(&mut feed, None, 2)
      .await
      .expect("the first page");
    assert_eq!(
      page.items().iter().map(|i| *i.key()).collect::<Vec<_>>(),
      [1, 2]
    );
    assert_eq!(page.items()[0].value().title, "one");
    // The key column and the row's own id are the same fact read twice, and the feed reads the
    // former by name rather than by position.
    assert_eq!(page.items()[0].value().id, 1);

    let page = AsyncChanges::<sqlx::Sqlite>::pull(&mut feed, Some(&2), 10)
      .await
      .expect("the next page");
    assert_eq!(
      page.items().iter().map(|i| *i.key()).collect::<Vec<_>>(),
      [3, 4]
    );

    let page = AsyncChanges::<sqlx::Sqlite>::pull(&mut feed, Some(&4), 10)
      .await
      .expect("the end");
    assert!(page.is_empty());
  }

  #[tokio::test]
  async fn a_table_or_column_name_that_is_not_an_identifier_is_refused_at_construction() {
    // The check is a `Result` rather than an assertion because a caller-supplied name reaching a
    // store at runtime must be refused without panicking — and refusing here is what lets the pull
    // splice the name at all.
    let db = corpus(&[]).await;
    let (_hint, bell) = doorbell();
    let refused = SqliteFeed::<Scene>::new(db, "scene; DROP TABLE scene", "id", bell)
      .expect_err("not an identifier");
    assert!(matches!(refused, SqliteFeedError::Identifier(_)));
    assert!(refused.to_string().contains("bare identifier"));

    let db = corpus(&[]).await;
    let (_hint, bell) = doorbell();
    assert!(SqliteFeed::<Scene>::new(db, "scene", "id\"", bell).is_err());
  }

  #[tokio::test]
  async fn the_floor_drives_a_real_table_from_the_backlog_to_the_position() {
    let db = corpus(&[(1, "one"), (2, "two"), (3, "three")]).await;
    let (_hint, bell) = doorbell();
    let feed: SqliteFeed<Scene> = SqliteFeed::new(db, "scene", "id", bell).expect("the feed");
    let (out, inbox) = channel(8);
    let mut intake = ChangeIntake::<sqlx::Sqlite, _, _>::new(
      Track::new("keyframes", "scene"),
      feed,
      RecordedPositions::new(),
      out,
    )
    .with_page(2);

    let report = intake.drain().await.expect("the walk");
    assert_eq!(report.pulled(), 3);
    assert_eq!(intake.position(), None, "nothing answered yet");

    let mut titles = Vec::new();
    for wake in inbox.drain() {
      let Wake::Delivered(delivery) = wake else {
        continue;
      };
      let (payload, ack) = delivery.into_parts();
      let ack = ack.expect("a delivery off the wire carries its custody token");
      let released: HashSet<ItemId> = payload.keys().copied().collect();
      for item in payload {
        titles.push(item.into_parts().1.title);
      }
      ack.send(Ack::new(released, "consumer", Lifecycle::Persisted(())));
    }
    assert_eq!(titles, ["one", "two", "three"]);

    intake.drain().await.expect("the second pass");
    assert_eq!(intake.position(), Some(&3));
  }

  #[tokio::test]
  async fn rows_written_after_the_walk_arrive_on_the_next_look() {
    let db = corpus(&[(1, "one")]).await;
    let (_hint, bell) = doorbell();
    let feed: SqliteFeed<Scene> = SqliteFeed::new(db, "scene", "id", bell).expect("the feed");
    let (out, inbox) = channel(8);
    let mut intake = ChangeIntake::<sqlx::Sqlite, _, _>::new(
      Track::new("keyframes", "scene"),
      feed,
      RecordedPositions::new(),
      out,
    );
    intake.drain().await.expect("the walk");
    for wake in inbox.drain() {
      if let Wake::Delivered(delivery) = wake {
        let (payload, ack) = delivery.into_parts();
        let ack = ack.expect("a delivery off the wire carries its custody token");
        let released: HashSet<ItemId> = payload.keys().copied().collect();
        ack.send(Ack::new(released, "consumer", Lifecycle::Persisted(())));
      }
    }
    intake.drain().await.expect("settle");
    assert_eq!(intake.position(), Some(&1));

    // A writer appends; the feed picks it up strictly past the position.
    let mut feed = intake.into_feed();
    // The connection is the feed's, so writing through it is what a co-located writer does.
    {
      let page = AsyncChanges::<sqlx::Sqlite>::pull(&mut feed, Some(&1), 10)
        .await
        .expect("nothing yet");
      assert!(page.is_empty());
    }
    let mut db = feed.into_connection();
    sqlx::query("INSERT INTO scene (id, title) VALUES (2, 'two')")
      .execute(&mut db)
      .await
      .expect("the append");
    let (_hint, bell) = doorbell();
    let mut feed: SqliteFeed<Scene> = SqliteFeed::new(db, "scene", "id", bell).expect("the feed");
    let page = AsyncChanges::<sqlx::Sqlite>::pull(&mut feed, Some(&1), 10)
      .await
      .expect("the append");
    assert_eq!(page.len(), 1);
    assert_eq!(page.items()[0].value().title, "two");
  }
}

#[test]
fn an_intake_reads_back_what_it_was_wired_with_and_both_halves_of_a_knob_agree() {
  let (_hint, rows) = feed(&[(1, "a"), (2, "b")]);
  let (out, _inbox) = channel(8);
  let track = Track::new("keyframes", "scene");
  let fluent =
    ChangeIntake::<InMemory, _, _>::new(track.clone(), rows, RecordedPositions::<i64>::new(), out)
      .with_page(64);
  assert_eq!(fluent.page(), 64);
  assert_eq!(fluent.track(), &track);
  assert_eq!(fluent.position(), None, "nothing is durable before a pass");
  assert!(fluent.taps().is_empty());
  assert_eq!(fluent.attribution(), &());
  assert_eq!(fluent.feed().rows.len(), 2);
  assert_eq!(fluent.positions().len(), 0);
  // The doorbell reached through the intake is the feed's own, which is what a `Sweeper` has to be
  // handed to wake this feed at all.
  assert_eq!(fluent.doorbell().take(), Rung::Swept);

  // And the in-place half lands the same value, since the consuming one delegates to it.
  let (_second, rows) = feed(&[(1, "a")]);
  let (out, _inbox) = channel(8);
  let mut in_place =
    ChangeIntake::<InMemory, _, _>::new(track, rows, RecordedPositions::<i64>::new(), out);
  assert_eq!(
    in_place.page(),
    ChangeIntake::<InMemory, Rows, RecordedPositions<i64>>::PAGE,
    "the record's own page, until something says otherwise"
  );
  in_place.set_page(64).set_taps(super::super::Taps::new());
  assert_eq!(in_place.page(), fluent.page());
}

#[test]
fn the_message_parameter_defaults_away_so_no_caller_spells_it() {
  use super::super::{Doorbell, Hint};

  // The whole point of the default, proven by the compiler rather than asserted: the pair the
  // constructor mints goes into slots typed BOTH ways, so `Hint` and `Hint<()>` are one type and
  // every call site that named the old spelling still names it.
  let bare: (Hint, Doorbell) = doorbell();
  let spelled: (Hint<()>, Doorbell<()>) = bare;
  assert!(spelled.0.ring());
  assert_eq!(spelled.1.take(), Rung::Rung);

  // And the trait's half of the same seam: a feed declares what its ring carries, and every feed
  // this crate ships declares nothing.
  fn rings_with_nothing<S: AsyncChanges<Db, Message = ()>, Db>() {}
  rings_with_nothing::<Rows, InMemory>();
  #[cfg(feature = "sqlite")]
  rings_with_nothing::<super::super::SqliteFeed<(i64,)>, sqlx::Sqlite>();
}

// ── The intake's own inflight counting ──────────────────────────────────────────────────────────

/// One root for every row this suite pulls — the projection an intake carries, standing in for the
/// one a record declaration emits.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct MediaId(u64);

/// The key the counting walks below work on.
const MEDIA: MediaId = MediaId(3);

struct OneMedia;

impl crate::Attributes<&'static str> for OneMedia {
  const FAMILY: &'static str = "media";

  type Root = MediaId;

  fn root(&self, _record: &&'static str) -> MediaId {
    MEDIA
  }

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

/// [`MEDIA`]'s inflight count, read through the family the projection names.
fn inflight(registries: &super::super::Registries) -> u32 {
  registries
    .of::<MediaId>()
    .map_or(0, |family| family.inflight(&MEDIA))
}

/// **AN INTAKE IS A PRODUCER, AND ITS ROWS ARE INFLIGHT.** The page is counted out as it is sent
/// and counted back in as the consumer answers.
///
/// R1 holds here for the resident's reason, one hop up: the whole page is counted before
/// `deliver_async` hands it over, and this party sends no ack at all — it advances a durable
/// POSITION, in `settle`, after the answers have already been counted back.
#[tokio::test]
async fn an_intake_counts_the_rows_it_sends_and_credits_the_answers() {
  let registries = std::sync::Arc::new(super::super::Registries::default());
  let (_hint, rows) = feed(&[(1, "a"), (2, "b"), (3, "c")]);
  let (out, inbox) = channel(8);
  let mut intake = ChangeIntake::<InMemory, _, _>::new(
    Track::new("keyframes", "scene"),
    rows,
    RecordedPositions::new(),
    out,
  )
  .attributing(OneMedia)
  .with_registries(std::sync::Arc::clone(&registries));

  intake.drain().await.expect("the walk");
  assert_eq!(
    inflight(&registries),
    3,
    "three rows out, and the position has not moved"
  );
  assert_eq!(intake.position(), None);

  assert_eq!(take_and_release(&inbox), ["a", "b", "c"]);
  intake.drain().await.expect("the second pass");
  assert_eq!(
    inflight(&registries),
    0,
    "every row was answered, so nothing is out"
  );
  assert_eq!(intake.position(), Some(&3));
}

/// **A REWIND CREDITS WHAT IT RETRACTS.** A delivery whose answer was dropped is re-read under
/// fresh ids, so the old ids' counts have to go back — otherwise every retry would add a `+1` that
/// nothing will ever cancel and the key would never leave `Analyzing`.
#[tokio::test]
async fn a_rewind_gives_the_retracted_rows_count_back() {
  let registries = std::sync::Arc::new(super::super::Registries::default());
  let (_hint, rows) = feed(&[(1, "a"), (2, "b"), (3, "c")]);
  let (out, inbox) = channel(8);
  let mut intake = ChangeIntake::<InMemory, _, _>::new(
    Track::new("keyframes", "scene"),
    rows,
    RecordedPositions::new(),
    out,
  )
  .attributing(OneMedia)
  .with_registries(std::sync::Arc::clone(&registries));

  intake.drain().await.expect("the walk");
  assert_eq!(inflight(&registries), 3);

  // The consumer takes the page and dies without answering.
  for wake in inbox.drain() {
    if let Wake::Delivered(delivery) = wake {
      let (_payload, ack) = delivery.into_parts();
      drop(ack.expect("a delivery off the wire carries its custody token"));
    }
  }

  let report = intake.drain().await.expect("the sweep");
  assert_eq!(report.retracted(), 3);
  assert_eq!(
    inflight(&registries),
    3,
    "the three that came back were credited, and the three re-read were counted out — a net \
     three, never six"
  );

  assert_eq!(take_and_release(&inbox), ["a", "b", "c"]);
  intake.drain().await.expect("the third pass");
  assert_eq!(inflight(&registries), 0);
}

/// A page of MANY rows from one root is many ITEMS: the count is per row, and never the one
/// `(root, node)` journal row the same page earns.
#[tokio::test]
async fn a_partial_answer_leaves_the_unanswered_rows_counted() {
  let registries = std::sync::Arc::new(super::super::Registries::default());
  let (_hint, rows) = feed(&[(1, "a"), (2, "b"), (3, "c")]);
  let (out, inbox) = channel(8);
  let mut intake = ChangeIntake::<InMemory, _, _>::new(
    Track::new("keyframes", "scene"),
    rows,
    RecordedPositions::new(),
    out,
  )
  .attributing(OneMedia)
  .with_registries(std::sync::Arc::clone(&registries));
  intake.drain().await.expect("the walk");

  // Release the first and the third, holding the second.
  for wake in inbox.drain() {
    let Wake::Delivered(delivery) = wake else {
      continue;
    };
    let (payload, ack) = delivery.into_parts();
    let ack = ack.expect("a delivery off the wire carries its custody token");
    let keys: Vec<ItemId> = payload.keys().copied().collect();
    ack.send(Ack::new(
      [keys[0], keys[2]].into_iter().collect(),
      "consumer",
      Lifecycle::Persisted(()),
    ));
  }
  intake.drain().await.expect("the second pass");
  assert_eq!(
    inflight(&registries),
    0,
    "an answer SPEAKS FOR every key it covered, released or not — the held row comes back under \
     a fresh id, which is a fresh count"
  );
  assert_eq!(intake.position(), Some(&1));
}

/// An intake with no projection contributes nothing and opens no family — the resident's own rule,
/// at the producer end.
#[tokio::test]
async fn an_intake_with_no_attribution_opens_no_family() {
  let registries = std::sync::Arc::new(super::super::Registries::default());
  let (_hint, rows) = feed(&[(1, "a")]);
  let (out, inbox) = channel(8);
  let mut intake = ChangeIntake::<InMemory, _, _>::new(
    Track::new("keyframes", "scene"),
    rows,
    RecordedPositions::new(),
    out,
  )
  .with_registries(std::sync::Arc::clone(&registries));

  intake.drain().await.expect("the walk");
  assert_eq!(take_and_release(&inbox), ["a"]);
  intake.drain().await.expect("the second pass");
  assert!(registries.is_empty(), "no projection, no family");
}