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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
//! THE TWO EMITTED-NAME AUDITS a derived index answers, and the pins that keep them honest.
//!
//! A front end refuses a declaration whose emitted names collide, and it asks THIS crate which those
//! names are — [`IndexModel::emitted_methods`] for the methods, [`IndexModel::emitted_types`] for the
//! markers. Both are SECOND READINGS of the emitter's walk: the shapes have one home each (see
//! [`crate::method`]), but which of them a given declaration writes follows the emission, so the
//! membership is asserted against the emission itself rather than maintained by hand.
//!
//! Both directions matter, and they fail differently. A name the emitter GROWS and an enumeration
//! does not know about is a collision that goes back to being reported inside the expansion, at a
//! span the author cannot edit; a name an enumeration INVENTS is a declaration refused for a clash
//! that could never have happened — over an ordinary field name its author chose.
//!
//! Beside [`super::engines`] and [`super::tests`] rather than inside either, on this directory's own
//! precedent: one file per thing being proved.

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

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

fn column(name: &str, ty: &str, project: Projection) -> Column {
  Column {
    name: ident(name),
    source: ident(name),
    ty: syn::parse_str(ty).expect("a type"),
    project,
  }
}

fn projected(field: &str, ty: &str) -> Projected {
  Projected {
    field: ident(field),
    from: ident(field),
    ty: syn::parse_str(ty).expect("a type"),
  }
}

/// One field's engine blocks, and whether all of them are live at once.
fn stored(field: &str, engines: &[&str], fanout: bool) -> FieldEngines {
  FieldEngines {
    field: ident(field),
    engines: engines
      .iter()
      .map(|word| Engine::bare(ident(word)))
      .collect(),
    fanout,
  }
}

/// One election, spelled by hand so that the label and the fold are each stated.
fn elects(field: &str, label: ElectionLabel) -> Elected {
  Elected::new(
    ident(field),
    label,
    syn::parse_str("Embedding<f32, 4>").expect("a type"),
    None,
  )
}

/// A FULL-TEXT declaration whose searched field is FANNED across two engines, beside a payload
/// column that is copied — so the fan door and the whole accessor family stand on one type.
fn document() -> IndexModel {
  IndexModel {
    prefix: EmissionPrefix::default(),
    numbers: crate::index::Numbers::default(),
    field_numbers: Vec::new(),
    index: ident("SearchDocument"),
    kind: NodeKind::Fulltext,
    vis: syn::Visibility::Public(syn::token::Pub::default()),
    krate: syn::parse_quote!(::ingraph),
    source: Upstream {
      node: syn::parse_quote!(asr::Segment),
      projections: vec![projected("title", "String"), projected("ordinal", "u32")],
    },
    dedup: Dedup::Hash,
    embeddings: Vec::new(),
    labelled: Vec::new(),
    searchable: vec![ident("title")],
    engines: vec![stored("title", &["tantivy", "hnsw"], true)],
    stores: Vec::new(),
    extension: None,
    data: false,
    keys: false,
    subscribe: false,
    graphql: Some(IndexGraphql::of(GraphqlKind::AsyncGraphql)),
    rename: None,
    slot: None,
    fields: vec![
      column("title", "String", Projection::Borrowed),
      column("ordinal", "u32", Projection::Copied),
    ],
  }
}

/// A VECTOR declaration carrying every door the read surface has: a SET election with a declared ask
/// road, a single election with none, and one fanned field.
///
/// One model rather than three, because what the pins below compare is a WALK — a roster of models
/// each exercising one condition would prove every row in isolation and nothing about the order the
/// emitter puts them in.
fn frames() -> IndexModel {
  IndexModel {
    prefix: EmissionPrefix::default(),
    numbers: crate::index::Numbers::default(),
    field_numbers: Vec::new(),
    index: ident("ClipVectors"),
    kind: NodeKind::Vector,
    vis: syn::Visibility::Public(syn::token::Pub::default()),
    krate: syn::parse_quote!(::ingraph),
    source: Upstream {
      node: syn::parse_quote!(media::Clip),
      projections: vec![
        projected("frames", "Vec<Embedding<f32, 4>>"),
        projected("poster", "Embedding<f32, 4>"),
      ],
    },
    dedup: Dedup::Hash,
    embeddings: vec![
      elects("frames", ElectionLabel::List),
      elects("poster", ElectionLabel::Embedding),
    ],
    labelled: Vec::new(),
    searchable: Vec::new(),
    engines: vec![
      stored("frames", &["lance", "hnsw"], true),
      stored("poster", &["lance"], false),
    ],
    stores: Vec::new(),
    extension: None,
    data: false,
    keys: false,
    subscribe: false,
    graphql: Some(IndexGraphql::of(GraphqlKind::AsyncGraphql)),
    rename: None,
    slot: None,
    fields: vec![
      column("frames", "Vec<Embedding<f32, 4>>", Projection::Borrowed),
      column("poster", "Embedding<f32, 4>", Projection::Borrowed),
    ],
  }
}

