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
//! The AGGREGATE fold: [`Measure`], the contract a declared aggregate's measure column is filled
//! through, and the two citizens this framework ships as implementations of it.
//!
//! # ONE WORD AT THREE GRAINS
//!
//! `measure` is already this grammar's block word and its field marker — *a word may be shared where
//! it means the same thing at both grains*, which the aggregate front end argues for the two it
//! already had. The contract is the third grain of the same word, and it means what the other two
//! mean: WHAT FILLS THIS COLUMN.
//!
//! ```text
//! measure(count = counting)     the declaration's entry     — the VALUE is the fold
//!  #[ingraph(measure)] count    the field's role
//!         Measure<T>            the contract
//!         Counting, Summing     the citizens the two bare words name
//! ```
//!
//! # The vocabulary IS the trait, and the shipped members are CITIZENS
//!
//! There is no `enum Measure` here. What folds a group is a TYPE implementing [`Measure`], and
//! [`Counting`] and [`Summing`] are the two that happen to ship. A third — framework or downstream —
//! is one type and one impl, purely additive: no match site widens, no enum gains an arm, and
//! nothing that compiled before stops compiling. That is the `FoldSemantics` family's own shape one
//! kind over, and the closed design took it deliberately.
//!
//! What is CLOSED is the set of BARE WORDS the grammar takes. `counting` and `summing` are a promise
//! this crate can write the whole binding for, which it can only keep for a fold it ships; every
//! other measure there is arrives QUOTED as the type that implements it —
//! `measure(median = "app::Median")` — and needs no admission to any vocabulary. MINT BARE, REFER
//! QUOTED, read at one more position.
//!
//! # It is UNGATED, and the tier is the aggregate's own
//!
//! An aggregate is RECORD SUGAR: it mints a `(group…, measure…)` row and hands it to the record
//! pass. `record` is ungated, so this is. Two readers make the gate the wrong answer rather than a
//! cautious one — the emitted recompute, which exists wherever the record it upserts into does, and
//! a DOWNSTREAM IMPLEMENTOR, who must be able to write `impl Measure<…> for MyFold` in a build that
//! turned every optional face off. Putting the seam behind `engine` would have bought a feature the
//! kind does not use, and locked the open half behind it.
//!
//! # Every empty type here is SEALED, and that is this crate's law for one
//!
//! `pub struct Counting(());` rather than `pub struct Counting;`. A bare unit struct is constructible
//! by anybody who can name it, so the day a citizen grows a field is the day every downstream
//! literal stops compiling. The private `()` funnels construction through [`Counting::new`] from the
//! first version, and the type can grow without breaking a caller.

use core::ops::Add;

#[cfg(test)]
mod tests;

