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
//! [`Detection`]: a label and a confidence, which is the whole of what a classification with no
//! geometry IS.

use core::fmt;

use crate::{
  ColumnKind, ColumnName, ColumnShape, CompositeFilterMarker, CompositeMarker, ConfidenceFilter,
  DefaultMarker, DefaultVecMarker, FieldName, QuantifiedMarker, Score, TextFilter,
  column::column_eq,
};

use super::{Label, LabelWire};

#[cfg(test)]
mod tests;

/// **A CLASSIFICATION** — what something was decided to be, and how sure the decider was.
///
/// The pair is deliberate, for the reason every DETECTION type's is. A classifier emits several
/// candidates per subject, each with its own confidence, so a row that recorded only the label would
/// lose the one number that says whether to believe it — and a query narrowing on label and on
/// confidence separately would let a frame where `cat` scored `0.2` answer a question about cats
/// above `0.8`, on the strength of some other label scoring `0.9`.
///
/// That is [`DetectedLanguage`](crate::primitives::lang::DetectedLanguage)'s own sentence one house
/// over, and it holds here for the same reason rather than because the two types are one: a language
/// is a STANDARD's identity and a label is a model's word, so the two carriers are different types
/// carrying the same shape.
///
/// # IT HAS NO GEOMETRY, and that is the type rather than a field left out
///
/// A whole-frame classification has no box. `avanalyze`'s contract states it plainly — *a labelled,
/// scored classification with no geometry of its own, used both for whole-frame image
/// classification and as the label half of a subject detection* — so this is the honest shape for
/// the first of those two, and [`LocatedDetection<T>`](super::LocatedDetection) is the honest shape
/// for the second.
///
/// **There is no `Option<BoundingBox<T>>` anywhere in this house**, and the absence is the ruling.
/// One type with an optional box would make *a classification that has a box* and *a located
/// detection whose box went missing* the same value, so every consumer reading a location would
/// carry a branch the type could have refused to represent. Two types make the branch unnecessary
/// and the invalid state unrepresentable.
///
/// # The confidence is a [`Score`] and the type is NOT carrier-generic
///
/// `Score` is [`Confidence<f32>`](crate::Confidence) — the width every classifier this framework has
/// met measures in — and this type names it rather than taking a width parameter of its own. The
/// precedent is exact and it is in this same house:
/// [`DetectedLanguage`](crate::primitives::lang::DetectedLanguage) holds a `Score`, not a
/// `Confidence<S>`, and it is the sibling shape.
///
/// It is worth saying what the alternative would have cost, because it is not obviously worse. A
/// `Detection<S>` would be open at the width the way [`BoundingBox<T>`](crate::BoundingBox) is open
/// at its component — but the two parameters are not the same question. A geometry component is a
/// UNIT the caller owns and the crate could not guess; a confidence width is a REPRESENTATION of one
/// invariant this crate already wrote four carriers for, and the bare name a caller wants is the one
/// the type is called. `Confidence<S>` could put that bare name into [`Score`]; `Detection<S>`
/// cannot, `Detection` being the name already. The door is open — a second parameter is an additive
/// change to an unpublished crate — and it opens when a caller measuring in something else arrives.
///
/// # Equality is the PAIR
///
/// The same label detected twice at different confidences is two detections, so the confidence is
/// part of the identity rather than a payload hanging off it. That is every detection type's rule.
///
/// # Examples
///
/// ```
/// use ingraph::{Detection, Label, Score};
///
/// let seen = Detection::new(
///   Label::new("golden retriever").unwrap(),
///   Score::new(0.87).unwrap(),
/// );
///
/// assert_eq!(seen.label().as_str(), "golden retriever");
/// assert_eq!(seen.confidence().get(), 0.87);
/// ```
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Detection {
  pub(super) label: Label,
  pub(super) confidence: Score,
}

