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
use std::{
  collections::HashSet,
  sync::{Arc, Mutex},
};

use jiff::SignedDuration;

use super::super::{
  Ack, Answer, Custody, Delivery, DropOldest, Failure, Handover, Item, ItemId, Lifecycle,
  LifecycleTap, NodeName, Observation, Occupancy, Outbound, OverflowDecision, Owed, Payload,
  Policies, QueryDeadline, QueryError, ShedKey, Station, Taps, Terminal, ack_channel, channel,
  reply,
};

use super::Fate;

#[derive(Debug, derive_more::Display)]
#[display("the reader gave out")]
struct GaveOut;

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

/// A shed fate for the item keyed `key`, at the default message.
fn shed(key: u64) -> Fate {
  Fate::Shed {
    key: ShedKey::new(ItemId::new(key)),
    decision: OverflowDecision::DropOldest,
    occupancy: Occupancy::bounded(1, 1),
    message: (),
  }
}

/// A tap that keeps the STATION or the TERMINAL of everything it is shown, which is the pair an
/// account is counted with — and `None` for the observations that moved an item neither way.
#[derive(Debug, Default)]
struct Counting {
  seen: Mutex<Vec<(Option<Station>, Option<Terminal>)>>,
}

impl Counting {
  fn seen(&self) -> Vec<(Option<Station>, Option<Terminal>)> {
    self.seen.lock().expect("the counter").clone()
  }

  fn terminals(&self) -> Vec<Terminal> {
    self
      .seen()
      .into_iter()
      .filter_map(|(_, terminal)| terminal)
      .collect()
  }
}

impl LifecycleTap for Counting {
  fn observe(&self, _node: &NodeName, observation: &Observation) {
    self
      .seen
      .lock()
      .expect("the counter")
      .push((observation.station(), observation.terminal()));
  }
}

/// A counting tap and the composite it is registered in.
fn counted() -> (Arc<Counting>, Taps) {
  let tap = Arc::new(Counting::default());
  let taps = Taps::new().with(tap.clone());
  (tap, taps)
}

// ---------------------------------------------------------------------------------------------
// THE VOCABULARY: one fate type, and the two streams it speaks in.
// ---------------------------------------------------------------------------------------------

#[test]
fn every_terminal_names_itself_without_its_payload() {
  assert_eq!(shed(7).terminal(), Terminal::Shed);
  assert_eq!(
    Fate::GivenUp {
      attempt: 3,
      failure: Some(Failure::new(GaveOut)),
      message: (),
    }
    .terminal(),
    Terminal::GivenUp
  );
  assert_eq!(
    Fate::Expired {
      budget: SignedDuration::from_millis(50),
      message: (),
    }
    .terminal(),
    Terminal::Expired
  );
}

#[test]
fn the_terminal_names_are_stable() {
  assert_eq!(Terminal::Shed.as_str(), "shed");
  assert_eq!(Terminal::GivenUp.as_str(), "given_up");
  assert_eq!(Terminal::Expired.as_str(), "expired");
  assert_eq!(Terminal::Expired.to_string(), "expired");
}

/// **ONE VOCABULARY, TWO STREAMS.** Whatever terminal a fate speaks, the observation it erases into
/// reports the SAME terminal — C-2's one law as a round trip rather than as a promise in a doc.
#[test]
fn every_terminal_a_fate_speaks_is_a_terminal_an_observation_names() {
  for fate in [
    shed(1),
    Fate::GivenUp {
      attempt: 1,
      failure: None,
      message: (),
    },
    Fate::Expired {
      budget: SignedDuration::ZERO,
      message: (),
    },
  ] {
    let terminal = fate.terminal();
    let (observation, ()) = fate.erase();
    assert_eq!(
      observation.terminal(),
      Some(terminal),
      "the stream saw a different ending from the one the fate spoke"
    );
    // A terminal reaches no station, and a station is not an ending: the two columns of an account
    // are disjoint, so nothing here can be counted twice.
    assert_eq!(observation.station(), None);
  }
}

