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
//! The level vocabulary, and — where this build compiles observation — what the tap and the four
//! spans actually say to a subscriber.
//!
//! The subscriber is HAND-WRITTEN and there is no `tracing-subscriber` dev-dependency, which is a
//! decision rather than an omission: cargo has no optional dev-dependencies, so such an entry would
//! be compiled by every test build of this crate including the lanes that turn observation off. What
//! is under test is also exactly the `Subscriber` contract — a span is created, a level is carried,
//! a field is visited — so implementing it is the more direct assertion of the two.

use super::TracingLevel;

#[test]
fn the_level_vocabulary_round_trips() {
  for level in TracingLevel::ALL {
    assert_eq!(
      TracingLevel::named(level.as_str()),
      Some(level),
      "{level} did not survive its own word"
    );
  }
}

#[test]
fn a_word_the_framework_does_not_ship_names_no_level() {
  assert_eq!(TracingLevel::named("verbose"), None);
  assert_eq!(
    TracingLevel::named("Debug"),
    None,
    "the words are lowercase"
  );
  assert_eq!(TracingLevel::named(""), None);
}

#[test]
fn the_default_level_is_info() {
  assert_eq!(TracingLevel::default(), TracingLevel::Info);
  // Two halves of one default: what a declaration with no word gets, and what a node that states
  // nothing on the facts trait gets. They are one fact, and this is where they are pinned equal.
  assert_eq!(
    <Silent as crate::Declared>::TRACING,
    TracingLevel::Info,
    "the trait's default and the vocabulary's default are one fact"
  );
}

/// A node that states nothing but what the facts trait demands — the reader for
/// [`Declared::TRACING`](crate::Declared::TRACING)'s own default.
struct Silent;

impl crate::Declared for Silent {
  type Channels = crate::Unchanneled;
  type Options = ();
  type Mode = crate::Block;
  type Pair = crate::Buffered;
  type Wires<O> = crate::Downstream<O>;
  type Attribution<O> = ();

  const EFFECT: crate::Effect = crate::Effect::Pure;
}

#[cfg(feature = "tracing")]
mod saying {
  //! The capturing subscriber, and what it captures.

  use core::{
    fmt,
    sync::atomic::{AtomicU64, Ordering},
  };

  use std::sync::{Arc, Mutex};

  use tracing::{
    Event, Level, Metadata, Subscriber,
    field::{Field, Visit},
    span,
  };

  /// One span or one event, as a subscriber was shown it.
  #[derive(Debug, Clone)]
  pub(super) struct Said {
    /// A span's name; for an event, `tracing`'s own synthesised `event <file>:<line>`, which is why
    /// an event is matched here on its FIELDS and never on this.
    pub(super) name: String,
    pub(super) level: Level,
    /// Every field the CALLSITE declares, recorded or not — the metadata half.
    declared: Vec<String>,
    /// Every field a value was actually visited for.
    fields: Vec<(String, String)>,
  }

  impl Said {
    /// What was recorded under `field`, or `None` where nothing was — which is the answer for a
    /// declared `Option` field that carried no value.
    pub(super) fn field(&self, field: &str) -> Option<&str> {
      self
        .fields
        .iter()
        .find(|(name, _)| name == field)
        .map(|(_, value)| value.as_str())
    }

    /// Whether `field` was DECLARED at the callsite, whether or not a value reached the visitor.
    pub(super) fn declares(&self, field: &str) -> bool {
      self.declared.iter().any(|name| name == field)
    }
  }

  /// Everything one run said.
  #[derive(Debug, Default)]
  pub(super) struct Heard {
    spans: Vec<Said>,
    events: Vec<Said>,
  }

  impl Heard {
    /// Every span with this name, in the order they were opened.
    pub(super) fn spans(&self, name: &str) -> Vec<Said> {
      self
        .spans
        .iter()
        .filter(|said| said.name == name)
        .cloned()
        .collect()
    }

    /// Every span, whatever its name — what *the list is four long* is asserted against.
    pub(super) fn span_names(&self) -> Vec<String> {
      self.spans.iter().map(|said| said.name.clone()).collect()
    }

    /// Every event whose callsite declared `field` — how an event is identified, an event's own
    /// name being a file and a line.
    pub(super) fn events_with(&self, field: &str) -> Vec<Said> {
      self
        .events
        .iter()
        .filter(|said| said.declares(field))
        .cloned()
        .collect()
    }