impl Detection {
  /// A classification at a confidence.
  ///
  /// INFALLIBLE, because both halves have already been validated: a [`Label`] cannot be empty and a
  /// [`Score`] cannot exist outside `[0.0, 1.0]`. There is nothing left for this constructor to
  /// check, which is what building out of validated parts buys.
  #[inline]
  #[must_use]
  pub const fn new(label: Label, confidence: Score) -> Self {
    Self { label, confidence }
  }

  /// The word that was put on the subject.
  #[inline]
  #[must_use]
  pub const fn label(&self) -> &Label {
    &self.label
  }

  /// How confident the classifier was, in `[0.0, 1.0]`.
  #[inline]
  #[must_use]
  pub const fn confidence(&self) -> Score {
    self.confidence
  }
}

/// The label and the confidence, which is the whole of what a detection is.
impl fmt::Debug for Detection {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("Detection")
      .field("label", &self.label.as_str())
      .field("confidence", &self.confidence.get())
      .finish()
  }
}

/// The word, then the confidence in brackets — `golden retriever (0.87)`.
///
/// A rendering rather than a round trip, and it is worth saying which: nothing parses this back. A
/// label may hold a bracket, a digit or a space, so no grammar over this text could tell a label
/// ending in `(0.5)` from a detection.
impl fmt::Display for Detection {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(f, "{} ({})", self.label, self.confidence.get())
  }
}

/// The label column's segment.
pub(crate) const LABEL: &FieldName = FieldName::new("label");

/// The confidence column's segment.
///
/// `confidence` rather than `score`, and the choice is deliberate rather than inherited.
/// [`DetectedLanguage`](crate::primitives::lang::DetectedLanguage)'s own storage note records the
/// open question — *a classifier's is a SCORE, a detector's is a CONFIDENCE*, two words for one type
/// — and asks that it be settled deliberately rather than quietly. This house settles it the same
/// way that one did, on the type's own name: what this pair holds is a DETECTION, so its degree
/// column is a confidence, and a schema carrying both houses carries one word between them.
pub(crate) const CONFIDENCE: &FieldName = FieldName::new("confidence");

/// **The TWO columns a detection spans.**
///
/// Both are `Plain`: each half is a leaf, so the whole of a detection is two named columns and there
/// is nothing to nest. A detection at `top` reaches `top_label` and `top_confidence`.
pub(super) const SEGMENTS: &[ColumnShape] = &[
  ColumnShape::Plain(ColumnName::of(LABEL)),
  ColumnShape::Plain(ColumnName::of(CONFIDENCE)),
];

/// **The STORAGE half of the width** — two columns, each its own leaf's.
impl ColumnKind for Detection {
  const SEGMENTS: &'static [ColumnShape] = SEGMENTS;
}

/// **One leaf, and it is the value.** A detection means its two columns as declared, so no term over one expands.
impl crate::DeclaredLeaves for Detection {}

// A detection is one column value when the word and the confidence both are — the same pairing
// this type's own `PartialEq` already reads.
column_eq! { Detection }

/// **The DECLARED half — TWO words**, each read off the half that owns it.
///
/// The arity is FIXED because both halves are, which is what lets this row exist at all: a
/// `StoredAs` row is an array whose length is written into the impl, and the boundary
/// [`TimeRanged<T>`](crate::TimeRanged) records — a generic payload whose word count no length
/// position can name — is a boundary this type never approaches.
impl<Db> crate::StoredAs<Db> for Detection
where
  Label: crate::StoredAs<Db>,
  Score: crate::StoredAs<Db>,
{
  const WORDS: &'static [&'static str] = &[
    <Label as crate::StoredAs<Db>>::WORDS[0],
    <Score as crate::StoredAs<Db>>::WORDS[0],
  ];
}

/// **THE ADMISSION** — a detection is one element of a collection, and this is the row a TOP-K field
/// needs.
///
/// A classifier emits *k* candidates per subject, so `Vec<Detection>` is what a row actually holds.
/// [`CollectionElement`](crate::CollectionElement) states the one fact a width cannot — whether this
/// type is itself MANY — and a detection is a word and a number, so it is not.
impl crate::CollectionElement for Detection {}