/// **THE SHED KEEPS THE ARM IT ALREADY HAD.** The observation stream has carried a shed obituary
/// since the policy seam landed, and the fate vocabulary reuses it rather than minting a second
/// wording for the same ending.
#[test]
fn the_shed_terminal_erases_onto_the_arm_the_stream_already_had() {
  let (observation, ()) = shed(41).erase();
  let Observation::Shed {
    key,
    decision,
    occupancy,
  } = observation
  else {
    panic!("a shed fate is the shed arm, and not an arm of its own");
  };
  assert_eq!(key.rendered(), ItemId::new(41).to_string());
  assert_eq!(decision, OverflowDecision::DropOldest);
  assert_eq!(occupancy.queued(), 1);
}

/// **THE TWO SILENT ENDINGS GET ARMS OF THEIR OWN**, shaped like the shed arm they joined: the
/// ending's own payload, read straight off the arm. A tap that wants which attempt was the last, or
/// how long the wait was allowed to be, asks a field — not a rendering, and not a second value
/// nested inside the arm that already named the ending.
#[test]
fn the_given_up_and_expired_terminals_carry_the_endings_own_payload() {
  let (observation, ()) = Fate::GivenUp {
    attempt: 4,
    failure: Some(Failure::new(GaveOut)),
    message: (),
  }
  .erase();
  let Observation::GivenUp {
    attempt,
    failure: Some(failure),
  } = observation
  else {
    panic!("a given-up fate is the given-up arm, carrying its own attempt and error");
  };
  assert_eq!(attempt, 4);
  assert_eq!(failure.to_string(), "the reader gave out");

  let (observation, ()) = Fate::Expired {
    budget: SignedDuration::from_secs(2),
    message: (),
  }
  .erase();
  let Observation::Expired { budget } = observation else {
    panic!("an expired fate is the expired arm, carrying the budget that ran out");
  };
  assert_eq!(budget, SignedDuration::from_secs(2));
}

/// **THE EXTRA MESSAGE LEAVES THE ERASURE INTACT**, and it leaves it BESIDE the observation rather
/// than inside it. The arms a tap already had are not widened to hold it, which is why the crossing
/// hands it back to the caller instead.
#[test]
fn the_extra_message_survives_the_erasure_beside_the_observation() {
  let fate = Fate::Shed {
    key: ShedKey::new(ItemId::new(9)),
    decision: OverflowDecision::DropNewest,
    occupancy: Occupancy::unbounded(3),
    message: Why("the frame was already stale"),
  };
  assert_eq!(fate.message(), &Why("the frame was already stale"));

  let (observation, message) = fate.erase();
  assert_eq!(observation.terminal(), Some(Terminal::Shed));
  assert_eq!(message, Why("the frame was already stale"));
}

/// The default parameter is the framework's own posture: every one of its three sites ends a
/// delivery with nothing to add, so `Fate` spelled bare is the type they all build.
#[test]
fn the_default_message_is_the_unit_and_needs_no_turbofish() {
  let fate: Fate = Fate::Expired {
    budget: SignedDuration::from_millis(1),
    message: (),
  };
  assert!(fate.is_expired());
  assert_eq!(fate.message(), &());
}

/// A station is what a CONSUMER reached and a terminal is what the FRAMEWORK did instead, so no
/// observation is ever both — the property an account leans on when it adds the two columns.
#[test]
fn nothing_is_both_a_station_and_a_terminal() {
  let arrived = Lifecycle::Processed(0u8).erase();
  assert_eq!(arrived.station(), Some(Station::Processed));
  assert_eq!(arrived.terminal(), None);
}

// ---------------------------------------------------------------------------------------------
// THE ANSWER: what the sender of an ended delivery is actually told.
// ---------------------------------------------------------------------------------------------

/// A deployment's own extra message, for the cases where `M` is not `()`.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Why(&'static str);