/// A `blob` — the kind that elects nothing, retrieves nothing and fans nothing.
fn artifacts() -> IndexModel {
  IndexModel {
    prefix: EmissionPrefix::default(),
    kind: NodeKind::Blob,
    searchable: Vec::new(),
    engines: Vec::new(),
    ..document()
  }
}

/// The emission, read back as a file with every conditional-expansion gate opened — [`super::tests`]'
/// own reader, reached rather than copied: the retrieve face rides the observation gate pair, and a
/// walk that stepped over a macro invocation would find no doors at all and pass vacuously.
fn emission(model: &IndexModel) -> syn::File {
  let file: syn::File = syn::parse2(model.emit()).expect("the emission is a parsable file");
  syn::File {
    items: crate::tests::ungate(file.items),
    ..file
  }
}

/// Every INHERENT method the emission declares, in emission order, descending into the anonymous
/// const the retrieve face lives in.
///
/// The descent is what makes the comparison mean anything: an inherent impl is GLOBAL whatever block
/// it was written in, so the doors inside that const share one namespace with the fan at module scope
/// and with the carrier's accessors.
fn declared_methods(file: &syn::File) -> Vec<String> {
  items(file)
    .into_iter()
    .filter_map(|item| match item {
      syn::Item::Impl(declared) if declared.trait_.is_none() => Some(declared),
      _ => None,
    })
    .flat_map(|declared| &declared.items)
    .filter_map(|item| match item {
      syn::ImplItem::Fn(method) => Some(method.sig.ident.to_string()),
      _ => None,
    })
    .collect()
}

/// The TYPES the emission lands in the DECLARING SCOPE, in order — top level only.
///
/// The collision rule's own scope: a type minted inside the anonymous const is in no scope an
/// author's own name could clash with.
fn scoped_types(file: &syn::File) -> Vec<String> {
  file
    .items
    .iter()
    .filter_map(|item| match item {
      syn::Item::Struct(item) => Some(item.ident.to_string()),
      syn::Item::Enum(item) => Some(item.ident.to_string()),
      _ => None,
    })
    .collect()
}

/// Every item the emission declares, descending into the const the impls live in.
fn items(file: &syn::File) -> Vec<&syn::Item> {
  let mut found = Vec::new();
  for item in &file.items {
    found.push(item);
    if let syn::Item::Const(anonymous) = item
      && let syn::Expr::Block(block) = &*anonymous.expr
    {
      found.extend(
        block
          .block
          .stmts
          .iter()
          .filter_map(|statement| match statement {
            syn::Stmt::Item(inner) => Some(inner),
            _ => None,
          }),
      );
    }
  }
  found
}

/// The anti-drift half of the METHOD rule, and the half worth more than the refusal.
///
/// In ORDER, because the order is what lets a refusal name the earlier method as the one already
/// there — and because the order IS the claim: the fan is written before the const the rest of the
/// expansion lives in, and the doors after the accessors.
#[test]
fn the_enumeration_names_exactly_the_methods_the_emission_declares() {
  for model in [document(), frames(), artifacts()] {
    let declared = declared_methods(&emission(&model));
    let named: Vec<String> = model
      .emitted_methods()
      .iter()
      .map(|emitted| emitted.name.to_string())
      .collect();
    assert_eq!(named, declared, "`{}`", model.index);
  }
}

/// The same anti-drift half one level UP: the TYPES a declaration mints into one scope.
#[test]
fn the_enumeration_names_exactly_the_types_the_emission_declares() {
  for model in [document(), frames(), artifacts()] {
    let declared = scoped_types(&emission(&model));
    let named: Vec<String> = model
      .emitted_types()
      .iter()
      .map(|declared| declared.name.to_string())
      .collect();
    assert_eq!(named, declared, "`{}`", model.index);
  }
}

/// THE FAN DOOR IS ON THE TABLE — the first of the two names R2 minted without telling the audits.
///
/// Named after the FANNED field, so the row a `copy` field called `fan_title` collides with is the
/// one belonging to `title`.
#[test]
fn the_fan_door_is_enumerated_under_the_field_it_fans() {
  let names: Vec<String> = document()
    .emitted_methods()
    .iter()
    .map(|emitted| emitted.name.to_string())
    .collect();
  assert!(names.contains(&"fan_title".to_owned()), "{names:?}");
  assert!(
    !names.contains(&"fan_ordinal".to_owned()),
    "and only for a field that declared a fan: {names:?}",
  );
}

