ingraph-derive 0.1.0

The attribute and derive macros for ingraph: the words a record, node, key, filter and vocabulary declaration is written in.
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
//! A derived index's acceptance: the upstream it names, the projections it declares, and every
//! family it may not claim.
//!
//! The kind is a parameter of the pass, so each test states the one it is about and the `for` loops
//! below are what prove the other two say the same thing in their own nouns.

use ingraph_codegen::{
  index::{Dedup, ElectionLabel, Fold, IndexModel},
  prelude::*,
};
use quote::ToTokens as _;

/// Every kind that reaches this pass, for the assertions about the pass rather than about a word.
const DERIVED: [NodeKind; 3] = [NodeKind::Fulltext, NodeKind::Vector, NodeKind::Blob];

/// The pass under test, over a declaration written the way the derive took one — see
/// [`host::split`](crate::host::split).
pub(super) fn parse(input: &syn::DeriveInput, kind: NodeKind) -> syn::Result<IndexModel> {
  let (host, arguments) = crate::host::split(input);
  super::parse(&host, &arguments, kind)
}

/// The full-text kind, which every test that is not about the word uses.
pub(super) fn fulltext(input: &syn::DeriveInput) -> syn::Result<IndexModel> {
  parse(input, NodeKind::Fulltext)
}

/// Every refusal the pass reported, JOINED — one compile reports every rule it can still see, and a
/// `syn::Error` renders only the first of a combined one.
fn refusals(input: syn::DeriveInput) -> String {
  refused(input, NodeKind::Fulltext)
}

/// The same, under a stated kind.
pub(super) fn refused(input: syn::DeriveInput, kind: NodeKind) -> String {
  parse(&input, kind)
    .expect_err("the declaration is refused")
    .into_iter()
    .map(|e| e.to_string())
    .collect::<Vec<_>>()
    .join("\n")
}

/// A minimal document over one upstream, as every test that needs an accepted one writes it.
///
/// Both fields wear `searchable`, which is what a full-text declaration now has to say: a
/// declaration marking none is refused by name, since an index that searches nothing indexes
/// nothing. The asymmetric shape — a searched field beside a payload one — is pinned in
/// `tests/elections.rs`, where the emission can be read.
fn document() -> syn::DeriveInput {
  syn::parse_quote! {
    #[ingraph(upstream(node = "asr::Segment", title = "speaker", body = "text"), dedup(hash))]
    pub struct SearchDocument {
      #[ingraph(searchable)]
      title: String,
      #[ingraph(searchable)]
      body: String,
    }
  }
}

/// The same, under the BLOB kind — the one derived index that elects nothing under any spelling.
///
/// It is a fixture of its own rather than [`document`] reused, and the reason is the flip: an
/// artifact family takes NEITHER marker, so a document carrying `searchable` is refused there by
/// name. One fixture per kind is what the three-kind walk needs now that each kind's answer differs.
fn blob_document() -> syn::DeriveInput {
  syn::parse_quote! {
    #[ingraph(upstream(node = "asr::Segment", title = "speaker", body = "text"))]
    pub struct Artifact { title: String, body: String }
  }
}

/// The same, under the VECTOR kind — which marks the one thing the other two refuse.
///
/// TWO embedding-typed fields, and the elected one is the SECOND. That ordering is deliberate
/// everywhere this shape appears: a reader taking *the first field of embedding type* would answer
/// `caption_embedding` here, so the order is what makes that reading fail rather than coincide.
fn vector_document() -> syn::DeriveInput {
  syn::parse_quote! {
    #[ingraph(
      upstream(
        node = "asr::Segment",
        caption_embedding = "caption_embedding",
        image_embedding = "image_embedding",
      ),
      dedup(hash),
    )]
    pub struct SegmentEmbedding {
      caption_embedding: Embedding<f32, 4>,
      #[ingraph(embedding, knn)]
      image_embedding: Embedding<f32, 4>,
    }
  }
}

#[test]
fn an_index_is_its_upstream_and_its_fields_in_order() {
  let m = fulltext(&document()).expect("a derived index");
  assert_eq!(m.index, "SearchDocument");
  assert_eq!(m.kind, NodeKind::Fulltext);
  assert_eq!(
    m.source.node.to_token_stream().to_string(),
    "asr :: Segment"
  );
  assert_eq!(
    m.fields
      .iter()
      .map(|column| column.name.to_string())
      .collect::<Vec<_>>(),
    ["title", "body"]
  );
}

/// The projections are ordered by the DECLARATION, not by the attribute — so the emitted audits read
/// down the struct and one declaration has one model however its entries were written.
#[test]
fn the_projections_are_ordered_by_the_declaration() {
  let m = fulltext(&syn::parse_quote! {
    #[ingraph(upstream(node = "asr::Segment", body = "text", title = "speaker"), dedup(hash))]
    struct SearchDocument {
      #[ingraph(searchable)] title: String,
      #[ingraph(searchable)] body: String,
    }
  })
  .expect("a derived index");
  assert_eq!(
    m.source
      .projections
      .iter()
      .map(|projected| (projected.field.to_string(), projected.from.to_string()))
      .collect::<Vec<_>>(),
    [
      ("title".to_owned(), "speaker".to_owned()),
      ("body".to_owned(), "text".to_owned()),
    ]
  );
}