    /// How many events were said at all.
    pub(super) fn events(&self) -> usize {
      self.events.len()
    }
  }

  /// A subscriber that keeps what it was shown.
  #[derive(Debug)]
  pub(super) struct Capturing {
    heard: Arc<Mutex<Heard>>,
    next: AtomicU64,
  }

  impl Capturing {
    /// The subscriber and the handle its record is read through.
    pub(super) fn new() -> (Self, Arc<Mutex<Heard>>) {
      let heard = Arc::new(Mutex::new(Heard::default()));
      (
        Self {
          heard: Arc::clone(&heard),
          // A span id is NON-ZERO, so the counter starts where the first `fetch_add` answers 1.
          next: AtomicU64::new(1),
        },
        heard,
      )
    }
  }

  impl Subscriber for Capturing {
    /// Everything, at every level — the filtering under test is the framework's own choice of level
    /// and not a subscriber's, so this one refuses nothing.
    fn enabled(&self, _metadata: &Metadata<'_>) -> bool {
      true
    }

    fn new_span(&self, attrs: &span::Attributes<'_>) -> span::Id {
      let mut fields = Fields::default();
      attrs.record(&mut fields);
      self
        .heard
        .lock()
        .expect("the capture lock")
        .spans
        .push(said(attrs.metadata(), fields.0));
      span::Id::from_u64(self.next.fetch_add(1, Ordering::Relaxed))
    }

    fn record(&self, _span: &span::Id, _values: &span::Record<'_>) {}

    fn record_follows_from(&self, _span: &span::Id, _follows: &span::Id) {}

    fn event(&self, event: &Event<'_>) {
      let mut fields = Fields::default();
      event.record(&mut fields);
      self
        .heard
        .lock()
        .expect("the capture lock")
        .events
        .push(said(event.metadata(), fields.0));
    }

    fn enter(&self, _span: &span::Id) {}

    fn exit(&self, _span: &span::Id) {}
  }

  /// One record, built from the metadata every span and event carries.
  fn said(metadata: &Metadata<'_>, fields: Vec<(String, String)>) -> Said {
    Said {
      name: metadata.name().to_owned(),
      level: *metadata.level(),
      declared: metadata
        .fields()
        .iter()
        .map(|field| field.name().to_owned())
        .collect(),
      fields,
    }
  }

  /// The visitor: every value as the text a reader would see.
  #[derive(Debug, Default)]
  struct Fields(Vec<(String, String)>);

  impl Visit for Fields {
    fn record_str(&mut self, field: &Field, value: &str) {
      self.0.push((field.name().to_owned(), value.to_owned()));
    }

    fn record_u64(&mut self, field: &Field, value: u64) {
      self.0.push((field.name().to_owned(), value.to_string()));
    }

    fn record_i64(&mut self, field: &Field, value: i64) {
      self.0.push((field.name().to_owned(), value.to_string()));
    }

    fn record_bool(&mut self, field: &Field, value: bool) {
      self.0.push((field.name().to_owned(), value.to_string()));
    }

    fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
      self.0.push((field.name().to_owned(), format!("{value:?}")));
    }
  }
}

#[cfg(feature = "tracing")]
mod live {
  //! What a real run says: the tap's whole vocabulary, and the four spans.

  use crate::Context;

  use core::time::Duration;

  use crate::drive::Drives;

  use std::{
    io,
    sync::{Arc, Mutex},
    thread,
  };

  use jiff::SignedDuration;
  use tracing::Level;

  use super::{
    TracingLevel,
    saying::{Capturing, Heard},
  };
  use crate::{
    Ack, AckMode, AckReceiver, Answers, Concern, Delivery, Effect, Emitter, Failure, Inbox, Item,
    ItemId, Lifecycle, LifecycleTap, NodeName, Observation, Occupancy, Outbox, OverflowDecision,
    Payload, PollUpstream, QueryArm, Resident, Schedule, Seats, ShedKey, Skip, SkipReason, Swept,
    Taps, TracingTap, Wake, channel, door,
  };

