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
//! [`Route<T>`] — the EDGE of the fusion tree: what a parent knows about one of its routes, wrapped
//! around what that route knows about itself.

use core::num::{NonZeroU32, NonZeroUsize};

/// ONE ROUTE of a fusing tier — the parent's own facts about the edge, and the route's package
/// inside them.
///
/// ```text
/// TranscriptFuseOptions {                     the TIER's package
///   fusion:   Option<FusionOptions>,          the tier's own algorithm
///   body:     Option<Route<…FulltextOptions>>,   ─┐ one edge per route,
///   captions: Option<Route<…FuseOptions>>,       ─┘ slot and child tier alike
/// }
/// ```
///
/// # WHOSE fact is on the edge, and that is the whole of the split
///
/// Three beliefs a parent holds about one route: **how much to trust it, whether to walk it, and how
/// deep to ask it.** A weight is a coefficient in the PARENT's fold — `wᵢ / (k + rankᵢ)` — so it is a
/// fact about the edge and not about the route, and a route asked as a standalone door has no weight
/// because there is no fold for one to enter. `enabled` is the same fact one step further: whether
/// this parent walks this route at all. [`depth`](Self::depth) is the third: how many hits this
/// parent wants FETCHED down this edge, which is a fact about what the parent's fold needs and not
/// about the route's own storage. The route's OWN facts — its floors, its engine knobs, its
/// sub-fusion — live in [`options`](Self::options), which is the package the route would have carried
/// anyway.
///
/// The split is what kills the dead fields. Before it, a tier package had to carry a weight even
/// where nothing fused it, and a standalone tier door had to take a weight nobody read. Here a
/// standalone door takes the bare interior package and never sees this type at all, while a slot
/// route and a child-tier route wear the SAME wrapper — which is what makes the tree fractal rather
/// than two shapes that happen to nest.
///
/// # WHY a depth is worth its own number, where a `limit` was already there
///
/// Reciprocal rank fusion is SUM-FAMILY — `Σ wᵢ / (k + rankᵢ)` — so a root's final ordering depends
/// on positions no single route's own top slice determines. Fetching deeper than the answer is wide
/// is the standing pattern for that: ask each route for a candidate pool, fold, then cut at `limit`.
/// The VALUE is the caller's — there is no number this framework could invent that would be right for
/// two corpora — so the seat is here and empty by default, and [`route_depth`] is the whole of the
/// law that spends it.
///
/// `depth < limit` is LEGAL and is not refused: every number in this pipeline is a CEILING rather
/// than a promise, and a caller cheapening one route while asking for a wide answer is asking for
/// exactly what it asked for. `depth` ABOVE a declared ceiling is legal to WRITE and is capped when
/// spent — see [`route_depth`], where the wall law is stated.
///
/// # The de-Option law, read off the four fields
///
/// `Option` is for absence that DEFERS to a resolution chain, and for nothing else. `weight` and
/// `enabled` defer to nobody: a route the client said nothing about is walked at
/// [`DEFAULT_WEIGHT`](Self::DEFAULT_WEIGHT) and [`DEFAULT_ENABLED`](Self::DEFAULT_ENABLED), full
/// stop, so they are BARE fields carrying those constants. The other two DO defer, and to two
/// different chains: `options` to the declaration's own knobs — a route nobody configured takes them,
/// and there is no value of the package type that means *the declaration's* — and `depth` to the
/// caller's budget, which is [`route_depth`]. Two bare fields and two [`Option`]s, each one for the
/// law's own stated reason.
///
/// What `depth` does NOT defer to is the declared CEILING, and that is the wall law rather than an
/// omission: a ceiling is protective, so it caps this number instead of standing behind it, and it
/// is not on this type at all because a protective number never crosses the wire.
///
/// On the wire all four are omissible, and that is the same law rather than a second one: the two
/// bare fields render with their constants as the schema's own defaults, the two deferring fields
/// render with none, and a client that writes `{}` gets exactly what a client that wrote nothing
/// gets.
///
/// # `f64` for the weight, where every score in this crate is the engine's own type
///
/// A weight is not a score. It never meets a score: RRF reads ORDINALS, and the weight multiplies
/// `1 / (k + rank)` — a number this crate mints, in [`FusedScore`](super::FusedScore)'s own
/// arithmetic, which is `f64`. So there is no currency to be generic over here, and the parameter a
/// [`FloorSpec`](super::FloorSpec) needs would be a parameter with nothing to bind.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Route<T> {
  weight: f64,
  enabled: bool,
  depth: Option<NonZeroUsize>,
  options: Option<T>,
}

