ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
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
//! **THE SET ELECTION'S BY-EXAMPLE WIRE ROAD** — which door the published field reaches, what it
//! answers with, and everything the label leaves exactly where it was.
//!
//! ```text
//!   #[ingraph(embedding,       knn, toy(type=…))]  →  shotsSimilarByClipKeys → retrieve_similar_by_clip
//!   #[ingraph(list(embedding), knn, toy(type=…))]  →  shotsSimilarByClipKeys → retrieve_similar_by_clip_with
//! ```
//!
//! Beside [`answers`](super::answers) and [`similar_set`](super::similar_set) on this directory's
//! one-file-per-thing precedent: `answers` proves what the unit carries, `similar_set` proves the
//! RUST door this road calls, and this file proves the ROUTING between them.
//!
//! # The claim is a PAIR, and half of it is about what did NOT move
//!
//! A road that quietly became a second one is how a routing change goes wrong, so every assertion
//! below has an exclusion beside it: the set arm must not reach the single-vector door, the unit arm
//! must not reach the `_with` one, and the field NAME must be the same string either way. A suite
//! that only read the set arm would pass for an emission that had rerouted every road it touched.
//!
//! # What is asserted HERE and nowhere else
//!
//! | the ruling | the assertion |
//! |---|---|
//! | the LABEL picks the by-example door | [`the_label_picks_the_by_example_door`] |
//! | one field NAME per (declaration × election) | [`the_label_moves_the_road_and_never_the_name`] |
//! | the answer is the SET hit at both tiers | [`the_set_road_answers_the_set_hit_family`] |
//! | the question road is routed by the label too | [`the_question_road_is_routed_by_the_label_too`] |
//! | the fold is the door's, else the election's | [`the_fold_is_the_installed_one_or_the_elections_own`] |
//! | the span names the fold | [`the_set_doors_span_carries_the_folds_name`] |
//! | the roster gains nothing | [`the_set_road_lands_no_type_of_its_own`] |
//!
//! The EXECUTING half — that the fold's order reaches a client, that the carried scores add up, that
//! an empty example set is refused by name — is `ingraph/tests/similar_set_wire.rs`, which is the
//! only place a schema can be built and asked.

use super::{Dedup, Elected, ElectionLabel, IndexGraphql, IndexModel, Numbers, Upstream};
use crate::{
  engine::{Engine, FieldEngines},
  model::{GraphqlKind, NodeKind},
  prefix::EmissionPrefix,
};

fn ident(name: &str) -> syn::Ident {
  syn::Ident::new(name, proc_macro2::Span::call_site())
}

/// A dressed vector declaration over ONE typed election, at whatever label a case hands it.
///
/// Its own fixture rather than [`super::answers`]'s, because the fork under test IS the label and a
/// fixture reached through another module's private constructor would put the thing being varied
/// out of this file's reach.
fn declared(label: ElectionLabel) -> IndexModel {
  elections(&[("clip", label)])
}

/// ONE ELECTED FIELD at one label, with the type the label implies.
fn elected(field: &str, label: ElectionLabel) -> Elected {
  let ty: syn::Type = match label {
    ElectionLabel::List => syn::parse_quote!(::std::vec::Vec<::ingraph::Embedding<f32, 4, Clip>>),
    ElectionLabel::Embedding => syn::parse_quote!(::ingraph::Embedding<f32, 4, Clip>),
  };
  Elected::new(ident(field), label, ty, None)
}

/// A dressed vector declaration over ANY NUMBER of typed elections, each at its own label.
fn elections(fields: &[(&str, ElectionLabel)]) -> IndexModel {
  IndexModel {
    prefix: EmissionPrefix::default(),
    numbers: Numbers::default(),
    field_numbers: Vec::new(),
    index: ident("Shots"),
    kind: NodeKind::Vector,
    vis: syn::parse_quote!(pub),
    krate: syn::parse_quote!(::ingraph),
    source: Upstream {
      node: syn::parse_quote!(Keyframe),
      projections: Vec::new(),
    },
    dedup: Dedup::Hash,
    embeddings: fields
      .iter()
      .map(|(field, label)| elected(field, *label))
      .collect(),
    labelled: Vec::new(),
    searchable: Vec::new(),
    engines: fields
      .iter()
      .map(|(field, _)| FieldEngines {
        field: ident(field),
        engines: vec![Engine {
          resource: Some(syn::parse_quote!(crate::Store)),
          ..Engine::bare(ident("toy"))
        }],
        fanout: false,
      })
      .collect(),
    stores: Vec::new(),
    data: false,
    keys: false,
    subscribe: false,
    extension: None,
    graphql: Some(IndexGraphql::of(GraphqlKind::AsyncGraphql)),
    rename: None,
    slot: None,
    fields: Vec::new(),
  }
}