/// **(a) AN EVICTED DELIVERY ANSWERS ITS OWN ONESHOT.** A bounded edge of one, a policy that drops
/// the oldest, and the sender of the message that was pulled back out reads a TYPED SHED — not the
/// disconnected oneshot that a dropped token has always looked like, and which is
/// indistinguishable from a consumer that died.
///
/// The released set is the other half of the same ruling: the item is gone, so its key is credited
/// rather than held, and the sender's watermark moves past work that is never coming back.
#[test]
fn the_sender_of_an_evicted_delivery_is_told_the_shed_and_credited_for_it() {
  let (outbox, inbox) = channel::<ItemId, u64>(1);
  let evictor = inbox.evictor();
  let (tap, taps) = counted();
  let sheds = Policies::new()
    .with_overflow_policy(Box::new(DropOldest))
    .sheds("stage", taps);

  let (ack, answers) = ack_channel::<ItemId>();
  outbox
    .deliver(Delivery::new(
      Payload::One(Item::new(ItemId::new(1), 10u64)),
      ack,
    ))
    .expect("the edge is empty and the consumer is there");

  let (newest, _newest_answers) = ack_channel::<ItemId>();
  let handover = sheds.deliver(
    &outbox,
    Some(&evictor),
    Delivery::new(Payload::One(Item::new(ItemId::new(2), 20u64)), newest),
  );
  let Handover::Evicted(evicted) = handover else {
    panic!("the oldest was pulled out to make room");
  };

  let answer = answers.take();
  assert!(
    !answer.is_hung_up(),
    "a shed delivery is answered, and never left to read as a consumer that hung up"
  );
  let Answer::Settled(settled) = answer else {
    panic!("the shed answered the token it was owed");
  };
  assert_eq!(settled.observation().terminal(), Some(Terminal::Shed));
  assert!(settled.released().contains(&ItemId::new(1)));
  assert_eq!(settled.worker().as_str(), "stage");

  // What comes back in the handover owes nothing: its token has been spent, so a holder that drops
  // it cannot answer twice and cannot fail to answer at all.
  let (payload, custody) = evicted.into_parts();
  assert!(custody.is_none());
  assert_eq!(payload.len(), 1);

  // The obituary is unchanged and still per item — the fate did not replace it.
  assert_eq!(tap.terminals(), vec![Terminal::Shed]);
}

/// **A CONSUMER THAT DIED IS NOT AN ENDING A POLICY CHOSE.** The delivery comes back WHOLE — token
/// and all — so its sender is still the party that states what became of it, and the shed
/// vocabulary is not conscripted to describe a hang-up. The line between [`Handover::Gone`] and the
/// two shedding arms is the whole of what keeps a terminal meaning something.
#[test]
fn a_delivery_refused_by_a_dead_consumer_keeps_its_token() {
  let (outbox, inbox) = channel::<ItemId, u64>(1);
  let (_tap, taps) = counted();
  let sheds = Policies::new()
    .with_overflow_policy(Box::new(DropOldest))
    .sheds("stage", taps);
  drop(inbox);

  let (ack, answers) = ack_channel::<ItemId>();
  let handover = sheds.deliver(
    &outbox,
    None,
    Delivery::new(Payload::One(Item::new(ItemId::new(1), 10u64)), ack),
  );
  let Handover::Gone(returned) = handover else {
    panic!("the consumer hung up, and nothing was shed");
  };
  // The custody is HELD across the look, because dropping it is the very thing that would make the
  // receiver read a hang-up — which is the state this arm is being distinguished from.
  let (_payload, custody) = returned.into_parts();
  assert!(custody.is_some(), "the token is still owed");
  assert!(answers.take().is_waiting(), "and still unanswered");
  drop(custody);
}

/// **(b) A GIVE-UP ANSWERS ITS ONESHOT, AND IS SAID OUT LOUD.** The retry seat decides, the
/// obligation answers, and both halves speak the same word. Before this vocabulary, the decision was
/// the one a deployment could not watch: a scheduled retry was announced and an exhausted one was
/// announced nowhere.
#[test]
fn a_given_up_delivery_answers_its_oneshot_and_the_gate_says_so() {
  let (tap, taps) = counted();
  // The shipped retry policy never schedules anything, so the first failure exhausts it.
  let retries = Policies::new().retries("stage", taps);

  let failure = Failure::new(GaveOut);
  let decision = retries.settling(Station::Failed, 3, Some(&failure));
  assert!(decision.is_give_up());
  assert_eq!(tap.terminals(), vec![Terminal::GivenUp]);

  let (ack, answers) = ack_channel::<ItemId>();
  let mut owed = Owed::open([ItemId::new(5)], Some(Custody::sole(ack)));
  assert!(owed.settle_fate(
    "stage",
    Fate::GivenUp {
      attempt: 3,
      failure: Some(failure),
      message: (),
    }
  ));

  let Answer::Settled(settled) = answers.take() else {
    panic!("the give-up answered the token it was owed");
  };
  assert_eq!(settled.observation().terminal(), Some(Terminal::GivenUp));
  // Credited even though nothing was ever released: an ending means nothing is coming back, so a
  // key left outstanding would stall the watermark forever.
  assert!(settled.released().contains(&ItemId::new(5)));
}