impl<T> Route<T> {
  /// The coefficient a route takes in its parent's fold when nobody names one.
  ///
  /// One, because RRF's own term is `1 / (k + rank)` and the neutral coefficient of a product is the
  /// multiplicative identity — so a tier where nobody weighted anything runs the unweighted fold
  /// exactly, rather than an approximation of it.
  pub const DEFAULT_WEIGHT: f64 = 1.0;

  /// Whether a route is walked when nobody says.
  ///
  /// True, because the routes of a tier are the routes its DECLARATION wrote: a client who wants
  /// fewer says so, and a client who says nothing gets the declaration. The opposite default would
  /// make an unconfigured fused query answer with nothing at all, which is the one answer that
  /// cannot be right.
  pub const DEFAULT_ENABLED: bool = true;

  /// An unconfigured edge: the two constants, no depth, and no package.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self {
      weight: Self::DEFAULT_WEIGHT,
      enabled: Self::DEFAULT_ENABLED,
      depth: None,
      options: None,
    }
  }

  /// The same edge at another coefficient.
  #[inline]
  #[must_use]
  pub fn with_weight(mut self, weight: f64) -> Self {
    self.weight = weight;
    self
  }

  /// The same edge, walked or not.
  #[inline]
  #[must_use]
  pub fn with_enabled(mut self, enabled: bool) -> Self {
    self.enabled = enabled;
    self
  }

  /// The same edge asked that deep.
  #[inline]
  #[must_use]
  pub const fn with_depth(mut self, depth: NonZeroUsize) -> Self {
    self.depth = Some(depth);
    self
  }

  /// This edge's depth, named in place.
  ///
  /// The IN-PLACE form exists because a depth is the one edge fact a holder narrows AFTER the edge
  /// was built: a request package parsed off a wire is owned whole, and reaching one route inside it
  /// to say *ask this one deeper* has no other spelling than `&mut`. The consuming
  /// [`with_depth`](Self::with_depth) beside it is the building form, and the three older fields keep
  /// that form alone rather than being widened by a round that had no call for it.
  #[inline]
  pub const fn set_depth(&mut self, depth: Option<NonZeroUsize>) -> &mut Self {
    self.depth = depth;
    self
  }

  /// The same edge carrying the route's own package.
  #[inline]
  #[must_use]
  pub fn with_options(mut self, options: T) -> Self {
    self.options = Some(options);
    self
  }

  /// This route's coefficient in its parent's fold.
  #[inline]
  #[must_use]
  pub const fn weight(&self) -> f64 {
    self.weight
  }

  /// Whether the parent walks this route at all.
  #[inline]
  #[must_use]
  pub const fn enabled(&self) -> bool {
    self.enabled
  }

  /// HOW DEEP this parent asks this route, where it named a depth at all.
  ///
  /// [`None`] defers to the caller's budget — see [`route_depth`], which is also where a declared
  /// ceiling CAPS whatever this says. It is a ceiling in the ordinary sense like every other number
  /// here: a route holding fewer hits than this answers with fewer.
  #[inline]
  #[must_use]
  pub const fn depth(&self) -> Option<NonZeroUsize> {
    self.depth
  }

  /// The route's own package, where the caller configured one.
  #[inline]
  pub const fn options(&self) -> Option<&T> {
    self.options.as_ref()
  }
}