/// The three projection words reach an index's fields exactly as they reach a value's, because it is
/// one rule read in one place — see [`column::projection_markers`](crate::column::projection_markers).
#[test]
fn the_three_projection_words_reach_the_model() {
  let m = fulltext(&syn::parse_quote! {
    #[ingraph(upstream(node = "a::A", w = "w", tags = "tags", note = "note", plain = "plain"), dedup(hash))]
    struct D {
      #[ingraph(copy)] w: u32,
      #[ingraph(repeated)] tags: Vec<String>,
      #[ingraph(optional)] note: Option<String>,
      #[ingraph(searchable)] plain: String,
    }
  })
  .expect("a derived index");
  let project = |name: &str| {
    m.fields
      .iter()
      .find(|column| column.name == name)
      .unwrap_or_else(|| panic!("`{name}` is a field"))
      .project
  };
  assert_eq!(project("w"), Projection::Copied);
  assert_eq!(project("tags"), Projection::Repeated);
  assert_eq!(project("note"), Projection::Optional);
  assert_eq!(project("plain"), Projection::Borrowed);
}

#[test]
fn the_crate_path_defaults_and_is_moveable() {
  let m = fulltext(&document()).expect("the default");
  assert_eq!(m.krate.to_token_stream().to_string(), ":: ingraph");
  let m = fulltext(&syn::parse_quote! {
    #[ingraph(crate = "shim::vendored", upstream(node = "a::A", w = "w"), dedup(hash))]
    struct D { #[ingraph(searchable)] w: String }
  })
  .expect("a re-export shim");
  assert_eq!(m.krate.to_token_stream().to_string(), "shim :: vendored");
}

/// THE PASS IS ONE PASS, and the macro word is what differs: one declaration is accepted under each
/// of the three, carrying the kind it was written under and nothing else about it.
///
/// Each kind writes its OWN election and refuses the other two's, so this walk takes three
/// declarations rather than one. What is asserted across all three is unchanged — one grammar, one
/// edge, one projection list per declaration — and the election is a fact of the KIND rather than of
/// the pass.
#[test]
fn the_three_storages_share_one_grammar() {
  for kind in DERIVED {
    let written = match kind {
      NodeKind::Vector => vector_document(),
      NodeKind::Fulltext => document(),
      _ => blob_document(),
    };
    let m = parse(&written, kind).expect("one grammar");
    assert_eq!(m.kind, kind);
    assert_eq!(m.source.projections.len(), 2);
    assert_eq!(!m.embeddings.is_empty(), kind == NodeKind::Vector);
    assert_eq!(!m.searchable.is_empty(), kind == NodeKind::Fulltext);
  }
}

/// EVERY identity spelling a node writes, refused by name — one rule seen from four sides, since the
/// key is the upstream's.
///
/// `subscribe = "…"` is still refused and its SENTENCE moved, which is the launch word landing: the
/// bare form is a real word here now, so the refusal is about the VALUE rather than about the word,
/// and it points at the edge `upstream(…)` already carries instead of turning the author away. See
/// `index/subscribe_word.rs`, where the whole of the new grammar is read.
#[test]
fn every_spelling_of_an_identity_is_refused_by_name() {
  let e = refusals(syn::parse_quote! {
    #[ingraph(
      subscribe = "a::A",
      key(rename = "DKey"),
      lineage(fields(a)),
      upstream(node = "a::A", a = "a"),
    )]
    struct D { #[ingraph(id)] a: u32 }
  });
  for rule in [
    "`subscribe` is a BARE word here",
    "does not name its key type, because it declares none",
    "does not declare a lineage",
    "because it mints none",
  ] {
    assert!(e.contains(rule), "missing `{rule}` in: {e}");
  }
}

/// Every STORAGE family, refused in one pass, each carrying the one-storage law it follows from —
/// the same law a record's refusals carry, since it is one law and one reader.
///
/// `graphql(…)` LEFT this list in the index-graphql round: on the two retrieving kinds it is a real
/// block now, and the blob's refusal of it has a sentence and a fixture of its own.
///
/// `persist(…)` STAYED, wrapper and all, and the record's unwrap is why: the store words came out of
/// the block at a RECORD's head, where storage is the essence. Nothing came out of anything here —
/// this grammar names no store at any level — so the word an author reaches for is still the
/// wrapper, and it is still what this table answers.
#[test]
fn every_family_a_derived_index_does_not_claim_is_refused_by_name() {
  let e = refusals(syn::parse_quote! {
    #[ingraph(
      persist(sqlite),
      derived(captions = "a::Caption"),
      implements(Searchable),
      vector(lance),
      blob(fs),
      upstream(node = "a::A", a = "a"))]
    struct D { a: u32 }
  });
  for rule in [
    "a derived index stores no rows",
    "a derived index declares no reverse positions",
    "an interface's members are NODES WITH ROWS",
    "a full-text index owns no embedding index",
    "a full-text index owns no artifact family",
  ] {
    assert!(e.contains(rule), "missing `{rule}` in: {e}");
  }
  assert!(
    e.contains("One node holds ONE storage"),
    "and every one of them carries the ruling it follows from: {e}"
  );
}