/// **TWO BINDS OUT**, in segment order, with the one comma between them.
#[cfg(feature = "sqlx")]
impl<Db> crate::Carrier<Db> for Detection
where
  Db: sqlx::Database,
  Label: crate::Carrier<Db>,
  Score: crate::Carrier<Db>,
{
  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    <Label as crate::Carrier<Db>>::push_bind(&self.label, qb);
    qb.push(", ");
    <Score as crate::Carrier<Db>>::push_bind(&self.confidence, qb);
  }
}

/// **AND THE TWO BACK IN**, by name.
///
/// It states no invariant of its own, and that is the layering rather than an omission: whatever
/// each half refuses at its own column it refuses here — an empty stored label is
/// [`EmptyLabel`](super::EmptyLabel), named by the column that held it, and a stored `1.5` in the
/// confidence column is refused by [`Confidence`](crate::Confidence)'s row. A detection has no rule
/// ACROSS its two columns, so there is nothing left for this level to re-prove.
#[cfg(feature = "sqlx")]
impl<'a, R> crate::Assemble<'a, R> for Detection
where
  R: sqlx::Row,
  Label: crate::Assemble<'a, R>,
  Score: crate::Assemble<'a, R>,
{
  fn assemble(row: &'a R, under: Option<&crate::Path<'_>>) -> sqlx::Result<Self> {
    let label: Label = crate::assembled(row, LABEL, under)?;
    let confidence: Score = crate::assembled(row, CONFIDENCE, under)?;

    Ok(Self::new(label, confidence))
  }
}

/// **THE KEYSET POSITION** — the two halves in segment order, each behind its own four-byte length.
///
/// # The FRAMING is this holder's, and it is the framework's own spelling of it
///
/// [`write_member`](crate::cursor::write_member) and
/// [`read_member`](crate::cursor::read_member) are the crate's one authority for *several values in
/// one buffer* — the pair a generated composite frames its columns with and the varying list rows
/// frame their elements with — and this row reaches it rather than inventing a delimiter.
///
/// The alternative was to divide the payload by known widths, which is what
/// [`BoundingBox<T>`](crate::BoundingBox) and [`TimeRanged<T>`](crate::TimeRanged) do. **Neither
/// division is available here**: a label is VARIABLE-WIDTH and it is FIRST in segment order, so
/// there is no constant split point from either end — a fixed tail would work only while the
/// confidence's width could not change, and the label's own bytes could contain anything. Four bytes
/// a member is what buys a read that REFUSES instead of one that returns a plausible value for bytes
/// this type never wrote.
///
/// The ORDER the bytes encode is the COLUMNS' rather than a claim about detections: this type
/// publishes no [`Ord`], and a page's need for *an* order is not a claim about *the* order. That is
/// [`TimeRanged<T>`](crate::TimeRanged)'s own sentence at its own cursor.
impl crate::CursorValue for Detection {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    crate::cursor::write_member(&self.label, out);
    crate::cursor::write_member(&self.confidence, out);
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let mut rest = bytes;
    let label = crate::cursor::read_member::<Label>(&mut rest)?;
    let confidence = crate::cursor::read_member::<Score>(&mut rest)?;

    // Both members have been read, so anything left is bytes no member owns — a frame this type did
    // not write.
    rest.is_empty().then(|| Self::new(label, confidence))
  }
}