/// WHAT FILLS ONE MEASURE COLUMN — the contract a declared aggregate's fold satisfies.
///
/// # The primitive it folds over
///
/// An aggregate RECOMPUTES WHOLE on every trigger: it reads the upstream's rows, groups them by the
/// declaration's group columns, and folds each group into one row. This trait is the last step of
/// that walk — ONE group's projected items, in, one column value out. The slice is the group's, not
/// the table's, and it is a slice rather than an iterator because the recompute has the group in
/// hand already: it grouped to get here.
///
/// # `T` IS THE PROJECTION'S, AND THAT IS WHY IT IS THE TRAIT'S PARAMETER
///
/// `T` is what the emission projects out of each upstream row for this column, and a measure has no
/// say in it: [`Counting`] never looks at an item and [`Summing`] adds whatever the column holds. So
/// the item type is where the IMPLEMENTOR states what it can fold — one impl per item type, or a
/// blanket over all of them — and the emission instantiates it with what the declaration's upstream
/// actually carries. Nothing here decides how that projection is materialised.
///
/// # `Value` IS AN ASSOCIATED TYPE, because a measure's answer is not its input
///
/// This is the one place the shape departs from `FoldSemantics`, and the departure is forced rather
/// than chosen: that trait folds `m` scores into ONE SCORE, so its input and its answer are the same
/// currency and one parameter carries both. A measure's are not. [`Counting`] answers a [`Count`]
/// about items of every type there is; [`Summing`] answers the column's own type. A second trait
/// parameter would have made both a caller's to name and neither inferable; an associated type makes
/// the answer the IMPLEMENTOR's, which is whose it is.
///
/// # THE QUOTED-PATH ESCAPE, which is what this trait being public is FOR
///
/// The bare words are closed. The types are not: a measure the declaring crate wrote is named in the
/// declaration as `measure(<field> = "path::to::Fold")` and reaches the emission as that path
/// verbatim — nothing in this framework resolves it, because two macro expansions cannot see each
/// other, so a path naming nothing is rustc's own refusal at the string its author wrote and a type
/// that does not implement this trait is `E0277` where the fold is constructed.
///
/// The emission CONSTRUCTS what the entry named, and it constructs both halves of the axis the same
/// way: `<F as Default>::default()`, which is the elected fold's own line one kind over. So a
/// declared measure is [`Default`] as well as an implementation of this trait, and one that is not
/// is `E0277` at the string that named it.
///
/// Writing one is this and nothing else:
///
/// ```
/// use ingraph::Measure;
///
/// /// The biggest value a group holds — a measure this framework ships no word for.
/// ///
/// /// Named in the declaration as `measure(peak = "app::Largest")`, which is why it derives
/// /// `Default`: the emission constructs the fold an entry named.
/// #[derive(Default)]
/// pub struct Largest;
///
/// impl<T: Clone + PartialOrd + Send + Sync> Measure<T> for Largest {
///   type Value = T;
///
///   fn fold(&self, items: &[T]) -> T {
///     items
///       .iter()
///       .cloned()
///       .reduce(|running, next| if next > running { next } else { running })
///       .expect("a group is folded because at least one upstream row projected into it")
///   }
///
///   fn name(&self) -> &str {
///     "largest"
///   }
/// }
///
/// assert_eq!(Largest.fold(&[3_u64, 9, 4]), 9);
/// assert_eq!(<Largest as Measure<u64>>::name(&Largest), "largest");
/// ```
///
/// Nothing widened to admit it. The blanket above is over `T` for ONE measure type, so it constrains
/// nothing about what other measures may implement, and a measure that folds exactly one item type
/// writes `impl Measure<ThatType>` for the concrete type without colliding with it.
///
/// # The EMPTY SLICE is unreachable through this crate's own road, and the citizens still differ
///
/// A group is folded because at least one upstream row projected into it — a group with no rows is
/// not a group, it is an absence, and the recompute writes no row for it. So `items` is non-empty
/// wherever this framework calls it.
///
/// That does not make the empty case one answer. [`Counting`] answers `0`, which is TRUE for a group
/// with no rows in every currency there is; [`Summing`] panics, because a sum of nothing is a value
/// only the currency could name and it was not asked. The difference is not a posture this trait
/// takes — it is a fact about the two folds, and a third citizen decides it for itself.
///
/// # `Send + Sync`
///
/// The recompute is `async` and holds the measure across the read that fetches the rows and the
/// upsert that writes them back, so a measure that could not cross a task boundary would make that
/// future `!Send` and be unusable from every runtime that spawns. It costs the shipped citizens
/// nothing and costs a stateful one exactly what it would have cost at the call site.
pub trait Measure<T>: Send + Sync {
  /// What folding one group produces — this column's stored value.
  type Value;

  /// Fold ONE GROUP's projected items into its column value.
  fn fold(&self, items: &[T]) -> Self::Value;

  /// A stable name for a tap, a refusal and a doc — `"counting"`, `"summing"`.
  ///
  /// # It is a ROW rather than a default, for `FoldSemantics`' reason
  ///
  /// There is no default body: a measure that inherited `"unnamed"` would silently make every trace
  /// of a recompute running it useless, and one line per implementation buys the whole reporting
  /// surface. The same trade `Concern::as_str` and the fate vocabulary make one layer up.
  ///
  /// # A CITIZEN'S NAME IS ITS BARE WORD
  ///
  /// `counting` names [`Counting`] in the grammar and [`Counting`] answers `"counting"` here, so the
  /// word an author WROTE and the word a trace REPORTS are one string. The two halves are pinned
  /// against each other in this module's tests, against the grammar's own list.
  ///
  /// # It is NOT the wire's self-description
  ///
  /// An aggregate publishes through the RECORD path, whose field names are the declaration's own —
  /// `count: Count` is on the wire because the author named a field `count`, not because a fold is
  /// spelled `counting`. Nothing here reaches a schema, exactly as `FoldSemantics::name` states for
  /// its own family.
  ///
  /// `&str` rather than `&'static str`, so a measure assembled at launch — a fold parameterised by
  /// configuration, a tenant's own — can name itself from a [`String`] it holds.
  fn name(&self) -> &str;
}