/// A PORTABLE field gets no door, so the table names none — the exclusion, which is the half an
/// inclusion-only suite cannot see.
#[test]
fn a_portable_field_is_enumerated_with_no_fan_door() {
  let mut portable = document();
  portable.engines = vec![stored("title", &["tantivy", "hnsw"], false)];
  let names: Vec<String> = portable
    .emitted_methods()
    .iter()
    .map(|emitted| emitted.name.to_string())
    .collect();
  assert!(
    !names.iter().any(|name| name.starts_with("fan_")),
    "{names:?}",
  );
}

/// THE R3 / GET FAMILY IS ON THE TABLE — the by-key read, the by-example door and the set door, each
/// under the election that mints it.
///
/// The ASKED PAIR was on this list until 2026-08-19 and is now asserted ABSENT, one entry down: the
/// question road left the declaration for `#[ingraph::tower]`, so `ask_keys_by_<field>` is a name no
/// election mints at any label. That direction is the one worth pinning — a retirement half-done
/// leaves the door emitted and the word refused.
#[test]
fn the_read_surface_is_enumerated_election_by_election() {
  let names: Vec<String> = frames()
    .emitted_methods()
    .iter()
    .map(|emitted| emitted.name.to_string())
    .collect();
  for door in [
    "retrieve_keys_by_frames",
    "retrieve_by_frames",
    "get_frames",
    "retrieve_similar_by_frames",
    "retrieve_keys_by_frames_with",
    "retrieve_keys_by_poster",
    "retrieve_by_poster",
    "get_poster",
    "retrieve_similar_by_poster",
    "fold_by_frames",
  ] {
    assert!(names.contains(&door.to_owned()), "`{door}`: {names:?}");
  }
  for absent in [
    // The SET door rides a word `poster` did not write, and a table that named it would refuse a
    // declaration for a collision the expansion could not have.
    "retrieve_keys_by_poster_with",
    "fold_by_poster",
    // The RETIRED question road, at BOTH elections — the set-labelled one and the unit one — since
    // what retired is the road and not one label's version of it.
    "ask_keys_by_frames",
    "ask_by_frames",
    "ask_keys_by_poster",
    "ask_by_poster",
  ] {
    assert!(!names.contains(&absent.to_owned()), "`{absent}`: {names:?}");
  }
}

/// The UNSUFFIXED pair is the full-text subject's, and the suffixed one is never spelled beside it.
#[test]
fn the_full_text_subject_is_enumerated_unsuffixed() {
  let names: Vec<String> = document()
    .emitted_methods()
    .iter()
    .map(|emitted| emitted.name.to_string())
    .collect();
  assert!(
    names.contains(&"retrieve_keys".to_owned()) && names.contains(&"retrieve".to_owned()),
    "{names:?}",
  );
  assert!(
    !names.iter().any(|name| name.starts_with("get_")),
    "a full-text index elects no column, so there is nothing to read back by key: {names:?}",
  );
}

/// THE COLLISION THE METHOD TABLE NOW SEES: a `copy` field spelled like another field's fan door.
///
/// The pair is what a front end reports; this is the fact it reports FROM, and the mutation is the
/// field's name — `fan_title` collides and `banner` does not, over one otherwise identical model.
#[test]
fn a_copy_field_named_after_a_fan_door_is_two_of_one_name() {
  let mut declared = document();
  declared
    .fields
    .push(column("fan_title", "u32", Projection::Copied));
  declared
    .source
    .projections
    .push(projected("fan_title", "u32"));
  assert_eq!(taken(&declared, "fan_title"), 2, "the fan and the accessor");

  let mut apart = document();
  apart
    .fields
    .push(column("banner", "u32", Projection::Copied));
  apart.source.projections.push(projected("banner", "u32"));
  assert_eq!(taken(&apart, "fan_title"), 1, "the fan alone");
}

/// The same class over the READ surface — the family #258's L-6 asked for.
#[test]
fn a_copy_field_named_after_a_by_key_read_is_two_of_one_name() {
  let mut declared = frames();
  declared
    .fields
    .push(column("get_poster", "u32", Projection::Copied));
  declared
    .source
    .projections
    .push(projected("get_poster", "u32"));
  assert_eq!(taken(&declared, "get_poster"), 2);
  assert_eq!(taken(&frames(), "get_poster"), 1, "the door alone");
}

/// How many of this declaration's emitted methods are called `name`.
fn taken(model: &IndexModel, name: &str) -> usize {
  model
    .emitted_methods()
    .iter()
    .filter(|emitted| emitted.name == name)
    .count()
}

