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
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
//! THE GATE MATRIX — what the `graphql(…)` block changes about an emission, and what it must not.
//!
//! The ruling this file pins is one sentence: *the word gates the SKIN, never the BONES.* Two
//! emissions of the SAME model, differing only in whether a backend was named, are compared
//! item-for-item — so a package that went missing under the gate, or a wire impl that survived
//! without one, fails here rather than in somebody's schema.
//!
//! # Why the assertions are written as a DIFFERENCE
//!
//! A gate is a claim about two runs, and an inclusion-only suite proves half of it: *the face is
//! present when dressed* passes on an emission that always emits it. So every claim below is a
//! pair — present dressed, absent undressed — and the bone claims add the third leg, that the two
//! emissions declare the SAME types under the same names.
//!
//! Token-level, like its neighbours. That a dressed emission actually SERVES a schema is asserted
//! where the emission can be run, in `ingraph/tests/fusion_spine.rs`.

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

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

/// A VECTOR declaration electing TWO fields, one engine TYPED — the widest shape this crate mints,
/// so that every face the gate covers has an instance in one fixture.
///
/// The typed word buys the `@oneOf` selector and its per-engine input; the set label buys the fold
/// vocabulary; the two elections buy the multi-route packages. One model exercises all three faces,
/// which is what makes the absent half meaningful. The EVIDENCE needs two UNSET elections and is
/// reached by narrowing this fixture where it is asked about.
fn dressed(graphql: Option<IndexGraphql>) -> IndexModel {
  IndexModel {
    prefix: EmissionPrefix::default(),
    numbers: crate::index::Numbers::default(),
    field_numbers: Vec::new(),
    index: ident("Frames"),
    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: vec![
      Elected::new(
        ident("frames"),
        ElectionLabel::List,
        syn::parse_quote!(::std::vec::Vec<::ingraph::Embedding<f32, 4, Clip>>),
        None,
      ),
      Elected::new(
        ident("poster"),
        ElectionLabel::Embedding,
        syn::parse_quote!(::ingraph::Embedding<f32, 4, Clip>),
        None,
      ),
    ],
    labelled: Vec::new(),
    searchable: Vec::new(),
    engines: vec![
      FieldEngines {
        field: ident("frames"),
        engines: vec![Engine {
          resource: Some(syn::parse_quote!(crate::Lance)),
          ..Engine::bare(ident("lance"))
        }],
        fanout: false,
      },
      FieldEngines {
        field: ident("poster"),
        engines: vec![Engine::bare(ident("hnsw"))],
        fanout: false,
      },
    ],
    stores: Vec::new(),
    extension: None,
    data: false,
    keys: false,
    subscribe: false,
    graphql,
    rename: None,
    slot: None,
    fields: Vec::new(),
  }
}

/// The same declaration, dressed for `async_graphql`.
fn with_skin() -> IndexModel {
  dressed(Some(IndexGraphql::of(GraphqlKind::AsyncGraphql)))
}

/// The same declaration, dressed for nobody.
fn bare() -> IndexModel {
  dressed(None)
}

/// The same declaration, dressed and RENAMED — `skin` says how.
fn renamed(skin: impl FnOnce(&mut IndexBackend)) -> IndexModel {
  let mut backend = IndexBackend::of(GraphqlKind::AsyncGraphql);
  skin(&mut backend);
  dressed(Some(IndexGraphql {
    backends: vec![backend],
  }))
}

/// A word as a declaration writes one, at the call site's span.
fn word(spelled: &str) -> syn::LitStr {
  syn::LitStr::new(spelled, proc_macro2::Span::call_site())
}

/// EVERY SDL NAME one emission publishes, in the order the faces write them.
///
/// Read off the emitted TOKENS rather than off the model, because what a client sees is what the
/// registry entry says and nothing else: a rename that reached the model and missed a face would
/// pass a model-level assertion and ship a schema with two names for one type.
fn published(model: &IndexModel) -> Vec<String> {
  let said = model.tier().emit().to_string();
  let mut names = Vec::new();
  let mut rest = said.as_str();
  // `name : std :: string :: String :: from ( "…" )` is the registry's own spelling of a type name,
  // and `Cow :: Borrowed ( "…" )` is `type_name`'s. Both are read, so a face that published one and
  // not the other is visible here.
  while let Some(at) = rest.find("Borrowed (\"") {
    rest = &rest[at + "Borrowed (\"".len()..];
    if let Some(end) = rest.find('"') {
      names.push(rest[..end].to_owned());
      rest = &rest[end..];
    }
  }
  names
}