/// The DEPTH one route is fetched at: **the ask, capped by the wall** —
/// `min(depth.unwrap_or(limit), declared_ceiling)`.
///
/// ```text
/// depth: Some(50),     ceiling: Some(100)  →   50   the ask, inside the wall
/// depth: Some(500000), ceiling: Some(100)  →  100   the wall, and no request may raise it
/// depth: None,         ceiling: Some(100)  →  min(limit, 100)
/// depth: Some(50),     ceiling: None       →   50   the author's informed openness
/// depth: None,         ceiling: None       →  limit
/// ```
///
/// # THE ONE-SENTENCE LAW: protective numbers never cross the wire; preference numbers do
///
/// A `depth` and a `fold`'s knobs and a `floor` are PREFERENCES — a requester's own statement about
/// the answer it wants — so they travel on the request, and a client rewriting one is a client
/// asking a different question. A ceiling is not of that family: it is PROTECTIVE, an upper bound on
/// what a request may cost this deployment, and a bound the requester can rewrite binds nothing. So
/// it is the one number that leaves the request surface, and its only home is the declaration.
///
/// # CAPS, never replaces — and that is the correction the law forced
///
/// The chain this function used to run read *the edge, else the ceiling, else the budget*, so a
/// written `depth` REPLACED the ceiling outright. That was defensible while both numbers were the
/// same caller's, written in one request; the wire road makes `depth` client-writable, and against a
/// client-writable ask a bound that yields to it is not a bound. The ceiling is a WALL now: the ask
/// runs free INSIDE it and cannot step past it, whatever it says.
///
/// An absent ceiling is the author's INFORMED OPENNESS rather than a gap — a declaration that named
/// no wall is one whose author decided there is none to name, and the framework does not invent one
/// on their behalf. The engine's own corpus clamp is the final safety there.
///
/// # It is one function because it is one law, spent at four grains
///
/// A fanned leg, a tier route, a root member and a member's own single route all cap the same way,
/// and a chain written out at each of them is a chain that can drift at one of them. The emission
/// calls this; nothing else decides a depth.
///
/// # A grain with no declared ceiling passes [`None`] and loses nothing
///
/// A ROOT holds a member's package by projection and cannot read a declaration out of it; a fanned
/// leg outside the leaderboard holds no [`Route`] at all. Both resolve as *the ask, uncapped*, which
/// is this function with its middle argument absent rather than a second function.
#[inline]
#[must_use]
pub fn route_depth(
  edge: Option<NonZeroUsize>,
  declared: Option<&NonZeroU32>,
  budget: NonZeroUsize,
) -> NonZeroUsize {
  // THE ASK first, and it is the caller's whole statement: a named depth, else the budget the answer
  // is being cut at. Nothing below widens it — a wall only ever narrows.
  let asked = edge.unwrap_or(budget);
  match declared {
    // A declared ceiling is a `NonZeroU32` — the width a declaration publishes it at — and there is
    // no infallible widening to `usize`, because a target's `usize` may be sixteen bits. On every
    // target this crate is built for the conversion holds; where it could not, the widest number
    // that target can express is what *this many, and there are not that many* already means here,
    // and it caps nothing that a `usize` could have expressed anyway.
    Some(ceiling) => asked.min(NonZeroUsize::try_from(*ceiling).unwrap_or(NonZeroUsize::MAX)),
    None => asked,
  }
}

/// The unconfigured edge — [`Route::new`].
///
/// Written rather than derived, because the derived body would have demanded `T: Default` of a
/// package whose absence is the whole point: `None` means *this route was not configured*, and a
/// derived `Default` would have had to build one instead of leaving it absent.
impl<T> Default for Route<T> {
  #[inline]
  fn default() -> Self {
    Self::new()
  }
}