/// How many of this declaration's emitted types are called `name`.
fn minted(model: &IndexModel, name: &str) -> usize {
  model
    .emitted_types()
    .iter()
    .filter(|declared| declared.name == name)
    .count()
}

/// THE COLLISION THE TYPE TABLE EXISTS FOR: the camel-case join loses the boundary the durable name
/// keeps.
///
/// `a` × `b_c` and `a_b` × `c` are two slots, two durable names and ONE marker. The durable half is
/// asserted beside it, because that asymmetry is the whole argument for refusing rather than
/// respelling: the NAME already solves this, and a type cannot take its separator.
#[test]
fn two_slots_can_mint_one_marker_and_two_distinct_names() {
  let mut declared = document();
  declared.engines = vec![stored("a", &["b_c"], false), stored("a_b", &["c"], false)];
  assert_eq!(minted(&declared, "SearchDocumentABC"), 2);

  let names: Vec<String> = declared
    .slots()
    .iter()
    .map(|slot| slot.name(&declared.index))
    .collect();
  assert_eq!(
    names,
    ["search_document__a__b_c", "search_document__a_b__c"],
    "the `__` join keeps the boundary the camel-case one cannot",
  );
}

/// THE SECOND COLLISION: a slot marker landing on an ELECTION's, which is the two families sharing
/// one scope.
///
/// Field `by` × engine `image` is `<Index>ByImage`, and so is the marker of an election on `image`.
#[test]
fn a_slot_marker_can_land_on_an_election_marker() {
  let mut declared = frames();
  declared.embeddings = vec![elects("image", ElectionLabel::Embedding)];
  declared.engines = vec![stored("by", &["image"], false)];
  assert_eq!(minted(&declared, "ClipVectorsByImage"), 2);
}

/// The camel-case join loses a boundary WITHIN one family too: two elections whose fields differ
/// only in a separator mint one marker.
#[test]
fn two_elections_can_mint_one_marker() {
  let mut declared = frames();
  declared.embeddings = vec![
    elects("image_1", ElectionLabel::Embedding),
    elects("image1", ElectionLabel::Embedding),
  ];
  declared.engines = Vec::new();
  assert_eq!(minted(&declared, "ClipVectorsByImage1"), 2);
}

/// AND NOTHING ELSE COLLIDES. The exclusion is the assertion a false-positive rule would fail: an
/// ordinary declaration mints one name per marker, so no author is refused over a clash that is not
/// there.
#[test]
fn an_ordinary_declaration_mints_every_marker_once() {
  for model in [document(), frames(), artifacts()] {
    let mut names: Vec<String> = model
      .emitted_types()
      .iter()
      .map(|declared| declared.name.to_string())
      .collect();
    let minted = names.len();
    names.sort_unstable();
    names.dedup();
    assert_eq!(names.len(), minted, "`{}`: {names:?}", model.index);
  }
}

/// The ROLE names the PAIRING, which is what lets a refusal tell two identical names apart.
#[test]
fn a_marker_arrives_with_the_pairing_that_minted_it() {
  let mut declared = document();
  declared.engines = vec![stored("a", &["b_c"], false), stored("a_b", &["c"], false)];
  // The MARKER rows alone: the fuse family's types and the wire query unit ride the same roster and
  // neither role names a pairing, which is this test's subject and not its counterexample.
  let markers = |model: &IndexModel| -> Vec<String> {
    model
      .emitted_types()
      .iter()
      .filter(|declared| !matches!(declared.role, Role::Fuse | Role::Queries))
      .map(|declared| declared.role.to_string())
      .collect()
  };
  assert_eq!(
    markers(&declared),
    ["the `a` × `b_c` slot marker", "the `a_b` × `c` slot marker"],
  );

  assert_eq!(
    markers(&frames()),
    [
      "the `frames` election's marker",
      "the `poster` election's marker",
      "the `frames` × `lance` slot marker",
      "the `frames` × `hnsw` slot marker",
      "the `poster` × `lance` slot marker",
    ],
    "elections first, then slots — the emitter's own walk",
  );
}

/// The refusal points at a DECLARED token, and for a marker that is the FIELD: an engine word names
/// a real engine and is not the author's to rename.
#[test]
fn a_marker_names_the_field_a_refusal_points_at() {
  let at: Vec<String> = frames()
    .emitted_types()
    .iter()
    .filter_map(|declared| declared.role.at())
    .map(ToString::to_string)
    .collect();
  assert_eq!(
    at,
    ["frames", "poster", "frames", "frames", "poster"],
    "one per marker, and never the engine word",
  );
}