/// One emission, as one line of whitespace-free tokens — the form every claim below reads.
fn emitted(model: &IndexModel) -> String {
  model.tier().emit().to_string().split_whitespace().collect()
}

/// EVERY TYPE one emission declares, by name — the bone census.
fn declared(model: &IndexModel) -> Vec<String> {
  let file: syn::File = syn::parse2(model.tier().emit()).expect("the tier emission parses");
  file
    .items
    .into_iter()
    .filter_map(|item| match item {
      syn::Item::Struct(declared) => Some(declared.ident.to_string()),
      syn::Item::Enum(declared) => Some(declared.ident.to_string()),
      _ => None,
    })
    .collect()
}

/// The three hand-written faces, by the trait each one lands.
///
/// Written as trait PATHS rather than as type names because that is what the gate is about: the
/// types are there either way, and what a backend word buys is an `impl` of that backend's traits
/// over them.
const FACES: [&str; 4] = [
  "async_graphql::InputType",
  "async_graphql::InputObjectType",
  "async_graphql::OneofObjectType",
  "async_graphql::resolver_utils::EnumItem",
];

#[test]
fn a_declared_backend_lands_every_hand_written_face() {
  let said = emitted(&with_skin());
  for face in FACES {
    let spelled: String = face.split_whitespace().collect();
    assert!(
      said.contains(&spelled),
      "a dressed declaration should land `{face}`",
    );
  }
}

#[test]
fn a_declaration_that_named_no_backend_lands_none_of_them() {
  let said = emitted(&bare());
  for face in FACES {
    let spelled: String = face.split_whitespace().collect();
    assert!(
      !said.contains(&spelled),
      "an undressed declaration should land no `{face}`",
    );
  }
}

#[test]
fn the_binding_gate_itself_is_absent_without_a_backend_word() {
  // The FEATURE gate is one axis and the DECLARATION's word is the other. A model that named no
  // backend must not even reach for the macro that asks whether the feature is on: there is no
  // backend for the answer to be about.
  assert!(!emitted(&bare()).contains("if_async_graphql"));
  assert!(emitted(&with_skin()).contains("if_async_graphql"));
}

#[test]
fn the_two_emissions_declare_exactly_the_same_types() {
  // THE BONE CLAIM, and the one that makes the round's ruling more than a feature flag: the
  // packages, the fold vocabulary, the selector enum and the evidence are the SAME set under the
  // same names whether or not anything renders them.
  assert_eq!(declared(&with_skin()), declared(&bare()));
  assert!(
    !declared(&bare()).is_empty(),
    "the fixture should mint types for the claim to be about",
  );
}

#[test]
fn the_selector_enum_survives_the_gate_and_only_its_face_falls() {
  // The one emitter that mints a BONE and a SKIN in one function — so it is the one where a gate
  // written a token too wide would take the type with the face.
  let bones = declared(&bare());
  assert!(
    bones.iter().any(|name| name == "FramesFramesEngineInput"),
    "the `@oneOf` selector is a Rust enum a backend-only pipeline matches on: {bones:?}",
  );
  assert!(!emitted(&bare()).contains("OneofObjectType"));
  assert!(emitted(&with_skin()).contains("OneofObjectType"));
}

#[test]
fn the_roster_is_the_same_whether_or_not_a_backend_was_named() {
  // The roster is what the front end's collision refusals are measured against, and a gate that
  // moved it would make one declaration legal and its dressed twin refused.
  let dressed: Vec<String> = with_skin()
    .tier()
    .emitted_types()
    .iter()
    .map(ToString::to_string)
    .collect();
  let plain: Vec<String> = bare()
    .tier()
    .emitted_types()
    .iter()
    .map(ToString::to_string)
    .collect();
  assert_eq!(dressed, plain);
}

#[test]
fn a_backend_the_declaration_did_not_name_dresses_nothing() {
  // The multi-backend law read from the only side one variant can show it: the predicate asks about
  // ONE backend, so a block naming a different one would leave this backend's face off. With one
  // variant in the vocabulary the check is a tautology at runtime and a REGRESSION FENCE in the
  // source — the day a second word lands, a face emitted for whatever was declared first fails
  // here.
  let block = IndexGraphql {
    backends: vec![IndexBackend::of(GraphqlKind::AsyncGraphql)],
  };
  assert!(block.renders(GraphqlKind::AsyncGraphql));
  let empty = IndexGraphql {
    backends: Vec::new(),
  };
  assert!(
    !empty.renders(GraphqlKind::AsyncGraphql),
    "a block naming nobody dresses nobody",
  );
}