/// A BORROWED measure measures — what lets a call taking its measure BY VALUE be handed one that
/// lives somewhere else.
///
/// `FoldSemantics`' own impl, at this trait: the recompute's measure is either a local the emission
/// constructed or one a deployment holds behind an [`Arc`](std::sync::Arc), and without this line
/// every caller generic over the measure would monomorphize twice for a decision made once.
///
/// `?Sized` so `&dyn Measure<T, Value = V>` is one of them. Nothing is added to the measure —
/// [`fold`](Measure::fold) and [`name`](Measure::name) forward, and a borrow cannot disagree with
/// what it borrows.
impl<T, M> Measure<T> for &M
where
  M: Measure<T> + ?Sized,
{
  type Value = M::Value;

  #[inline]
  fn fold(&self, items: &[T]) -> Self::Value {
    M::fold(self, items)
  }

  #[inline]
  fn name(&self) -> &str {
    M::name(self)
  }
}

/// `count(*)` — HOW MANY ROWS the group holds, whatever they hold.
///
/// The blanket over every `T` is the citizen's whole character: counting does not read an item, so
/// there is no item it cannot count. A group of embeddings, of strings, of a type this framework has
/// never heard of — the answer is the same walk.
///
/// # ZERO IS A TRUE ANSWER HERE, and it is the only measure that can say so
///
/// A group with no rows has a count, and it is `0` in every currency there is. That is why this
/// citizen does not carry [`Summing`]'s panic: the sum of nothing needs an identity the currency
/// must name, and the count of nothing needs none. The case is still unreachable through this
/// framework's own road — an empty group has no row to write — and answering it honestly costs a
/// branch nobody takes.
///
/// # THE ANSWER IS [`Count`], which is this framework's cardinality CURRENCY
///
/// A count is a cardinality, and this crate has a type for one. So the answer is that type rather
/// than the declaration's choice, and a column of any other is refused AT THE DECLARATION by name —
/// the aggregate grammar knows what this citizen answers, because this crate is what wrote it, so
/// the mistake never reaches an `E0308` inside an expansion. `Summing`'s twin mistake cannot be
/// caught there and is not: its answer is the upstream column's own type, which two macro
/// expansions cannot share.
///
/// # A `counting` COLUMN STORES ON EVERY DIALECT, and [`Count`] is what makes it one
///
/// **This section records a hole that has been RULED AND CLOSED** (2026-08-27), and it is written
/// out because the road taken was neither of the two the hole's own note was holding open.
///
/// What the hole was: `Value` used to be a bare [`u64`], and `u64` has no carrier in SQLite or
/// PostgreSQL — sqlx-sqlite ships `Type` and `Decode` for it and no `Encode`, and sqlx-postgres
/// ships none of the three — so an ordinary `u64` COLUMN declares `<db>(type = "BeU64", …)` and
/// crosses into the big-endian form. An aggregate's field grammar takes its ROLE and the projection
/// words and nothing else, by that grammar's own ruling: *a per-database word here would be
/// configuring a column of a row this declaration does not write by hand*. The two were consistent
/// and their intersection was empty, so a `counting` measure stored in SQLite or PostgreSQL was
/// `E0277` at the declaration, carrying [`Carrier`]'s own note.
///
/// **The two exits that note recorded are both SUPERSEDED**, and by name:
///
/// - *the storage words carried to the record pass at the field grain* — this would have opened the
///   aggregate's field grammar to per-database configuration, which is the exact ruling the field
///   grammar is built on. Not taken;
/// - *a shipped citizen whose answer is a width those dialects hold* — a second fold, differing from
///   this one only in the width of its answer, would have made the DECLARER choose between two
///   spellings of one question. Not taken.
///
/// **What was taken is a third road: the value type is the CITIZEN's, and the per-dialect knowledge
/// lives where every type's per-dialect knowledge already lives — in its own carrier rows.**
/// [`Count`] is a `u64` carrying one invariant a bare `u64` has not got: *a cardinality counts rows
/// that EXIST*, so it is bounded by the physical store, and its crossings are allowed to SPEND that
/// bound. On SQLite and PostgreSQL it narrows into an `i64` over an arm no count reaches; on MySQL
/// it is the native `BIGINT UNSIGNED`; on MongoDB it is an `Int64`. The column type is
/// dialect-invariant — `Count` everywhere — so nothing in the emission changed and no word entered
/// any grammar. See [`Count`] for the invariant and [`Carrier`] for the per-dialect table.
///
/// This is NOT the removed magic returning. What was removed was the framework silently wrapping a
/// DECLARER's `u64` field into a big-endian blob behind their back; what this is, is a fold this
/// crate wrote answering in a type this crate owns, which the declaration then names outright. The
/// declarer writes `tracks: Count` and can read exactly what that stores.
///
/// # [`Summing`]'s corner is NOT closed by this, and that is the honest residual
///
/// A `summing` measure whose column is a bare `u64` is still `E0277` on SQLite and PostgreSQL, and
/// it stays so. The two cases are not the same: a count is bounded by the store, and a TOTAL is
/// bounded by nothing — two `u64`s just under `i64::MAX` genuinely sum past it, so no physical fact
/// backs a narrowing and one written anyway would lose a value the caller put in. That refusal is
/// CORRECT rather than an unclosed hole.
///
/// **What it leaves is a real corner and it is recorded rather than papered over**: a wide UNSIGNED
/// total on those two dialects has no shipped road, the aggregate's field grammar having no seat for
/// a storage form and this crate shipping no unsigned total that could carry one. A signed total is
/// the ordinary road and is what the shipped lanes take. A deployment that needs the unsigned one
/// has the framework-open escape the vocabulary is a TRAIT for: a fold of its own, whose `Value` is a
/// type of its own carrying its own carrier rows — which is exactly what [`Count`] is, written by
/// the party that needs it.
///
/// [`Carrier`]: crate::Carrier
/// [`Count`]: crate::Count
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Counting(());