/// The whole expansion with the spaces taken out — what a claim about a call or a row is read off.
fn tight(model: &IndexModel) -> String {
  model.emit().to_string().split_whitespace().collect()
}

/// The UNIT election's expansion, and the SET one's — every test below reads both.
fn both() -> (String, String) {
  (
    tight(&declared(ElectionLabel::Embedding)),
    tight(&declared(ElectionLabel::List)),
  )
}

/// ONE RESOLVER's tokens, cut at the next one — so a claim about a body is not answered by a
/// neighbour's.
fn resolver<'a>(emission: &'a str, method: &str) -> &'a str {
  let at = emission
    .split(&format!("asyncfn{method}("))
    .nth(1)
    .unwrap_or_else(|| panic!("`{method}` is emitted: {emission}"));
  let end = [at.find("#[doc"), at.find("asyncfn")]
    .into_iter()
    .flatten()
    .min()
    .unwrap_or(at.len());
  &at[..end]
}

/// ONE EMITTED DOOR CALL, spelled the way the wire road now spells it.
///
/// The turbofish is the CORPUS the pointed resource mints — `<crate::Store as VectorMount>::Handle`
/// — rather than the resource itself: a resource is the MOUNT and the read faces belong to the
/// handle it mints, so a door bounded on a read face is spelled with the handle. `extra` is
/// whatever parameters ride beside it (`,_` for a fold).
fn door(method: &str, extra: &str) -> String {
  format!(
    "Shots::{method}::<<crate::Storeas::ingraph::__private::store::VectorMount>::Handle{extra}>"
  )
}

/// **THE LABEL PICKS THE BY-EXAMPLE DOOR**, and each arm reaches its own and only its own.
///
/// The exclusions carry the weight: routing that reached BOTH doors would answer twice, and routing
/// that reached the wrong one is precisely the runtime `Several { held }` this change ends.
#[test]
fn the_label_picks_the_by_example_door() {
  let (unit, set) = both();
  let unit_leg = resolver(&unit, "__async_graphql_shots_similar_by_clip_keys");
  let set_leg = resolver(&set, "__async_graphql_shots_similar_by_clip_keys");

  assert!(
    unit_leg.contains(&door("retrieve_similar_by_clip", "")),
    "the unit road left the single-vector door: {unit_leg}",
  );
  assert!(
    !unit_leg.contains("retrieve_similar_by_clip_with"),
    "the unit road reached the set door: {unit_leg}",
  );

  assert!(
    set_leg.contains(&door("retrieve_similar_by_clip_with", ",_")),
    "the set road did not reach the set door: {set_leg}",
  );
  assert!(
    !set_leg.contains("retrieve_similar_by_clip::<"),
    "the set road also reached the single-vector door: {set_leg}",
  );
}

/// **THE LABEL MOVES THE ROAD AND NEVER THE NAME** — one field name per (declaration × election), at
/// both tiers, whichever door answers.
///
/// The names cannot collide because the two arms are EXCLUSIVE: each is minted once, by whichever
/// road the label chose. The counts are TWO at the keys tier and ONE at the hydrated one, and that
/// asymmetry is the `if_sqlx` pair's rather than this road's — the unit's face is written twice and
/// only the SQL half carries the hydrated legs.
#[test]
fn the_label_moves_the_road_and_never_the_name() {
  let (unit, set) = both();
  for (label, emission) in [("unit", &unit), ("set", &set)] {
    for (name, minted) in [
      ("shotsSimilarByClipKeys", 2),
      ("shotsSimilarByClip", 1),
      ("shotsByClipKeys", 2),
      ("shotsByClip", 1),
    ] {
      assert_eq!(
        emission
          .matches(&format!("graphql(name=\"{name}\")"))
          .count(),
        minted,
        "the {label} road does not mint `{name}` exactly {minted} time(s): {emission}",
      );
    }
  }
}