/// **(c) AN EXPIRY ANSWERS ITS ONESHOT, AND THE CALLER'S OWN VIEW DOES NOT MOVE.** Two views of one
/// truth: the asker still reads [`QueryError::TimedOut`] — which is what it can act on — and the
/// arrangement reads a terminal naming the node that ran out of budget, which the asker could never
/// have computed.
#[test]
fn an_expired_wait_is_a_terminal_to_the_stream_and_a_timeout_to_the_caller() {
  let (tap, taps) = counted();
  let budget = SignedDuration::from_millis(20);
  let deadlines = Policies::new()
    .with_deadline_policy(Box::new(QueryDeadline::of(budget)))
    .deadlines("door", taps);

  // The reply is held and never answered, which is what makes the wait run out rather than end as
  // a drop.
  let (held, awaiting) = reply::<u64>();
  let taken = deadlines.take(awaiting, None);
  assert_eq!(taken.expect_err("the budget ran out"), QueryError::TimedOut);
  assert_eq!(tap.terminals(), vec![Terminal::Expired]);
  drop(held);

  let (ack, answers) = ack_channel::<ItemId>();
  assert!(Custody::sole(ack).fate(
    HashSet::from([ItemId::new(8)]),
    "door",
    Fate::Expired {
      budget,
      message: (),
    }
  ));
  let Answer::Settled(settled) = answers.take() else {
    panic!("the expiry answered the token it was owed");
  };
  assert_eq!(settled.observation().terminal(), Some(Terminal::Expired));
  assert!(settled.released().contains(&ItemId::new(8)));
}

/// **(d) THE ACCOUNT BALANCES.** Five deliveries go out; one arrives at a station, three end at the
/// three terminals, one is still in flight — and every one of them is visible to a tap. That sum is
/// the whole of what C-2's one law buys: before it, the three endings were a silent hang-up and the
/// only honest count a sender could make was *outstanding*.
#[test]
fn every_delivery_a_sender_put_out_is_arrived_ended_or_still_in_flight() {
  // The tap is fed by the harvest walk below rather than by a gate, which is the sender's own
  // vantage: what a node learns about its outputs is exactly what came back on their tokens.
  let tap = Counting::default();
  let mut window: Outbound<ItemId> = Outbound::new();
  let mut acks = Vec::new();
  for key in 1..=5u64 {
    let (ack, answers) = ack_channel::<ItemId>();
    window.record([ItemId::new(key)], answers);
    acks.push(ack);
  }
  let mut acks = acks.into_iter();

  assert!(acks.next().expect("the first").send(Ack::new(
    HashSet::from([ItemId::new(1)]),
    "consumer",
    Lifecycle::Processed(()),
  )));
  assert!(
    acks
      .next()
      .expect("the second")
      .fate(HashSet::from([ItemId::new(2)]), "stage", shed(2))
  );
  assert!(acks.next().expect("the third").fate(
    HashSet::from([ItemId::new(3)]),
    "stage",
    Fate::GivenUp {
      attempt: 2,
      failure: None,
      message: (),
    }
  ));
  assert!(acks.next().expect("the fourth").fate(
    HashSet::from([ItemId::new(4)]),
    "door",
    Fate::Expired {
      budget: SignedDuration::from_millis(5),
      message: (),
    }
  ));
  // The fifth is held rather than dropped: a dropped token is the hang-up this ruling exists to
  // stop being the only story, and *still in flight* is a different column from *ended*.
  let held = acks.next().expect("the fifth");

  let harvest = window.harvest();
  let mut arrived = 0usize;
  let mut ended = 0usize;
  for answer in harvest.answers() {
    tap.observe(answer.worker(), answer.observation());
    arrived += usize::from(answer.observation().station().is_some());
    ended += usize::from(answer.observation().terminal().is_some());
  }

  assert_eq!(arrived, 1);
  assert_eq!(ended, 3);
  assert_eq!(window.outstanding(), 1, "the fifth is still in flight");
  assert_eq!(
    arrived + ended + window.outstanding(),
    5,
    "every delivery is in exactly one column"
  );
  assert_eq!(
    window.lost(),
    0,
    "nothing hung up: an ending is an answer, not a disconnect"
  );
  let mut terminals = tap.terminals();
  terminals.sort_by_key(|terminal| terminal.as_str());
  assert_eq!(
    terminals,
    vec![Terminal::Expired, Terminal::GivenUp, Terminal::Shed]
  );
  drop(held);
}