  /// Run `body` with a capturing subscriber as the thread-local default, and hand back what it
  /// heard.
  ///
  /// `with_default` and not `set_global_default`, because a global one can be installed once per
  /// PROCESS and every test in this file needs its own record. The cost is that everything under
  /// observation has to run on THIS thread, which is why the walks below drive the thread engine in
  /// place rather than spawning it.
  fn heard(body: impl FnOnce()) -> Arc<Mutex<Heard>> {
    let (subscriber, heard) = Capturing::new();
    tracing::subscriber::with_default(subscriber, body);
    heard
  }

  /// Emits `2 * item`, and lands nothing.
  struct Doubling;

  impl crate::Operator for Doubling {
    type Error = core::convert::Infallible;
    type In = u64;
    type Out = u64;

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

  /// The no-capability lending: a poll node granted nothing carries `()`, which seats the operator
  /// and hands it nothing.
  impl Seats<Doubling> for () {
    type Error = core::convert::Infallible;
    type Info = ();

    async fn seat(
      &mut self,
      _operator: &mut Doubling,
      _source: PollUpstream,
    ) -> Result<Swept<Self::Info>, Self::Error> {
      Ok(Swept::Ran(()))
    }
  }

  /// Deliver one batch of `keys`.
  fn send(out: &Outbox<ItemId, u64>, keys: &[u64]) -> AckReceiver<ItemId> {
    let (ack, answers) = crate::ack_channel();
    let items = keys
      .iter()
      .map(|&key| Item::new(ItemId::new(key), key))
      .collect();
    out
      .deliver(Delivery::new(Payload::Batch(items), ack))
      .expect("the resident is listening");
    answers
  }

  /// Take everything off `inbox` and answer it, until the last sender is gone.
  ///
  /// The `Wake::Sweep` arm is why this is a `while let` over the WAKE rather than over a delivery:
  /// a park that times out is not an empty inbox, and a walk that stopped there would leave the
  /// resident's window open while the clock it is waiting on is exactly what the walk is testing.
  fn drain(inbox: &Inbox<ItemId, u64>) {
    while let Some(wake) = inbox.park(Duration::from_millis(5)) {
      let Wake::Delivered(delivery) = wake else {
        continue;
      };
      let (payload, ack) = delivery.into_parts();
      let released = payload.keys().copied().collect();
      if let Some(ack) = ack {
        ack.send(Ack::new(released, "consumer", Lifecycle::Persisted(())));
      }
    }
  }

  /// Hold `feed` open for long enough that a cadence measured in milliseconds actually comes due,
  /// then let the resident's loop end.
  ///
  /// The engine runs on the TEST's own thread, because the capturing subscriber is a thread-local
  /// default — so the thing that has to happen on another thread is the shutdown, not the work.
  fn holding(feed: Outbox<ItemId, u64>) -> thread::JoinHandle<()> {
    thread::spawn(move || {
      thread::sleep(Duration::from_millis(60));
      drop(feed);
    })
  }