/// **THE SET ROAD ANSWERS THE SET HIT FAMILY**, at both tiers, and crosses through the fold's own
/// answer rather than assembling one.
#[test]
fn the_set_road_answers_the_set_hit_family() {
  let (unit, set) = both();

  // ONE TYPE, TWO INSTANTIATIONS, and the assertion says which is which by the NODE it carries:
  // `FoldedMatch` collapsed to one Rust type on 2026-08-19, so a pin naming the type alone would
  // pass on either tier alone — the shape this file's own tier-B leg was once caught by.
  assert!(
    set.contains("graphql::FoldedMatch<__INGRAPH_ANSWER_KEY__,"),
    "the keys tier's set hit is missing: {set}",
  );
  assert!(
    set.contains("graphql::FoldedMatch<__INGRAPH_ANSWER_ENTITY__,"),
    "the hydrated tier's set hit is missing: {set}",
  );
  assert!(set.contains("graphql::folded_matches("), "{set}");
  assert!(
    set.contains("retrieve::Folded::map_node"),
    "the crossing did not carry the fold's own answer: {set}",
  );
  assert!(
    set.contains("retrieve::folded_filled("),
    "the hydrated set road did not use the fill loop at its own arity: {set}",
  );

  // AND THE UNIT ROAD IS UNTOUCHED: no set hit anywhere in it.
  assert!(!unit.contains("FoldedMatch"), "{unit}");
  assert!(!unit.contains("folded_filled"), "{unit}");
}

/// **THE QUESTION ROAD IS ROUTED BY THE LABEL TOO** — the pin this file carried in the NEGATIVE
/// while the `m`-vector question road's wire surface had not landed, flipped by the round that
/// minted it.
///
/// It used to assert that both labels' question road reached `retrieve_keys_by_clip` and answered
/// the single-vector hit, with its reason written into its own name. That is no longer so: a set
/// election's question is `m` POINTS, so its question road is the `_with` one and its answer is the
/// folded hit. What did NOT change is the name, which is this file's other half.
///
/// The whole of the new road — the deepened arm, the two refusals, the guard — is
/// [`set_question_wire`](super::set_question_wire). What is asserted HERE is the one thing this file
/// owns: that the LABEL is what picks the door, on this road exactly as on the by-example one.
#[test]
fn the_question_road_is_routed_by_the_label_too() {
  let (unit, set) = both();
  let unit_leg = resolver(&unit, "__async_graphql_shots_by_clip_keys");
  let set_leg = resolver(&set, "__async_graphql_shots_by_clip_keys");

  assert!(
    unit_leg.contains(&door("retrieve_keys_by_clip", "")),
    "the unit question road moved: {unit_leg}",
  );
  assert!(
    !unit_leg.contains("retrieve_keys_by_clip_with"),
    "the unit question road reached the `_with` door: {unit_leg}",
  );
  assert!(
    unit_leg.contains("graphql::Match<"),
    "the unit question road stopped answering the single-vector hit: {unit_leg}",
  );

  assert!(
    set_leg.contains(&door("retrieve_keys_by_clip_with", ",_")),
    "the set question road did not reach the `_with` door: {set_leg}",
  );
  assert!(
    !set_leg.contains("retrieve_keys_by_clip::<"),
    "the set question road also reached the single-vector door: {set_leg}",
  );
  assert!(
    set_leg.contains("graphql::FoldedMatch<"),
    "the set question road did not answer the folded hit: {set_leg}",
  );
}

/// **THE FOLD IS THE INSTALLED ONE, ELSE THE ELECTION'S OWN** — the chain written out, with no arm
/// for a request to have taken.
///
/// The last assertion is the ruling read as an absence: no argument is emitted for the fold, at
/// either tier, so the request side cannot choose one.
#[test]
fn the_fold_is_the_installed_one_or_the_elections_own() {
  let set = tight(&declared(ElectionLabel::List));

  assert!(
    set.contains("graphql::installed_fold::<crate::Store,ShotsByClip>"),
    "the deployment's seat is not keyed on (engine × election): {set}",
  );
  assert!(
    set.contains("graphql::FoldDoor::semantics("),
    "the installed fold is not read off the door: {set}",
  );
  assert!(
    set.contains("Shots::fold_by_clip()"),
    "the election's own fold is not the fallback: {set}",
  );
  assert!(
    !set.contains("graphql(name=\"fold\")"),
    "the request was given a fold to choose: {set}",
  );
}