#[test]
fn every_minted_name_is_built_on_the_declarations_own() {
  // THE INVARIANT `Tier::sdl` RE-BASES BY, stated where it can fail. Every type this family mints
  // is the index's ident followed by at least one more camel-case segment — the fact
  // `IndexModel::emitted_types` already states out loud — so swapping that leading segment is
  // exactly what a base rename is. A name that stopped carrying it would silently keep its Rust
  // spelling on the wire, and this is where that shows.
  let model = bare();
  let index = model.index.to_string();
  for name in declared(&model) {
    assert!(
      name
        .strip_prefix(&index)
        .is_some_and(|rest| !rest.is_empty()),
      "`{name}` is not `{index}` plus a segment, so a base rename could not reach it",
    );
  }
}

#[test]
fn the_backend_prefix_reaches_every_sdl_name_and_no_rust_one() {
  let model = renamed(|skin| skin.prefix = Some(word("shotSearch")));
  let names = published(&model);
  assert!(!names.is_empty(), "the fixture publishes a schema");
  for name in &names {
    assert!(
      name.starts_with("ShotSearch"),
      "`{name}` kept its Rust base under a backend rename: {names:?}",
    );
  }
  // UPPER CAMEL at the type positions, which is GraphQL's own convention and what the word is a
  // BASE for — the declaration wrote `shotSearch` and the types read `ShotSearch…`.
  assert!(names.iter().any(|name| name == "ShotSearchFuseOptions"));
  // AND NO RUST NAME MOVED. The bones are the same set under the same spellings, which is the axis
  // law read from the emission: a skin's word renames a schema and nothing else.
  assert_eq!(declared(&model), declared(&bare()));
}

#[test]
fn a_per_face_override_names_that_face_verbatim_and_leaves_the_rest_on_the_base() {
  let model = renamed(|skin| {
    skin.prefix = Some(word("shotSearch"));
    skin.options = Some(word("ShotKnobs"));
    skin.question = Some(word("ShotAsk"));
  });
  let names = published(&model);
  for owed in ["ShotKnobs", "ShotAsk"] {
    assert!(
      names.iter().any(|name| name == owed),
      "the override should name its face outright: {names:?}",
    );
  }
  // VERBATIM: a per-face word names ONE type, so it is not composed with anything and not re-cased.
  assert!(
    !names.iter().any(|name| name == "ShotSearchFuseOptions"),
    "the base should not also publish the face its override named: {names:?}",
  );
  // And the interior packages still take the base — an override is one type, not a family.
  assert!(
    names.iter().any(|name| name.starts_with("ShotSearch")),
    "the base still reaches everything the overrides did not name: {names:?}",
  );
}

#[test]
fn an_override_with_no_base_moves_only_its_own_face() {
  let model = renamed(|skin| skin.options = Some(word("ShotKnobs")));
  let names = published(&model);
  assert!(names.iter().any(|name| name == "ShotKnobs"));
  assert!(
    names.iter().any(|name| name == "FramesFuseQuestion"),
    "every face the override did not name keeps the declaration's own: {names:?}",
  );
  assert!(
    !names.iter().any(|name| name == "FramesFuseOptions"),
    "and the renamed one is gone from the schema: {names:?}",
  );
}