/// The WIRE FACE, written over the PARAMETER — [`EnumFilter`](crate::EnumFilter)'s road, and taken
/// for the same reason it was taken there.
///
/// A route's interior is an EMITTED package, so the set of instantiations is open and a table with a
/// row per one is a table this crate cannot write. One generic impl closes it with nothing orphaned:
/// [`Route`] is this crate's own type, so the impl is local at every `T`, and what a declaring crate
/// supplies is the package's own face.
///
/// # The NAME is derived, and the derivation is the modifier convention
///
/// `<T's schema name>Route` — `TranscriptFulltextOptions` gives `TranscriptFulltextOptionsRoute`.
/// Injective, because suffixing preserves distinctness, so two distinct package names give two
/// distinct route names without a hand-maintained table saying so. The names are long by design:
/// they are minted at slot grain, where two declarations may elect a field of the same name.
///
/// # Both bare fields carry their DEFAULT into the schema, and the two deferring ones carry none
///
/// `weight: Float = 1` and `enabled: Boolean = true` are published rather than left to a sentence,
/// which is what makes the wire and the Rust type say the same thing: a client reading the SDL sees
/// the constant a Rust caller gets from [`Route::new`]. It is also the only spelling under which
/// *omit the field* and *write the default* are the same request, which the de-Option law needs them
/// to be.
///
/// `depth: Int` and `options` publish NO default, and that is the same law from its other side: there
/// is no number that means *whatever the route or the caller said*, so an SDL default would be a
/// literal claiming to be a deferral. `Int` is the scalar a `NonZeroUsize` crosses under, and the
/// refusal of a zero is that scalar's own — a client writing `depth: 0` is told so at the parse
/// rather than served an empty answer.
#[cfg(feature = "async-graphql")]
impl<T: async_graphql::InputType> async_graphql::InputType for Route<T> {
  type RawValueType = Self;

  fn type_name() -> ::std::borrow::Cow<'static, str> {
    ::std::borrow::Cow::Owned(::std::format!("{}Route", T::type_name()))
  }

  fn create_type_info(registry: &mut async_graphql::registry::Registry) -> ::std::string::String {
    registry.create_input_type::<Self, _>(
      async_graphql::registry::MetaTypeId::InputObject,
      |registry| {
        let mut fields = async_graphql::indexmap::IndexMap::new();
        fields.insert(
          ::std::string::String::from("weight"),
          route_input_value::<f64>(registry, "weight", "1"),
        );
        fields.insert(
          ::std::string::String::from("enabled"),
          route_input_value::<bool>(registry, "enabled", "true"),
        );
        fields.insert(
          ::std::string::String::from("depth"),
          async_graphql::registry::MetaInputValue {
            name: ::std::string::String::from("depth"),
            description: ::std::option::Option::None,
            ty: <::core::option::Option<::core::num::NonZeroUsize> as async_graphql::InputType>
              ::create_type_info(registry),
            deprecation: async_graphql::registry::Deprecation::NoDeprecated,
            default_value: ::std::option::Option::None,
            visible: ::std::option::Option::None,
            inaccessible: false,
            tags: ::std::vec::Vec::new(),
            is_secret: false,
            directive_invocations: ::std::vec::Vec::new(),
          },
        );
        fields.insert(
          ::std::string::String::from("options"),
          async_graphql::registry::MetaInputValue {
            name: ::std::string::String::from("options"),
            description: ::std::option::Option::None,
            ty: <::core::option::Option<T> as async_graphql::InputType>::create_type_info(registry),
            deprecation: async_graphql::registry::Deprecation::NoDeprecated,
            default_value: ::std::option::Option::None,
            visible: ::std::option::Option::None,
            inaccessible: false,
            tags: ::std::vec::Vec::new(),
            is_secret: false,
            directive_invocations: ::std::vec::Vec::new(),
          },
        );
        async_graphql::registry::MetaType::InputObject {
          name: ::std::borrow::Cow::into_owned(Self::type_name()),
          description: ::std::option::Option::None,
          input_fields: fields,
          visible: ::std::option::Option::None,
          inaccessible: false,
          tags: ::std::vec::Vec::new(),
          rust_typename: ::std::option::Option::Some(::std::any::type_name::<Self>()),
          oneof: false,
          directive_invocations: ::std::vec::Vec::new(),
        }
      },
    )
  }

  fn parse(
    value: ::std::option::Option<async_graphql::Value>,
  ) -> async_graphql::InputValueResult<Self> {
    let ::std::option::Option::Some(async_graphql::Value::Object(object)) = value else {
      return ::std::result::Result::Err(async_graphql::InputValueError::expected_type(
        value.unwrap_or_default(),
      ));
    };
    ::std::result::Result::Ok(Self {
      weight: route_slot::<f64, Self>(&object, "weight")?.unwrap_or(Self::DEFAULT_WEIGHT),
      enabled: route_slot::<bool, Self>(&object, "enabled")?.unwrap_or(Self::DEFAULT_ENABLED),
      depth: route_slot::<NonZeroUsize, Self>(&object, "depth")?,
      options: route_slot::<T, Self>(&object, "options")?,
    })
  }

  fn to_value(&self) -> async_graphql::Value {
    let mut map = async_graphql::indexmap::IndexMap::new();
    map.insert(
      async_graphql::Name::new("weight"),
      async_graphql::InputType::to_value(&self.weight),
    );
    map.insert(
      async_graphql::Name::new("enabled"),
      async_graphql::InputType::to_value(&self.enabled),
    );
    map.insert(
      async_graphql::Name::new("depth"),
      async_graphql::InputType::to_value(&self.depth),
    );
    map.insert(
      async_graphql::Name::new("options"),
      async_graphql::InputType::to_value(&self.options),
    );
    async_graphql::Value::Object(map)
  }

  #[inline]
  fn as_raw_value(&self) -> ::std::option::Option<&Self::RawValueType> {
    ::std::option::Option::Some(self)
  }
}