impl Counting {
  /// The citizen's stable name — ONE spelling, and the grammar's own bare word.
  ///
  /// A const rather than a literal at each site, and the reason is a MEASUREMENT rather than
  /// tidiness: `self.name()` inside a `Measure<T>` body is **`E0282`** — *type annotations needed*,
  /// answered by *try using a fully qualified path* — this citizen implementing the trait at every
  /// `T` there is, so the call would have to be written out in full with a type the body has no
  /// other use for. A const on the citizen is the same fact reached without naming `T` at all.
  /// `Sum::NAME` is the same measurement one family over, where the parameter rides the RETURN type
  /// and the same call is `E0284` instead.
  const NAME: &'static str = "counting";

  /// The citizen.
  ///
  /// A constructor rather than a bare unit struct — see this module's note on the sealed form.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self(())
  }
}

impl<T> Measure<T> for Counting {
  type Value = crate::Count;

  /// # The narrowing SATURATES, and the arm is unreachable
  ///
  /// A slice's length is a [`usize`] and no target this crate builds for has one wider than 64 bits,
  /// so the conversion cannot fail here. It is written rather than cast because a cast that
  /// truncates silently is the failure mode this crate refuses everywhere, and it SATURATES rather
  /// than panicking because the caller is a CLOCK: an aggregate that aborted a scheduled recompute
  /// over an impossibility would stop answering forever, which is the swallowed failure the kind's
  /// mandatory clock exists to prevent. The same form the poll layer narrows a tick count with, and
  /// the same form [`Count::to_signed`](crate::Count::to_signed) narrows the OTHER direction with —
  /// where the arm is unreachable for this one's reason read one step on: a length that came from a
  /// slice is a length of something in memory.
  ///
  /// The wrap into [`Count`](crate::Count) is where the length stops being an arbitrary magnitude
  /// and becomes a cardinality, which is the fact every carrier row downstream of here spends.
  #[inline]
  fn fold(&self, items: &[T]) -> crate::Count {
    crate::Count::new(u64::try_from(items.len()).unwrap_or(u64::MAX))
  }