/// **(e) THE EXTRA MESSAGE REACHES THE SENDER, TYPED.** `M` is the generic amendment's whole point:
/// some acks carry more than the fact of the ending. It crosses erased — one window is harvested by
/// code that knows nothing about the type — and comes back as itself at the one end that asked.
#[test]
fn a_fate_carrying_more_than_the_ending_round_trips_to_the_sender() {
  let (ack, answers) = ack_channel::<ItemId>();
  let mut window: Outbound<ItemId> = Outbound::new();
  window.record([ItemId::new(3)], answers);

  assert!(Custody::sole(ack).fate(
    HashSet::from([ItemId::new(3)]),
    "stage",
    Fate::Shed {
      key: ShedKey::new(ItemId::new(3)),
      decision: OverflowDecision::DropOldest,
      occupancy: Occupancy::bounded(1, 1),
      message: Why("the frame was already stale"),
    }
  ));

  let harvest = window.harvest();
  let [answer] = harvest.answers() else {
    panic!("one delivery, one answer");
  };
  assert_eq!(answer.observation().terminal(), Some(Terminal::Shed));
  assert_eq!(
    answer.message::<Why>(),
    Some(&Why("the frame was already stale"))
  );
  // A reader asking for the wrong type gets nothing rather than a coercion, exactly as an arrival's
  // own info does.
  assert_eq!(answer.message::<u8>(), None);
}

/// **(f) A DELIVERY WITH NO ONESHOT IS UNCHANGED: TAP-ONLY.** The ruling widens what an owed token
/// is told and nothing else. A delivery that arrived without one has nobody to tell, so the shed
/// leaves exactly the obituary it always left — and an obligation with no custody answers `false`
/// rather than inventing somebody to answer.
#[test]
fn a_delivery_with_no_token_is_still_only_tapped() {
  let (outbox, inbox) = channel::<ItemId, u64>(1);
  let evictor = inbox.evictor();
  let (tap, taps) = counted();
  let sheds = Policies::new()
    .with_overflow_policy(Box::new(DropOldest))
    .sheds("stage", taps);

  outbox
    .deliver(Delivery::in_custody(Payload::One(Item::new(
      ItemId::new(1),
      10u64,
    ))))
    .expect("the edge is empty and the consumer is there");
  let handover = sheds.deliver(
    &outbox,
    Some(&evictor),
    Delivery::in_custody(Payload::One(Item::new(ItemId::new(2), 20u64))),
  );
  assert!(matches!(handover, Handover::Evicted(_)));
  assert_eq!(tap.terminals(), vec![Terminal::Shed]);

  let mut nobody: Owed<ItemId> = Owed::open([ItemId::new(1)], None);
  assert!(
    !nobody.settle_fate(
      "stage",
      Fate::GivenUp {
        attempt: 1,
        failure: None,
        message: (),
      }
    ),
    "an obligation with no custody has nobody to answer"
  );
}

/// The ordinary answer is untouched by all of it: a released item still reaches its station, still
/// carries no fate, and still leaves the extra-message slot empty.
#[test]
fn an_ordinary_answer_still_arrives_and_carries_no_fate() {
  let (ack, answers) = ack_channel::<ItemId>();
  let mut owed = Owed::open([ItemId::new(1)], Some(Custody::sole(ack)));
  owed.release(ItemId::new(1));
  assert!(owed.settle("consumer", Lifecycle::Processed(())));

  let Answer::Settled(settled) = answers.take() else {
    panic!("the consumer answered");
  };
  assert_eq!(settled.observation().station(), Some(Station::Processed));
  assert_eq!(settled.observation().terminal(), None);
  assert!(settled.message::<()>().is_none());
}