  #[test]
  fn the_tap_says_every_arm_of_the_vocabulary() {
    let tap = TracingTap::new();
    let node = NodeName::new("clip");
    let heard = heard(|| {
      tap.observe(node, &Lifecycle::<u64>::Persisted(1).erase());
      tap.observe(
        node,
        &Lifecycle::<u64>::Skipped(Skip::new(SkipReason::Filtered).about("clip-7")).erase(),
      );
      tap.observe(
        node,
        &Lifecycle::<u64>::Failed(Failure::new(io::Error::other("the store said no"))).erase(),
      );
      tap.observe(
        node,
        &Observation::Retrying {
          attempt: 2,
          after: Some(SignedDuration::from_secs(3)),
        },
      );
      tap.observe(
        node,
        &Observation::Shed {
          key: ShedKey::new("segment(clip-7, 2)"),
          decision: OverflowDecision::DropOldest,
          occupancy: Occupancy::bounded(8, 8),
        },
      );
      tap.observe(
        node,
        &Observation::PolicyFailed {
          concern: Concern::Overflow,
          error: Box::new(io::Error::other("the advisor panicked")),
        },
      );
    });
    let heard = heard.lock().expect("the capture lock");
    assert_eq!(heard.events(), 6, "one event per observation, and no more");

    let stations = heard.events_with("station");
    assert_eq!(stations.len(), 3, "the three shapes an arrival takes");
    let persisted = &stations[0];
    assert_eq!(persisted.level, Level::DEBUG);
    assert_eq!(persisted.field("node"), Some("clip"));
    assert_eq!(persisted.field("station"), Some("persisted"));

    let skipped = &stations[1];
    assert_eq!(skipped.level, Level::DEBUG);
    assert_eq!(skipped.field("station"), Some("skipped"));
    assert_eq!(skipped.field("reason"), Some("filtered"));
    assert_eq!(skipped.field("content"), Some("clip-7"));

    let failed = &stations[2];
    assert_eq!(
      failed.level,
      Level::ERROR,
      "a failure is an error and never a debug line"
    );
    assert_eq!(failed.field("station"), Some("failed"));
    assert_eq!(failed.field("error"), Some("the store said no"));

    let retrying = heard.events_with("attempt");
    assert_eq!(retrying.len(), 1);
    assert_eq!(retrying[0].level, Level::WARN);
    assert_eq!(retrying[0].field("attempt"), Some("2"));
    assert_eq!(retrying[0].field("after"), Some("PT3S"));

    let shed = heard.events_with("decision");
    assert_eq!(shed.len(), 1);
    assert_eq!(shed[0].level, Level::WARN);
    assert_eq!(
      shed[0].field("key"),
      Some("segment(clip-7, 2)"),
      "the obituary carries the node's COMPLETE item key"
    );
    assert_eq!(shed[0].field("decision"), Some("drop_oldest"));
    assert_eq!(shed[0].field("queued"), Some("8"));
    assert_eq!(shed[0].field("capacity"), Some("8"));

    let sick = heard.events_with("concern");
    assert_eq!(sick.len(), 1);
    assert_eq!(sick[0].level, Level::ERROR);
    assert_eq!(sick[0].field("concern"), Some("overflow"));
    assert_eq!(sick[0].field("error"), Some("the advisor panicked"));
  }

  #[test]
  fn an_unstated_optional_field_is_declared_and_not_recorded() {
    let tap = TracingTap::new();
    let node = NodeName::new("clip");
    let heard = heard(|| {
      // A refusal naming no content, and a retry with no backoff: two `Option`s that carry nothing.
      tap.observe(
        node,
        &Lifecycle::<u64>::Skipped(Skip::new(SkipReason::NoConsumers)).erase(),
      );
      tap.observe(
        node,
        &Observation::Retrying {
          attempt: 1,
          after: None,
        },
      );
    });
    let heard = heard.lock().expect("the capture lock");
    let skipped = heard.events_with("station");
    assert_eq!(skipped.len(), 1);
    assert!(
      skipped[0].declares("content"),
      "the callsite names the field in every build"
    );
    assert_eq!(
      skipped[0].field("content"),
      None,
      "and records it only where the operator stated one"
    );
    let retrying = heard.events_with("attempt");
    assert!(retrying[0].declares("after"));
    assert_eq!(retrying[0].field("after"), None);
  }

  #[test]
  fn a_pure_units_batch_and_tick_are_spanned_and_its_commit_is_not() {
    let (feed, inbox) = channel::<ItemId, u64>(8);
    let (out, downstream) = channel::<ItemId, u64>(8);
    let mut resident = Resident::new("double", Doubling, inbox)
      .publish(out)
      .polling(Schedule::new().every(Duration::from_millis(5)), ())
      .with_sweep(Duration::from_millis(5))
      .with_tracing_level(TracingLevel::Debug);
    let answers = send(&feed, &[1, 2, 3]);
    let holder = holding(feed);
    // The consumer answers on another thread; nothing it does opens a span of this node's.
    let consumer = thread::spawn(move || drain(&downstream));

    // MOVED into the closure, so the resident — and the sending half every downstream inbox is
    // parked on — is dropped the moment the run ends. A walk that kept it alive would leave a
    // consumer thread parking forever on a channel nobody will ever close.
    let heard = heard(move || {
      resident.run();
    });
    holder.join().expect("the feed holder");
    consumer.join().expect("the consumer thread");
    drop(answers);

    let heard = heard.lock().expect("the capture lock");
    let batches = heard.spans("ingraph.batch");
    assert_eq!(batches.len(), 1, "one delivery, one batch span");
    assert_eq!(batches[0].level, Level::DEBUG, "the DECLARED level");
    assert_eq!(batches[0].field("node"), Some("double"));
    assert_eq!(batches[0].field("items"), Some("3"));

    assert!(
      heard.spans("ingraph.commit").is_empty(),
      "a node that lands nothing has no commit to time: {:?}",
      heard.span_names()
    );

    let ticks = heard.spans("ingraph.tick");
    assert!(!ticks.is_empty(), "the clock ran: {:?}", heard.span_names());
    assert_eq!(ticks[0].level, Level::DEBUG);
    assert_eq!(ticks[0].field("node"), Some("double"));
    assert_eq!(ticks[0].field("source"), Some("0"));
  }