/// **THE DOCUMENT'S FORM: TWO KEYS AT ONE LEVEL** — the label, then the confidence.
///
/// ```text
///   { "label": "golden retriever", "confidence": 0.87 }
/// ```
///
/// The confidence is a `Double` through the width's own row: BSON's only binary float is 64 bits and
/// an `f32` widens into it exactly. The `[0.0, 1.0]` invariant is the DOMAIN's rather than the
/// column's, so nothing about it is encoded — which is the same sentence the SQL bind makes by
/// binding the wrapped float.
///
/// As with every other row of its kind here, this is the FILTER OPERAND's form and not a serde row.
#[cfg(feature = "mongo")]
impl crate::MongoCarrier for Detection {
  fn to_bson(&self) -> bson::Bson {
    let mut detection = bson::Document::new();

    detection.insert(LABEL.as_str(), crate::MongoCarrier::to_bson(&self.label));
    detection.insert(
      CONFIDENCE.as_str(),
      crate::MongoCarrier::to_bson(&self.confidence),
    );

    bson::Bson::Document(detection)
  }
}

/// **THE READ: the two keys back through their own doors** —
/// [`MongoCarrier`](crate::MongoCarrier)'s mirror, key for key.
#[cfg(feature = "mongo")]
impl crate::query::mongo::MongoExtract for Detection {
  const BSON: &'static str = "object";

  fn extract(value: Option<&bson::Bson>) -> Result<Self, crate::query::mongo::MongoTypeError> {
    let held = match value {
      Some(bson::Bson::Document(held)) => held,
      Some(other) => {
        return Err(crate::query::mongo::MongoTypeError::wrong_type(
          Self::BSON,
          crate::query::mongo::alias(other),
        ));
      }
      None => return Err(crate::query::mongo::MongoTypeError::Absent),
    };

    let label = <Label as crate::query::mongo::MongoExtract>::extract(held.get(LABEL.as_str()))?;
    let confidence =
      <Score as crate::query::mongo::MongoExtract>::extract(held.get(CONFIDENCE.as_str()))?;

    Ok(Self::new(label, confidence))
  }
}

/// What guards a [`Detection`] column — its own filter at both seats.
///
/// A detection stores every field it declares, so the two seats name one predicate.
impl CompositeFilterMarker for Detection {
  type Filter = DetectionFilter;
  type ColumnFilter = DetectionFilter;
}

/// The interpretation a [`Detection`] field is read under — the COMPOSITE reading, because the value
/// occupies columns of its own and both can be absent together.
impl DefaultMarker for Detection {
  type Marker = CompositeMarker<Detection>;
}

/// **A COLLECTION of detections is asked through the QUANTIFIERS alone.**
///
/// This is [`DetectedLanguage`](crate::primitives::lang::DetectedLanguage)'s ruling read over a
/// second detection type, and every clause of its argument transfers unchanged, because what makes
/// the argument is the FLOAT rather than the language. Each of the seven operators a
/// [`ListFilter`](crate::ListFilter) would publish takes a whole detection as its operand, and a
/// whole detection carries a confidence:
///
/// * `hasElement` is exact float equality against a number a client typed, so it answers *no rows*
///   to the question the caller believed they had asked — *was this label seen at about this
///   confidence*.
/// * `eq` and `ne` are that same falseness per element, multiplied by the collection's length.
/// * `gt`, `gte`, `lt` and `lte` compare two whole collections lexicographically, under an order
///   composed of a label's bytewise one and a float's.
///
/// What is left is `any` and `count`, and `any` loses nothing: it carries the whole
/// [`DetectionFilter`], so `any: { label: { eq: "cat" }, confidence: { gte: 0.8 } }` is *a cat was
/// seen, and confidently* — which is the question `hasElement` was pretending to be able to ask.
///
/// **This is where TOP-K lives.** A ranked list of candidates is a collection, `count` asks how many
/// there were, and `any` asks about each — so nothing about ranking belongs in the element type.
impl DefaultVecMarker for Detection {
  type Marker = QuantifiedMarker<Vec<Detection>>;
}