/// A node's OWN storage block is refused FOR GOOD, and what changed is the reason rather than the
/// verdict: it was a WAIT for a grammar that had not arrived, and the grammar arrived somewhere else.
///
/// The engines are per FIELD, because a slot is one field in one engine — so a block on the head
/// could only name them for the whole declaration, which is a grain coarser than the storage
/// actually is. The refusal says exactly that, on every kind.
#[test]
fn a_nodes_own_storage_block_is_the_wrong_grain_for_its_engines() {
  for kind in DERIVED {
    let block: proc_macro2::TokenStream = kind.as_str().parse().expect("a word");
    let e = refused(
      syn::parse_quote! {
        #[ingraph(#block(engine), upstream(node = "a::A", a = "a"))]
        struct D { a: u32 }
      },
      kind,
    );
    assert!(
      e.contains("is not where") && e.contains("a slot is one FIELD in one engine"),
      "{}: {e}",
      kind.as_str(),
    );
    assert!(
      !e.contains("has not arrived"),
      "{}: and it is no longer a wait: {e}",
      kind.as_str(),
    );
  }
}

/// The upstream is not optional, and its absence STOPS the pass: with no upstream there is no key to
/// be addressed by, so there is no model left to build.
#[test]
fn a_derived_index_names_one_upstream() {
  let e = refusals(syn::parse_quote! { struct D { a: u32 } });
  assert!(
    e.contains("draws its documents from an upstream")
      && e.contains("without an upstream it has no key to be addressed by either"),
    "{e}"
  );
  let e = refusals(syn::parse_quote! {
    #[ingraph(upstream(a = "a"), dedup(hash))]
    struct D { a: u32 }
  });
  assert!(
    e.contains("`upstream(…)` needs `node = \"path::To::Upstream\"`"),
    "{e}"
  );
}

/// The projections are still checked when the upstream is missing — one walk gets every answer it
/// could reach, rather than one refusal per compile.
#[test]
fn a_source_with_no_node_still_reports_its_projections() {
  let e = refusals(syn::parse_quote! {
    #[ingraph(upstream(missing = "a"), dedup(hash))]
    struct D { a: u32 }
  });
  assert!(
    e.contains("`missing` is not one of `D`'s") && e.contains("`a` is read out of nothing"),
    "{e}"
  );
}

/// A SECOND source is the multi-upstream shape rather than a repeat, and the refusal says what changes
/// — the carried key stops being one upstream's and becomes an enum over both.
#[test]
fn a_second_source_is_the_multi_source_shape() {
  let e = refusals(syn::parse_quote! {
    #[ingraph(upstream(node = "a::A", w = "w"), upstream(node = "b::B", w = "w"), dedup(hash))]
    struct D { w: u32 }
  });
  assert!(
    e.contains("a second `upstream(…)` is the MULTI-UPSTREAM shape")
      && e.contains("becomes an enum over both upstreams' keys"),
    "{e}"
  );
}

/// THE TWO LISTS MUST MATCH: an entry naming no field of this declaration, and a field named by no
/// entry, are the two halves of the rule that makes the emitted audit total.
#[test]
fn every_field_is_projected_and_every_projection_names_a_field() {
  let e = refusals(syn::parse_quote! {
    #[ingraph(upstream(node = "a::A", caption = "text"), dedup(hash))]
    struct D { body: String }
  });
  assert!(
    e.contains("`caption` is not one of `D`'s"),
    "the entry names no field: {e}"
  );
  assert!(
    e.contains("`body` is read out of nothing"),
    "and the field is named by no entry: {e}"
  );
}

/// One field, one entry — a second entry for one field is refused rather than silently taking the
/// first or the last.
#[test]
fn a_field_is_projected_once() {
  let e = refusals(syn::parse_quote! {
    #[ingraph(upstream(node = "a::A", w = "w", w = "v"), dedup(hash))]
    struct D { w: u32 }
  });
  assert!(e.contains("`w` is projected more than once"), "{e}");
}

/// The LIST form is in the ruled grammar and its MEANING is not: several upstream fields reaching one
/// index field need a combining rule, and an emission that picked one would be inventing the answer.
#[test]
fn several_upstream_fields_are_a_named_refuse_until() {
  let e = refusals(syn::parse_quote! {
    #[ingraph(upstream(node = "a::A", body = ["text", "notes"]), dedup(hash))]
    struct D { body: String }
  });
  assert!(
    e.contains("reads SEVERAL of the upstream's fields into one of this declaration's")
      && e.contains("one goes in as a list, another joined on a separator"),
    "{e}"
  );
}

/// `node` is `upstream(…)`'s own entry, so a field of that name can never be projected — refused where
/// the collision is rather than by the consequence it would otherwise produce.
#[test]
fn a_field_cannot_be_called_node() {
  let e = refusals(syn::parse_quote! {
    #[ingraph(upstream(node = "a::A", w = "w"), dedup(hash))]
    struct D { node: String, w: u32 }
  });
  assert!(
    e.contains("`node` cannot be a full-text index's field"),
    "{e}"
  );
  assert!(
    !e.contains("`node` is read out of nothing"),
    "and it is not ALSO reported as unprojected, which would send the author to write the one \
     entry that cannot exist: {e}"
  );
}

/// THE ONE-STORAGE LAW, caught by this pass rather than by the marker: the first index rewrote the
/// item, so the second is handed a declaration that already carries the injected key.
#[test]
fn a_declaration_that_already_carries_a_key_has_its_storage() {
  let e = refusals(syn::parse_quote! {
    #[ingraph(upstream(node = "a::A", w = "w"), dedup(hash))]
    struct D { w: u32, __ig_key__: SegmentKey }
  });
  assert!(
    e.contains("already carries a storage macro's injected key")
      && e.contains("One node holds ONE storage"),
    "{e}"
  );
}