  #[inline]
  fn name(&self) -> &str {
    Self::NAME
  }
}

/// `sum(<column>)` — the TOTAL of what the group's rows hold.
///
/// # NO ZERO, and no identity anywhere — `Sum`'s argument, at this grain
///
/// The fold starts from the FIRST item and adds the rest pairwise. It does not start from a zero,
/// because a zero is a value only the column's own currency can name: a duration has one, a
/// temperature's is a convention, and a type that is summable without being nameable-at-zero has
/// none at all. [`iter::Sum`](core::iter::Sum) was rejected one family over for exactly this — its
/// empty case MANUFACTURES a value — and the same rejection holds here, where the manufactured value
/// would be STORED and read back as a fact about the upstream.
///
/// What this does instead is start from a real item, which is available because a group is folded
/// only where a row projected into it.
///
/// # OVERFLOW IS THE COLUMN'S OWN POSTURE, and this fold adds nothing to it
///
/// [`Add`] is the whole of the arithmetic in the signature, so a sum of `u64`s overflows exactly as
/// `u64 + u64` does — panicking under `debug-assertions`, wrapping without them. A checked or
/// saturating total is not a knob on this citizen: it is a DIFFERENT fold with a different answer,
/// and this vocabulary is a trait, so it is one type and one impl by whoever wants it.
///
/// # A `u64` TOTAL ON SQLITE AND POSTGRESQL IS STILL REFUSED, and here that refusal is CORRECT
///
/// [`Counting`]'s own note records the hole that was closed on 2026-08-27 and why this citizen is
/// not carried through it. A `summing` measure whose column is a bare `u64` is `E0277` at the
/// declaration on those two dialects, and it stays so: what bought the count a carrier was a
/// PHYSICAL BOUND — a cardinality counts rows that exist — and a total has none. Two values just
/// under `i64::MAX` sum past it, so a narrowing here would lose what the caller put in.
///
/// The corner that leaves is recorded at [`Counting`]'s note beside the ruling. Nothing in this
/// module closes it, and the escape is the vocabulary's own openness rather than a word: a fold is a
/// TYPE here, so a total with a storage form of its own is one impl by whoever needs it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Summing(());

impl Summing {
  /// The citizen's stable name — [`Counting::NAME`]'s twin, and the same measurement.
  const NAME: &'static str = "summing";

  /// The citizen — [`Counting::new`]'s twin, and the same law.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self(())
  }
}

impl<T> Measure<T> for Summing
where
  T: Clone + Add<Output = T> + Send + Sync,
{
  type Value = T;

  /// # Panics
  ///
  /// If the group is empty, which the road above this cannot produce: a group is folded because at
  /// least one upstream row projected into it. The alternative is a manufactured zero, which this
  /// citizen's own note refuses.
  #[inline]
  fn fold(&self, items: &[T]) -> T {
    let mut present = items.iter().cloned();
    let first = first_of(&mut present, Self::NAME);
    present.fold(first, |running, next| running + next)
  }

  #[inline]
  fn name(&self) -> &str {
    Self::NAME
  }
}

/// The value a measure STARTS from, or the panic that names WHICH MEASURE had nothing to start from
/// and why there was none.
///
/// One sentence for every citizen that needs one, so the invariant is written once and reads the
/// same wherever it fires. The measure's own [`name`](Measure::name) rides the message: a deployment
/// reading this abort in a log knows whether the fold that hit it was the shipped `summing` or one
/// it declared, which is exactly the fork it would otherwise have to reproduce to find out.
///
/// # It is this module's own rather than the retrieve family's, and the TIER is why
///
/// The identical helper beside `Sum` is behind the `engine` feature, and this seam is ungated for
/// the reasons this module's own note gives. Reaching for it would have dragged the aggregate's fold
/// contract behind a feature the kind does not use — a sentence duplicated is the cheaper of the
/// two.
///
/// # Panics
///
/// Where the group holds nothing at all, which this crate's own road cannot produce.
#[inline]
fn first_of<T>(present: &mut impl Iterator<Item = T>, measure: &str) -> T {
  present.next().unwrap_or_else(|| {
    panic!(
      "the `{measure}` measure was handed a group with no rows: a group is folded because at least \
       one upstream row projected into it",
    )
  })
}