  #[test]
  fn a_landing_units_commit_is_spanned_and_carries_its_rows() {
    let (feed, inbox) = channel::<ItemId, u64>(8);
    let mut resident = Resident::new("store", Doubling, inbox)
      .with_effect(Effect::Lands)
      .with_ack(AckMode::Local)
      .with_tracing_level(TracingLevel::Warn);
    let answers = send(&feed, &[1, 2]);
    drop(feed);

    // MOVED into the closure, so the resident — and the sending half every downstream inbox is
    // parked on — is dropped the moment the run ends. A walk that kept it alive would leave a
    // consumer thread parking forever on a channel nobody will ever close.
    let heard = heard(move || {
      resident.run();
    });
    drop(answers);

    let heard = heard.lock().expect("the capture lock");
    let commits = heard.spans("ingraph.commit");
    assert_eq!(commits.len(), 1, "one batch, one commit span");
    assert_eq!(
      commits[0].level,
      Level::WARN,
      "the declared level governs every one of the four"
    );
    assert_eq!(commits[0].field("node"), Some("store"));
    assert_eq!(commits[0].field("rows"), Some("2"));
  }

  /// A responder that answers the length of what it was asked.
  struct Counting;

  impl Answers<String> for Counting {
    type Error = core::convert::Infallible;
    type Output = usize;

    fn on_invoke(&mut self, input: String) -> Result<usize, Self::Error> {
      Ok(input.len())
    }
  }

  #[test]
  fn a_query_doors_round_trip_is_spanned_once_per_invoke() {
    let (front, invokes) = door::<String, usize>(4);
    let mut arm = QueryArm::new("tower", Counting, invokes).with_tracing_level(TracingLevel::Trace);
    let first = front.invoke("red".to_owned()).expect("listening");
    let second = front.invoke("blue car".to_owned()).expect("listening");
    drop(front);

    let heard = heard(move || {
      arm.run();
    });

    assert_eq!(first.take().expect("answered"), 3);
    assert_eq!(second.take().expect("answered"), 8);
    let heard = heard.lock().expect("the capture lock");
    let doors = heard.spans("ingraph.door");
    assert_eq!(doors.len(), 2, "one span per invoke, not per arm");
    assert_eq!(doors[0].level, Level::TRACE, "the DECLARED level");
    assert_eq!(doors[0].field("node"), Some("tower"));
    assert_eq!(doors[0].field("query"), Some("1"), "the arm's own count");
    assert_eq!(doors[1].field("query"), Some("2"));
  }

  #[test]
  fn the_span_list_is_the_four_and_nothing_else() {
    let (feed, inbox) = channel::<ItemId, u64>(8);
    let mut resident = Resident::new("store", Doubling, inbox)
      .with_effect(Effect::Lands)
      .polling(Schedule::new().every(Duration::from_millis(5)), ())
      .with_sweep(Duration::from_millis(5))
      .with_taps(Taps::new().with(Arc::new(TracingTap::new())));
    let answers = send(&feed, &[1]);
    let holder = holding(feed);

    // MOVED into the closure, so the resident — and the sending half every downstream inbox is
    // parked on — is dropped the moment the run ends. A walk that kept it alive would leave a
    // consumer thread parking forever on a channel nobody will ever close.
    let heard = heard(move || {
      resident.run();
    });
    holder.join().expect("the feed holder");
    drop(answers);

    let heard = heard.lock().expect("the capture lock");
    let names = heard.span_names();
    for name in &names {
      assert!(
        matches!(
          name.as_str(),
          "ingraph.batch" | "ingraph.door" | "ingraph.commit" | "ingraph.tick"
        ),
        "{name} is a fifth span: {names:?}"
      );
    }
    assert!(
      !names.is_empty(),
      "the walk opened no span at all, so it proves nothing"
    );
    assert!(
      heard.events() > 0,
      "the tap rode along and said something about the same run"
    );
  }
}