/// The rest of the field grammar is the OPEN half: a word the framework does not own is an ENGINE,
/// and an engine is where an ELECTED field is written.
///
/// This used to be a WAIT naming the block that would read the word. The block never came — the
/// engines landed on the field instead — so the wait became a rule about the field's own election:
/// an unmarked field is payload, and payload has no index for an engine to hold.
#[test]
fn an_unelected_field_has_no_index_for_an_engine_to_hold() {
  let e = refusals(syn::parse_quote! {
    #[ingraph(upstream(node = "a::A", w = "w"), dedup(hash))]
    struct D { #[ingraph(lexical(each))] w: u32 }
  });
  assert!(
    e.contains("names `lexical` and is not elected")
      && e.contains("there is no index for that engine to hold"),
    "{e}"
  );
  assert!(
    e.contains("#[ingraph(searchable)]"),
    "and the refusal offers the marker, which is the repair usually meant: {e}"
  );
}

#[test]
fn the_shape_rules_are_the_tiers_own() {
  let e = refusals(syn::parse_quote! { enum D { A } });
  assert!(
    e.contains("`#[ingraph::fulltext]` supports structs only"),
    "{e}"
  );
  let e = refusals(syn::parse_quote! { struct D(u32); });
  assert!(e.contains("`upstream(…)` fills a field BY NAME"), "{e}");
  let e = refusals(syn::parse_quote! {
    #[ingraph(upstream(node = "a::A", w = "w"), dedup(hash))]
    struct D<T> { w: T }
  });
  assert!(
    e.contains("generic full-text indexes are not supported"),
    "{e}"
  );
  let e = refusals(syn::parse_quote! {
    #[ingraph(upstream(node = "a::A"), dedup(hash))]
    struct D {}
  });
  assert!(e.contains("with no fields indexes nothing"), "{e}");
}

/// The two EMISSION rules a declaration is held to, in this tier's terms: the framework's namespace
/// is fenced, and no two names may reach one method — the FIXED ones included.
#[test]
fn the_emission_rules_hold_over_an_index_too() {
  let e = refusals(syn::parse_quote! {
    #[ingraph(upstream(node = "a::A", __w__ = "w"), dedup(hash))]
    struct D { __w__: u32 }
  });
  assert!(
    e.contains("__w__"),
    "the framework namespace is fenced: {e}"
  );
  let e = refusals(syn::parse_quote! {
    #[ingraph(upstream(node = "a::A", key = "k", new = "n"), dedup(hash))]
    struct D { key: String, #[ingraph(copy)] new: u32 }
  });
  assert!(
    e.contains("would declare `key_ref` twice")
      && e.contains("the borrow of the upstream key it carries"),
    "the carried key's borrow is a name a field can collide with: {e}"
  );
  assert!(
    e.contains("would declare `new` twice") && e.contains("the type's own constructor"),
    "and so is the constructor, which this tier emits and a record does not: {e}"
  );
}

/// The `dedup(…)` word is accepted on the two kinds that RETRIEVE, and the model carries what was
/// written.
#[test]
fn the_dedup_word_reaches_the_model() {
  for kind in [NodeKind::Fulltext, NodeKind::Vector] {
    for (written, chosen) in [("hash", Dedup::Hash), ("eq", Dedup::Eq)] {
      let word = syn::Ident::new(written, proc_macro2::Span::call_site());
      // The declaration the mechanism rides on is the KIND's, since each kind marks its own
      // election and refuses the other's. What is under test is neither — it is that `dedup(…)`
      // reaches the model the same way from both.
      let input: syn::DeriveInput = if kind == NodeKind::Vector {
        syn::parse_quote! {
          #[ingraph(upstream(node = "a::A", body = "text", vec = "vec"), dedup(#word))]
          struct D { body: String, #[ingraph(embedding, knn)] vec: Embedding<f32, 4> }
        }
      } else {
        syn::parse_quote! {
          #[ingraph(upstream(node = "a::A", body = "text"), dedup(#word))]
          struct D { #[ingraph(searchable)] body: String }
        }
      };
      let m = parse(&input, kind).expect("a derived index");
      assert_eq!(m.dedup, chosen, "{kind:?} {written}");
    }
  }
}

/// The MARKER reaches the model, and what it carries is the field it was written on, its LABEL and
/// its type — carried whole and read nowhere.
///
/// The marked field is the declaration's SECOND embedding, so this also pins that the model holds
/// what was ELECTED rather than what was found first.
#[test]
fn the_knn_marker_elects_the_field_it_is_written_on() {
  let m = parse(&vector_document(), NodeKind::Vector).expect("an embedding index");
  let [elected] = &m.embeddings[..] else {
    panic!("one marker, one election: {}", m.embeddings.len());
  };
  assert_eq!(elected.field, "image_embedding");
  assert_eq!(elected.label, ElectionLabel::Embedding);
  assert_eq!(
    elected.ty.to_token_stream().to_string(),
    "Embedding < f32 , 4 >",
  );
}

/// SEVERAL fields may wear the marker, and each election reaches the model carrying its OWN field's
/// facts, in DECLARED order.
///
/// One spelling where there used to be two: `embedding(a, b)` and two head words were one law under
/// two forms, and a marker is under neither — it is written on the field, so the count of elections is
/// the count of marked fields and the order is the struct's. The widths differ so that a reader
/// taking the FIRST election's facts for every entry is visible here.
#[test]
fn several_fields_may_wear_the_marker() {
  let m = parse(
    &syn::parse_quote! {
      #[ingraph(
        upstream(
          node = "a::A",
          caption_embedding = "caption_embedding",
          image_embedding = "image_embedding",
        ),
        dedup(hash),
      )]
      struct D {
        #[ingraph(embedding, knn)]
        caption_embedding: Embedding<f32, 4>,
        #[ingraph(embedding, knn)]
        image_embedding: Embedding<f32, 8>,
      }
    },
    NodeKind::Vector,
  )
  .expect("two elections are one declaration");

  assert_eq!(
    m.embeddings
      .iter()
      .map(|elected| (
        elected.field.to_string(),
        elected.ty.to_token_stream().to_string()
      ))
      .collect::<Vec<_>>(),
    [
      (
        "caption_embedding".to_owned(),
        "Embedding < f32 , 4 >".to_owned(),
      ),
      (
        "image_embedding".to_owned(),
        "Embedding < f32 , 8 >".to_owned(),
      ),
    ],
    "each election carries its own field's type, in declared order",
  );
}

/// **THE LABEL GRAMMAR**, and every shape it will not carry — the record label reader's own
/// container machinery, one vocabulary over.
#[test]
fn every_way_a_label_can_be_wrong_is_refused() {
  let labelled = |label: proc_macro2::TokenStream| {
    refused(
      syn::parse_quote! {
        #[ingraph(upstream(node = "a::A", vec = "vec"), dedup(hash))]
        struct D {
          #[ingraph(#label, knn)]
          vec: Vec<Embedding<f32, 4>>,
        }
      },
      NodeKind::Vector,
    )
  };

  let bare = labelled(quote::quote!(list));
  assert!(
    bare.contains("`list` names a COLLECTION and a collection has elements")
      && bare.contains("`list(embedding)`"),
    "a container word written bare is told what it holds: {bare}"
  );

  let nested = labelled(quote::quote!(list(list(embedding))));
  assert!(
    nested.contains("no backend carries a collection of collections")
      && nested.contains("`(owner, ordinal)`"),
    "the nested refusal is inherited, with this family's own reason: {nested}"
  );

  let valued = labelled(quote::quote!(embedding(list)));
  assert!(
    valued.contains("`embedding` names ONE embedding and one embedding has no elements"),
    "a value word carries no element: {valued}"
  );

  let reserved = labelled(quote::quote!(set(embedding)));
  assert!(
    reserved.contains("`set` is not the container word")
      && reserved.contains("ORDINALS")
      && reserved.contains("reserved for a true unordered container"),
    "the near miss is told apart from the word it nearly is: {reserved}"
  );

  let unknown = labelled(quote::quote!(list(scalar)));
  assert!(
    unknown.contains("the element of an election's container is `embedding`"),
    "and an unknown element names the vocabulary: {unknown}"
  );

  let twice = labelled(quote::quote!(embedding, list(embedding)));
  assert!(
    twice.contains("`vec` is labelled more than once"),
    "one label, one field: {twice}"
  );
}

/// The label is the VECTOR kind's own, refused BY NAME on the two that elect nothing — the same
/// asymmetry `embedding(…)` itself is under, read from the field's side.
#[test]
fn a_label_is_refused_on_the_kinds_that_elect_nothing() {
  for kind in [NodeKind::Fulltext, NodeKind::Blob] {
    let e = refused(
      syn::parse_quote! {
        #[ingraph(upstream(node = "a::A", body = "text"))]
        struct D {
          #[ingraph(embedding)]
          body: String,
        }
      },
      kind,
    );
    assert!(
      e.contains("is labelled as an embedding field") && e.contains("the `vector` kind's own"),
      "{kind:?}: {e}"
    );
  }
}

/// **`dedup(…)` IS MANDATORY on every retrieving declaration** — single elections and set ones
/// alike, because it is one word picking one bound on one key.
#[test]
fn a_retrieving_declaration_states_how_it_tells_two_keys_apart() {
  for (kind, written) in [
    (
      NodeKind::Fulltext,
      quote::quote! {
        #[ingraph(upstream(node = "a::A", body = "text"))]
        struct D { #[ingraph(searchable)] body: String }
      },
    ),
    (
      NodeKind::Vector,
      quote::quote! {
        #[ingraph(upstream(node = "a::A", vec = "vec"))]
        struct D {
          #[ingraph(embedding, knn)]
          vec: Embedding<f32, 4>,
        }
      },
    ),
  ] {
    let e = refused(syn::parse_quote!(#written), kind);
    assert!(
      e.contains("does not say HOW it tells two of its keys apart")
        && e.contains("`dedup(hash)`")
        && e.contains("`PartialEq` alone")
        && e.contains("There is no default"),
      "{kind:?}: {e}"
    );
  }
}

/// **THE SEMANTICS WORD** reaches the model as a PATH, keyed by the semantic KIND — and the whole
/// vocabulary of kinds is `fold`, because a query makes one kind of decision this framework has a
/// door for.
#[test]
fn the_semantics_word_carries_its_kinds_implementation() {
  let m = parse(
    &syn::parse_quote! {
      #[ingraph(upstream(node = "a::A", frames = "frames"), dedup(hash))]
      struct D {
        #[ingraph(list(embedding), knn(semantics(fold = "app::PositionWeighted")))]
        frames: Vec<Embedding<f32, 4>>,
      }
    },
    NodeKind::Vector,
  )
  .expect("a set election with a declared fold");

  assert!(
    matches!(
      m.embeddings[0].fold.as_ref(),
      Some(Fold::Custom(path)) if path.to_token_stream().to_string() == "app :: PositionWeighted"
    ),
    "the custom rides as a PATH, carried verbatim",
  );
}

/// An election that wrote no word carries none, and the emission is what falls back to the shipped
/// fold — so the model states what the DECLARATION said and nothing else.
#[test]
fn an_election_with_no_semantics_word_declares_no_fold() {
  let m = parse(
    &syn::parse_quote! {
      #[ingraph(upstream(node = "a::A", frames = "frames"), dedup(hash))]
      struct D {
        #[ingraph(list(embedding), knn)]
        frames: Vec<Embedding<f32, 4>>,
      }
    },
    NodeKind::Vector,
  )
  .expect("a set election");

  assert!(m.embeddings[0].fold.is_none());
}

/// **THE SHORTHAND**: a shipped citizen by its bare word, told from a custom by the SHAPE of the
/// value — mint bare, refer quoted, which is the split every word in this grammar is under.
#[test]
fn the_shorthand_names_a_shipped_citizen_by_its_word() {
  for (written, expected) in [
    (quote::quote!(semantics(fold(sum))), Fold::Sum),
    (quote::quote!(semantics(fold(max))), Fold::Max),
  ] {
    let m = parse(
      &syn::parse_quote! {
        #[ingraph(upstream(node = "a::A", frames = "frames"), dedup(hash))]
        struct D {
          #[ingraph(list(embedding), knn(#written))]
          frames: Vec<Embedding<f32, 4>>,
        }
      },
      NodeKind::Vector,
    )
    .expect("a set election with a shorthand fold");

    assert!(
      matches!(
        (m.embeddings[0].fold.as_ref(), &expected),
        (Some(Fold::Sum), Fold::Sum) | (Some(Fold::Max), Fold::Max)
      ),
      "{written} reaches the model as its citizen",
    );
  }
}

/// Every way the SHORTHAND can be wrong — and the two near misses are told what they ARE rather
/// than that they are unknown, because an author who wrote either had a coherent idea.
#[test]
fn every_way_the_shorthand_can_be_wrong_is_refused() {
  let written = |word: proc_macro2::TokenStream| {
    refused(
      syn::parse_quote! {
        #[ingraph(upstream(node = "a::A", frames = "frames"), dedup(hash))]
        struct D {
          #[ingraph(list(embedding), knn(semantics(#word)))]
          frames: Vec<Embedding<f32, 4>>,
        }
      },
      NodeKind::Vector,
    )
  };

  let mean = written(quote::quote!(fold(mean)));
  assert!(
    mean.contains("`mean` is WITHDRAWN")
      && mean.contains("INCLUDING the empty ones")
      && mean.contains("fold = \"app::MyMean\""),
    "the withdrawal note carries the road to a custom: {mean}"
  );

  let weighted = written(quote::quote!(fold(weighted)));
  assert!(
    weighted.contains("`weighted` ships and cannot be named here")
      && weighted.contains("AT CONSTRUCTION")
      && weighted.contains("pass a `Weighted` at the query"),
    "the constructor-checked citizen is sent to the query layer: {weighted}"
  );

  let unknown = written(quote::quote!(fold(rrf)));
  assert!(
    unknown.contains("unknown fold in `fold(…)`")
      && unknown.contains("`sum` or `max`")
      && unknown.contains("fold = \"app::MyFold\""),
    "an unknown word names the vocabulary and the escape: {unknown}"
  );

  let carried = written(quote::quote!(fold(sum(k = 60))));
  assert!(
    carried.contains("a shipped fold is named by a BARE WORD"),
    "a citizen takes no arguments: {carried}"
  );

  for both in [
    quote::quote!(fold(sum), fold = "app::MyFold"),
    quote::quote!(fold(sum), fold(max)),
    quote::quote!(fold = "app::One", fold = "app::Two"),
  ] {
    let twice = written(both);
    assert!(
      twice.contains("`fold` is declared more than once on one election"),
      "one election, one declaration-level fold: {twice}"
    );
  }
}

/// **A LABEL ON AN UNELECTED FIELD IS ACCEPTED** — the ruling that made it a forward declaration
/// rather than a spenderless word: the structural fact it states has a storage-side reader coming,
/// and a field nothing queries can still be laid out by what it holds.
///
/// What acceptance does NOT buy is a face. The field is not elected, so it grows no column and no
/// door, and the model carries it in its own list.
#[test]
fn a_label_on_a_field_no_marker_elects_is_carried_rather_than_refused() {
  let m = parse(
    &syn::parse_quote! {
      #[ingraph(upstream(node = "a::A", a = "a", b = "b"), dedup(hash))]
      struct D {
        #[ingraph(embedding, knn)]
        a: Embedding<f32, 4>,
        #[ingraph(list(embedding))]
        b: Vec<Embedding<f32, 4>>,
      }
    },
    NodeKind::Vector,
  )
  .expect("a labelled payload field is a forward declaration");

  assert_eq!(m.embeddings.len(), 1, "one marker, one election");
  assert_eq!(m.embeddings[0].field, "a");
  let [labelled] = &m.labelled[..] else {
    panic!("the payload label is carried: {}", m.labelled.len());
  };
  assert_eq!(labelled.field, "b");
  assert_eq!(labelled.label, ElectionLabel::List);
}

/// Every way the word can be wrong, refused by the rule it broke.
#[test]
fn every_way_the_semantics_word_can_be_wrong_is_refused() {
  let written = |word: proc_macro2::TokenStream, label: proc_macro2::TokenStream| {
    refused(
      syn::parse_quote! {
        #[ingraph(upstream(node = "a::A", frames = "frames"), dedup(hash))]
        struct D {
          #[ingraph(#label, knn(#word))]
          frames: Vec<Embedding<f32, 4>>,
        }
      },
      NodeKind::Vector,
    )
  };

  // **THE LABEL-CONDITIONED REFUSAL**: the word is the set election's, and the label is what says
  // whether this is one.
  let single = written(
    quote::quote!(semantics(fold = "app::MyFold")),
    quote::quote!(embedding),
  );
  assert!(
    single.contains("is labelled `embedding` and `semantics(fold = …)` is the SET election's word")
      && single.contains("nothing for a fold to fold"),
    "{single}"
  );

  let unkeyed = written(
    quote::quote!(semantics = "app::MyFold"),
    quote::quote!(list(embedding)),
  );
  assert!(
    unkeyed.contains("takes a semantic KIND and the type implementing it"),
    "the key is the kind: {unkeyed}"
  );

  let unknown = written(
    quote::quote!(semantics(rank = "app::MyRank")),
    quote::quote!(list(embedding)),
  );
  assert!(
    unknown.contains("the kinds are `fold`"),
    "an unknown kind names the vocabulary: {unknown}"
  );

  let bare = written(
    quote::quote!(semantics(fold = app::MyFold)),
    quote::quote!(list(embedding)),
  );
  assert!(
    bare.contains("QUOTED because it refers to a type this declaration did not mint"),
    "mint bare, refer quoted: {bare}"
  );

  let twice = written(
    quote::quote!(semantics(fold = "a::One", fold = "a::Two")),
    quote::quote!(list(embedding)),
  );
  assert!(
    twice.contains("`fold` is declared more than once on one election"),
    "{twice}"
  );
}

/// Every way an election can be wrong, refused by the rule it broke — on BOTH electing kinds, since
/// the law is one law under two markers.
///
/// The MISSING marker is the one worth stating twice: the vector declaration it is refused on has
/// exactly one embedding-typed field, so an unambiguous-single fallback would have accepted it.
/// There is none, and the refusal is what says so.
///
/// TWO refusals that used to be here are gone with the head word, and neither was replaced: *names
/// no field of this declaration* and *names a path rather than a name* were both about a referent
/// written OUTSIDE the field. A marker has no referent to get wrong — it is on the field it elects.
#[test]
fn every_way_an_election_can_be_wrong_is_refused() {
  for (kind, written) in [
    (
      NodeKind::Vector,
      syn::parse_quote! {
        #[ingraph(upstream(node = "a::A", vec = "vec"), dedup(hash))]
        struct D { vec: Embedding<f32, 4> }
      },
    ),
    (
      NodeKind::Fulltext,
      syn::parse_quote! {
        #[ingraph(upstream(node = "a::A", body = "text"), dedup(hash))]
        struct D { body: String }
      },
    ),
  ] {
    let missing: syn::DeriveInput = written;
    let missing = refused(missing, kind);
    assert!(
      missing.contains("does not say WHICH of its fields it indexes")
        && missing.contains("elects at least one")
        && missing.contains("Mandatory even where exactly one")
        && missing.contains("`D` declares"),
      "{kind:?}: one candidate is still not an election: {missing}"
    );
  }

  // A field of ANOTHER TYPE is no longer refused here, and the absence is this round's own: the
  // pass reads no types, so what it can say about `body` is that it carries no LABEL. Whether the
  // labelled type is an embedding at all is rustc's, through the marker the emission projects
  // through — pinned as a trybuild refusal, where the compiler's own sentence is under test.
  let unlabelled = refused(
    syn::parse_quote! {
      #[ingraph(upstream(node = "a::A", vec = "vec"), dedup(hash))]
      struct D { #[ingraph(knn)] vec: Embedding<f32, 4> }
    },
    NodeKind::Vector,
  );
  assert!(
    unlabelled.contains("`vec` is marked `knn` and carries no LABEL")
      && unlabelled.contains("`#[ingraph(list(embedding), knn)]`")
      && unlabelled.contains("there is no default"),
    "an elected field states its multiplicity: {unlabelled}"
  );

  // The SAME MARKER TWICE on one field, which is the ordinary declared-twice family every field
  // marker is held to — and the whole of what the head word's own repeat refusal retired into.
  for (kind, marker) in [
    (NodeKind::Vector, quote::quote!(knn, knn)),
    (NodeKind::Fulltext, quote::quote!(searchable, searchable)),
  ] {
    let e = refused(
      syn::parse_quote! {
        #[ingraph(upstream(node = "a::A", a = "a"), dedup(hash))]
        struct D { #[ingraph(#marker)] a: Embedding<f32, 4> }
      },
      kind,
    );
    assert!(
      e.contains("is declared more than once on `a` — one marker, one field"),
      "{kind:?}: {e}"
    );
  }
}

/// Each marker is ITS OWN kind's, refused by name on the kinds that do not take it.
///
/// It is the retired head word's wrong-kind refusal re-aimed, and it now runs in four directions
/// rather than two: `knn` on a full-text and on a blob, `searchable` on a vector and on a blob.
#[test]
fn each_marker_is_refused_on_the_kinds_that_do_not_take_it() {
  for (marker, owner, kind) in [
    (quote::quote!(knn), "vector", NodeKind::Fulltext),
    (quote::quote!(knn), "vector", NodeKind::Blob),
    (quote::quote!(searchable), "fulltext", NodeKind::Vector),
    (quote::quote!(searchable), "fulltext", NodeKind::Blob),
  ] {
    let e = refused(
      syn::parse_quote! {
        #[ingraph(upstream(node = "a::A", body = "text"), dedup(hash))]
        struct D { #[ingraph(#marker)] body: String }
      },
      kind,
    );
    assert!(
      e.contains(&format!("The marker is the `{owner}` kind's own")),
      "{kind:?} is told which kind carries it: {e}"
    );
    assert!(
      e.contains("elects `body` into"),
      "and the refusal names the field it was written on: {e}"
    );
  }
}

/// The RETIRED head word, refused by name on every kind, each told the marker its OWN declaration
/// takes.
///
/// It is a migration refusal rather than a wrong-kind one: the word elects nothing anywhere now, so
/// what an author who wrote it needs is the successor and not a lecture about which kind owned it.
#[test]
fn the_retired_head_word_teaches_the_marker_that_replaced_it() {
  for (kind, successor) in [
    (NodeKind::Vector, "`#[ingraph(knn)]` on the field itself"),
    (NodeKind::Fulltext, "`#[ingraph(searchable)]` on it"),
    (NodeKind::Blob, "elects nothing under any spelling"),
  ] {
    let e = refused(
      syn::parse_quote! {
        #[ingraph(upstream(node = "a::A", body = "text"), embedding(body), dedup(hash))]
        struct D { body: String }
      },
      kind,
    );
    assert!(
      e.contains("`embedding(<field>)` has retired"),
      "{kind:?}: {e}"
    );
    assert!(e.contains(successor), "{kind:?}: {e}");
    assert!(
      e.contains("reported at the TYPE its author wrote"),
      "and the sentence says what the move bought: {e}"
    );
  }
}

/// ABSENT is `hash`, and that is a default rather than a wait: every key a node macro emits is built
/// from the closed segment vocabulary and every member of it hashes, so the mechanism a declaration
/// does not name is the one that always compiles.
#[test]
fn a_declaration_that_names_no_mechanism_hashes() {
  assert_eq!(
    fulltext(&document()).expect("a derived index").dedup,
    Dedup::Hash
  );
  assert_eq!(Dedup::default(), Dedup::Hash);
}

/// A word the framework has no membership for is refused AT THE WORD, and the message states what
/// each real word costs the key — because the choice IS a bound rather than a preference.
#[test]
fn an_unknown_mechanism_is_refused_by_name() {
  let e = refusals(syn::parse_quote! {
    #[ingraph(upstream(node = "a::A", body = "text"), dedup(ord))]
    struct D { body: String }
  });
  assert!(e.contains("`ord` is not a dedup mechanism"), "{e}");
  assert!(e.contains("`hash` or `eq`"), "{e}");
  assert!(e.contains("Hash + Eq") && e.contains("PartialEq"), "{e}");
}

/// TWO mechanisms is refused rather than taken as an override, and the refusal says why: a
/// declaration asking for both is asking for neither bound.
#[test]
fn one_index_dedupes_one_way() {
  let e = refusals(syn::parse_quote! {
    #[ingraph(upstream(node = "a::A", body = "text"), dedup(hash, eq))]
    struct D { body: String }
  });
  assert!(
    e.contains("names ONE mechanism and `hash` was already named"),
    "{e}"
  );

  let e = refusals(syn::parse_quote! {
    #[ingraph(upstream(node = "a::A", body = "text"), dedup(hash), dedup(eq))]
    struct D { body: String }
  });
  assert!(e.contains("`dedup` is declared more than once"), "{e}");
}

/// An ARTIFACT FAMILY has no `dedup(…)`: it answers an address rather than a ranking, so there is no
/// hit stream for a mechanism to collapse.
#[test]
fn an_artifact_family_does_not_dedup() {
  let e = refused(
    syn::parse_quote! {
      #[ingraph(upstream(node = "a::A", payload = "bytes"), dedup(hash))]
      struct D { payload: String }
    },
    NodeKind::Blob,
  );
  assert!(
    e.contains("`dedup(…)` is a RETRIEVE's word and an artifact family does not retrieve"),
    "{e}"
  );
}

/// The unknown-entry message LISTS `dedup(…)` where the kind admits one and does not where it does
/// not — so an author writing a near miss is sent to the words their own declaration has.
#[test]
fn the_unknown_entry_message_lists_what_the_kind_takes() {
  for (kind, listed) in [
    (NodeKind::Fulltext, true),
    (NodeKind::Vector, true),
    (NodeKind::Blob, false),
  ] {
    let e = refused(
      syn::parse_quote! {
        #[ingraph(upstream(node = "a::A", body = "text"), rank = "score")]
        struct D { body: String }
      },
      kind,
    );
    assert_eq!(e.contains("`dedup(…)`"), listed, "{kind:?}: {e}");
  }
}