/// The filter that guards a [`Detection`] column: the WORD's own filter, and the CONFIDENCE beside
/// it.
///
/// ```text
/// input DetectionFilter {
///   label: LabelFilter
///   confidence: ConfidenceFilter
/// }
/// ```
///
/// # `label` takes the TEXT family's twenty words
///
/// [`TextFilter`] — `eq`, `ne`, the four orderings, `in`/`notIn`, and the three affix families with
/// a `nocase` and a negation apiece. Every one of them is a question somebody asks of a label:
/// `eq: "cat"` is the exact word, `contains: "retriever"` is the breed family, and
/// `startsWithNocase` is where the case this crate refuses to fold gets asked about instead. See
/// [`Label`], where the division with the engine is argued.
///
/// # `confidence` takes the framework's SIX confidence words
///
/// [`ConfidenceFilter`] — `eq`, `ne`, `gt`, `gte`, `lt`, `lte` — and every one is well-defined,
/// because [`Score`]'s constructor refuses `NaN` and the resulting order is total. `eq` and `ne`
/// earn their place: `eq: 1.0` is a saturated classifier and `ne: 0.0` is *was it a candidate at
/// all*, both exactly representable and both genuinely asked.
///
/// `in` and `notIn` are ABSENT FROM THE KIND rather than declined here — a membership list over a
/// continuous measurement resolves each member at a width the client cannot see. See
/// [`ConfidenceFilter`], where the framework argues it.
///
/// # NO WHOLE-DETECTION OPERATOR, and the leaf-tuple equality is still askable
///
/// There is no `eq` slot holding a whole detection, no `ne`, no `in`, and no ordering. The leaf
/// tuple IS the conjunction of the two facets — `{ label: { eq: "cat" }, confidence: { eq: 0.9 } }`
/// lowers to `label = ? AND confidence = ?`, which is what whole-value equality over a composite
/// means and the only operator that decomposes conjunctively — so a separate slot would be a second
/// spelling of one question and a conflict to adjudicate when a client wrote both.
///
/// A whole-value `ne` over a composite is a DISJUNCTION, which does not decompose into the
/// conjunction a filter's slots are joined by; a whole-value `in` spelled per-column is the CARTESIAN
/// PRODUCT. Ordering is refused for the reason the [`DefaultVecMarker`] row above gives: an order
/// composed of a word's and a float's is an order over the storage that would read like a ranking.
/// That is [`BoundingBoxFilter`](crate::BoundingBoxFilter)'s posture one house over, reached by the
/// same road.
#[derive(Default)]
pub struct DetectionFilter {
  pub(super) label: Option<TextFilter<Label, LabelWire>>,
  pub(super) confidence: Option<ConfidenceFilter>,
}

impl DetectionFilter {
  /// The empty filter — no facet set, so a column guarded by it is unconstrained.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self {
      label: None,
      confidence: None,
    }
  }

  /// True while NO operator slot is set on EITHER facet.
  pub fn is_empty(&self) -> bool {
    self
      .label
      .as_ref()
      .is_none_or(crate::GraphqlFilter::is_empty)
      && self
        .confidence
        .as_ref()
        .is_none_or(ConfidenceFilter::is_empty)
  }

  crate::graphql::filter::opt_accessor!(
    label: TextFilter<Label, LabelWire> => with_label, set_label, maybe_label, update_label
  );
  crate::graphql::filter::opt_accessor!(
    confidence: ConfidenceFilter => with_confidence, set_confidence, maybe_confidence, update_confidence
  );
}

impl crate::GraphqlFilter for DetectionFilter {
  #[inline]
  fn is_empty(&self) -> bool {
    Self::is_empty(self)
  }
}

impl fmt::Debug for DetectionFilter {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_struct("DetectionFilter")
      .field("label", &self.label)
      .field("confidence", &self.confidence)
      .finish()
  }
}

impl Clone for DetectionFilter {
  fn clone(&self) -> Self {
    Self {
      label: self.label.clone(),
      confidence: self.confidence.clone(),
    }
  }
}

impl PartialEq for DetectionFilter {
  fn eq(&self, other: &Self) -> bool {
    self.label == other.label && self.confidence == other.confidence
  }
}