/// **THE SET DOOR'S SPAN CARRIES THE FOLD'S NAME** — the TracingTap half of the `name` row, which is
/// the only place the arithmetic that authored an answer's order is observable from outside.
///
/// Read off the INSTRUMENTED half alone: the uninstrumented one opens no span, so a search of the
/// whole emission would pass for an emitter that wrote the field in neither.
#[test]
fn the_set_doors_span_carries_the_folds_name() {
  let set = tight(&declared(ElectionLabel::List));
  assert!(
    set.contains("fold=<__INGRAPH_FOLD__as::ingraph::__private::retrieve::FoldSemantics<"),
    "the span does not name the fold it ran: {set}",
  );
  assert!(
    set.contains("entry=\"retrieve_similar_by_clip_with\""),
    "the span field landed on some other door: {set}",
  );
  // FULLY QUALIFIED and not `fold.name()`, which is the measurement rather than a style: the fold
  // is a type parameter, so a method call would resolve against a bound and an `S` the body has no
  // other use for.
  assert!(
    !set.contains("fold.name()"),
    "the span reached the fold's name through inference: {set}",
  );
  // The UNIT road's span is unchanged — the field belongs to the door that has a fold.
  let unit = tight(&declared(ElectionLabel::Embedding));
  assert!(!unit.contains("fold=<"), "{unit}");
}

/// **THE SET ROAD LANDS NO TYPE OF ITS OWN** — the hit shapes are the framework's generics, named
/// through `TypeName` off the node exactly as `Match` already is, so nothing new joins the roster
/// the collision refusals are measured against.
///
/// The two rosters are NOT equal and were not expected to be: a set election already landed
/// `<Index><Field>Semantics`, the fold's own wire vocabulary, before this road existed. What the
/// assertion says is that the set roster CONTAINS the unit one and that the difference names
/// nothing from the answer family.
#[test]
fn the_set_road_lands_no_type_of_its_own() {
  let roster = |label| -> Vec<String> {
    declared(label)
      .emitted_types()
      .into_iter()
      .map(|declared| declared.name.to_string())
      .collect()
  };
  let unit = roster(ElectionLabel::Embedding);
  let set = roster(ElectionLabel::List);

  for name in &unit {
    assert!(
      set.contains(name),
      "the label dropped `{name}` from the roster: {set:?}",
    );
  }
  for name in &set {
    assert!(
      !["FoldedMatch", "StreamSighting", "Match"]
        .iter()
        .any(|hit| name.contains(hit)),
      "a hit shape was minted per declaration: {name}",
    );
  }
  // ONE answer-family type at each label, and it is the question input — which is the whole of what
  // a road publishes when its ANSWER is somebody else's generic. Spelled exactly, because the tier
  // package beside it (`ShotsClipVectorQuestion`) ends in the same noun and is a different thing.
  for roster in [&unit, &set] {
    assert_eq!(
      roster
        .iter()
        .filter(|name| *name == "ShotsClipQuestion")
        .count(),
      1,
      "{roster:?}",
    );
  }
}

/// **EVERY SET ELECTION IS ROUTED SEPARATELY** — two elections in one declaration, and the label is
/// read per election rather than per declaration.
#[test]
fn each_election_is_routed_by_its_own_label() {
  let emission = tight(&elections(&[
    ("clip", ElectionLabel::List),
    ("poster", ElectionLabel::Embedding),
  ]));

  let set = resolver(&emission, "__async_graphql_shots_similar_by_clip_keys");
  assert!(
    set.contains(&door("retrieve_similar_by_clip_with", ",_")),
    "the set election was not routed to the set door: {set}",
  );
  let unit = resolver(&emission, "__async_graphql_shots_similar_by_poster_keys");
  assert!(
    unit.contains(&door("retrieve_similar_by_poster", "")),
    "the unit election beside it was routed with its neighbour: {unit}",
  );
  assert!(!unit.contains("retrieve_similar_by_poster_with"), "{unit}",);
}