/// THE MEASUREMENT BEHIND `fused(rename = …)`'s REFUSAL, pinned where it can change — and RE-TAKEN
/// after the first thing it was watching for arrived without it noticing.
///
/// # What the old reading missed, and why the shape of the claim had to change
///
/// It read one thing: the tier's evidence enum is a declared Rust type whose name no face
/// publishes. That is still true, and it was never going to fire. When the FANNED road grew its
/// answer face, the evidence enum did not gain a schema name — a NEW type did:
/// `<Index><Field>Sighting`, a minted wire union the evidence crosses into. A pin written on the
/// evidence's own name is blind to exactly the event it exists for.
///
/// So the claim below is about the TIER'S FUSED DOOR rather than about one type's name: it publishes
/// no query field, so nothing on its answer side is on a schema at all. The second half reads the
/// fanned road's face as the POSITIVE control — the thing that did arrive — so a suite that passed
/// by measuring nothing is not what this is.
#[test]
fn the_tier_fused_door_publishes_nothing_for_a_word_to_move() {
  // Both elections UNSET, so both are fused routes and the evidence enum is emitted — the base
  // fixture's set election keeps it out, which is the additive door law rather than the gate.
  let mut model = with_skin();
  model.embeddings[0] = Elected::new(
    ident("frames"),
    ElectionLabel::Embedding,
    syn::parse_quote!(::ingraph::Embedding<f32, 4, Clip>),
    None,
  );
  let evidence = model.tier().evidence_name().to_string();
  assert!(
    declared(&model).contains(&evidence),
    "the evidence is a declared Rust type",
  );
  assert!(
    !published(&model).contains(&evidence),
    "and it publishes no schema name: {:?}",
    published(&model),
  );

  // THE HALF THE OLD PIN COULD NOT SEE. The tier's fused pair is a Rust door and nothing else, so
  // no name minted FOR it — under any spelling — is on the schema. Read as the ABSENCE of the whole
  // family a wire answer would bring, which is what the slot grain shows one row down.
  let names = published(&model);
  for absent in ["FramesSighting", "FramesFusedKeyMatch"] {
    assert!(
      !names.iter().any(|name| name == absent),
      "the tier's fused door published `{absent}`, so its answer is on the wire and the word the \
       front end refuses now has something to move: {names:?}",
    );
  }
}

/// **THE POSITIVE CONTROL** — a fused answer that IS on a schema, so the pin above is measuring an
/// absence that could have been a presence.
///
/// A fanned election publishes `<Index><Field>Sighting` and `<Index><Field>FusedKeyMatch`, and the
/// slot's own evidence enum keeps its Rust-only name beside them: the union is a MINTED wire type
/// the evidence crosses into, not the evidence wearing an SDL name. That is the exact shape a tier
/// grain answer face would take, and it is why the pin above reads for the FAMILY rather than for
/// the evidence's own spelling.
///
/// Read off `IndexModel::emit` rather than off the tier's, because the answer family is the
/// declaration's emission and not the tier's package set. `index::answers` is where the whole field
/// list is proved; what is stated here is the one row that makes the neighbour above meaningful.
#[test]
fn a_fanned_road_does_publish_an_answer_and_the_evidence_is_still_not_it() {
  // The POSTER election, because it is the fixture's UNIT one: a `list(embedding)` election is not
  // a fused route at all — RRF joins ordinals and a set answer has none across its streams — so
  // fanning that one would prove the absence for the wrong reason.
  let mut model = with_skin();
  model.engines[1].fanout = true;
  model.engines[1].engines = vec![
    Engine {
      resource: Some(syn::parse_quote!(crate::Lance)),
      ..Engine::bare(ident("lance"))
    },
    Engine {
      resource: Some(syn::parse_quote!(crate::Hnsw)),
      ..Engine::bare(ident("hnsw"))
    },
  ];

  let said = model.emit().to_string();
  for owed in ["FramesPosterSighting", "FramesPosterFusedKeyMatch"] {
    assert!(
      said.contains(&format!("\"{owed}\"")),
      "the fanned road publishes `{owed}`",
    );
  }
  // AND THE EVIDENCE ENUM IS NOT AMONG THEM. It is declared, it is generic per route, and no face
  // renders it — the union beside it is what a client reads.
  let evidence = model.tier().slot_evidence_name(&model.embeddings[1]);
  assert!(
    said.contains(&format!("enum {evidence}")),
    "the slot evidence is a declared Rust type",
  );
  assert!(
    !said.contains(&format!("\"{evidence}\"")),
    "and it is not what the schema publishes",
  );
}

#[test]
fn the_engine_selector_is_named_only_where_the_declaration_mints_exactly_one() {
  // The fixture elects two fields and TYPES one of them, so there is one selector to name.
  let model = renamed(|skin| skin.engine = Some(word("WhichStore")));
  assert!(published(&model).iter().any(|name| name == "WhichStore"));

  // A declaration that types BOTH mints two, and a face word names a face rather than a set — so
  // `Tier` answers `None` and the front end is what refuses the word.
  let mut two = with_skin();
  two.engines[1].engines = vec![Engine {
    resource: Some(syn::parse_quote!(crate::Hnsw)),
    ..Engine::bare(ident("hnsw"))
  }];
  assert!(two.tier().engine_selector().is_none());
  assert!(with_skin().tier().engine_selector().is_some());
}