#[cfg(feature = "async-graphql")]
impl<T: async_graphql::InputType> async_graphql::InputObjectType for Route<T> {}

/// One registered field of the wire face, nullable and carrying its Rust constant as the schema's
/// default.
///
/// The default is the SDL literal rather than the Rust value, because that is what a registry entry
/// holds — async-graphql renders `default_value` verbatim into the schema.
#[cfg(feature = "async-graphql")]
fn route_input_value<V: async_graphql::InputType>(
  registry: &mut async_graphql::registry::Registry,
  name: &str,
  default: &str,
) -> async_graphql::registry::MetaInputValue {
  async_graphql::registry::MetaInputValue {
    name: ::std::string::String::from(name),
    description: ::std::option::Option::None,
    ty: <::core::option::Option<V> as async_graphql::InputType>::create_type_info(registry),
    deprecation: async_graphql::registry::Deprecation::NoDeprecated,
    default_value: ::std::option::Option::Some(::std::string::String::from(default)),
    visible: ::std::option::Option::None,
    inaccessible: false,
    tags: ::std::vec::Vec::new(),
    is_secret: false,
    directive_invocations: ::std::vec::Vec::new(),
  }
}

/// One slot of the incoming object, read through async-graphql's own nullable wrapper so an ABSENT
/// field and a `null` one are the same request.
#[cfg(feature = "async-graphql")]
fn route_slot<V, F>(
  object: &async_graphql::indexmap::IndexMap<async_graphql::Name, async_graphql::Value>,
  name: &str,
) -> ::std::result::Result<::std::option::Option<V>, async_graphql::InputValueError<F>>
where
  V: async_graphql::InputType,
  F: async_graphql::InputType,
{
  <::core::option::Option<V> as async_graphql::InputType>::parse(object.get(name).cloned())
    .map_err(async_graphql::InputValueError::propagate)
}

#[cfg(test)]
mod depth;
#[cfg(test)]
mod tests;