ingraph_codegen/index.rs
1//! A DERIVED INDEX's emission — the expansion that carries an identity it did not mint.
2//!
3//! A full-text index, an embedding index and a family of artifacts are one shape with three
4//! storages: each subscribes to exactly one upstream, holds one document per message it saw, and is
5//! addressed by THAT MESSAGE's key. *The key is not its to mint* — so there is no `id` field, no
6//! `*Key` struct and no `*Lineage` struct in this emission, and the two address types a record
7//! declares are here as PROJECTIONS of the upstream's instead.
8//!
9//! ```ignore
10//! #[ingraph::fulltext(upstream(node = "asr::Segment", title = "speaker", body = "text"))]
11//! pub struct SearchDocument {
12//! #[ingraph(searchable)] title: String,
13//! #[ingraph(searchable)] body: String,
14//! }
15//! ```
16//!
17//! # The two halves the compiler checks, and why neither could be checked here
18//!
19//! A macro holds tokens. The upstream is another declaration's, and two macro expansions cannot see
20//! each other — so nothing about `asr::Segment` is knowable at the moment this expansion is written.
21//! Both facts the declaration asserts are therefore EMITTED for rustc to resolve, each at the string
22//! the author wrote:
23//!
24//! | asserted | emitted | refused as |
25//! |---|---|---|
26//! | the upstream is a node | the entity binding's own bound | `E0412` unresolved · `E0277` not a node |
27//! | a projection names a field of it | [`IndexModel::projections`] | `E0609` no field · `E0616` private · `E0308` wrong type |
28//!
29//! A DIRECT FIELD READ rather than an accessor call, and that was the fork: a record's accessor is
30//! spelled four ways depending on the projection its own declaration asked for — `x`, `x_ref`,
31//! `x_slice` — and this expansion cannot see which. The field's name is the one spelling that does
32//! not vary, which is also why the pivot stamps `pub(crate)` on a declaration's fields: the read has
33//! to be legal from the module the index was declared in.
34//!
35//! # What it does NOT emit, and the absences are not eras
36//!
37//! No `*Key`, no `*Lineage`, no row, no wire face and no order — a derived index stores documents in
38//! an engine of its own rather than rows in a database, and every one of those is the row half of a
39//! record.
40//!
41//! WHICH engines hold the documents IS emitted, and it is per FIELD: each `(elected field × declared
42//! engine)` becomes a slot marker at module scope, and a `fanout` field gets the door that writes all
43//! of them at once. See [`crate::engine`] for the semantics — several engines are portability, the
44//! default is single-write, and the marker is the one departure. What is still nobody's here is the
45//! READ side's fan-and-fuse, which is the face round's.
46
47use quote::{format_ident, quote, quote_spanned};
48
49use syn::spanned::Spanned as _;
50
51use crate::{
52 emit::{framework, leading, wide_signature},
53 engine::{Engine, EngineKind, FieldEngines, Road, Slot},
54 extension::Extension,
55 method::{Door, DoorOrigin, Emitted, Origin, Owner, fan_door, fold_accessor},
56 model::{
57 Column, Conversion, Declared, GraphqlKind, NodeKind, Role, TracingLevel, borrowed_key,
58 elected_marker, one_storage_marker,
59 },
60 prefix::EmissionPrefix,
61};
62
63#[cfg(test)]
64mod answer_seats;
65#[cfg(test)]
66mod answers;
67#[cfg(test)]
68mod audits;
69#[cfg(test)]
70mod bones;
71#[cfg(test)]
72mod by_key;
73#[cfg(test)]
74mod citizen;
75#[cfg(test)]
76mod depth;
77#[cfg(test)]
78mod elections;
79#[cfg(test)]
80mod engines;
81#[cfg(test)]
82mod habitats;
83#[cfg(test)]
84mod hydrated;
85#[cfg(test)]
86mod k_seat;
87#[cfg(test)]
88mod kind_audits;
89#[cfg(test)]
90mod knobs;
91#[cfg(test)]
92mod rename_resolution;
93#[cfg(test)]
94mod roads;
95#[cfg(test)]
96mod set_question_wire;
97#[cfg(test)]
98mod similar;
99#[cfg(test)]
100mod similar_set;
101#[cfg(test)]
102mod similar_set_wire;
103#[cfg(test)]
104mod subscriber;
105#[cfg(test)]
106mod tests;
107#[cfg(test)]
108mod tiers;
109#[cfg(test)]
110mod tracing_tests;
111
112/// HOW a retrieve tells two of this index's keys apart — the `dedup(…)` word.
113///
114/// A retrieve dedupes the engine's hit stream BY KEY, first sighting winning, because the store
115/// faces are open traits and no backend owes uniqueness across the sources sharing a slot. What a
116/// declaration chooses here is not whether that happens; it is the MECHANISM, and the mechanism is a
117/// BOUNDS choice on the key type:
118///
119/// | word | the emitted method names | the key must satisfy |
120/// |---|---|---|
121/// | `dedup(hash)` | `HashSeen` | `Hash + Eq` |
122/// | `dedup(eq)` | `EqSeen` | `PartialEq` |
123///
124/// A CLOSED unit enum, because the vocabulary is the FRAMEWORK's: each word names one of the
125/// framework's own membership implementations, and a fourth mechanism is an arm here plus an
126/// implementor there rather than a redesign. That is the crate's rule for a framework-owned
127/// vocabulary, and the open surface is one level down — a third party's KEY joins by implementing
128/// `Hash` or `PartialEq`, which it already does.
129///
130/// [`Hash`](Self::Hash) is the default when the word is absent: every key a node macro emits today
131/// is built from the closed segment vocabulary and every member of it hashes, so the default always
132/// compiles. `eq` is the escape for a key that cannot — a float in an address, a foreign type with
133/// no `Hash` impl — and it asks less of the type, which is why the choice is declared rather than
134/// fixed.
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
136pub enum Dedup {
137 /// `dedup(hash)` — membership through a `HashSet`.
138 #[default]
139 Hash,
140 /// `dedup(eq)` — membership through a list walked by field-wise equality.
141 Eq,
142}
143
144impl Dedup {
145 /// The WORD, as a declaration writes it inside `dedup(…)`.
146 #[must_use]
147 pub const fn as_str(self) -> &'static str {
148 match self {
149 Self::Hash => "hash",
150 Self::Eq => "eq",
151 }
152 }
153
154 /// Every word this grammar admits, for the front end that lists them in a refusal.
155 ///
156 /// One list rather than a sentence per message, so a fourth mechanism reaches every refusal by
157 /// arriving here.
158 pub const WORDS: [&'static str; 2] = [Self::Hash.as_str(), Self::Eq.as_str()];
159
160 /// The framework membership the emitted methods name.
161 const fn membership(self) -> &'static str {
162 match self {
163 Self::Hash => "HashSeen",
164 Self::Eq => "EqSeen",
165 }
166 }
167
168 /// The framework JOIN the emitted fused doors name — the same word, one family over.
169 ///
170 /// A fold's join answers *have I already placed this root* and a dedup's membership answers *have
171 /// I already admitted this key*; both ask the KEY for the same thing, so a declaration reached for
172 /// `eq` because its key cannot hash must not be closed out of fusion for that reason. The rows
173 /// move together for [`accumulator`](Self::accumulator)'s stated reason.
174 ///
175 /// Read at TWO GRAINS: an index tier spends it on its own fused doors, and a graph root spends it
176 /// on its three ([`crate::graph`]). The root's key is a PREFIX of its members' keys and inherits
177 /// the property rather than escaping it, so the two grains name one row rather than each carrying
178 /// a copy of it.
179 pub(crate) const fn join(self) -> &'static str {
180 match self {
181 Self::Hash => "HashJoin",
182 Self::Eq => "EqJoin",
183 }
184 }
185
186 /// The framework ACCUMULATOR the emitted set door names — [`membership`](Self::membership)'s twin,
187 /// one grain over.
188 ///
189 /// The same word picks both, because both ask the KEY for the same thing. A declaration reached
190 /// for `eq` because its key cannot hash, and the set road must not be closed to it for that
191 /// reason; a declaration on `hash` must not silently pay a linear scan there either. So the two
192 /// rows move together, and a third mechanism arrives in both at once.
193 const fn accumulator(self) -> &'static str {
194 match self {
195 Self::Hash => "HashBests",
196 Self::Eq => "EqBests",
197 }
198 }
199
200 /// What the key must satisfy for this mechanism — the `where` clause the emitted methods carry.
201 ///
202 /// Written here rather than assembled at each emission site, so the choice and its cost are one
203 /// line and cannot drift apart. [`join`](Self::join)'s twin, and read at the same two grains: the
204 /// row a root's fused door states about its ROOT parameter is this one.
205 ///
206 /// `Clone` is on BOTH rows and is the mechanism's own price rather than either word's: a
207 /// membership owns the keys it has seen and the survivor list owns them too, so one of the two
208 /// holds a copy. What the DECLARATION is choosing is the other half — `Hash + Eq` against
209 /// `PartialEq`.
210 pub(crate) fn admits(self) -> proc_macro2::TokenStream {
211 match self {
212 Self::Hash => quote!(::core::hash::Hash + ::core::cmp::Eq + ::core::clone::Clone),
213 Self::Eq => quote!(::core::cmp::PartialEq + ::core::clone::Clone),
214 }
215 }
216}
217
218/// WHICH FOLD an election declared — a shipped CITIZEN by its word, or a type by its PATH.
219///
220/// # Two spellings, and the split is the crossing this whole family is built on
221///
222/// `semantics(fold(sum))` names one of the framework's own, BARE and in parentheses, which is the
223/// spelling every framework-owned mechanism word in this grammar takes — `dedup(hash)` is the same
224/// shape one family over. `semantics(fold = "app::MyFold")` names a type the DECLARING CRATE owns,
225/// QUOTED, which is the spelling every reference to somebody else's declaration takes. So the
226/// closed half and the open half are told apart by the shape of the value rather than by a rule a
227/// reader has to remember: mint bare, refer quoted.
228///
229/// # The shorthand's vocabulary is the DEFAULT-ABLE citizens, and that is not an arbitrary two
230///
231/// The emission builds a declared fold through [`Default`] — it holds a word or a path and no value
232/// — so a citizen reachable by word is one that can be built from nothing. `Sum` and `Max` are; a
233/// `Weighted` is not, its weights being checked against a query the declaration cannot see. `Mean`
234/// is not a citizen at all: the word is withdrawn, and a fold that divides is one somebody writes
235/// where they can see their own absences. Both are refused BY NAME rather than as unknown words,
236/// because an author who wrote either had a coherent idea.
237#[derive(Debug, Clone)]
238pub enum Fold {
239 /// `fold(sum)` — `Σⱼ bⱼ`, the shipped default, named explicitly.
240 Sum,
241 /// `fold(max)` — `maxⱼ bⱼ`.
242 Max,
243 /// `fold = "app::MyFold"` — a type the declaring crate owns, carried VERBATIM and resolved nowhere
244 /// in this crate: a path naming nothing is `E0412` at the string its author wrote, and a type
245 /// that does not fold this engine's currency is `E0277` where the fold is constructed.
246 Custom(syn::Path),
247}
248
249impl Fold {
250 /// The two shorthand WORDS, in the order a refusal lists them.
251 ///
252 /// One list rather than a sentence per message, so a third default-able citizen reaches every
253 /// refusal by arriving here.
254 pub const WORDS: [&'static str; 2] = ["sum", "max"];
255
256 /// The citizen a shorthand word names, or [`None`] where the word is not one of them.
257 #[must_use]
258 pub fn shipped(word: &str) -> Option<Self> {
259 match word {
260 "sum" => Some(Self::Sum),
261 "max" => Some(Self::Max),
262 _ => None,
263 }
264 }
265}
266
267/// WHAT AN ELECTED FIELD HOLDS, as its own LABEL states it — `embedding` or `list(embedding)`.
268///
269/// # The label is what the EXPANSION reads, and it is a WORD because a macro holds tokens
270///
271/// An earlier round read this off the field's TYPE: peel a `Vec<…>`, and what is left says one or
272/// many. That is a guess at a meaning only rustc has — wrong for `type ClipFrames = Vec<…>`, wrong
273/// for a re-export renamed on the way in, and wrong for every carrier not literally spelled `Vec`.
274/// So the declaration STATES it, exactly as a record's field states its kind, and the type-read is
275/// gone from this crate entirely.
276///
277/// # It restates NO fact, which is what dissolves the *disagreement refusal* worry
278///
279/// The label carries no width, no element and no space — those are the type's, projected through
280/// [`EmbeddingMarker`] at rustc time. What it carries is STRUCTURAL INTENT: which faces this
281/// declaration emits and which doors it grows. So the two readers cannot disagree about a fact,
282/// only about a shape, and that disagreement is settled by the compiler rather than by this crate:
283/// the emission states the label's claim as a bound, and a label that lied is `E0277` carrying a
284/// sentence that names both sides.
285///
286/// # `list(embedding)` and not `set(embedding)`
287///
288/// The container word is the ordered, duplicate-bearing one, because that is what a set election IS:
289/// its members are stored under ORDINALS, and `set` in this grammar's collection vocabulary promises
290/// unordered-and-deduplicated, which the structure does not have. The word `set` stays reserved for
291/// a true unordered container.
292#[derive(Debug, Clone, Copy, PartialEq, Eq)]
293pub enum ElectionLabel {
294 /// `embedding` — one embedding, the form every declaration written before the set arrived has.
295 Embedding,
296 /// `list(embedding)` — a per-entity SET, variable in length, EMPTY being legal.
297 ///
298 /// An empty set is a legal value and is never similarity-matched: a collection has no null state,
299 /// so *no members* is what a record with nothing to index says, and a knn over its column simply
300 /// does not reach it.
301 List,
302}
303
304impl ElectionLabel {
305 /// The label as a DECLARATION writes it, which is also how a refusal quotes it.
306 #[must_use]
307 pub const fn as_str(self) -> &'static str {
308 match self {
309 Self::Embedding => "embedding",
310 Self::List => "list(embedding)",
311 }
312 }
313
314 /// The framework MULTIPLICITY marker this label claims — the type an emitted audit holds the
315 /// field's own type to.
316 #[must_use]
317 pub const fn multiplicity(self) -> &'static str {
318 match self {
319 Self::Embedding => "One",
320 Self::List => "Set",
321 }
322 }
323
324 /// The framework AUDIT this label is stated as, spanned at the election word.
325 ///
326 /// A function rather than the projection bound itself, for the reason the audit's own doc gives:
327 /// `Multiplicity = One` reports `E0271`, a type mismatch, and the `on_unimplemented` attribute
328 /// rides unsatisfied TRAIT bounds only — so the claim is spelled as a trait that can carry the
329 /// sentence.
330 #[must_use]
331 pub const fn audit(self) -> &'static str {
332 match self {
333 Self::Embedding => "elects_one",
334 Self::List => "elects_a_set",
335 }
336 }
337
338 /// Whether this label states a SET — the one question the emission asks it twice, at the write
339 /// face and at the door.
340 #[must_use]
341 pub const fn is_set(self) -> bool {
342 matches!(self, Self::List)
343 }
344}
345
346/// WHICH field of a vector declaration a knn runs over — one `#[ingraph(knn)]` marker's answer.
347///
348/// # The type states the SHAPE; the ROLE is declared
349///
350/// `Embedding<E, N>` says a field holds `N` coordinates of `E`. It does not say *this is the field
351/// this index indexes*, and welding that onto the type would make **an embedding you store and do
352/// not index** undeclarable — a shape real nodes have, a caption vector kept for hydration beside
353/// the image vector the knn runs over. Role and shape are two facts, and the record for a role is a
354/// MARKER. It is the split the three-layer law draws between a field and its accessor, one family
355/// over: one fact, one record.
356///
357/// So a vector declaration may hold any number of embedding-typed fields; the ones wearing the
358/// marker are elected; the rest are ordinary payload — stored, hydrated, never reached by a knn.
359///
360/// # N ELECTIONS, and the slot is one PER (field × engine)
361///
362/// Any number of fields may wear it, and every election is queryable. That is the shape real nodes
363/// have — an upstream operator producing two vectors, or a storage node accumulating the embeddings
364/// of several compute nodes it subscribes.
365///
366/// The geometry that carries them USED to be one slot holding N vector columns, on the keystone
367/// *one declaration, one slot*. The engine grammar moved that keystone: a slot is `(field × engine)`
368/// now (see [`Slot`]), because the per-slot laws are per-corpus and two fields sharing one corpus
369/// move each other's scores. What did NOT move is the column axis one grain finer — a slot may still
370/// hold several columns of one field's own geometry, and `VectorRead::knn`'s selector still says
371/// which. Electing the same field twice is not a case either way: a marker is written on the field it
372/// elects, so a second one is the ordinary declared-twice refusal.
373///
374/// # MANDATORY, including where exactly one embedding field exists
375///
376/// At least one, and there is no unambiguous-single fallback; the absence is the design rather than
377/// an unbuilt convenience. A fallback would readmit type-inference as a silent mechanism, so a
378/// declaration's meaning would shift when a SECOND embedding field arrived elsewhere in the struct —
379/// the index silently indexing a field nobody elected. *必须指定* is a property of the signature or
380/// it is a property of the documentation, which is the argument that made a retrieve's floor a
381/// positional parameter rather than an option with a default.
382///
383/// # ON THE FIELD, and that is what buys the spans
384///
385/// The marker is a token of the field's own attribute, and the field's TYPE is the next token along.
386/// So *this is not an `Embedding<E, N>`* refuses AT THE TYPE — the half a reader has to go and edit
387/// — where the retired head word named the field from outside and could only land on its own ident.
388#[derive(Debug, Clone)]
389pub struct Elected {
390 /// The elected field, carrying the ident's own span — which is where both refusals about it land.
391 pub field: syn::Ident,
392 /// ONE embedding or a SET of them, as the FIELD's own label states it — see [`ElectionLabel`].
393 pub label: ElectionLabel,
394 /// The field's declared type, VERBATIM and unread.
395 ///
396 /// Every emitted projection goes through it — `<#ty as EmbeddingMarker>::…` — so the tokens are
397 /// the declaration's and a type with no impl is `E0277` at the author's own spelling, carrying the
398 /// trait's teaching sentence rather than one this crate guessed at.
399 pub ty: syn::Type,
400 /// `semantics(fold(sum))` / `semantics(fold = "app::MyFold")` — this election's DECLARATION-LEVEL
401 /// fold, and [`None`] where it wrote none and takes the shipped default.
402 ///
403 /// # The KEY is the semantic KIND, and the value is an implementation
404 ///
405 /// A *semantics* is a kind of decision a query makes, and the FOLD — how `m` per-query numbers
406 /// become one — is the first of them. So the word is keyed: the key names the kind, out of a
407 /// vocabulary this framework closes, and the value names an IMPLEMENTATION, out of a set nobody
408 /// closes. A second kind arrives as a second key and collides with nothing.
409 ///
410 /// # It is the ELECTION's, and only a SET election has one
411 ///
412 /// A single embedding has one best per query vector, so there is nothing to fold and the word is
413 /// refused on an `embedding`-labelled field by name. The chain it takes part in is
414 /// *query explicit > this > the shipped `Sum`*.
415 pub fold: Option<Fold>,
416 /// `knn(searchable(tower = "…"))` — the TOWER a question is walked through to reach this
417 /// column, and [`None`] where the election wrote none.
418 ///
419 /// # It is the SUGAR's word, and this emission spends none of it
420 ///
421 /// A road here does not change one token of what [`IndexModel::emit`] writes. What reads it is the
422 /// front end, which forges the `#[ingraph::search]` recipe the author would otherwise have
423 /// written by hand and puts it through the unchanged recipe pipeline — so the model carries the
424 /// word for the same reason it carries every other one: a second front end must be able to state
425 /// the same declaration.
426 ///
427 /// A TYPE and not a path, matching the arm word it becomes: the tower is a type this pass cannot
428 /// resolve, and every claim about it — that it IS a tower, what it is asked, what it answers, and
429 /// whether that answer meets these coordinates — is the compiler's at the binding.
430 pub tower_road: Option<syn::Type>,
431}
432
433impl Elected {
434 /// One election, as the front end read it: the field, its label, its type and its fold.
435 ///
436 /// PLAIN, for the model's own reason — nothing is parsed here and nothing is checked, so the
437 /// derive today and a manifest front end later build the same one.
438 ///
439 /// # NOTHING IS READ OFF THE TYPE
440 ///
441 /// An earlier round read `E`, `N` and `S` out of the field's spelling, after stripping a `Vec<…>`
442 /// to find out how many of them there were. That is a macro guessing at a meaning only rustc has:
443 /// `type ClipFrames = Vec<Embedding<f32, 768, Clip>>` read as *not an embedding*, and a downstream
444 /// carrier read as nothing at all. The reader is gone, the shape comes from the LABEL, and every
445 /// other fact is projected through `EmbeddingMarker` in the emission.
446 #[must_use]
447 pub const fn new(
448 field: syn::Ident,
449 label: ElectionLabel,
450 ty: syn::Type,
451 fold: Option<Fold>,
452 ) -> Self {
453 Self {
454 field,
455 label,
456 ty,
457 fold,
458 tower_road: None,
459 }
460 }
461
462 /// The TOWER ROAD this election named — [`Elected::tower_road`], set.
463 ///
464 /// Beside [`new`](Self::new) rather than inside it, because the road is the ONE word of an
465 /// election that most declarations do not write: a fifth parameter would put a `None` at every
466 /// call site that has nothing to say, which is a token a reader has to decode rather than one
467 /// that carries a fact.
468 #[must_use]
469 pub fn asked_through(mut self, tower: syn::Type) -> Self {
470 self.tower_road = Some(tower);
471 self
472 }
473}
474
475/// A LABELLED FIELD no election names — the field, its type and the label it wrote.
476///
477/// See [`IndexModel::labelled`] for why one is accepted at all. It carries no `fold`: that word
478/// qualifies an ELECTION, and this field is not one.
479#[derive(Debug, Clone)]
480pub struct Labelled {
481 /// The field, carrying the ident's own span.
482 pub field: syn::Ident,
483 /// ONE embedding or a SET of them, as the field's label states it.
484 pub label: ElectionLabel,
485 /// The field's declared type, VERBATIM and unread — what the audit is written against.
486 pub ty: syn::Type,
487}
488
489impl Labelled {
490 /// One labelled field, as the front end read it.
491 #[must_use]
492 pub const fn new(field: syn::Ident, label: ElectionLabel, ty: syn::Type) -> Self {
493 Self { field, label, ty }
494 }
495}
496
497/// ONE SUBJECT a retrieve answers about — the pair of method names it is spelled under, and the
498/// grain it queries at.
499///
500/// It exists because the two retrieving kinds differ in CARDINALITY and not only in flavour, and
501/// because ONE kind now differs from itself: a full-text declaration has a whole-subject subject and
502/// one per elected field, and an embedding declaration has one per elected column. Collapsing them
503/// here rather than at the emission is what keeps the pair of methods ONE `quote!` — so the shared
504/// half of the pipeline cannot drift between the kinds, which is the parity claim the flavour test
505/// pins.
506struct Subject<'a> {
507 /// Tier A's emitted name.
508 keys: syn::Ident,
509 /// Tier B's emitted name.
510 whole: syn::Ident,
511 /// What the doc line adds to name this subject — empty where there is nothing to distinguish.
512 about: String,
513 /// WHICH grain this subject asks at, and it is the one thing the two kinds' subjects disagree
514 /// about.
515 grain: Grain<'a>,
516}
517
518/// WHAT a subject narrows to — the third axis beside the pair's names and its doc line.
519///
520/// The two retrieving kinds narrow at different grains and by different mechanisms, and this is
521/// where that is stated once: a knn is told a [`VectorColumn`] and a search is handed a
522/// [`FulltextSubset`], so an emission reading this enum writes the right call for each without a
523/// second `match` on the node's kind.
524enum Grain<'a> {
525 /// The whole subject — every searchable column the slot holds. The full-text kind's unsuffixed
526 /// pair, and the `All` the seam takes.
527 Whole,
528 /// ONE searchable field, by name — the full-text kind's per-field pair, which mints a one-element
529 /// subset rather than taking one.
530 Column(&'a syn::Ident),
531 /// ONE ELECTION's coordinates — the vector kind's per-field pair, which mints its own
532 /// `VectorColumn`.
533 Election(&'a Elected),
534}
535
536/// WHICH QUERY FIELD one election mounts, and the engines the resolver behind it names.
537///
538/// Two arms because the two roads call two different doors with two different answer shapes — a
539/// ranked list of addresses against ONE store, and a fused one across every store a fanned field is
540/// written to. The engines are carried rather than re-derived, so the predicate that CHOSE the road
541/// and the emission that writes it cannot come to disagree about which legs are in it.
542///
543/// Named for the ROAD rather than for the door, because a road is the pair *(what a client sends,
544/// what it reads back)* and the door is one call inside it.
545enum AnswerRoad<'a> {
546 /// ONE TYPED ENGINE, unfanned, over a UNIT election — `retrieve_keys_by_<field>` and
547 /// `retrieve_similar_by_<field>`, answering `[<Key>Match!]!`.
548 Plain(&'a Engine),
549 /// The SAME ENGINE over a SET election — the question road unchanged, and the BY-EXAMPLE road
550 /// answering `[<Key>FoldedMatch!]!` out of `retrieve_similar_by_<field>_with`.
551 ///
552 /// A road of its own rather than a flag on [`Plain`](Self::Plain), because the two differ in what
553 /// their by-example half ANSWERS: one hit shape carries a rank and the other carries `m`
554 /// per-stream sightings, and a shape that hung off a boolean read at the leg would be the label
555 /// decided twice.
556 Set(&'a Engine),
557 /// EVERY LEG of a fanned slot, all typed — `vector_fuse_by_<field>`, answering the fused hit.
558 Fanned(Vec<&'a Engine>),
559}
560
561/// A validated derived index: which storage it is, what it draws from, and the fields it declares.
562///
563/// PLAIN, for [`RecordModel`](crate::model::RecordModel)'s reason — public fields, no constructor,
564/// nothing that parses — so the derive today and a manifest front end later build the same one.
565#[derive(Debug, Clone)]
566pub struct IndexModel {
567 /// The EMISSION NAMESPACE this declaration's minted names wear.
568 ///
569 /// [`EmissionPrefix::INGRAPH`] for everything `ingraph`'s own front ends build, and a domain
570 /// framework's own mark for a model `mediagraph-codegen` or its successors build — see
571 /// [`crate::prefix`] for what the seat covers and why it is a field rather than a constant.
572 pub prefix: EmissionPrefix,
573 /// The index's own name — the declaration this model came from.
574 pub index: syn::Ident,
575 /// WHICH of the three storages this is.
576 ///
577 /// Spent on the sentences a front end writes, on which SEAM the emitted doors name — a full-text
578 /// engine or a vector one — and on nothing else this emission does: all three mint the one-storage
579 /// marker and all three carry the upstream's key. WHICH engines hold the documents is no longer
580 /// read off the kind at all: it is [`engines`](Self::engines), declared per field.
581 pub kind: NodeKind,
582 /// How visible the index is, and therefore how visible each emitted method is.
583 ///
584 /// Mirrored rather than fixed at `pub`, exactly as a record's: no one can widen a type they did
585 /// not declare.
586 pub vis: syn::Visibility,
587 /// The path to the `ingraph` crate itself — `::ingraph` unless `crate = "…"` named another.
588 pub krate: syn::Path,
589 /// The ONE upstream this index draws from, and what it takes from it.
590 ///
591 /// One rather than a list: several upstreams key a derived index by an ENUM over their keys, and
592 /// the field that carries it is a different field of a different type. The model holds what this
593 /// emission spends.
594 pub source: Upstream,
595 /// The dedup MECHANISM a retrieve over this index runs — the `dedup(…)` word, or its default.
596 ///
597 /// Spent by the two emitted retrieve methods and by nothing else, which is also why it is on the
598 /// model rather than on [`Upstream`]: it is a property of how this node ANSWERS, not of where its
599 /// documents came from.
600 pub dedup: Dedup,
601 /// WHICH fields a knn over this index may run over — every `knn`-marked field, on the one kind
602 /// that has any.
603 ///
604 /// NON-EMPTY on every VECTOR declaration and EMPTY on the other two, and the asymmetry is the
605 /// marker's own: it is mandatory where it applies and refused by name where it does not, so a
606 /// front end that produced an empty list for a vector has already refused the declaration. In
607 /// DECLARED order, which is the order the emitted columns and the record face are written in.
608 ///
609 /// A LIST rather than one, because a declaration may elect several and each is queryable — see
610 /// [`Elected`] for the geometry that carries them and for why the role is declared rather than
611 /// read off the type.
612 pub embeddings: Vec<Elected>,
613 /// Every LABELLED field NO election names — the forward declarations, in declared order.
614 ///
615 /// # A label on payload is ACCEPTED, and that is a ruling rather than an oversight
616 ///
617 /// The label states a STRUCTURAL fact about a field — one embedding, or a set of them — and the
618 /// party that will spend it is not only the query side. A storage layer that lays a set out
619 /// differently from a single vector, or that carries a weight per member, reads the same fact
620 /// about a field nothing queries. So a labelled field with no election is a declaration made
621 /// EARLY rather than a word nobody reads, and this crate's usual refusal — *a word parsed into a
622 /// model nothing spends is a promise rather than a rule* — does not reach it.
623 ///
624 /// What the acceptance does NOT buy is a face: no column, no door, no projection. The election
625 /// marker is still what grows those, and a labelled payload field is hydrated by its own accessor
626 /// exactly as an unlabelled one is.
627 ///
628 /// ACCEPTED IS NOT UNEXAMINED. The label's claim is audited here as it is on an election, so a
629 /// payload field labelled `list(embedding)` over a single embedding is `E0277` at its own type.
630 pub labelled: Vec<Labelled>,
631 /// WHICH fields a search over this index runs over — every `searchable`-marked field, on the one
632 /// kind that has any.
633 ///
634 /// [`embeddings`](Self::embeddings)' mirror one kind over, and the same law: NON-EMPTY on every
635 /// FULL-TEXT declaration, EMPTY on the other two, in DECLARED order.
636 ///
637 /// # Idents rather than an [`Elected`], and the asymmetry is the ENGINE's rather than this model's
638 ///
639 /// An election carries what the EMISSION has to read off it, and the two kinds hand over different
640 /// amounts. A knn's column is opened at an element and a width, so `Elected` carries `E`, `N` and
641 /// the space it lives in — every one read off the field's own type, all three spent on the query
642 /// type the emitted pair takes. A search takes a STRING, and what a searched field must BE is not
643 /// this crate's to say: [`FulltextRecord::Document`](https://docs.rs/ingraph) is deliberately
644 /// bound by nothing, *what a document must be is the searching engine's question*. So the name is
645 /// the whole of what a full-text election has to carry, and inventing a shape for it here would
646 /// answer that question for engines that have not arrived.
647 ///
648 /// What it is SPENT on is BOTH halves of the read face. The whole-subject pair's doc line names
649 /// the fields it searches — the sentence that used to say *every projection* — and each name in
650 /// this list also mints its own `retrieve_keys_by_<field>` / `retrieve_by_<field>` pair, at vector
651 /// parity, narrowing to a one-column `FulltextSubset`. The selector the per-field doors waited on
652 /// is the seam's now: `FulltextRead::search` takes the subset beside the query.
653 pub searchable: Vec<syn::Ident>,
654 /// WHERE each elected field is written — one entry per election, in declared order, carrying the
655 /// engine blocks that field wore and whether all of them are live at once.
656 ///
657 /// ONE list over BOTH kinds, kept in step with the elections above by construction: the engine
658 /// grammar is one grammar, and a knn's field and a search's field name their engines alike. An
659 /// election that named NO engine has an entry with an empty list — declaring none is legal, and
660 /// means the deployment says instead, which is what a record with no `persist(…)` means one family
661 /// over.
662 ///
663 /// See [`engine`](crate::engine) for the semantics this carries: several blocks are declared
664 /// PORTABILITY, the default is SINGLE-WRITE, and [`fanout`](FieldEngines::fanout) is the one
665 /// departure.
666 pub engines: Vec<FieldEngines>,
667 /// WHERE an ARTIFACT FAMILY's objects are written — the engine blocks a `blob` declaration wrote
668 /// at its HEAD, beside `upstream(…)`.
669 ///
670 /// NON-EMPTY only on a blob, and the reason it is a second list rather than an entry in
671 /// [`engines`](Self::engines) is that the GRAIN differs. A slot on the other two kinds is
672 /// `(field × engine)`, because a declaration elects several fields and each is searched
673 /// independently; an artifact family elects nothing and holds ONE object per message, so its slot
674 /// is `(declaration × engine)` and the head is the only position coarse enough to name it. Writing
675 /// blob engines on a field would have asked which of a payload's fields the object is — a question
676 /// with no answer.
677 ///
678 /// The SEMANTICS are the field grammar's, unchanged: several blocks are declared PORTABILITY, the
679 /// deployment selects, and the default is SINGLE-WRITE. `fanout` is NOT among them — see the
680 /// `fanout` refusal on this kind, which names the deferral rather than pretending the word is
681 /// unknown.
682 ///
683 /// EMPTY is legal and means the deployment says instead, exactly as a record with no `persist(…)`
684 /// does one family over.
685 pub stores: Vec<Engine>,
686 /// HOW this family's addresses END — the `extension` word, in whichever of its forms was written.
687 ///
688 /// [`None`] is the OMITTED form and a real one: extensionless storage, which a heterogeneous
689 /// family takes at zero tax, its per-entry type travelling as metadata or as the host channel's
690 /// `Content-Type`. It is not *unset* — there is nothing to set it to.
691 ///
692 /// NON-`None` only on a blob; `extension` on the other two kinds is refused by name.
693 pub extension: Option<Extension>,
694 /// WHETHER this family's BYTES may travel beside its address — the bare `data` word at the head.
695 ///
696 /// An artifact family answers an ADDRESS, and the whole kind is built around that posture: what a
697 /// caller is handed is where the object lives, and going to get it is a second hop against the
698 /// store. On a family of large objects that is the only sane answer — nothing wants a video
699 /// inlined into a response. On a family of small ones the hop costs more than the bytes it fetches,
700 /// and a thumbnail served as an address alone is a round trip bought for nothing.
701 ///
702 /// `data` is where a declaration says which of the two it is. WRITTEN, this family's object may be
703 /// served inline — base64, BESIDE the address rather than instead of it, so nothing a caller could
704 /// already reach stops being reachable. OMITTED, the address is the whole of what is served, and
705 /// that is a real form rather than an unset field: it is the default because it is the one that
706 /// cannot hand anybody a payload they did not ask for.
707 ///
708 /// A BOOL because the word carries nothing — no value and no block, since *these bytes may be
709 /// served* has no knob inside it. MAY rather than WILL is the deliberate half: what a DECLARATION
710 /// can settle is whether inline bytes are on the table for this family at all.
711 ///
712 /// `false` on the other two kinds ALWAYS — `data` there is refused by name, for
713 /// [`data_wrong_kind`]'s reason.
714 pub data: bool,
715 /// Whether this declaration's upstream is an ENTITY, so its dressed answer family mounts the KEYS
716 /// TIER ALONE — the `keys` word.
717 ///
718 /// # The word declares a TIER FACT, and the two clocks are why one exists at all
719 ///
720 /// A dressed election answers each road twice: the KEYS tier hands back addresses and touches no
721 /// store, the HYDRATED tier hands back the upstream's whole entities and reads them out of one.
722 /// The hydrated pair projects `<Upstream as Hydrates>::Db`, whose impl only a record with a
723 /// queryable row emits — so which tiers this declaration can mount is decided by which RUNG of the
724 /// record ladder its upstream sits on, and the two derives cannot see each other.
725 ///
726 /// `false` — a RECORD upstream — mounts BOTH, unconditionally and with no word to write: rows are
727 /// a record's essence now, so storage is guaranteed and hydration can never miss. `true` — an
728 /// ENTITY upstream — mounts the keys tier, which is the pure-engine deployment's honest home: a
729 /// search surface over a node whose messages land in no database anywhere.
730 ///
731 /// A declaration that has an entity upstream and writes NO word is not silently narrowed. The
732 /// hydrated demand is emitted, the compiler cannot satisfy it, and the `E0277` lands at
733 /// `upstream(node = "…")` carrying `Hydrates`' own sentence — which names both exits, persist the
734 /// upstream or wear the word. Guessing here would be this crate deciding a deployment's storage
735 /// posture from what happens to compile.
736 ///
737 /// `false` on `blob` ALWAYS: an artifact family answers an address rather than a ranking, so it
738 /// mounts no tier pair for the word to narrow, and the word is refused there by name.
739 pub keys: bool,
740 /// **WHETHER THIS DECLARATION LAUNCHES** — the bare `subscribe` word at the head.
741 ///
742 /// `false` is the HAND ROAD and it is the shipped one: the declaration mints its corpora, its
743 /// slot markers and its search doors, and a deployment fills those corpora through the branded
744 /// handle itself. Every expansion this crate wrote before the word existed is that road, and none
745 /// of them moves — subscription is purely additive, so the emission below is the only thing the
746 /// word adds and nothing it touches is rewritten.
747 ///
748 /// `true` mints a NODE beside the declaration — see
749 /// [`subscriber`](IndexModel::subscriber) — which the deployment mounts like any other, and which
750 /// receives the upstream's messages, projects them per this declaration's own `upstream(…)`
751 /// entries, and lands them in the corpora this declaration already names.
752 ///
753 /// `false` on every kind but `fulltext`, where the word is refused by name: the write lane is a
754 /// per-family seam and the full-text one is the family with a live engine behind it.
755 pub subscribe: bool,
756 /// WHICH GRAPHQL BACKENDS this declaration is dressed for — see [`IndexGraphql`] for the law the
757 /// word states.
758 ///
759 /// [`None`] is *no wire face*, and it is a real form rather than an unset field: a declaration
760 /// with no block emits every Rust type and every door it would otherwise emit, and emits no wire
761 /// impl for any of them. Nothing is missing programmatically — what is missing is a schema, which
762 /// is what a backend-only search pipeline wants.
763 pub graphql: Option<IndexGraphql>,
764 /// THE CONTAINER TIER's numbers — `limit`, `depth` and `ceiling` written at the head.
765 ///
766 /// Empty is the ordinary state and means the framework's own answers stand; see [`Numbers`] for
767 /// the trichotomy the three words divide into, and [`wire_first`](Self::wire_first) /
768 /// [`pool_depth`](Self::pool_depth) / [`declared_ceiling`](Self::declared_ceiling) for the three
769 /// chains that read them.
770 pub numbers: Numbers,
771 /// THE ELECTION TIER's numbers, one entry per field that wrote one — in the order the declaration
772 /// wrote the fields.
773 ///
774 /// A field with nothing written on it has NO entry rather than an empty one, so the list is
775 /// exactly what a declaration said and a chain that finds nothing falls to the container.
776 pub field_numbers: Vec<FieldNumbers>,
777 /// WHAT THIS DECLARATION'S MINTED RUST TYPES ARE CALLED — see [`IndexRename`].
778 ///
779 /// [`None`] is *the declaration's own ident is the base*, which is where this family started and
780 /// is what every declaration written before the word arrived means.
781 pub rename: Option<IndexRename>,
782 /// WHAT THIS FAMILY'S CORPUS IS CALLED WHERE IT IS STORED — the `slot = "…"` word, blob only.
783 ///
784 /// # A DURABLE name, which is the whole reason it is not the Rust `rename`
785 ///
786 /// The slot is the directory an artifact family's objects live under, and it survives every
787 /// rebuild: two deployments of one declaration address the same objects because they agree on
788 /// this string. So it is deliberately NOT moved by [`rename`](Self::rename) — a Rust word
789 /// repointing a live store would be a rename that loses data — and it is deliberately additive:
790 /// the DEFAULT stays `snake_case(<declaration name>)`, which is what every family written before
791 /// the word arrived is stored under.
792 ///
793 /// [`None`] is that default rather than an unset field. Non-`None` only on a blob: the other two
794 /// kinds' slots are `(field × engine)` pairings and a declaration-level word is the wrong grain
795 /// for one, which the front end says by name.
796 pub slot: Option<syn::LitStr>,
797 /// EVERY field the index declares, in declared order — the injected key field is NOT among them,
798 /// being the emitter's rather than the declaration's.
799 ///
800 /// A [`Column`] rather than a [`Field`](crate::model::Field), for
801 /// [`FieldsModel`](crate::fields::FieldsModel)'s reason: a `Field` carries `identity` and a
802 /// `reference`, and every field here is on the same side of an identity it does not hold.
803 pub fields: Vec<Column>,
804}
805
806/// The upstream a derived index draws from, and which of its fields each of the index's own is read
807/// out of.
808#[derive(Debug, Clone)]
809pub struct Upstream {
810 /// The upstream node, as the declaration spelled it.
811 ///
812 /// Carried VERBATIM and resolved nowhere in this crate. It is emitted, and the spans it carries
813 /// are the authored string's — so every error about it lands where the author can edit it.
814 pub node: syn::Path,
815 /// One entry per field of the index, in declared order.
816 pub projections: Vec<Projected>,
817}
818
819/// One field of the index, and the upstream field it is read out of.
820#[derive(Debug, Clone)]
821pub struct Projected {
822 /// The INDEX's own field.
823 pub field: syn::Ident,
824 /// The UPSTREAM's field, carrying the span of the string that named it — which is the span every
825 /// refusal about this projection lands at.
826 pub from: syn::Ident,
827 /// The index field's declared type, which is the audit's RETURN type: a projection that reads the
828 /// wrong shape out of the upstream is `E0308` here rather than a mismatch inside a store.
829 pub ty: syn::Type,
830}
831
832/// WHICH GRAPHQL BACKENDS DRESS THIS DECLARATION — the `graphql(…)` block, or [`None`] where the
833/// declaration named none.
834///
835/// # The word gates the SKIN and never the BONES
836///
837/// Without a block the RUST surface emits WHOLE: the doors, the packages, the evidence, the
838/// selector and the [`Fusable`](https://docs.rs/ingraph) binding are all there, and a pipeline
839/// driven from Rust is missing nothing. What the word buys is one backend's WIRE IMPLS over those
840/// same types — the hand-written `InputType` / `@oneOf` / enum faces, and the registry entries the
841/// SDL is read out of.
842///
843/// That is why a backend WORD is what the block holds rather than a bare `graphql`: the framework
844/// renders through several, the types are backend-NEUTRAL, and each declared word adds one skin over
845/// the one set of bones. The `__<backend>_` ident prefix is what keeps two coexisting skins from
846/// colliding, and it is reserved per backend for exactly this.
847#[derive(Debug, Clone)]
848pub struct IndexGraphql {
849 /// The backends this declaration named, in the order it wrote them.
850 ///
851 /// A LIST rather than one, because the block is *which skins*, and a declaration that grows a
852 /// second word grows a second skin over the types it already had. EMPTY is the bare `graphql`
853 /// spelling, which names no backend and therefore dresses nothing — refused at the front end,
854 /// where the sentence can name the words on offer.
855 pub backends: Vec<IndexBackend>,
856}
857
858impl IndexGraphql {
859 /// A block naming ONE backend — the shape a declaration writing `graphql(async_graphql)` builds.
860 #[must_use]
861 pub fn of(kind: GraphqlKind) -> Self {
862 Self {
863 backends: vec![IndexBackend::of(kind)],
864 }
865 }
866
867 /// Whether this declaration named `kind`.
868 #[must_use]
869 pub fn renders(&self, kind: GraphqlKind) -> bool {
870 self.backends.iter().any(|backend| backend.kind == kind)
871 }
872
873 /// `kind`'s block, or [`None`] where this declaration named that backend nowhere.
874 #[must_use]
875 pub fn skin(&self, kind: GraphqlKind) -> Option<&IndexBackend> {
876 self.backends.iter().find(|backend| backend.kind == kind)
877 }
878}
879
880/// THE FOUR NUMBERS a declaration writes about its own doors — the BONES tier of the wire road's
881/// number design.
882///
883/// ```text
884/// #[ingraph::vector(upstream(…), limit = 50, depth = 200, ceiling = 1000)] the CONTAINER
885/// pub struct Shots {
886/// #[ingraph(list(embedding), knn, lance, limit = 10, streams = 16)] the ELECTION
887/// clips: Vec<Embedding<f32, 4, Clip>>,
888/// }
889/// ```
890///
891/// # The TRICHOTOMY, which is what makes several words rather than one
892///
893/// `limit` and `depth` are PREFERENCES — an author's semantic defaults for every door of the thing
894/// they are written on, and a request may write past either. `ceiling` and `streams` are PROTECTION
895/// — the #293-B ruling's WALL and the 2026-08-16 SET ruling's stream guard, upper bounds on what any
896/// one request may cost this deployment, which a request may never rewrite because a bound the
897/// requester can rewrite binds nothing.
898///
899/// The two families sit in one struct because they are written in one position and read by one
900/// chain; what keeps them apart is where each is SPENT — a preference lands as an SDL default a
901/// client overrides, and neither protective number reaches any wire row at all.
902///
903/// # The two protective words bound two INDEPENDENT axes, which is why there are two
904///
905/// `ceiling` caps HOW DEEP one stream is walked and `streams` caps HOW MANY streams there are. The
906/// ruling that minted the second said so in the user's own words — *一词多义* — and the measurement
907/// behind it is that one number cannot serve both: a per-stream depth of 500 under a stream cap of 16
908/// is unspellable as a single widened ceiling.
909///
910/// # `NonZeroU32` and not a plain integer, at both tiers
911///
912/// The door family's currency is `NonZeroUsize` and a declaration's is `NonZeroU32` — the width
913/// `route_depth` already takes a wall at, chosen there because a declaration writes a number a
914/// person typed rather than a machine's address space. A zero is UNREPRESENTABLE rather than
915/// refused twice over: `limit = 0` asks for an answer with no rows, which the retype round made a
916/// type error everywhere else in this family.
917///
918/// # And `first` is still not one of these
919///
920/// `first` is the SAME NUMBER as `limit` wearing GraphQL's own spelling, so it lives in the skin
921/// block ([`IndexBackend::first`], [`ElectionBackend::first`]) and never here. Q6a's own sentence:
922/// *first 是 graphql 的术语*.
923#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
924pub struct Numbers {
925 /// `limit = N` — how many rows a door of this thing answers with when nothing asks otherwise.
926 pub limit: Option<core::num::NonZeroU32>,
927 /// `depth = N` — how deep each stream behind a fold is fetched when nothing asks otherwise.
928 ///
929 /// [`None`] falls to the limit chain, which is the same deferral `Route::depth` spells one grain
930 /// up: there is no number that means *as deep as whatever is below me*.
931 pub depth: Option<core::num::NonZeroU32>,
932 /// `ceiling = N` — the WALL, and the one number here a request can never reach.
933 ///
934 /// [`None`] is the AUTHOR'S INFORMED OPENNESS rather than a gap the framework fills: the engine's
935 /// own corpus clamp is the final safety, exactly as the #293-B ruling states it.
936 pub ceiling: Option<core::num::NonZeroU32>,
937 /// `streams = N` — HOW MANY QUERY VECTORS one request may ask a `_with` road with.
938 ///
939 /// PROTECTION beside [`ceiling`](Self::ceiling) rather than a preference beside `limit`: the
940 /// number bounds what a REQUEST states, so a request able to rewrite it would bound nothing. Past
941 /// it is a REFUSAL naming the count and never a clamp — the ruled clamp-vs-refuse line is *clamp
942 /// preferences, refuse mutilated questions*, and dropping query vectors answers a different
943 /// question under the same name.
944 ///
945 /// It guards the `_with` QUESTION road ALONE. The by-example set road's `m` comes out of the
946 /// example's own stored set, which is this deployment's own data rather than anything a request
947 /// can inflate — see [`IndexModel::similar_set_leg`], whose doc states the same absence.
948 ///
949 /// [`None`] is `ceiling`'s own reading of an unwritten word: no guard is emitted at all, and the
950 /// road is byte-for-byte what it was before the word existed.
951 ///
952 /// The wire ROW called `streams` on a set hit is a DIFFERENT word in a different vocabulary — see
953 /// `ingraph_derive::index::FLOOR_WORDS`, where it is the framework's own answer row and is refused
954 /// every rename. One concept, a bones word and a wire surface, which is `depth`'s own precedent.
955 pub streams: Option<core::num::NonZeroU32>,
956}
957
958impl Numbers {
959 /// Whether this tier wrote nothing at all — the ordinary state, and what a front end builds for a
960 /// declaration that names no number.
961 #[must_use]
962 pub const fn is_empty(&self) -> bool {
963 self.limit.is_none() && self.depth.is_none() && self.ceiling.is_none() && self.streams.is_none()
964 }
965}
966
967/// **THE FRAMEWORK'S OWN ANSWER TO *HOW MANY*** — the floor of the wire default's chain, and the
968/// number a schema publishes where no tier of a declaration wrote one.
969///
970/// Twenty, on the Q6a/Q6b ruling's own words (*框架默认就设置 20 吧*). It is a CODEGEN constant and
971/// not a runtime one, which is the whole of why it may exist at all: what spends it is
972/// [`IndexModel::wire_first`], whose answer becomes an SDL LITERAL — so the number is written into
973/// the schema at expansion and no door, seam or fold ever reads it. The homelessness #292-E ruled
974/// deliberate ends exactly here and nowhere wider: `DEFAULT_LIMIT` does not come back to the seam.
975pub const FRAMEWORK_LIMIT: core::num::NonZeroU32 = match core::num::NonZeroU32::new(20) {
976 Some(twenty) => twenty,
977 None => panic!("twenty is not zero"),
978};
979
980/// ONE FIELD's numbers, and the skins that dress them — the ELECTION tier.
981///
982/// A list parallel to [`FieldEngines`](crate::engine::FieldEngines) rather than a member of
983/// [`Elected`], and the reason is that BOTH KINDS elect: a vector declaration's elections are
984/// [`Elected`] values and a full-text declaration's are bare idents
985/// ([`searchable`](IndexModel::searchable)), so a per-field fact both kinds carry has no one struct
986/// to sit inside. The engine list solved that same problem the same way, and one shape for
987/// per-field facts is what keeps a reader from having to learn two.
988#[derive(Debug, Clone)]
989pub struct FieldNumbers {
990 /// The election these numbers are about.
991 pub field: syn::Ident,
992 /// What this field wrote — the BONES tier's own words.
993 pub numbers: Numbers,
994 /// `graphql(<backend>(first = N))` ON THE FIELD — the SKIN tier, one entry per backend named.
995 pub skins: Vec<ElectionBackend>,
996}
997
998impl FieldNumbers {
999 /// A field's entry with nothing written on it.
1000 #[must_use]
1001 pub fn of(field: syn::Ident) -> Self {
1002 Self {
1003 field,
1004 numbers: Numbers::default(),
1005 skins: Vec::new(),
1006 }
1007 }
1008
1009 /// `kind`'s block on this field, or [`None`] where the field named that backend nowhere.
1010 #[must_use]
1011 pub fn skin(&self, kind: GraphqlKind) -> Option<&ElectionBackend> {
1012 self.skins.iter().find(|backend| backend.kind == kind)
1013 }
1014}
1015
1016/// ONE backend's block on an ELECTION — `graphql(async_graphql(first = 20, keys(rename = "…")))`.
1017///
1018/// The field-level twin of [`IndexBackend`], and it exists for that one's reason: a wire default is
1019/// the SKIN's fact, so it lives in the block that names the skin, and a second backend sets its own
1020/// without touching the first's.
1021///
1022/// # ONE GRAMMAR FOR EVERY NAME SEAT, and `first` is not one of them
1023///
1024/// The 2026-08-16 ruling, in the user's own words — *不要有糖, 糖留给以后其他东西, rename 不值得一个
1025/// 糖*. Every seat here that names something is a BLOCK carrying a bare `rename = "…"` row, so a
1026/// reader who has learnt one has learnt all of them and the flat position stays free for whatever
1027/// later earns it. [`first`](Self::first) keeps its flat spelling because it is a COUNT: there is no
1028/// name for a `rename` row to carry, and `first(rename = 20)` would be a sentence about renaming a
1029/// number.
1030///
1031/// # The seats split by WHAT each names: two TYPES and five ROADS
1032///
1033/// [`question`](Self::question) and [`engines`](Self::engines) name TYPES this election mints — the
1034/// two a request builds by hand. The five road seats name QUERY FIELDS, one per road an election can
1035/// mount, which is [`Field`]'s own vocabulary read as a grammar: five roads, five words, and no
1036/// composition between any two of them.
1037#[derive(Debug, Clone)]
1038pub struct ElectionBackend {
1039 /// The backend this block dresses the election for.
1040 pub kind: GraphqlKind,
1041 /// `first = N` — the GraphQL-term spelling of the number [`Numbers::limit`] carries, and the
1042 /// literal this field's query arguments publish as their SDL default.
1043 ///
1044 /// SKIN and never bones: `first` is GraphQL's own word for *how many*, so it has no business at a
1045 /// Rust-facing tier — a hand-caller's number is the positional `limit` the doors already take.
1046 ///
1047 /// FLAT where every neighbour is a block, and the asymmetry is the ruling's: a block exists to
1048 /// hold a `rename` row, and a count has no name to move.
1049 pub first: Option<core::num::NonZeroU32>,
1050 /// `question(rename = "…")` — what this backend calls `<Index><Field>Question`, the `@oneOf` a
1051 /// request names a point with.
1052 ///
1053 /// # The TYPE moves and the ARGUMENT WORD does not, which is law 3's whole line
1054 ///
1055 /// The parameter is spelled `question:` in every schema this framework writes, on every road, at
1056 /// every declaration — the UNIFORM FLOOR, and the argument words are Relay's precedent read one
1057 /// grain down. What a client cannot predict is the type BEHIND that argument, because it is minted
1058 /// per election and per declaration; that one is nameable, and this is the seat.
1059 ///
1060 /// A [`syn::LitStr`] on the 2026-08-13 ruling every SDL rename in this workspace carries: the word
1061 /// names a type in GraphQL's own namespace and nothing in Rust, so a Rust keyword is an ordinary
1062 /// word here.
1063 pub question: Option<syn::LitStr>,
1064 /// `engines(rename = "…")` — what this backend calls `<Index><Field>Engines`, the PRODUCT a fused
1065 /// read states one floor per leg in.
1066 ///
1067 /// [`question`](Self::question)'s twin over the other per-election argument type, and PLURAL for
1068 /// the shape it names: the selector beside it is a SUM over one leg and this names them ALL,
1069 /// because a fused road walks every leg and each one needs a floor in its own currency.
1070 ///
1071 /// Distinct from [`IndexBackend::engine`], which names the `@oneOf` SELECTOR at the head. The two
1072 /// words differ by a letter and name two shapes; the near-miss line is what tells an author which
1073 /// position they are at.
1074 pub engines: Option<syn::LitStr>,
1075 /// `sighting(rename = "…")` — what this backend calls `<Index><Field>Sighting`, the wire UNION a
1076 /// fused answer's evidence list holds.
1077 ///
1078 /// # An ANSWER-side type, which is why it is a seat rather than a floor word
1079 ///
1080 /// The two seats above name types a REQUEST builds; this one names a type a request READS. Both
1081 /// are the same KIND of name and are nameable for the same reason: the union is minted per
1082 /// election and per declaration, so no client could predict it, while the uniform floor covers the
1083 /// ROW WORDS a client writes (`score`, `evidence`, `node`) rather than the types behind them.
1084 ///
1085 /// The ARMS take no seat of their own. Each is `<Index><Field><Engine>Sighting`, derived from the
1086 /// leg's own word, so one word here would move a SET of types — exactly the shape
1087 /// [`IndexBackend::engine`] is refused for on a declaration that types two fields. A declaration
1088 /// that wants the arms moved moves the leg words, which are its own.
1089 pub sighting: Option<syn::LitStr>,
1090 /// `fused_key_match(rename = "…")` — what this backend calls `<Index><Field>FusedKeyMatch`, the
1091 /// ROW a fused read answers with: the address, the fused score, and the evidence list.
1092 ///
1093 /// [`sighting`](Self::sighting)'s twin over the other half of the fused answer, and a seat of its
1094 /// own for the reason every road pair in this block has two: the two types are two names in one
1095 /// namespace, and a declaration that renamed the union has said nothing about the row carrying it.
1096 ///
1097 /// The word is SNAKE-CASED where its neighbours are single nouns, which is the minted name read
1098 /// back: `FusedKeyMatch` is three words, and a word spelling only one of them would name a type
1099 /// its author could not find.
1100 pub fused_key_match: Option<syn::LitStr>,
1101 /// `keys(rename = "…")` — what this backend calls the KEYS query field this election publishes,
1102 /// replacing the derived `<index>By<Field>Keys` VERBATIM.
1103 ///
1104 /// # A FIELD name, which is why it is not the type-renaming axis
1105 ///
1106 /// [`IndexRename`] moves RUST types and the two seats above move SDL type names; a query field is
1107 /// neither. It is a name in the ROOT's own namespace, where every mounted declaration's fields
1108 /// meet — so two declarations electing a field of the same name are the collision this word
1109 /// exists to break, and it has to be sayable per field and per backend.
1110 ///
1111 /// A [`syn::LitStr`] and never an ident, on the 2026-08-13 ruling the type-level renames already
1112 /// carry. Carried VERBATIM — the derived name is composed from three parts and a word that
1113 /// replaced only one of them would be a rename an author could not predict.
1114 pub keys: Option<syn::LitStr>,
1115 /// `hydrated(rename = "…")` — the same word over the TIER BELOW that road: `<index>By<Field>`,
1116 /// the question answered with the upstream's whole entities.
1117 ///
1118 /// A SEAT OF ITS OWN and never a composition off [`keys`](Self::keys), which is what the verbatim
1119 /// law forces: a declared word is carried exactly as written, so a name derived from the keys
1120 /// word — `clipNeighbours` → `clipNeighboursHydrated` — would be a rename its author could not
1121 /// predict from what they typed. Two names in one namespace need two words or none.
1122 pub hydrated: Option<syn::LitStr>,
1123 /// `fused(rename = "…")` — the same word over the FUSED keys field, which exists where the
1124 /// election is fanned across two or more typed stores.
1125 ///
1126 /// A separate seat because the two fields are two names in one namespace: a declaration renaming
1127 /// its plain road has said nothing about its fused one, and a single word would have to move both
1128 /// or neither.
1129 pub fused: Option<syn::LitStr>,
1130 /// `similar(rename = "…")` — the same word over the BY-EXAMPLE keys field, which exists wherever
1131 /// the plain road does.
1132 ///
1133 /// The seats above's own argument, read one road further: the by-example field is a name in the
1134 /// same root namespace, and a declaration that renamed the road asked with a QUESTION has said
1135 /// nothing about the road asked with a KEY. It cannot share the fused word either — a fanned
1136 /// election publishes both, so one word would have to move two live names at once.
1137 pub similar: Option<syn::LitStr>,
1138 /// `similar_hydrated(rename = "…")` — the by-example road's own tier below: `<index>SimilarBy<Field>`.
1139 ///
1140 /// [`hydrated`](Self::hydrated)'s reason unchanged. It is ONE seat over TWO emitted shapes — the
1141 /// single-vector road and the SET road — because a declaration publishes one or the other and
1142 /// never both, so *which shape ran* is not a question a name has to answer.
1143 pub similar_hydrated: Option<syn::LitStr>,
1144}
1145
1146impl ElectionBackend {
1147 /// A backend named on a field and nothing else said about it.
1148 #[must_use]
1149 pub const fn of(kind: GraphqlKind) -> Self {
1150 Self {
1151 kind,
1152 first: None,
1153 question: None,
1154 engines: None,
1155 sighting: None,
1156 fused_key_match: None,
1157 keys: None,
1158 hydrated: None,
1159 fused: None,
1160 similar: None,
1161 similar_hydrated: None,
1162 }
1163 }
1164
1165 /// What this block calls `which`'s query field, or [`None`] where it named that road nothing.
1166 ///
1167 /// The ROAD LOOKUP, spelled once: [`Field`] is a closed five and so are the seats, so a road added
1168 /// to one without the other is a `non_exhaustive`-free match arm the compiler asks about here
1169 /// rather than a name silently falling back to the derived one.
1170 #[must_use]
1171 pub fn road(&self, which: Field) -> Option<&syn::LitStr> {
1172 match which {
1173 Field::Keys => self.keys.as_ref(),
1174 Field::Hydrated => self.hydrated.as_ref(),
1175 Field::Fused => self.fused.as_ref(),
1176 Field::Similar => self.similar.as_ref(),
1177 Field::SimilarHydrated => self.similar_hydrated.as_ref(),
1178 }
1179 }
1180}
1181
1182/// ONE backend's block inside a derived index's `graphql(…)`.
1183///
1184/// # Every name here is a SKIN's, and none of them moves a Rust type
1185///
1186/// The axis law, as the model holds it: a name is the SKIN's fact, so it lives in the block that
1187/// names the skin — one block per backend, and a second backend renames its own schema without
1188/// touching the first's. The Rust family is re-based by the TOP-LEVEL `rename`, which never appears
1189/// in here.
1190///
1191/// # THE RECORD-SIDE PLACEMENT AUDIT, and the divergence it found
1192///
1193/// The round asked for this comparison and for the divergence to be aligned or written down. It is
1194/// written down, because the two families differ in the fact that decides the placement.
1195///
1196/// A RECORD's SDL renames sit at the DOMAIN level of its own `graphql(…)` — `rename`, `plural`,
1197/// `output(rename = …)`, `key`/`filter`/`order_by(rename = …)`, `connection`, `edge`. Its BACKEND
1198/// block accepts a `rename` too, and that word is parsed and never read: the record's own note says
1199/// so out loud — *kept because the grammar takes it, and unread because the emitted types are ONE
1200/// per record: the SDL is identical whichever Rust library serves it*.
1201///
1202/// So the record's placement is not a competing design; it is the same design under a premise this
1203/// family does not share. A record emits one set of wire types and asserts every backend renders
1204/// them identically, which makes a domain-level name correct and a backend-level one redundant. A
1205/// derived index's ruled posture is the opposite — one skin per word, coexisting, kept apart by the
1206/// `__<backend>_` ident prefix — and under that premise a domain-level SDL name would be a name
1207/// asserted across skins that are free to differ.
1208///
1209/// ALIGNING would mean moving the record's live renames into its backend block, which is a change
1210/// to the record's grammar and to every declaration that writes one; it is out of this round's
1211/// scope and is recorded rather than done. What this family does NOT do is copy the record's dead
1212/// word: there is no domain-level SDL rename here, so nothing in this grammar is parsed and
1213/// discarded.
1214#[derive(Debug, Clone)]
1215pub struct IndexBackend {
1216 /// The backend this block dresses the declaration for.
1217 pub kind: GraphqlKind,
1218 /// `prefix = "…"` — the BASE this backend's whole SDL type family is built on.
1219 ///
1220 /// # The WORD is `prefix` because the seat is a STEM
1221 ///
1222 /// **`rename` names ONE thing verbatim; `prefix` re-stems a FAMILY.** This seat names no type
1223 /// literally: the emitted types are `<base>FuseOptions`, `<base>FusedEvidence` and their siblings,
1224 /// so what a declaration writes here is composed with a suffix and is upper-camel-cased at the type
1225 /// positions where GraphQL's own convention is. There is no schema name equal to what an author
1226 /// types at this position, which is the whole of why `rename` was the wrong word for it. A word
1227 /// that names ONE type outright is a per-face override below, and those are carried verbatim under
1228 /// their own `rename` rows.
1229 ///
1230 /// `rename` at this position is refused BY NAME, pointing here — see `ingraph-derive`'s
1231 /// `index_backend`, where the correction and its did-you-mean are written.
1232 ///
1233 /// A `LitStr` and never an ident, on the 2026-08-13 ruling: this word names types in GraphQL's
1234 /// own namespace and nothing in Rust, so a Rust keyword is an ordinary word here.
1235 pub prefix: Option<syn::LitStr>,
1236 /// `options(rename = "…")` — what this backend calls the package a client CONFIGURES a retrieve
1237 /// with, whichever of the binding table's shapes that is.
1238 ///
1239 /// The FACE and not every options package: a tier's `Fusable::Options` is the one a parent and a
1240 /// client name, and the per-slot packages inside it are interior — re-based by the base above and
1241 /// named by nothing here.
1242 pub options: Option<syn::LitStr>,
1243 /// `question(rename = "…")` — the sister tree's face, by the same table.
1244 pub question: Option<syn::LitStr>,
1245 /// `engine(rename = "…")` — what this backend calls the `@oneOf` selector over the typed engines.
1246 pub engine: Option<syn::LitStr>,
1247 /// `first = N` — the CONTAINER tier's SDL default for every query argument this skin publishes,
1248 /// and the GraphQL-term spelling of the same number [`Numbers::limit`] carries in Rust vocabulary.
1249 ///
1250 /// The bones/skin split ruled in Q6a: a container names `limit` and `depth` because those are the
1251 /// words a Rust door is called with, and it names `first` HERE because that is the word a schema
1252 /// publishes. Unwritten, the chain falls to the bones beside it — see
1253 /// [`wire_first`](IndexModel::wire_first), which is the one place the whole order is spelled.
1254 pub first: Option<core::num::NonZeroU32>,
1255 //
1256 // THE FOURTH FACE IS NOT HERE, and its absence is a measurement rather than an omission — one
1257 // that was RE-TAKEN when the fanned road grew an answer face, and narrowed by what it found.
1258 //
1259 // `fused(rename = "…")` at THIS position would name `<Index>FusedEvidence<S₁, …>`, the TIER's
1260 // fused door's evidence. That door mounts no query field: `answer_roads` walks ELECTIONS, and
1261 // `Door::Fused`/`Door::FusedSimilar` appear in the method roster and in the Rust impl and nowhere
1262 // on a schema. So nothing on its answer side reaches SDL, and the word would move a name that is
1263 // not published.
1264 //
1265 // A fused answer DOES reach a schema now, one grain down: `vector_fuse_by_<field>` publishes
1266 // `<Index><Field>Sighting` — a MINTED wire union, one arm per leg — beside
1267 // `<Index><Field>FusedKeyMatch`, and the slot's evidence enum crosses INTO that union while keeping
1268 // its own Rust-only name. Those are per-ELECTION types, so a word here would be a head word over
1269 // a SET of them, which is exactly the shape [`engine`](Self::engine) is refused for on a
1270 // declaration that types two fields.
1271 //
1272 // The word is therefore still refused at the front end, with the narrowed reason rather than the
1273 // old one, and it opens the day the TIER's fused door mounts a road of its own. The measurement
1274 // is pinned in `fuse::skins::the_tier_fused_door_publishes_nothing_for_a_word_to_move`, which
1275 // reads BOTH halves so that the next arrival cannot be silent the way this one was.
1276}
1277
1278impl IndexBackend {
1279 /// A backend named and nothing else said about it — the `graphql(async_graphql)` spelling.
1280 #[must_use]
1281 pub const fn of(kind: GraphqlKind) -> Self {
1282 Self {
1283 kind,
1284 prefix: None,
1285 options: None,
1286 question: None,
1287 engine: None,
1288 first: None,
1289 }
1290 }
1291}
1292
1293/// WHAT THIS DECLARATION'S MINTED RUST TYPES ARE CALLED — the top-level `rename` word, in whichever
1294/// of its two forms it was written.
1295///
1296/// # The BONES axis, and it never appears in a backend block
1297///
1298/// These are RUST names: the packages, the vocabularies, the evidence, the selector and the markers
1299/// this expansion lands in the declaring scope. A skin's names are [`IndexBackend`]'s, and the two
1300/// never cross — a schema rename that moved a Rust type would make one declaration's API depend on
1301/// which backends happened to be compiled in.
1302///
1303/// The declaration's OWN struct name is never among them. It is the author's item, sitting in the
1304/// author's file; nothing here renames what somebody wrote.
1305///
1306/// # Two forms, and they are exclusive for [`Extension`]'s reason
1307///
1308/// The `extension` word's precedent, one grammar over: a single fact is a key-value and a structured
1309/// one is a block, and writing both at one position is refused as a repeat. `rename = "ShotSearch"`
1310/// re-bases the WHOLE family; `rename(fuse_options = "MyKnobs", …)` names individual mints.
1311#[derive(Debug, Clone)]
1312pub enum IndexRename {
1313 /// `rename = "ShotSearch"` — the base every minted name is built on, replacing the declaration's
1314 /// own ident at the head of each.
1315 Base(syn::Ident),
1316 /// `rename(<piece> = "…", …)` — one entry per mint the declaration named, in written order.
1317 Pieces(Vec<(RenamePiece, syn::Ident)>),
1318}
1319
1320impl IndexRename {
1321 /// The BASE this family is built on, or [`None`] where the declaration named pieces instead.
1322 #[must_use]
1323 pub const fn base(&self) -> Option<&syn::Ident> {
1324 match self {
1325 Self::Base(base) => Some(base),
1326 Self::Pieces(_) => None,
1327 }
1328 }
1329
1330 /// What the declaration called `piece`, or [`None`] where it named that one nothing.
1331 #[must_use]
1332 pub fn piece(&self, piece: RenamePiece) -> Option<&syn::Ident> {
1333 match self {
1334 Self::Base(_) => None,
1335 Self::Pieces(named) => named
1336 .iter()
1337 .find_map(|(named, spelled)| (*named == piece).then_some(spelled)),
1338 }
1339 }
1340}
1341
1342/// WHICH MINT a `rename(…)` entry is about — the CLOSED vocabulary, read off the emitted-types
1343/// roster.
1344///
1345/// # Every word here names a type this declaration has AT MOST ONE of, and that is the whole rule
1346///
1347/// A word names an individual mint, so it can only exist where *which one* has an answer. These
1348/// seven do: a declaration mints one options package a parent absorbs, one question package, one
1349/// evidence enum, one column vocabulary, one engine selector.
1350///
1351/// The mints that are PER-FIELD or PER-SLOT — a slot's own options and question, a leg's options, a
1352/// fold vocabulary, an election marker, a slot marker — are named by no word here and are covered by
1353/// [`IndexRename::Base`] instead. A word for one of them would have to carry a field and an engine
1354/// beside it, which is a grammar this round did not rule; the front end refuses each by name and
1355/// says which form reaches it.
1356#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1357pub enum RenamePiece {
1358 /// `<Index>FuseOptions` — a vector tier's multi-route options package.
1359 FuseOptions,
1360 /// `<Index>FuseQuestion` — its sister.
1361 FuseQuestion,
1362 /// `<Index>FulltextOptions` — a full-text tier's options package.
1363 FulltextOptions,
1364 /// `<Index>FulltextQuestion` — its sister.
1365 FulltextQuestion,
1366 /// `<Index>FusedEvidence` — which routes agreed about a fused root.
1367 Evidence,
1368 /// `<Stem>EngineInput` — the `@oneOf` over the engines this declaration TYPED.
1369 EngineInput,
1370 /// `<Index>Column` — the full-text column vocabulary.
1371 Column,
1372}
1373
1374impl RenamePiece {
1375 /// Every word, in the order a refusal lists them — which is also the order the near-miss line
1376 /// measures a typo against.
1377 pub const ALL: [Self; 7] = [
1378 Self::FuseOptions,
1379 Self::FuseQuestion,
1380 Self::FulltextOptions,
1381 Self::FulltextQuestion,
1382 Self::Evidence,
1383 Self::EngineInput,
1384 Self::Column,
1385 ];
1386
1387 /// The word a declaration writes.
1388 #[must_use]
1389 pub const fn as_str(self) -> &'static str {
1390 match self {
1391 Self::FuseOptions => "fuse_options",
1392 Self::FuseQuestion => "fuse_question",
1393 Self::FulltextOptions => "fulltext_options",
1394 Self::FulltextQuestion => "fulltext_question",
1395 Self::Evidence => "evidence",
1396 Self::EngineInput => "engine_input",
1397 Self::Column => "column",
1398 }
1399 }
1400
1401 /// The word a path names, if it names one.
1402 #[must_use]
1403 pub fn of(path: &syn::Path) -> Option<Self> {
1404 Self::ALL
1405 .into_iter()
1406 .find(|word| path.is_ident(word.as_str()))
1407 }
1408
1409 /// What a refusal calls the type this word is about.
1410 #[must_use]
1411 pub const fn what(self) -> &'static str {
1412 match self {
1413 Self::FuseOptions => "the multi-route options package a parent absorbs",
1414 Self::FuseQuestion => "the multi-route question package",
1415 Self::FulltextOptions => "the full-text options package",
1416 Self::FulltextQuestion => "the full-text question package",
1417 Self::Evidence => "the evidence a fused door answers with",
1418 Self::EngineInput => "the `@oneOf` over the engines this declaration typed",
1419 Self::Column => "the column vocabulary a full-text retrieve narrows with",
1420 }
1421 }
1422}
1423
1424/// The `data` word itself, spelled once.
1425///
1426/// Here rather than in the front end that reads it, for
1427/// [`EXTENSION`](crate::extension::EXTENSION)'s reason: the derive is one front end and a manifest
1428/// is meant to be another, and a word spelled once per front end is a word that can come to mean
1429/// two things without anybody editing either of them.
1430pub const DATA: &str = "data";
1431
1432/// What an author who wrote `data` on the wrong kind is told.
1433///
1434/// The SENTENCE lives beside the model it fills rather than in the walk that pushes it, because the
1435/// fact it states is this crate's: [`IndexModel::data`] is `false` on the two retrieving kinds by
1436/// construction, and the reason it can never be anything else is exactly what a front end has to
1437/// say out loud when it refuses the word.
1438#[must_use]
1439pub fn data_wrong_kind(kind: NodeKind) -> String {
1440 format!(
1441 "`data` is an ARTIFACT FAMILY's word and {article} {noun} has no bytes to send — the word says \
1442 a stored OBJECT may ride inline, base64, beside the address that names it, and this \
1443 declaration stores no object and mints no address to put one beside: its documents live inside \
1444 an engine, and what it hands back is a RANKING over keys",
1445 article = kind.article(),
1446 noun = kind.noun(),
1447 )
1448}
1449
1450impl IndexModel {
1451 /// THE BASE EVERY MINTED NAME IS BUILT ON — the top-level `rename`'s word, or the declaration's
1452 /// own ident.
1453 ///
1454 /// The one place the two are chosen between, so that a name minted anywhere in this crate cannot
1455 /// be built on the wrong one. NOT the same question as *what is this type called*: the
1456 /// declaration's own ident is what an `impl … for` writes and what a doc link points at, and it
1457 /// never moves.
1458 #[must_use]
1459 pub fn base(&self) -> &syn::Ident {
1460 self
1461 .rename
1462 .as_ref()
1463 .and_then(IndexRename::base)
1464 .unwrap_or(&self.index)
1465 }
1466
1467 /// The whole expansion: the one-storage marker at module scope, and everything else inside the
1468 /// anonymous `const` this crate puts every impl in.
1469 ///
1470 /// The marker CANNOT move inside that const — see
1471 /// [`one_storage_marker`](crate::model::one_storage_marker); two of them in two anonymous consts
1472 /// are two items in two scopes and collide with nothing at all.
1473 #[must_use]
1474 pub fn emit(&self) -> proc_macro2::TokenStream {
1475 let index = &self.index;
1476 let marker = one_storage_marker(&self.prefix, index);
1477 let elections = self.elections();
1478 let slots = self.slot_markers();
1479 let carrier = self.carrier();
1480 let binding = self.binding();
1481 let projections = self.projections();
1482 let embedding = self.vector_record();
1483 let geometry = self.geometry_bindings();
1484 let folds = self.declared_folds();
1485 let audits = self.label_audits();
1486 let kinds = self.resource_audits();
1487 let roads = self.roads();
1488 let retrieve = self.retrieve();
1489 let emits = self.emits_binding();
1490 let fans = self.fanouts();
1491 // LAYER TWO's DECLARATION HALF, at module scope with the markers: `Describe<R>` is a trait impl
1492 // and lands anywhere, but the blueprints it carries name the SLOT MARKERS' own durable names and
1493 // read like the declaration's own surface, so they go where a reader looks for what this
1494 // declaration owns.
1495 let habitats = self.habitats();
1496 // The FUSION TREE, at module scope with the markers: a package is a type a CLIENT builds, so it
1497 // has to be spellable from the scope the declaration was written in. See `crate::fuse` for the
1498 // binding table and for the presence law that makes this empty on a kind that does not retrieve.
1499 let tier = self.tier().emit();
1500 let capability = self.capability();
1501 let bridge = self.artifact_bridge();
1502 let citizen = self.citizen();
1503 // THE SUBSCRIBER, at module scope with the markers: it is a TYPE a deployment mounts by name,
1504 // so it has to be spellable from the scope the declaration was written in — the query unit's
1505 // and the fusion tree's own reason, at the write side.
1506 let subscriber = self.subscriber();
1507 quote! {
1508 #[doc(hidden)]
1509 #[allow(dead_code, non_upper_case_globals)]
1510 const #marker: () = ();
1511
1512 #elections
1513 #slots
1514 #habitats
1515 #fans
1516 #tier
1517 #citizen
1518 #subscriber
1519
1520 const _: () = {
1521 #carrier
1522 #binding
1523 #projections
1524 #geometry
1525 // THE CAPABILITY IMPL rides INSIDE the anonymous const, beside the geometry bindings it
1526 // projects the elected widths through: a trait impl is global whatever scope it is written
1527 // in, and those two consts are nameable only here.
1528 #capability
1529 #embedding
1530 #folds
1531 #audits
1532 #kinds
1533 #roads
1534 #retrieve
1535 #emits
1536 #bridge
1537 };
1538 }
1539 }
1540
1541 /// **THE QUERY UNIT** this declaration mints — `<Decl>Queries`, the mountable home of its search
1542 /// root fields, and the [`Graphql`] binding that seats it.
1543 ///
1544 /// # It is the RECORD's citizenship, at a retrieving declaration
1545 ///
1546 /// The Q1 ruling, whose whole content is that there is NO second mounting mechanism: a `vector` or
1547 /// `fulltext` declaration wearing `graphql(async_graphql)` joins the three laws a record already
1548 /// lives under — the unit law (`Graphql::Query`, a root assembles UNITS), the graph root's emitted
1549 /// `MergedObject` (a member's unit joins the projection list), and the door-citizen state law
1550 /// (the resource's own `Shared<R>` citizen, handed over with `.data(…)`).
1551 ///
1552 /// # The road to the seat is ONE projection, as an interface's is
1553 ///
1554 /// A record is reached `<<R as Transformer>::Graphql as Graphql>::Query`, because a record's wire
1555 /// face is a member of its entity binding. A retrieving declaration binds `Transformer::Graphql =
1556 /// ()` — its wire face is a RANKING rather than a predicate, which is a different surface from the
1557 /// one that binding describes — so it implements [`Graphql`] DIRECTLY and a root projects
1558 /// `<M as Graphql>::Query`. The SEAT is the same seat; only the road to it is shorter.
1559 ///
1560 /// This paragraph used to say *a retrieving declaration implements no `Transformer` — it is not a
1561 /// launchable node*, and BOTH halves of that were false by the time it was read again. The
1562 /// [`binding`](Self::binding) has emitted a `Transformer` impl for as long as an index has carried
1563 /// its upstream's key, and [`subscriber`](Self::subscriber) now mints a launchable node beside a
1564 /// declaration that wears `subscribe`. What is still true is the only thing this section needs:
1565 /// the projection through `Transformer::Graphql` reaches `()` here, so the road to the seat is the
1566 /// direct one.
1567 ///
1568 /// # Both halves of the face bind the EMPTY PRODUCT, and that is an answer
1569 ///
1570 /// `GraphqlInput` is a predicate and an order, and `GraphqlOutput::Key` is the address a stored
1571 /// row is paged by. A retrieving declaration is asked by neither: its whole request surface is the
1572 /// question and options packages its fusion tree already mints, and its answer surface is the hits
1573 /// its doors hand back. So the two record-shaped halves have nothing to name, and `()` is what the
1574 /// framework's own absent forms are spelled with — the same statement `Graphql::Query = ()` makes
1575 /// at the member beside them.
1576 ///
1577 /// # UNGATED, like every emitted wire type's declaration
1578 ///
1579 /// `type Query = <Decl>Queries` is bound in an ungated impl, so a unit that existed only where
1580 /// async-graphql does would leave that binding naming nothing in every other build. The FACE — the
1581 /// `#[Object]` impl carrying the fields — rides the gate, in a const block of its own.
1582 ///
1583 /// Empty where the declaration named no backend: a model that dressed nothing must not even reach
1584 /// for the macro that asks whether the feature is on, which is the presence law this family's
1585 /// skins already hold.
1586 pub(crate) fn citizen(&self) -> proc_macro2::TokenStream {
1587 if !self.mounts() {
1588 return proc_macro2::TokenStream::new();
1589 }
1590 let vis = &self.vis;
1591 let index = &self.index;
1592 let name = self.queries_name();
1593 let face = framework(&self.krate, &["transform"], "Graphql");
1594 let answers = self.answers();
1595 let doc = crate::emit::leading(&format!(
1596 "The root fields [`{index}`] answers — its search doors, as one mountable value.\n\nMounted by folding it into a graph's root query; it holds nothing and reaches its store through the `Shared<R>` citizen the schema was built with."
1597 ));
1598 quote! {
1599 #[doc = #doc]
1600 #[derive(
1601 ::core::fmt::Debug,
1602 ::core::clone::Clone,
1603 ::core::marker::Copy,
1604 ::core::default::Default,
1605 )]
1606 #vis struct #name;
1607
1608 #[automatically_derived]
1609 impl #face for #index {
1610 // THE EMPTY PRODUCT ON BOTH RECORD-SHAPED HALVES — see this emission's own note: a
1611 // retrieving declaration is asked by no predicate and ordered by no column, so what a
1612 // record's face is built around has nothing to name here.
1613 type Input = ();
1614 type Output = ();
1615 type Query = #name;
1616 }
1617
1618 #answers
1619 }
1620 }
1621
1622 /// **WHETHER THIS DECLARATION MOUNTS AT ALL** — a retrieving kind wearing a backend word.
1623 ///
1624 /// The presence law at the tier that mints the unit: a declaration with no `graphql(…)` block
1625 /// emits every Rust door and package it would otherwise emit, and mints no citizenship — which is
1626 /// exactly what a backend-only search pipeline wants.
1627 #[must_use]
1628 pub fn mounts(&self) -> bool {
1629 matches!(self.kind, NodeKind::Fulltext | NodeKind::Vector)
1630 && self
1631 .graphql
1632 .as_ref()
1633 .is_some_and(|block| block.renders(GraphqlKind::AsyncGraphql))
1634 }
1635
1636 /// `<Decl>Queries` — this declaration's query unit, re-based by the BONES rename like every other
1637 /// name it mints.
1638 ///
1639 /// No piece word of its own, on the record unit's precedent: the unit is a Rust type a root spells
1640 /// once and a schema never sees, so a name for it is the base's business. The base moves it because
1641 /// the base moves the whole family — a rename that reached the packages and left this one behind
1642 /// would put two stems in one declaring scope.
1643 #[must_use]
1644 pub fn queries_name(&self) -> syn::Ident {
1645 format_ident!("{}Queries", self.base())
1646 }
1647
1648 /// WHICH ROAD one election's query fields take, or [`None`] where it mounts none.
1649 ///
1650 /// # Both roads need a TYPED engine, and that is the wall rather than a policy
1651 ///
1652 /// A resolver's corpus lookup is `Context::data::<Shared<R>>`, a `TypeId` on a CONCRETE
1653 /// pairing, and a resolver cannot be generic. So the `E` has to be a type this expansion can
1654 /// spell, and the only place one is written is `lance(resource = "path::To::Lance")`. An election
1655 /// naming its engines by word alone keeps every Rust door it had and publishes no field —
1656 /// the presence law, at the grain where a road either has an engine or does not.
1657 ///
1658 /// # The FANNED road needs EVERY leg typed, which is stricter than *some are*
1659 ///
1660 /// `vector_fuse_by_<field>` is generic over one engine per LEG and the call spells them all, so a
1661 /// slot with one untyped leg has a call this emission cannot write at all — not a road with a
1662 /// gap in it. `slot_legs` rather than `typed` is therefore what the predicate reads, and the
1663 /// `all` is what makes the two agree.
1664 ///
1665 /// A SET election takes the plain road and never the fused one, which is
1666 /// [`Tier::fanned_slots`](crate::fuse::Tier::fanned_slots)' own exclusion read at the wire: RRF
1667 /// joins ordinals and a set election's `m` streams have no order between them to read one from,
1668 /// so the door it would call is not emitted.
1669 ///
1670 /// # THE LABEL PICKS THE DOOR ON BOTH PAIRS, and that is the whole of the set routing
1671 ///
1672 /// One field NAME per (declaration × election), and the road behind it is the ELECTION's own
1673 /// label read at expansion — the same mechanism `get_<field>` already uses to answer one embedding
1674 /// or a whole group. `<decl>SimilarBy<Field>Keys` on a UNIT election calls
1675 /// `retrieve_similar_by_<field>`; on a SET election it calls `retrieve_similar_by_<field>_with`.
1676 /// `<decl>By<Field>Keys` reads the same way one road over: `retrieve_keys_by_<field>` at one
1677 /// label, `retrieve_keys_by_<field>_with` at the other.
1678 ///
1679 /// **It turns a runtime refusal into an answer, and that is the measurement.** The single-vector
1680 /// by-example door reads the example's stored group and then demands exactly one of it, so a set
1681 /// election published a field that answered `Several { held }` for every entity holding the set
1682 /// its own declaration promised — a field that could only work where the data did not use the
1683 /// label. Routing by the label is what makes the published name mean the same thing at both
1684 /// labels: *the neighbours of this entity's own `<field>*`.
1685 ///
1686 /// The QUESTION pair moved second and for a different reason: a set election is asked with `m`
1687 /// points, so its question type's `coordinates` arm is one list deeper (the 2026-08-16 SET ruling)
1688 /// and both tiers of the pair read it. There is ONE question type per election, so the two tiers
1689 /// could not have been split across the two depths even if a round had wanted to.
1690 ///
1691 /// NO NAME MOVES and none can collide. The roads are exclusive per election, so each name is
1692 /// minted once whichever arm answers, and the declared rename seats (`keys(rename = "…")` through
1693 /// `similar_hydrated(rename = "…")`) keep working unread by any of this.
1694 fn answer_road<'a>(
1695 &self,
1696 tier: &crate::fuse::Tier<'a>,
1697 elected: &Elected,
1698 ) -> Option<AnswerRoad<'a>> {
1699 let legs = tier.slot_legs(elected);
1700 if tier.fanned(elected) {
1701 let fused = !elected.label.is_set()
1702 && legs.len() >= 2
1703 && legs.iter().all(|engine| engine.resource.is_some());
1704 return fused.then_some(AnswerRoad::Fanned(legs));
1705 }
1706 match tier.typed(elected).as_slice() {
1707 [only] if elected.label.is_set() => Some(AnswerRoad::Set(only)),
1708 [only] => Some(AnswerRoad::Plain(only)),
1709 _ => None,
1710 }
1711 }
1712
1713 /// **WHY THIS ELECTION PUBLISHES NO `which` QUERY FIELD**, or [`None`] where it publishes one.
1714 ///
1715 /// # The law: seats may sit EMPTY, and a written word must point at something MINTED
1716 ///
1717 /// An unwritten seat is a capability nobody has asked for yet and costs a declaration nothing. A
1718 /// WRITTEN one that reaches no emitted name is a swallowed authoring error — the class this house
1719 /// already refuses at `lineage(rename)` on a lineage-less record — because the author believes they
1720 /// renamed a field and the schema still publishes the derived name, or publishes nothing at all.
1721 ///
1722 /// # What it reads is the DECLARATION'S OWN SHAPE, and that is the whole of its scope
1723 ///
1724 /// Two facts decide which roads an election mounts, and both are the declaration's:
1725 ///
1726 /// - a FANNED election publishes the fused field alone. Its four sibling roads are not emitted,
1727 /// because `vector_fuse_by_<field>` is the one door a multi-store election has.
1728 /// - the head's `keys` word says the upstream is an ENTITY, so the answer family mounts the KEYS
1729 /// tier alone and the two hydrated roads have no store to read rows out of.
1730 ///
1731 /// # Three cases it deliberately does NOT answer, each measured
1732 ///
1733 /// [`Field::Fused`] always answers [`None`] here. It is unmounted on a plain election exactly as
1734 /// its siblings are on a fanned one, and auditing it is a one-line change to the match below — but
1735 /// the round that wrote this law enumerated four roads, so the fifth is left for a ruling rather
1736 /// than taken by symmetry.
1737 ///
1738 /// A FULL-TEXT election mounts no query field at all: [`answer_roads`](Self::answer_roads) returns
1739 /// nothing for that kind, so every seat on one is currently unspent. That is the ANSWER FACE not
1740 /// having arrived for the kind rather than a shape the author chose, so a refusal there would be
1741 /// this crate claiming the face is never coming.
1742 ///
1743 /// An election naming its engines BY WORD ALONE publishes no field either — the portable case,
1744 /// which is legal and means the deployment picks the engine — and the same reasoning holds: the
1745 /// surface is absent for a reason outside the seat's own axis.
1746 ///
1747 /// Both are recorded here rather than fixed, so the next reader inherits the measurement.
1748 #[must_use]
1749 pub fn unmounted(&self, field: &syn::Ident, which: Field) -> Option<&'static str> {
1750 if self.kind != NodeKind::Vector || !self.mounts() {
1751 return None;
1752 }
1753 let tier = self.tier();
1754 let elected = self.embeddings.iter().find(|held| held.field == *field)?;
1755 let road = self.answer_road(&tier, elected)?;
1756 match which {
1757 // THE FIFTH ROAD, left unaudited on purpose — see the note above.
1758 Field::Fused => None,
1759 _ if matches!(road, AnswerRoad::Fanned(_)) => Some(
1760 "a FANNED election publishes its fused field and nothing else — every store this field is \
1761 written to answers one leaderboard, and the four per-store roads are not emitted for it. \
1762 The word this shape has is `fused(rename = \"…\")`; drop a store from the election to get \
1763 the others back",
1764 ),
1765 Field::Hydrated | Field::SimilarHydrated if self.keys => Some(
1766 "this declaration wears the head's `keys` word, so its upstream is an ENTITY and the answer \
1767 family mounts the KEYS tier alone: there is no store for a hydrated road to read whole rows \
1768 out of, and neither hydrated field is emitted. Drop `keys` where the upstream does have \
1769 rows, or drop this word",
1770 ),
1771 _ => None,
1772 }
1773 }
1774
1775 /// **WHY THIS ELECTION MINTS NO `<Index><Field>Engines`**, or [`None`] where it mints one.
1776 ///
1777 /// [`unmounted`](Self::unmounted)'s law at a TYPE seat rather than a field seat. The per-leg
1778 /// product is minted by the fused answer and by nothing else — a fused read states one floor per
1779 /// leg, and an election answered by one store has one leg and names it through the `@oneOf`
1780 /// selector at the head instead.
1781 ///
1782 /// Its sister seat `question(rename = "…")` has no such clause, and that is a MEASUREMENT rather
1783 /// than an omission: `question_input` runs for every election that mounts a road at all, on every
1784 /// road, so the question type is minted wherever the seat is reachable. The seat is audited and
1785 /// found always-spent, which is a different answer from unaudited.
1786 #[must_use]
1787 pub fn unminted_engines(&self, field: &syn::Ident) -> Option<&'static str> {
1788 if self.kind != NodeKind::Vector || !self.mounts() {
1789 return None;
1790 }
1791 let tier = self.tier();
1792 let elected = self.embeddings.iter().find(|held| held.field == *field)?;
1793 let road = self.answer_road(&tier, elected)?;
1794 if matches!(road, AnswerRoad::Fanned(_)) {
1795 return None;
1796 }
1797 Some(
1798 "`engines` names the PRODUCT a fused read states one floor per leg in, and this election is \
1799 answered by ONE typed store: it has one leg, so there is no product to name. What names its \
1800 engine is the `@oneOf` selector at the head — `engine(rename = \"…\")` in the declaration's \
1801 own backend block",
1802 )
1803 }
1804
1805 /// EVERY ELECTION that mounts a query field, with the road it takes — in declared order.
1806 fn answer_roads(&self) -> Vec<(&Elected, AnswerRoad<'_>)> {
1807 if !self.mounts() || self.kind != NodeKind::Vector {
1808 return Vec::new();
1809 }
1810 let tier = self.tier();
1811 self
1812 .embeddings
1813 .iter()
1814 .filter_map(|elected| self.answer_road(&tier, elected).map(|road| (elected, road)))
1815 .collect()
1816 }
1817
1818 /// **THE ANSWER FAMILY AND THE QUERY FIELDS** — what a client asks one election with, what it
1819 /// reads back, and the `#[Object]` face that joins them.
1820 ///
1821 /// # FOUR fields on a plain road: two questions, two tiers — or TWO, where the upstream is an
1822 /// entity
1823 ///
1824 /// One road is asked two ways — a QUESTION and an EXAMPLE KEY — and each is answered at two tiers.
1825 /// The KEYS tier hands back addresses and touches no store; the HYDRATED tier hands back the
1826 /// upstream's whole entities and reads them out of one. The tier noun is what tells the pair
1827 /// apart at every road, which is [`Field::derived`]'s own law.
1828 ///
1829 /// The hydrated half is what [`IndexModel::keys`] withholds. A record upstream mounts all four
1830 /// unconditionally — rows are a record's essence, so hydration can never miss — and an ENTITY
1831 /// upstream mounts the two keys fields alone, because there is no store for the other two to read
1832 /// out of. A declaration whose upstream is an entity and which wrote no word emits the demand and
1833 /// is refused by the compiler at `upstream(node = "…")`; nothing here guesses.
1834 ///
1835 /// What held the hydrated pair back was ONE LINE — `ctx.data::<SqlDoor<…>>` names a database and a
1836 /// derived index has none to name — and the line is written now:
1837 /// [`Hydrates`](../../../ingraph/trait.Hydrates.html) is the record's own projection of where its
1838 /// rows are read from, and this emission spends it. `ingraph/tests/hydrated_road.rs` and its
1839 /// by-example sibling are the hand-mounts that measured the body first, and they stay as the
1840 /// pattern an application writes when it wants a road of its own shape.
1841 ///
1842 /// # The SPLIT: declarations outside the gate, impls inside it
1843 ///
1844 /// Every type below is a plain `struct` or `enum` at module scope, and every async-graphql trait
1845 /// impl over it rides `if_async_graphql!`. That is the record's own split and it is load-bearing
1846 /// twice over: a build with no wire binding compiles the whole Rust surface, and
1847 /// [`emitted_types`](Self::emitted_types) can enumerate names the collision refusals are measured
1848 /// against — a name minted inside a gate would be invisible to the roster walk and visible to a
1849 /// declaring author.
1850 ///
1851 /// It is also why no `#[derive(Union)]` appears here. A derive is written ON a declaration, the
1852 /// declaration is ungated, and `#[cfg_attr]` cannot stand in — that predicate asks whether the
1853 /// DECLARING crate has a feature called `async-graphql`, which is a different manifest and usually
1854 /// no feature at all. So the union's three impls are written out, exactly as the `@oneOf` input
1855 /// faces beside them already are.
1856 fn answers(&self) -> proc_macro2::TokenStream {
1857 let roads = self.answer_roads();
1858 let text = self.text_roads();
1859 if roads.is_empty() && text.is_empty() {
1860 return proc_macro2::TokenStream::new();
1861 }
1862 let tier = self.tier();
1863 let ag = framework(&self.krate, &[], "async_graphql");
1864 let shelf = crate::emit::vendored(&self.krate, "async_graphql");
1865 let gate = framework(&self.krate, &["gate"], "if_async_graphql");
1866 let prelude = crate::emit::wire::prelude();
1867 let unit = self.queries_name();
1868 // The unit's own SDL name is its Rust name: a `MergedObject` fold takes the FIELDS and never
1869 // publishes the type that carried them, so this string reaches no schema — it is written
1870 // because `#[Object]` takes one, on the interface unit's own precedent.
1871 let unit_sdl = unit.to_string();
1872
1873 let mut declared = Vec::new();
1874 let mut faces = Vec::new();
1875 // THE FULL-TEXT LEGS FIRST, and they need neither a question type of their own nor an answer
1876 // face: the tier already mints the question package and the selector, so what this road adds is
1877 // the resolver and nothing else.
1878 let mut legs = text;
1879 let mut hydrated = Vec::new();
1880 let mut elections = Vec::new();
1881 for (elected, road) in roads {
1882 elections.push(elected);
1883 let (types, face) = self.question_input(&tier, elected);
1884 declared.push(types);
1885 faces.push(face);
1886 match road {
1887 AnswerRoad::Plain(engine) => {
1888 legs.push(self.keys_leg(&tier, elected, engine));
1889 // THE BY-EXAMPLE ROAD, beside the question road and on the SAME condition — one typed
1890 // store. It needs nothing the plain road did not already need: the door it calls takes a
1891 // `SlotHandle` and no `AsyncGather`, so the wall that holds tier B holds nothing here.
1892 legs.push(self.similar_leg(&tier, elected, engine));
1893 // THE TWO HYDRATED TWINS, held apart because they need what the two above do not: a
1894 // STORE. They name `SqlDoor` and `SqlPooledGather`, so they exist per SQL FAMILY where
1895 // everything beside them exists per build — see the gate pair below — and they exist at
1896 // all only where the upstream HAS rows, which is [`IndexModel::keys`]'s whole subject.
1897 if !self.keys {
1898 hydrated.push(self.hydrated_leg(&tier, elected, engine));
1899 hydrated.push(self.similar_hydrated_leg(&tier, elected, engine));
1900 }
1901 }
1902 // THE LABEL MOVES BOTH PAIRS, and the question one moved last. A set election's `question`
1903 // is `m` POINTS rather than one — the `_with` road's own wire surface, minted by the
1904 // 2026-08-16 SET ruling — so all four legs here call a `_with` door and answer the folded
1905 // hit. NO NAME MOVES: the four fields are the same four strings a unit election publishes.
1906 AnswerRoad::Set(engine) => {
1907 legs.push(self.set_keys_leg(&tier, elected, engine));
1908 legs.push(self.similar_set_leg(&tier, elected, engine));
1909 if !self.keys {
1910 hydrated.push(self.set_hydrated_leg(&tier, elected, engine));
1911 hydrated.push(self.similar_set_hydrated_leg(&tier, elected, engine));
1912 }
1913 }
1914 AnswerRoad::Fanned(ref slot_legs) => {
1915 let (types, face) = self.fused_answer(&tier, elected, slot_legs);
1916 declared.push(types);
1917 faces.push(face);
1918 legs.push(self.fused_leg(&tier, elected, slot_legs));
1919 }
1920 }
1921 }
1922 let bindings = self.answer_bindings(&elections);
1923 // THE UNIT'S FACE, WRITTEN TWICE — the `if_sqlx` pair, and the shape is forced rather than
1924 // chosen. A type has ONE `#[Object]` impl (a second is `E0119` on `ObjectType` before any schema
1925 // exists) and the attribute reads the impl block whole, so a gate written around one METHOD
1926 // would be a `macro_rules!` invocation the attribute expands before and never a field. The
1927 // serde pair's sentence at a different grain: what a macro cannot do is ADD to something that
1928 // has already been parsed, so the block is written twice and exactly one half survives.
1929 //
1930 // The halves differ in the hydrated legs and in nothing else, so the shut half is byte-for-byte
1931 // the unit a build without the SQL family already had.
1932 let object = |also: &[proc_macro2::TokenStream]| {
1933 quote! {
1934 #[#ag::Object(crate = #shelf, name = #unit_sdl)]
1935 impl #unit {
1936 #(#legs)*
1937 #(#also)*
1938 }
1939 }
1940 };
1941 // A declaration with NO hydrated leg gets ONE block and no pair at all, which is what keeps the
1942 // gate honest at both ends: a purely fanned declaration's expansion is byte-for-byte what it
1943 // was, and the projections — which demand `Hydrates` of the upstream — are written only where a
1944 // road spends them. A demand emitted for a road that does not exist would refuse a fanned
1945 // declaration over an unstored upstream for a field it never publishes.
1946 let face = if hydrated.is_empty() {
1947 object(&[])
1948 } else {
1949 let hydration = self.hydration_bindings();
1950 let (whole, bare) = (object(&hydrated), object(&[]));
1951 let sqlx = framework(&self.krate, &["gate"], "if_sqlx");
1952 let without = framework(&self.krate, &["gate"], "if_no_sqlx");
1953 quote! {
1954 #sqlx! {
1955 #hydration
1956
1957 #whole
1958 }
1959
1960 #without! {
1961 #bare
1962 }
1963 }
1964 };
1965
1966 quote! {
1967 #(#declared)*
1968
1969 #gate! {
1970 const _: () = {
1971 #prelude
1972
1973 #bindings
1974
1975 #(#faces)*
1976
1977 #face
1978 };
1979 }
1980 }
1981 }
1982
1983 /// **THE FULL-TEXT KEYS ROAD's QUERY FIELD** — one searchable field, one pointed resource, a
1984 /// ranked list of addresses.
1985 ///
1986 /// # It is [`keys_leg`](Self::keys_leg) with the QUESTION changed and nothing else
1987 ///
1988 /// A vector road is asked with COORDINATES, which have a width, a space and an element and are
1989 /// checked against the election's own geometry. A full-text road is asked with a STRING against
1990 /// whatever grammar the engine has — `store::fulltext`'s own division — so the whole point
1991 /// binding disappears and what is left is the text, taken off the tier's question package. The
1992 /// floor, the numbers, the page cut and the crossing are the vector road's, unchanged, because
1993 /// nothing about them is vector-flavoured.
1994 ///
1995 /// # ONE FIELD PER SEARCHABLE FIELD, because a SLOT is per election
1996 ///
1997 /// The corpus a search runs over is `(field × label)`, so two searchable fields are two corpora
1998 /// with two universes of BM25 statistics and no handle can serve both. The whole-subject door
1999 /// (`retrieve_keys`, `FulltextSubset::All`) is the Rust surface a caller that opened ONE slot
2000 /// reaches; what the wire publishes is the per-field pair, whose subset the emitted door mints
2001 /// from the field's own name.
2002 ///
2003 /// # The SELECTOR is at the DECLARATION grain
2004 ///
2005 /// A full-text declaration is ONE ROUTE however many fields it elects — the tier's own law — so
2006 /// the `engine` seat is `<Index>EngineInput` rather than a per-field one. Two fields therefore
2007 /// read their floor out of the same package, which is right: the floor is in the ENGINE's score
2008 /// currency and both fields are held by the same engine.
2009 fn text_keys_leg(
2010 &self,
2011 tier: &crate::fuse::Tier<'_>,
2012 field: &syn::Ident,
2013 engine: &Engine,
2014 ) -> proc_macro2::TokenStream {
2015 let IndexModel { krate, index, .. } = self;
2016 let ag = framework(krate, &[], "async_graphql");
2017 let seam = framework(krate, &["store"], "FulltextEngine");
2018 let hit = framework(krate, &["graphql"], "Match");
2019 let crossed = framework(krate, &["graphql"], "matches");
2020 let ranked = framework(krate, &["retrieve"], "Ranked");
2021 let query = framework(krate, &["retrieve"], "FulltextQuery");
2022 let connected = framework(krate, &["store"], "Connected");
2023 let ty = engine
2024 .resource
2025 .as_ref()
2026 .expect("a published full-text leg points at a resource");
2027 let handle = self.wire_handle(ty);
2028 let mint = self.wire_corpus(
2029 field,
2030 None,
2031 engine,
2032 ty,
2033 &format_ident!("__ingraph_slot"),
2034 &format_ident!("__ingraph_connection"),
2035 );
2036 let question = tier
2037 .question_name()
2038 .expect("a full-text tier mints its question");
2039 let selector = tier
2040 .subject_selector()
2041 .expect("a pointed full-text declaration mints its engine selector");
2042 let variant = format_ident!("{}", {
2043 use heck::ToUpperCamelCase as _;
2044 engine.word.to_string().to_upper_camel_case()
2045 });
2046 let key = wire_key_name();
2047 let sdl = self.road_name(field, Field::Keys);
2048 let method = crate::method::wire_method(&format_ident!("{}", crate::emit::snake(&sdl)));
2049 // THE WHOLE-SUBJECT DOOR, and the per-field one is deliberately NOT called — which is the slot
2050 // grain read at its own conclusion. A corpus is `(field × label)`, so everything inside the one
2051 // this leg opened belongs to THIS election and `FulltextSubset::All` is the honest scope. The
2052 // per-field door narrows by a `FulltextColumn` named after the ELECTION, which asks the backend
2053 // to have named its column that: the shipped engine's slot schema calls its one text field
2054 // `body` whatever elected it, so a subset spelled from the field's name is refused by the
2055 // engine at run time. `retrieve_keys_by_<field>` remains the Rust surface for a deployment that
2056 // opened ONE slot holding several columns.
2057 let door = format_ident!("retrieve_keys");
2058 let arity = wide_signature();
2059 let numbers = self.answer_numbers(field);
2060 // THE SCOPE — `keys_leg`'s own, one family over: the CONNECTION is the mount's manager and the
2061 // read scope is the unit, spanned at the `resource = "…"` path the author wrote.
2062 let scope = quote_spanned! {ty.span()=>
2063 #connected::new(__ingraph_connection, ())
2064 };
2065 let (floor, options) = (
2066 format_ident!("__ingraph_floor"),
2067 format_ident!("__ingraph_options"),
2068 );
2069 let floorless = format!(
2070 "`{sdl}` needs a floor in `{engine_word}`'s own score currency — write \
2071 `engine: {{ {engine_word}: {{ floor: … }} }}`. There is no number this framework could put \
2072 there instead: a score's DIRECTION belongs to the engine that measures in it, and a BM25 \
2073 score is unbounded above.",
2074 engine_word = engine.word,
2075 );
2076 let doc = leading(&format!(
2077 "The addresses [`{index}`]'s `{field}` ranks against a question, in `{engine_word}`.",
2078 engine_word = engine.word,
2079 ));
2080 let ctx = crate::method::wire_method(&format_ident!("ctx"));
2081 let (asked, chosen, first, depth) = (
2082 crate::method::wire_method(&format_ident!("question")),
2083 crate::method::wire_method(&format_ident!("engine")),
2084 crate::method::wire_method(&format_ident!("first")),
2085 crate::method::wire_method(&format_ident!("depth")),
2086 );
2087 let default = self
2088 .wire_first(GraphqlKind::AsyncGraphql, Some(field))
2089 .get();
2090 let default = syn::LitInt::new(&default.to_string(), field.span());
2091 quote! {
2092 #[doc = #doc]
2093 #[graphql(name = #sdl)]
2094 #arity
2095 async fn #method(
2096 &self,
2097 #ctx: &#ag::Context<'_>,
2098 #[graphql(name = "question")] #asked: #question,
2099 #[graphql(name = "engine")] #chosen: ::core::option::Option<#selector>,
2100 #[graphql(name = "first", default = #default)] #first: u32,
2101 #[graphql(name = "depth")] #depth: ::core::option::Option<u32>,
2102 ) -> #ag::Result<::std::vec::Vec<#hit<#key, <#ty as #seam>::Score>>> {
2103 #numbers
2104 // A QUESTION NOBODY ASKED IS THE EMPTY ANSWER, not the whole corpus — `participates`' law
2105 // at the one seat this road has.
2106 let ::core::option::Option::Some(__ingraph_text) = #question::question(&#asked) else {
2107 return ::core::result::Result::Ok(::std::vec::Vec::new());
2108 };
2109 let (#floor, #options) = match #chosen {
2110 ::core::option::Option::Some(#selector::#variant(ref __ingraph_named)) => (
2111 // `Option::map` OVER `Option::cloned`: the latter is inherent on BOTH `Option<&T>` and
2112 // `Option<&mut T>`, so a path call is `E0034` at a span the author cannot edit.
2113 ::core::option::Option::map(__ingraph_named.floor(), ::core::clone::Clone::clone),
2114 __ingraph_named.options(),
2115 ),
2116 ::core::option::Option::None => (
2117 ::core::option::Option::None,
2118 ::core::option::Option::None,
2119 ),
2120 };
2121 let ::core::option::Option::Some(#floor) = #floor else {
2122 return ::core::result::Result::Err(#ag::Error::new(#floorless));
2123 };
2124 #mint
2125 let __ingraph_query = #query::new(
2126 ::std::string::String::clone(__ingraph_text),
2127 #floor,
2128 );
2129 let mut __ingraph_ranked: ::std::vec::Vec<#ranked<_, _>> = #index::#door::<#handle>(
2130 &mut __ingraph_slot,
2131 #scope,
2132 &__ingraph_query,
2133 __ingraph_fetch,
2134 #options,
2135 )
2136 .await
2137 .map_err(|__ingraph_refusal| {
2138 #ag::Error::new(::std::string::ToString::to_string(&__ingraph_refusal))
2139 })?;
2140 // THE PAGE, cut after the walk: `depth` bought the FETCH and `first` is what a client asked
2141 // to read, and the two are different numbers whenever the floor or the dedup pruned.
2142 ::std::vec::Vec::truncate(
2143 &mut __ingraph_ranked,
2144 ::core::num::NonZeroUsize::get(__ingraph_page),
2145 );
2146 ::core::result::Result::Ok(#crossed(
2147 ::core::iter::Iterator::map(
2148 ::std::vec::Vec::into_iter(__ingraph_ranked),
2149 |__ingraph_hit| {
2150 let __ingraph_key = ::core::clone::Clone::clone(#ranked::node_ref(&__ingraph_hit));
2151 #ranked::map_node(
2152 __ingraph_hit,
2153 <#key as ::core::convert::From<_>>::from(__ingraph_key),
2154 )
2155 },
2156 ),
2157 ))
2158 }
2159 }
2160 }
2161
2162 /// EVERY FULL-TEXT WIRE LEG this declaration publishes — one per (searchable field × POINTED leg).
2163 ///
2164 /// An unpointed leg publishes nothing, which is the presence law this family already keeps: there
2165 /// is no `E` for the expansion to spell, so there is no resolver to write. A declaration whose
2166 /// legs are all unpointed mounts the Rust surface whole and no wire field at all.
2167 fn text_roads(&self) -> Vec<proc_macro2::TokenStream> {
2168 if !self.mounts() || self.kind != NodeKind::Fulltext {
2169 return Vec::new();
2170 }
2171 let tier = self.tier();
2172 if tier.subject_selector().is_none() {
2173 return Vec::new();
2174 }
2175 self
2176 .engines
2177 .iter()
2178 .filter(|declared| self.searchable.contains(&declared.field))
2179 .flat_map(|declared| {
2180 declared
2181 .engines
2182 .iter()
2183 .filter(|engine| engine.resource.is_some())
2184 .map(|engine| self.text_keys_leg(&tier, &declared.field, engine))
2185 })
2186 .collect()
2187 }
2188
2189 /// The THREE PROJECTIONS every answer face reads, bound to names inside the face's own `const`.
2190 ///
2191 /// The width lands in CONST-ARGUMENT position, where a qualified path is not a legal const
2192 /// argument and two braced blocks of identical text are two anonymous constants that do not unify
2193 /// — the measurement [`geometry_bindings`](Self::geometry_bindings) already made one const block
2194 /// over. Its bindings cannot be reached from here: they live inside the expansion's OTHER
2195 /// anonymous const, and a name in one is a name in one.
2196 ///
2197 /// The WIRE KEY is bound here for a different reason and it is the round's one open question: a
2198 /// hit's `node` is the upstream's ADDRESS OBJECT, whose name this expansion cannot spell — two
2199 /// derives are blind to each other — so it is reached as a projection off the upstream path the
2200 /// declaration wrote. Spanned at that path, so an upstream that publishes no wire face is `E0277`
2201 /// on `upstream(node = "…")` rather than inside an expansion.
2202 ///
2203 /// The EXAMPLE KEY is bound for that same reason at the other end of the same address: the
2204 /// by-example road takes the upstream's OWN key, whose name this expansion cannot spell either, so
2205 /// it is the same kind of projection at the same span. Its wire form is a second projection on top
2206 /// — `<Key as ToGraphqlInput>::Input` — which is where the root/compound fork is decided, by the
2207 /// RECORD's emission and never by this one.
2208 fn answer_bindings(&self, elections: &[&Elected]) -> proc_macro2::TokenStream {
2209 let krate = &self.krate;
2210 let marker = framework(krate, &["election"], "EmbeddingMarker");
2211 let shape = framework(krate, &["election"], "EmbeddingShape");
2212 let transformer = framework(krate, &["transform"], "Transformer");
2213 let face = framework(krate, &["transform"], "Graphql");
2214 let output = framework(krate, &["transform"], "GraphqlOutput");
2215 let upstream = &self.source.node;
2216 let key = wire_key_name();
2217 let example = example_key_name();
2218 // SPANNED AT `upstream(node = "…")`, which is the token an author edits when the projection has
2219 // nothing to resolve to.
2220 let at = upstream.span();
2221 let projected = quote_spanned! {at=>
2222 #[allow(dead_code, non_camel_case_types)]
2223 type #key = <<<#upstream as #transformer>::Graphql as #face>::Output as #output>::Key;
2224 #[allow(dead_code, non_camel_case_types)]
2225 type #example = <#upstream as #transformer>::Key;
2226 };
2227 let geometry = elections.iter().map(|elected| {
2228 let (width, space, element) = answer_geometry(elected);
2229 let ty = &elected.ty;
2230 let at = elected.field.span();
2231 quote_spanned! {at=>
2232 #[allow(dead_code, non_upper_case_globals)]
2233 const #width: usize = <<#ty as #marker>::Item as #shape>::WIDTH;
2234 #[allow(dead_code, non_camel_case_types)]
2235 type #space = <<#ty as #marker>::Item as #shape>::Space;
2236 #[allow(dead_code, non_camel_case_types)]
2237 type #element = <<#ty as #marker>::Item as #shape>::Element;
2238 }
2239 });
2240 quote! {
2241 #projected
2242 #(#geometry)*
2243 }
2244 }
2245
2246 /// **THE QUESTION** one election is asked with — an `@oneOf` input over the ways of naming a
2247 /// point, and today there is one of them.
2248 ///
2249 /// # `@oneOf` at ONE arm is deliberate, and it is the selector's own argument
2250 ///
2251 /// A choice-shaped input with one variant publishes the same shape a second modality will join —
2252 /// `text:` walked into these coordinates by a TOWER, an `example:` key — so the day one arrives
2253 /// it is an ADDED variant rather than a changed shape, and a client written today keeps working.
2254 /// The engine selector beside it made that argument first and it holds here word for word.
2255 ///
2256 /// # It is NOT the tier's `<Index><Field>VectorQuestion`, and the difference is the CARRIER
2257 ///
2258 /// That package holds an `Embedding<E, N, S>` — the declaration's own type, width-checked at
2259 /// construction — and `Row::rust_side` marks it as the one row of either tree with no wire form,
2260 /// because there is no `InputType` for a width a client cannot see. This type is the wire's side
2261 /// of the same fact: a list of coordinates, whose width is checked BY THE RESOLVER against
2262 /// the projection, so the refusal names the field and both numbers instead of failing to parse.
2263 ///
2264 /// # ONE LIST DEEPER ON A SET ELECTION, and that is the whole of the label's effect here
2265 ///
2266 /// Ruled 2026-08-16. A `list(embedding)` election's question road is the `_with` road, which is
2267 /// asked with `m` POINTS rather than one — so the SAME arm carries a list of them:
2268 ///
2269 /// ```text
2270 /// #[ingraph(embedding, …)] coordinates: [f32!] one point
2271 /// #[ingraph(list(embedding), …)] coordinates: [[f32!]!] m of them
2272 /// ```
2273 ///
2274 /// Nothing is invented for it: the arm WORD is reused, the EMPTY list reuses `FoldedQuery`'s own
2275 /// refusal, and the depth is the one dimension that moved. A second question TYPE would have been
2276 /// the invention, and the label already routes the by-example road the same way.
2277 ///
2278 /// # THE ELEMENT CROSSES ON THE ROSTER'S CARRIER, and that is a CURRENCY rather than a form
2279 ///
2280 /// Ruled 2026-08-18. This arm published async-graphql's own `Float` for an `f32` election, because
2281 /// the element crossed on its own face and that face is the library's. `Float` is GraphQL's
2282 /// DOUBLE-precision scalar, so publishing an `f32` coordinate under it is a width misreported —
2283 /// the same silence the whole scalar suite exists to end, met one road over.
2284 ///
2285 /// The arm's wire type is `<Element as ToGraphqlInput>::Input` now: the roster carrier the element
2286 /// already had, which for `f32` is `F32` and publishes the scalar `f32`. The constitution's
2287 /// *currencies cross AS THEMSELVES* is what this obeys rather than what it breaks — an `f32` has a
2288 /// name of its own in this framework, so crossing as itself IS crossing as `f32`. An election over
2289 /// a roster carrier is unchanged, its carrier's own crossing being the identity.
2290 ///
2291 /// The CONVERSION work is zero: the `Float` road already narrowed a double to an `f32` inside
2292 /// async-graphql's own impl, and `F32`'s scalar narrows the same `f64` in the same place. What
2293 /// moved is the NAME a client reads and the two total hops the arm now spells, one per coordinate.
2294 fn question_input(
2295 &self,
2296 tier: &crate::fuse::Tier<'_>,
2297 elected: &Elected,
2298 ) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
2299 let IndexModel {
2300 vis, krate, index, ..
2301 } = self;
2302 let ag = framework(krate, &[], "async_graphql");
2303 let marker = framework(krate, &["election"], "EmbeddingMarker");
2304 let shape = framework(krate, &["election"], "EmbeddingShape");
2305 let crossing = framework(krate, &["graphql"], "ToGraphqlInput");
2306 let name = self.question_name(tier, elected);
2307 let sdl = tier.packages().sdl(&name);
2308 let ty = &elected.ty;
2309 let (_, _, element) = answer_geometry(elected);
2310 let field = &elected.field;
2311 let doc = leading(&format!(
2312 "The question [`{index}`]'s `{field}` is asked over the wire — one way of naming a point, and \
2313 exactly one per request.\n\nA CHOICE rather than a record, on the engine selector's own \
2314 argument: naming two ways of saying where to look is two requests, and a second way arrives \
2315 as a second variant rather than as a changed shape."
2316 ));
2317 // THE LABEL DECIDES THE DEPTH, and nothing else about this type: a set election's question road
2318 // is the `_with` road, which is asked with `m` points.
2319 let set = elected.label.is_set();
2320 let coordinates = leading(&if set {
2321 format!(
2322 "The POINTS themselves, one list of coordinates each — every one as wide as `{field}` embeds \
2323 at, which the resolver checks per point and names the offending one when it does not \
2324 hold.\n\nAn EMPTY list is refused: a set query with no query vectors asks nothing."
2325 )
2326 } else {
2327 format!(
2328 "The point itself, coordinate by coordinate — as many as `{field}` embeds at, which the \
2329 resolver checks and names both numbers when it does not hold."
2330 )
2331 });
2332 // The ARM's HELD type and its WIRE type. They are NOT the same shape any more: the held one is
2333 // the election's own element, spelled through the projection the declaration owns; the wire one
2334 // is that element's ROSTER CARRIER, reached through the alias the face's const binds. See the
2335 // currency note above for why the two parted.
2336 let held = quote!(<<#ty as #marker>::Item as #shape>::Element);
2337 let carrier = quote!(<#element as #crossing>::Input);
2338 let (held, carried) = if set {
2339 (
2340 quote!(::std::vec::Vec<::std::vec::Vec<#held>>),
2341 quote!(::std::vec::Vec<::std::vec::Vec<#carrier>>),
2342 )
2343 } else {
2344 (
2345 quote!(::std::vec::Vec<#held>),
2346 quote!(::std::vec::Vec<#carrier>),
2347 )
2348 };
2349 // The two hops the carrier costs, one per coordinate, spelled by depth. `cross` is the wire's
2350 // refusal seat as well as its conversion — a carrier that cannot become its element says so in
2351 // the reading's own sentence, which `InputValueError::custom` carries verbatim to the client.
2352 let (crossed, carrying) = if set {
2353 (
2354 quote! {
2355 let mut __ingraph_points =
2356 ::std::vec::Vec::with_capacity(::std::vec::Vec::len(&__ingraph_chosen));
2357 for __ingraph_point in __ingraph_chosen {
2358 let mut __ingraph_coordinates =
2359 ::std::vec::Vec::with_capacity(::std::vec::Vec::len(&__ingraph_point));
2360 for __ingraph_coordinate in __ingraph_point {
2361 __ingraph_coordinates.push(
2362 <#element as #crossing>::cross(__ingraph_coordinate)
2363 .map_err(|__ingraph_refusal| #ag::InputValueError::custom(__ingraph_refusal))?,
2364 );
2365 }
2366 __ingraph_points.push(__ingraph_coordinates);
2367 }
2368 let __ingraph_chosen = __ingraph_points;
2369 },
2370 quote! {
2371 let __ingraph_carried: #carried = ::core::iter::Iterator::collect(
2372 ::core::iter::Iterator::map(
2373 ::core::iter::IntoIterator::into_iter(__ingraph_chosen),
2374 |__ingraph_point| ::core::iter::Iterator::collect(
2375 ::core::iter::Iterator::map(
2376 ::core::iter::IntoIterator::into_iter(__ingraph_point),
2377 <#element as #crossing>::carry,
2378 ),
2379 ),
2380 ),
2381 );
2382 },
2383 )
2384 } else {
2385 (
2386 quote! {
2387 let mut __ingraph_coordinates =
2388 ::std::vec::Vec::with_capacity(::std::vec::Vec::len(&__ingraph_chosen));
2389 for __ingraph_coordinate in __ingraph_chosen {
2390 __ingraph_coordinates.push(
2391 <#element as #crossing>::cross(__ingraph_coordinate)
2392 .map_err(|__ingraph_refusal| #ag::InputValueError::custom(__ingraph_refusal))?,
2393 );
2394 }
2395 let __ingraph_chosen = __ingraph_coordinates;
2396 },
2397 quote! {
2398 let __ingraph_carried: #carried = ::core::iter::Iterator::collect(
2399 ::core::iter::Iterator::map(
2400 ::core::iter::IntoIterator::into_iter(__ingraph_chosen),
2401 <#element as #crossing>::carry,
2402 ),
2403 );
2404 },
2405 )
2406 };
2407 let declared = quote! {
2408 #[doc = #doc]
2409 #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
2410 #vis enum #name {
2411 #[doc = #coordinates]
2412 Coordinates(#held),
2413 }
2414 };
2415 let face = quote! {
2416 #[automatically_derived]
2417 impl #ag::InputType for #name {
2418 type RawValueType = Self;
2419
2420 #[inline]
2421 fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
2422 ::std::borrow::Cow::Borrowed(#sdl)
2423 }
2424
2425 fn create_type_info(
2426 __ingraph_registry: &mut #ag::registry::Registry,
2427 ) -> ::std::string::String {
2428 __ingraph_registry.create_input_type::<Self, _>(
2429 #ag::registry::MetaTypeId::InputObject,
2430 |__ingraph_registry| #ag::registry::MetaType::InputObject {
2431 name: ::std::string::String::from(#sdl),
2432 description: ::core::option::Option::None,
2433 input_fields: {
2434 let mut __ingraph_fields = #ag::indexmap::IndexMap::new();
2435 __ingraph_fields.insert(
2436 ::std::string::String::from("coordinates"),
2437 #ag::registry::MetaInputValue {
2438 name: ::std::string::String::from("coordinates"),
2439 description: ::core::option::Option::None,
2440 ty: <::core::option::Option<#carried> as #ag::InputType>::create_type_info(
2441 __ingraph_registry,
2442 ),
2443 deprecation: #ag::registry::Deprecation::NoDeprecated,
2444 default_value: ::core::option::Option::None,
2445 visible: ::core::option::Option::None,
2446 inaccessible: false,
2447 tags: ::std::vec::Vec::new(),
2448 is_secret: false,
2449 directive_invocations: ::std::vec::Vec::new(),
2450 },
2451 );
2452 __ingraph_fields
2453 },
2454 visible: ::core::option::Option::None,
2455 inaccessible: false,
2456 tags: ::std::vec::Vec::new(),
2457 rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
2458 oneof: true,
2459 directive_invocations: ::std::vec::Vec::new(),
2460 },
2461 )
2462 }
2463
2464 fn parse(
2465 __ingraph_value: ::core::option::Option<#ag::Value>,
2466 ) -> #ag::InputValueResult<Self> {
2467 if let ::core::option::Option::Some(#ag::Value::Object(mut __ingraph_object)) =
2468 __ingraph_value
2469 {
2470 // EXACTLY ONE KEY, which is the whole of what `@oneOf` means — the validator refuses a
2471 // request naming two or none before anything runs, and this is the arm that reads the
2472 // one it admitted.
2473 if #ag::indexmap::IndexMap::contains_key(&__ingraph_object, "coordinates")
2474 && __ingraph_object.len() == 1
2475 {
2476 let __ingraph_chosen = <#carried as #ag::InputType>::parse(
2477 #ag::indexmap::IndexMap::swap_remove(&mut __ingraph_object, "coordinates"),
2478 )
2479 .map_err(#ag::InputValueError::propagate)?;
2480 #crossed
2481 return ::core::result::Result::Ok(Self::Coordinates(__ingraph_chosen));
2482 }
2483 return ::core::result::Result::Err(#ag::InputValueError::expected_type(
2484 #ag::Value::Object(__ingraph_object),
2485 ));
2486 }
2487 ::core::result::Result::Err(#ag::InputValueError::expected_type(
2488 ::core::option::Option::unwrap_or_default(__ingraph_value),
2489 ))
2490 }
2491
2492 fn to_value(&self) -> #ag::Value {
2493 let mut __ingraph_map = #ag::indexmap::IndexMap::new();
2494 match self {
2495 Self::Coordinates(__ingraph_chosen) => {
2496 #carrying
2497 __ingraph_map.insert(
2498 #ag::Name::new("coordinates"),
2499 <#carried as #ag::InputType>::to_value(&__ingraph_carried),
2500 );
2501 }
2502 }
2503 #ag::Value::Object(__ingraph_map)
2504 }
2505
2506 #[inline]
2507 fn as_raw_value(&self) -> ::core::option::Option<&Self::RawValueType> {
2508 ::core::option::Option::Some(self)
2509 }
2510 }
2511
2512 #[automatically_derived]
2513 impl #ag::InputObjectType for #name {}
2514
2515 #[automatically_derived]
2516 impl #ag::OneofObjectType for #name {}
2517 };
2518 (declared, face)
2519 }
2520
2521 /// `<Index><Field>Question` — re-based by the BONES rename like every other minted name.
2522 fn question_name(&self, tier: &crate::fuse::Tier<'_>, elected: &Elected) -> syn::Ident {
2523 format_ident!("{}Question", tier.stem(elected))
2524 }
2525
2526 /// **WHAT ONE ELECTION'S QUERY FIELD IS CALLED** — the declared word verbatim, or the derived
2527 /// name.
2528 ///
2529 /// ```text
2530 /// #[ingraph(embedding, knn, lance(resource = "…"),
2531 /// graphql(async_graphql(keys(rename = "clipNeighbours"))))]
2532 /// └── replaces the whole name
2533 /// ```
2534 ///
2535 /// VERBATIM, and that is the choice worth stating: the derived name is composed from three parts
2536 /// — the declaration, the election and the road — so a word that re-cased or re-composed what an
2537 /// author wrote would be a rename they could not predict from what they typed. The front end
2538 /// holds it to GraphQL's own Name grammar at the literal, which is where a caret can land.
2539 ///
2540 /// # The resolution is MEMBER, then BASE-DERIVED, then DEFAULT
2541 ///
2542 /// The road's own word answers first. Where it wrote none, the DERIVED half reads the rename-aware
2543 /// base, so `rename = "…"` moves the field with the rest of the family; and where the declaration
2544 /// wrote no base either, the derived name is built on its own ident. The declared half never moves
2545 /// with a base, being a name in the SCHEMA's namespace rather than Rust's.
2546 ///
2547 /// # FIVE seats for five roads, which is what closed the composition question
2548 ///
2549 /// A declared word is VERBATIM, so it cannot be composed: a seat for the keys road says nothing
2550 /// about what its hydrated twin should be called, and deriving `clipNeighboursHydrated` from
2551 /// `clipNeighbours` would be the composition the verbatim law refuses. Two more seats was
2552 /// therefore the only shape a word for the hydrated roads could take, and the 2026-08-16 rename
2553 /// ruling minted them — so the seat set and [`Field`] are now one closed five, matched by
2554 /// [`ElectionBackend::road`] where a missing arm is a compile error rather than a silent fallback.
2555 #[must_use]
2556 pub fn field_name(&self, elected: &Elected, which: Field) -> String {
2557 self.road_name(&elected.field, which)
2558 }
2559
2560 /// [`field_name`](Self::field_name) over a bare ident — the shape the FULL-TEXT kind has, whose
2561 /// elections carry a name and nothing else.
2562 ///
2563 /// One body for both, so the rename seat a vector election reads and the one a searchable field
2564 /// reads cannot come to disagree about which word wins.
2565 #[must_use]
2566 pub fn road_name(&self, field: &syn::Ident, which: Field) -> String {
2567 self
2568 .numbers_of(field)
2569 .and_then(|written| written.skin(GraphqlKind::AsyncGraphql))
2570 .and_then(|skin| skin.road(which))
2571 .map_or_else(|| which.derived(self.base(), field), syn::LitStr::value)
2572 }
2573
2574 /// **THE KEYS ROAD's QUERY FIELD** — one election, one typed store, a ranked list of addresses.
2575 ///
2576 /// # The ANSWER is the framework's [`Match<N, S>`], and nothing is minted for it
2577 ///
2578 /// `ingraph::Match` was written FOR this field — its own note says so — and it carries exactly
2579 /// what a retrieve produces: the engine's score in its own currency, the engine's ordinal with
2580 /// the pipeline's holes left in, and the thing that matched. Minting a two-row `{key, score}`
2581 /// object beside it would have dropped the ordinal, which is the number a client continues a
2582 /// single-shot answer from, and would have put a second hit shape in a schema that already has
2583 /// one. The SDL name is the NODE's, computed through async-graphql's `TypeName` hook — so the
2584 /// field answers `[<UpstreamKey>Match!]!` and two declarations over one upstream publish one hit
2585 /// type rather than two.
2586 ///
2587 /// # The FLOOR comes from the request, because the framework has no zero to invent
2588 ///
2589 /// `VectorEngine::Score` is bounded by `PartialOrd` and nothing else, so `Default::default()` is
2590 /// not spellable — and it would be wrong where it is: the walk's test is `score >= floor` on a
2591 /// score-DESCENDING stream, and the DIRECTION of an engine's currency is the engine's. A zero is
2592 /// neutral for a similarity and prunes the whole corpus for anything measured the other way. Every
2593 /// emitted Rust door takes its floor positionally from its caller for exactly this reason; the
2594 /// caller here is the request, and the ruled seat a request already has for it is the `engine`
2595 /// selector's own `floor` row. A request that names none is REFUSED by name — 宁短不凑, the
2596 /// ruling the mandatory floor exists for.
2597 ///
2598 /// # `first` is the PAGE and `depth` is the FETCH, and both are capped by the wall
2599 ///
2600 /// The door takes one number, which is both the engine's `k` and the survivor budget. So `depth`
2601 /// spends it — how deep the stream is walked, where the floor and the dedup do their pruning —
2602 /// and the answer is then cut to `first`. Both go through `route_depth`, which is where the
2603 /// declared ceiling caps an ask it can never be raised past.
2604 ///
2605 /// `first: 0` answers the empty list WITHOUT reaching the door, which is the edge-zero law: the
2606 /// door's currency is `NonZeroUsize`, so a zero is not a smaller question but no question at all.
2607 fn keys_leg(
2608 &self,
2609 tier: &crate::fuse::Tier<'_>,
2610 elected: &Elected,
2611 engine: &Engine,
2612 ) -> proc_macro2::TokenStream {
2613 let IndexModel { krate, index, .. } = self;
2614 let ag = framework(krate, &[], "async_graphql");
2615 let seam = framework(krate, &["store"], "VectorEngine");
2616 let hit = framework(krate, &["graphql"], "Match");
2617 let crossed = framework(krate, &["graphql"], "matches");
2618 let ranked = framework(krate, &["retrieve"], "Ranked");
2619 let query = framework(krate, &["retrieve"], "VectorQuery");
2620 let connected = framework(krate, &["store"], "Connected");
2621 let field = &elected.field;
2622 let ty = engine
2623 .resource
2624 .as_ref()
2625 .expect("a plain road names a typed engine");
2626 let handle = self.wire_handle(ty);
2627 let mint = self.wire_corpus(
2628 field,
2629 Some(&elected.ty),
2630 engine,
2631 ty,
2632 &format_ident!("__ingraph_slot"),
2633 &format_ident!("__ingraph_connection"),
2634 );
2635 let question = self.question_name(tier, elected);
2636 let selector = tier
2637 .slot_selector(elected)
2638 .expect("a typed election mints its engine selector");
2639 let variant = format_ident!("{}", {
2640 use heck::ToUpperCamelCase as _;
2641 engine.word.to_string().to_upper_camel_case()
2642 });
2643 let key = wire_key_name();
2644 let sdl = self.field_name(elected, Field::Keys);
2645 let method = crate::method::wire_method(&format_ident!("{}", crate::emit::snake(&sdl)));
2646 let door = Door::Keys.name(field);
2647 let arity = wide_signature();
2648 let numbers = self.answer_numbers(&elected.field);
2649 let point = self.point_binding(&question, elected);
2650 // THE SCOPE, and HALF of it stopped being a seam. The CONNECTION is the mount's own manager,
2651 // handed back beside the corpus by the mint below — so a resolver no longer writes `&()` where
2652 // an engine expects its store, which is what made the whole road unreadable by the shipped
2653 // engine. The READ SCOPE is still the unit: a lease is a value only the caller that opened a
2654 // transaction has, and a request carries none. Spanned at the `resource = "…"` path, so a
2655 // resource whose read scope is not the unit is `E0308` naming both, ON THE WORD THE AUTHOR
2656 // WROTE, rather than inside an expansion.
2657 let scope = quote_spanned! {ty.span()=>
2658 #connected::new(__ingraph_connection, ())
2659 };
2660 let (floor, options) = (
2661 format_ident!("__ingraph_floor"),
2662 format_ident!("__ingraph_options"),
2663 );
2664 let floorless = format!(
2665 "`{sdl}` needs a floor in `{engine_word}`'s own score currency — write \
2666 `engine: {{ {engine_word}: {{ floor: … }} }}`. There is no number this framework could put \
2667 there instead: a score's DIRECTION belongs to the engine that measures in it, so a zero is \
2668 neutral for a similarity and prunes the whole corpus for a distance.",
2669 engine_word = engine.word,
2670 );
2671 let doc = leading(&format!(
2672 "The addresses [`{index}`]'s `{field}` ranks nearest a question, in `{engine_word}`.",
2673 engine_word = engine.word,
2674 ));
2675 let ctx = crate::method::wire_method(&format_ident!("ctx"));
2676 let (asked, chosen, first, depth) = (
2677 crate::method::wire_method(&format_ident!("question")),
2678 crate::method::wire_method(&format_ident!("engine")),
2679 crate::method::wire_method(&format_ident!("first")),
2680 crate::method::wire_method(&format_ident!("depth")),
2681 );
2682 let default = self
2683 .wire_first(GraphqlKind::AsyncGraphql, Some(field))
2684 .get();
2685 let default = syn::LitInt::new(&default.to_string(), field.span());
2686 quote! {
2687 #[doc = #doc]
2688 #[graphql(name = #sdl)]
2689 #arity
2690 async fn #method(
2691 &self,
2692 #ctx: &#ag::Context<'_>,
2693 #[graphql(name = "question")] #asked: #question,
2694 #[graphql(name = "engine")] #chosen: ::core::option::Option<#selector>,
2695 #[graphql(name = "first", default = #default)] #first: u32,
2696 #[graphql(name = "depth")] #depth: ::core::option::Option<u32>,
2697 ) -> #ag::Result<::std::vec::Vec<#hit<#key, <#ty as #seam>::Score>>> {
2698 #numbers
2699 #point
2700 let (#floor, #options) = match #chosen {
2701 ::core::option::Option::Some(#selector::#variant(ref __ingraph_named)) => (
2702 // `Option::map` OVER `Option::cloned`: the latter is inherent on BOTH `Option<&T>` and
2703 // `Option<&mut T>`, so a path call is `E0034` at a span the author cannot edit.
2704 ::core::option::Option::map(__ingraph_named.floor(), ::core::clone::Clone::clone),
2705 __ingraph_named.options(),
2706 ),
2707 ::core::option::Option::None => (
2708 ::core::option::Option::None,
2709 ::core::option::Option::None,
2710 ),
2711 };
2712 let ::core::option::Option::Some(#floor) = #floor else {
2713 return ::core::result::Result::Err(#ag::Error::new(#floorless));
2714 };
2715 #mint
2716 // NO TURBOFISH: every parameter of the query is decided by what it is handed — the width and
2717 // the space ride the point, the currency rides the floor — so a spelled one would be a
2718 // second statement of a fact the arguments already carry.
2719 let __ingraph_query = #query::new(__ingraph_point, #floor);
2720 let mut __ingraph_ranked: ::std::vec::Vec<#ranked<_, _>> = #index::#door::<#handle>(
2721 &mut __ingraph_slot,
2722 #scope,
2723 &__ingraph_query,
2724 __ingraph_fetch,
2725 #options,
2726 )
2727 .await
2728 .map_err(|__ingraph_refusal| {
2729 #ag::Error::new(::std::string::ToString::to_string(&__ingraph_refusal))
2730 })?;
2731 // THE PAGE, cut after the walk: `depth` bought the FETCH and `first` is what a client asked
2732 // to read, and the two are different numbers whenever the floor or the dedup pruned.
2733 ::std::vec::Vec::truncate(
2734 &mut __ingraph_ranked,
2735 ::core::num::NonZeroUsize::get(__ingraph_page),
2736 );
2737 ::core::result::Result::Ok(#crossed(
2738 ::core::iter::Iterator::map(
2739 ::std::vec::Vec::into_iter(__ingraph_ranked),
2740 |__ingraph_hit| {
2741 let __ingraph_key = ::core::clone::Clone::clone(#ranked::node_ref(&__ingraph_hit));
2742 #ranked::map_node(
2743 __ingraph_hit,
2744 <#key as ::core::convert::From<_>>::from(__ingraph_key),
2745 )
2746 },
2747 ),
2748 ))
2749 }
2750 }
2751 }
2752
2753 /// **THE BY-EXAMPLE ROAD's QUERY FIELD** — one election, one typed store, an EXAMPLE KEY in, the
2754 /// ranked addresses nearest it out, without the example.
2755 ///
2756 /// # It is emitted on the PLAIN ROAD's own condition, and nothing more is needed
2757 ///
2758 /// `retrieve_similar_by_<field>` takes a `SlotHandle` and no `AsyncGather` — `similar`'s own
2759 /// `the_similar_door_takes_no_store` reads that off the signature — so the wall that holds tier B
2760 /// holds none of this. What both roads need is the same thing: an `E` this expansion can spell,
2761 /// which is `lance(resource = "…")` and nowhere else.
2762 ///
2763 /// # The ARGUMENT is the upstream's KEY, crossing inward through the OPERAND MAP
2764 ///
2765 /// Ruled 2026-08-16. Two derives are blind to each other, so this expansion cannot see whether the
2766 /// upstream is a root or a child — and it does not have to: the wire form is
2767 /// `<Key as ToGraphqlInput>::Input`, and the RECORD's own emission decides what that is. A root
2768 /// answers with its ID's wire form and mints no type (`similarBy…(key: Int!)`); a compound key
2769 /// answers with the product input object beside its address object
2770 /// (`similarBy…(key: KeyframeKeyInput!)`). Both crossings are `ToGraphqlInput::cross` here, and
2771 /// the refusal is `refused_address` — the same word the record's own `get(id:)` refuses a wrong
2772 /// address under, so a client reads one code for one class of mistake.
2773 ///
2774 /// A SCALAR encoding of a compound key was refused by the same ruling: a two-column address
2775 /// packed into one string is a format a client has to be told out of band, which is a magic string
2776 /// at an API floor.
2777 ///
2778 /// # TWO READ SCOPES, because the door makes TWO engine calls
2779 ///
2780 /// The door reads the example's own embedding and then asks the `knn`, and `Connected` is
2781 /// deliberately not `Clone` — a scope may be a lease. Both carry the MOUNT's own manager, which
2782 /// the one lookup hands back beside the corpus, and both read scopes are the unit — spanned at
2783 /// the `resource = "…"` path for [`keys_leg`](Self::keys_leg)'s reason: a resource whose read
2784 /// scope is not the unit is `E0308` naming both, on the word the author wrote.
2785 ///
2786 /// # The NUMBERS, the FLOOR and the EDGE ZERO are the plain road's, unchanged
2787 ///
2788 /// [`answer_numbers`](Self::answer_numbers) and the `engine` selector's `floor` seat are shared
2789 /// rather than restated, which is what keeps the two roads from drifting at the one place both
2790 /// spend a wall. `depth` is the FETCH and `first` is the PAGE here too — and the door's own note
2791 /// adds the by-example reading of the gap between them: the example occupies one of the fetched
2792 /// hits whenever it is among them, so an answer one short of the fetch is ordinary.
2793 ///
2794 /// # THIS LEG IS THE UNIT ELECTION'S, and a SET election takes its twin instead
2795 ///
2796 /// `retrieve_similar_by_<field>` is still emitted for every election whatever its label, and this
2797 /// leg is what calls it — but only where the label says ONE. A `list(embedding)` election's
2798 /// published field is the same NAME reaching
2799 /// [`similar_set_leg`](Self::similar_set_leg) instead, which calls the `_with` twin and answers
2800 /// the set hit; see [`answer_road`](Self::answer_road) for the routing and for the runtime
2801 /// refusal it ends. The two legs are exclusive, so nothing here has to know which one ran.
2802 fn similar_leg(
2803 &self,
2804 tier: &crate::fuse::Tier<'_>,
2805 elected: &Elected,
2806 engine: &Engine,
2807 ) -> proc_macro2::TokenStream {
2808 let IndexModel { krate, index, .. } = self;
2809 let ag = framework(krate, &[], "async_graphql");
2810 let seam = framework(krate, &["store"], "VectorEngine");
2811 let hit = framework(krate, &["graphql"], "Match");
2812 let crossed = framework(krate, &["graphql"], "matches");
2813 let crossing = framework(krate, &["graphql"], "ToGraphqlInput");
2814 let refused_address = framework(krate, &["graphql"], "refused_address");
2815 let ranked = framework(krate, &["retrieve"], "Ranked");
2816 let connected = framework(krate, &["store"], "Connected");
2817 let field = &elected.field;
2818 let ty = engine
2819 .resource
2820 .as_ref()
2821 .expect("a plain road names a typed engine");
2822 let selector = tier
2823 .slot_selector(elected)
2824 .expect("a typed election mints its engine selector");
2825 let variant = format_ident!("{}", {
2826 use heck::ToUpperCamelCase as _;
2827 engine.word.to_string().to_upper_camel_case()
2828 });
2829 let key = wire_key_name();
2830 let example = example_key_name();
2831 let sdl = self.field_name(elected, Field::Similar);
2832 let method = crate::method::wire_method(&format_ident!("{}", crate::emit::snake(&sdl)));
2833 let door = Door::Similar.name(field);
2834 let arity = wide_signature();
2835 let numbers = self.answer_numbers(&elected.field);
2836 // TWO of them, because the door takes two and a `Connected` is not `Clone` — the door's own
2837 // measurement, spent here rather than restated. Both carry the MOUNT's own manager, which the
2838 // mint below hands back beside the corpus: a stateless handle reaches its index through it, and
2839 // taking the two from one lookup is what stops a handle and a connection coming from two mounts.
2840 let handle = self.wire_handle(ty);
2841 let mint = self.wire_corpus(
2842 field,
2843 Some(&elected.ty),
2844 engine,
2845 ty,
2846 &format_ident!("__ingraph_slot"),
2847 &format_ident!("__ingraph_connection"),
2848 );
2849 let own = quote_spanned! {ty.span()=> #connected::new(__ingraph_connection, ())};
2850 let scope = quote_spanned! {ty.span()=> #connected::new(__ingraph_connection, ())};
2851 let (floor, options) = (
2852 format_ident!("__ingraph_floor"),
2853 format_ident!("__ingraph_options"),
2854 );
2855 let floorless = format!(
2856 "`{sdl}` needs a floor in `{engine_word}`'s own score currency — write \
2857 `engine: {{ {engine_word}: {{ floor: … }} }}`. There is no number this framework could put \
2858 there instead: a score's DIRECTION belongs to the engine that measures in it, so a zero is \
2859 neutral for a similarity and prunes the whole corpus for a distance.",
2860 engine_word = engine.word,
2861 );
2862 let doc = leading(&format!(
2863 "The addresses [`{index}`]'s `{field}` ranks nearest ONE ENTITY's own `{field}`, in \
2864 `{engine_word}` — the example itself excluded.",
2865 engine_word = engine.word,
2866 ));
2867 let ctx = crate::method::wire_method(&format_ident!("ctx"));
2868 let (asked, chosen, first, depth) = (
2869 crate::method::wire_method(&format_ident!("key")),
2870 crate::method::wire_method(&format_ident!("engine")),
2871 crate::method::wire_method(&format_ident!("first")),
2872 crate::method::wire_method(&format_ident!("depth")),
2873 );
2874 let default = self
2875 .wire_first(GraphqlKind::AsyncGraphql, Some(field))
2876 .get();
2877 let default = syn::LitInt::new(&default.to_string(), field.span());
2878 quote! {
2879 #[doc = #doc]
2880 #[graphql(name = #sdl)]
2881 #arity
2882 async fn #method(
2883 &self,
2884 #ctx: &#ag::Context<'_>,
2885 #[graphql(name = "key")] #asked: <#example as #crossing>::Input,
2886 #[graphql(name = "engine")] #chosen: ::core::option::Option<#selector>,
2887 #[graphql(name = "first", default = #default)] #first: u32,
2888 #[graphql(name = "depth")] #depth: ::core::option::Option<u32>,
2889 ) -> #ag::Result<::std::vec::Vec<#hit<#key, <#ty as #seam>::Score>>> {
2890 #numbers
2891 // THE EXAMPLE, read off the wire — the record's own `get(id:)` crossing, at the whole
2892 // address instead of at the id alone, and refused under the same word.
2893 let __ingraph_example = <#example as #crossing>::cross(#asked)
2894 .map_err(|__ingraph_refusal| #refused_address(&__ingraph_refusal))?;
2895 let (#floor, #options) = match #chosen {
2896 ::core::option::Option::Some(#selector::#variant(ref __ingraph_named)) => (
2897 ::core::option::Option::map(__ingraph_named.floor(), ::core::clone::Clone::clone),
2898 __ingraph_named.options(),
2899 ),
2900 ::core::option::Option::None => (
2901 ::core::option::Option::None,
2902 ::core::option::Option::None,
2903 ),
2904 };
2905 let ::core::option::Option::Some(#floor) = #floor else {
2906 return ::core::result::Result::Err(#ag::Error::new(#floorless));
2907 };
2908 #mint
2909 let mut __ingraph_ranked: ::std::vec::Vec<#ranked<_, _>> = #index::#door::<#handle>(
2910 &mut __ingraph_slot,
2911 #own,
2912 #scope,
2913 &__ingraph_example,
2914 #floor,
2915 __ingraph_fetch,
2916 #options,
2917 )
2918 .await
2919 .map_err(|__ingraph_refusal| {
2920 #ag::Error::new(::std::string::ToString::to_string(&__ingraph_refusal))
2921 })?;
2922 // THE PAGE, cut after the walk — the plain road's law, with one more way for the two
2923 // numbers to differ: the example consumes a fetched hit of its own.
2924 ::std::vec::Vec::truncate(
2925 &mut __ingraph_ranked,
2926 ::core::num::NonZeroUsize::get(__ingraph_page),
2927 );
2928 ::core::result::Result::Ok(#crossed(
2929 ::core::iter::Iterator::map(
2930 ::std::vec::Vec::into_iter(__ingraph_ranked),
2931 |__ingraph_hit| {
2932 let __ingraph_key = ::core::clone::Clone::clone(#ranked::node_ref(&__ingraph_hit));
2933 #ranked::map_node(
2934 __ingraph_hit,
2935 <#key as ::core::convert::From<_>>::from(__ingraph_key),
2936 )
2937 },
2938 ),
2939 ))
2940 }
2941 }
2942 }
2943
2944 /// **THE THREE PROJECTIONS A HYDRATED ROAD READS** — the upstream's hydration database, the row
2945 /// that database keeps it as, and the wire object that row raises into.
2946 ///
2947 /// Beside [`answer_bindings`](Self::answer_bindings) rather than inside it, and the split is the
2948 /// GATE rather than tidiness: these resolve through
2949 /// [`Hydrates`](../../../ingraph/trait.Hydrates.html), whose impl the RECORD emits inside its own
2950 /// database's gate, so a build carrying the wire binding and no SQL family has nothing for them to
2951 /// name. They therefore live in the `if_sqlx!` half beside the roads that spend them, where the
2952 /// bindings above are shared by both halves and demand nothing a keys road does not already need.
2953 ///
2954 /// Spanned at `upstream(node = "…")` for that function's reason: an upstream that is stored nowhere,
2955 /// dressed nowhere, or kept only in a store with no query face is `E0277` ON A TOKEN AN AUTHOR CAN
2956 /// EDIT, carrying `Hydrates`' own sentence, rather than somewhere inside an expansion. MEASURED,
2957 /// the caret lands on the whole `#[ingraph::vector(…)]` rather than on the string inside it — the
2958 /// same width every projection this expansion writes is reported at — so the span written here is
2959 /// what a narrower caret would need and not what it already has.
2960 ///
2961 /// The DATABASE is bound once and the other two are written over it, which is what makes the door
2962 /// a resolver opens and the row its gather reads the same store by construction — two independent
2963 /// spellings of `<Upstream as Hydrates>::Db` is where a page could open one connection and read
2964 /// another's columns.
2965 fn hydration_bindings(&self) -> proc_macro2::TokenStream {
2966 let krate = &self.krate;
2967 let hydrates = framework(krate, &["transform"], "Hydrates");
2968 let vocabulary = framework(krate, &["transform"], "Record");
2969 let transformer = framework(krate, &["transform"], "Transformer");
2970 let face = framework(krate, &["transform"], "Graphql");
2971 let upstream = &self.source.node;
2972 let (db, row, entity) = hydration_names();
2973 let at = upstream.span();
2974 quote_spanned! {at=>
2975 #[allow(dead_code, non_camel_case_types)]
2976 type #db = <#upstream as #hydrates>::Db;
2977 #[allow(dead_code, non_camel_case_types)]
2978 type #row = <#upstream as #vocabulary<#db>>::Row;
2979 #[allow(dead_code, non_camel_case_types)]
2980 type #entity = <<#upstream as #transformer>::Graphql as #face>::Output;
2981 }
2982 }
2983
2984 /// **THE QUESTION ROAD, HYDRATED** — the keys road's twin one tier down: the same question in, the
2985 /// upstream's WHOLE ENTITIES out.
2986 ///
2987 /// ```text
2988 /// shotsByClipKeys(question: …) → [KeyframeKeyMatch!]! the ADDRESSES — no store touched
2989 /// shotsByClip(question: …) → [KeyframeMatch!]! the ENTITIES — one pooled gather
2990 /// ```
2991 ///
2992 /// # It rides TIER A and a `AsyncGather`, not the emitted tier B, and the ROW is why
2993 ///
2994 /// `retrieve_by_<field>` answers the upstream's RECORDS, and there is no `Record → Output`
2995 /// crossing anywhere in the tree: `emit::graphql`'s `row_crossings` writes a wire object's only
2996 /// constructor as `TryFrom<<Record as Record<Db>>::Row>`, off the stored row. So a gather that
2997 /// answered records would hand this face a value it cannot render, whatever else it did right.
2998 /// [`SqlPooledGather`] answers ROWS, which is the fork point both crossings hang off — and this
2999 /// road therefore calls tier A itself and composes the fill loop over it, exactly as
3000 /// `ingraph/tests/hydrated_road.rs` measured before there was an emitter to ask for it.
3001 ///
3002 /// # `&Pool` and never a borrowed connection, and that is a MEASUREMENT
3003 ///
3004 /// `ingraph/tests/wire_trio.rs` put five shapes to the compiler: every one that held a borrowed
3005 /// `Db::Connection` across the fill loop's `await` inside a resolver is *implementation of
3006 /// `sqlx::Acquire` is not general enough*, because async-graphql bounds every resolver future
3007 /// `Send` and sqlx implements `Acquire<'c>` for `&'c mut Connection` at one lifetime. The gather is
3008 /// built from the door's pool for that reason and no other.
3009 ///
3010 /// # The PAGE is cut AT THE LOOP, where the keys road truncates after the walk
3011 ///
3012 /// A hydrated page is counted in ENTITIES: a key whose row the store has since lost drops, so a
3013 /// truncate over the KEYS would answer short by however many rows went missing. `filled`'s own
3014 /// limit is that cut — it keeps pulling keys until the page is full or the stream is exhausted —
3015 /// so `__ingraph_page` is spent there and no `Vec::truncate` follows. What `depth` bought is
3016 /// unchanged: it is the FETCH, capped by the declared ceiling, and it is what tier A is asked for.
3017 ///
3018 /// # THREE refusals cross under three words, because they are three parties
3019 ///
3020 /// The ENGINE's is the declarer's type and can implement no `ToErrorCode`, so it crosses as a bare
3021 /// sentence — the keys road's own treatment. The GATHER's is the framework's own `SqlQueryError`,
3022 /// which names its word, so it crosses through `refused`. The ROW's is the declaration's
3023 /// output-crossing error, which crosses through `refused_row` exactly as the record's own single
3024 /// leg raises a row — one code for one class of mistake, whichever road a client came down.
3025 ///
3026 /// [`SqlPooledGather`]: ../../../ingraph/struct.SqlPooledGather.html
3027 fn hydrated_leg(
3028 &self,
3029 tier: &crate::fuse::Tier<'_>,
3030 elected: &Elected,
3031 engine: &Engine,
3032 ) -> proc_macro2::TokenStream {
3033 let IndexModel { krate, index, .. } = self;
3034 let ag = framework(krate, &[], "async_graphql");
3035 let seam = framework(krate, &["store"], "VectorEngine");
3036 let hit = framework(krate, &["graphql"], "Match");
3037 let sql_door = framework(krate, &["graphql"], "SqlDoor");
3038 let refused = framework(krate, &["graphql"], "refused");
3039 let refused_row = framework(krate, &["graphql"], "refused_row");
3040 let gather = framework(krate, &["retrieve"], "SqlPooledGather");
3041 let fill = framework(krate, &["retrieve"], "filled");
3042 let ranked = framework(krate, &["retrieve"], "Ranked");
3043 let query = framework(krate, &["retrieve"], "VectorQuery");
3044 let connected = framework(krate, &["store"], "Connected");
3045 let field = &elected.field;
3046 let ty = engine
3047 .resource
3048 .as_ref()
3049 .expect("a plain road names a typed engine");
3050 let handle = self.wire_handle(ty);
3051 let mint = self.wire_corpus(
3052 field,
3053 Some(&elected.ty),
3054 engine,
3055 ty,
3056 &format_ident!("__ingraph_slot"),
3057 &format_ident!("__ingraph_connection"),
3058 );
3059 let question = self.question_name(tier, elected);
3060 let selector = tier
3061 .slot_selector(elected)
3062 .expect("a typed election mints its engine selector");
3063 let variant = format_ident!("{}", {
3064 use heck::ToUpperCamelCase as _;
3065 engine.word.to_string().to_upper_camel_case()
3066 });
3067 let (db, row, entity) = hydration_names();
3068 let sdl = self.field_name(elected, Field::Hydrated);
3069 let method = crate::method::wire_method(&format_ident!("{}", crate::emit::snake(&sdl)));
3070 let door = Door::Keys.name(field);
3071 let arity = wide_signature();
3072 let numbers = self.answer_numbers(&elected.field);
3073 let point = self.point_binding(&question, elected);
3074 let scope = quote_spanned! {ty.span()=>
3075 #connected::new(__ingraph_connection, ())
3076 };
3077 let (floor, options) = (
3078 format_ident!("__ingraph_floor"),
3079 format_ident!("__ingraph_options"),
3080 );
3081 let floorless = format!(
3082 "`{sdl}` needs a floor in `{engine_word}`'s own score currency — write \
3083 `engine: {{ {engine_word}: {{ floor: … }} }}`. There is no number this framework could put \
3084 there instead: a score's DIRECTION belongs to the engine that measures in it, so a zero is \
3085 neutral for a similarity and prunes the whole corpus for a distance.",
3086 engine_word = engine.word,
3087 );
3088 let doc = leading(&format!(
3089 "The WHOLE UPSTREAM ENTITIES [`{index}`]'s `{field}` ranks nearest a question, in \
3090 `{engine_word}` — each wearing the score and the ordinal its address carried.\n\nA hit whose \
3091 row the system of record no longer holds is absent, and the ordinal it held stays a hole: \
3092 the page is counted in entities, so the read pulls another address rather than closing the \
3093 gap up.",
3094 engine_word = engine.word,
3095 ));
3096 let ctx = crate::method::wire_method(&format_ident!("ctx"));
3097 let (asked, chosen, first, depth) = (
3098 crate::method::wire_method(&format_ident!("question")),
3099 crate::method::wire_method(&format_ident!("engine")),
3100 crate::method::wire_method(&format_ident!("first")),
3101 crate::method::wire_method(&format_ident!("depth")),
3102 );
3103 let default = self
3104 .wire_first(GraphqlKind::AsyncGraphql, Some(field))
3105 .get();
3106 let default = syn::LitInt::new(&default.to_string(), field.span());
3107 quote! {
3108 #[doc = #doc]
3109 #[graphql(name = #sdl)]
3110 #arity
3111 async fn #method(
3112 &self,
3113 #ctx: &#ag::Context<'_>,
3114 #[graphql(name = "question")] #asked: #question,
3115 #[graphql(name = "engine")] #chosen: ::core::option::Option<#selector>,
3116 #[graphql(name = "first", default = #default)] #first: u32,
3117 #[graphql(name = "depth")] #depth: ::core::option::Option<u32>,
3118 ) -> #ag::Result<::std::vec::Vec<#hit<#entity, <#ty as #seam>::Score>>> {
3119 #numbers
3120 #point
3121 let (#floor, #options) = match #chosen {
3122 ::core::option::Option::Some(#selector::#variant(ref __ingraph_named)) => (
3123 ::core::option::Option::map(__ingraph_named.floor(), ::core::clone::Clone::clone),
3124 __ingraph_named.options(),
3125 ),
3126 ::core::option::Option::None => (
3127 ::core::option::Option::None,
3128 ::core::option::Option::None,
3129 ),
3130 };
3131 let ::core::option::Option::Some(#floor) = #floor else {
3132 return ::core::result::Result::Err(#ag::Error::new(#floorless));
3133 };
3134 #mint
3135 // THE STORE DOOR, keyed on the UPSTREAM's own projection — the same door its record's root
3136 // fields take, so a schema installs one per store and never one per road.
3137 let __ingraph_door = #ag::Context::data::<#sql_door<#db>>(#ctx)?;
3138 let __ingraph_query = #query::new(__ingraph_point, #floor);
3139 let __ingraph_ranked: ::std::vec::Vec<#ranked<_, _>> = #index::#door::<#handle>(
3140 &mut __ingraph_slot,
3141 #scope,
3142 &__ingraph_query,
3143 __ingraph_fetch,
3144 #options,
3145 )
3146 .await
3147 .map_err(|__ingraph_refusal| {
3148 #ag::Error::new(::std::string::ToString::to_string(&__ingraph_refusal))
3149 })?;
3150 // HELD ACROSS THE `await` BELOW: the gather owns the pool borrow and, from its first batch
3151 // on, the one connection the rest of the page runs on — so a page cannot span two states of
3152 // the database.
3153 let mut __ingraph_gather = #gather::<#row, #db>::new(#sql_door::pool(__ingraph_door));
3154 let __ingraph_filled = #fill(
3155 __ingraph_ranked,
3156 &mut __ingraph_gather,
3157 ::core::option::Option::None,
3158 ::core::num::NonZeroUsize::get(__ingraph_page),
3159 )
3160 .await
3161 .map_err(|__ingraph_refusal| #refused(&__ingraph_refusal))?;
3162 // THE ONE CROSSING, and it is the record resolver's own: the row raises onto the wire
3163 // through the conversion its declaration wrote. The two numbers are read off the hit they
3164 // belong to and never assembled by hand.
3165 ::core::iter::Iterator::collect(::core::iter::Iterator::map(
3166 ::std::vec::Vec::into_iter(__ingraph_filled),
3167 |__ingraph_hit| {
3168 let (__ingraph_score, __ingraph_rank, __ingraph_row) =
3169 #ranked::into_components(__ingraph_hit);
3170 ::core::result::Result::map_err(
3171 ::core::result::Result::map(
3172 <#entity as ::core::convert::TryFrom<#row>>::try_from(__ingraph_row),
3173 |__ingraph_entity| #hit::new(__ingraph_score, __ingraph_rank, __ingraph_entity),
3174 ),
3175 |__ingraph_refusal| #refused_row(&__ingraph_refusal),
3176 )
3177 },
3178 ))
3179 }
3180 }
3181 }
3182
3183 /// **THE BY-EXAMPLE ROAD, HYDRATED** — one entity's address in, its neighbours' whole rows out,
3184 /// the example itself excluded.
3185 ///
3186 /// [`hydrated_leg`](Self::hydrated_leg)'s every measurement holds here word for word: the row is
3187 /// the fork point, the pool is the surface `Send` admits, the page is cut at the loop, and the
3188 /// three refusals cross under their three words. What differs is the ARGUMENT — the upstream's own
3189 /// key, crossing inward through the operand map, which is [`similar_leg`](Self::similar_leg)'s own
3190 /// ruling and is read from that leg rather than restated — and the second read scope the
3191 /// by-example door takes, `Connected` being deliberately not `Clone`.
3192 ///
3193 /// The exclusion is the DOOR's, so hydrating changes nothing about which keys there were: the
3194 /// example is absent, ordinal and all.
3195 fn similar_hydrated_leg(
3196 &self,
3197 tier: &crate::fuse::Tier<'_>,
3198 elected: &Elected,
3199 engine: &Engine,
3200 ) -> proc_macro2::TokenStream {
3201 let IndexModel { krate, index, .. } = self;
3202 let ag = framework(krate, &[], "async_graphql");
3203 let seam = framework(krate, &["store"], "VectorEngine");
3204 let hit = framework(krate, &["graphql"], "Match");
3205 let sql_door = framework(krate, &["graphql"], "SqlDoor");
3206 let crossing = framework(krate, &["graphql"], "ToGraphqlInput");
3207 let refused = framework(krate, &["graphql"], "refused");
3208 let refused_row = framework(krate, &["graphql"], "refused_row");
3209 let refused_address = framework(krate, &["graphql"], "refused_address");
3210 let gather = framework(krate, &["retrieve"], "SqlPooledGather");
3211 let fill = framework(krate, &["retrieve"], "filled");
3212 let ranked = framework(krate, &["retrieve"], "Ranked");
3213 let connected = framework(krate, &["store"], "Connected");
3214 let field = &elected.field;
3215 let ty = engine
3216 .resource
3217 .as_ref()
3218 .expect("a plain road names a typed engine");
3219 let selector = tier
3220 .slot_selector(elected)
3221 .expect("a typed election mints its engine selector");
3222 let variant = format_ident!("{}", {
3223 use heck::ToUpperCamelCase as _;
3224 engine.word.to_string().to_upper_camel_case()
3225 });
3226 let example = example_key_name();
3227 let (db, row, entity) = hydration_names();
3228 let sdl = self.field_name(elected, Field::SimilarHydrated);
3229 let method = crate::method::wire_method(&format_ident!("{}", crate::emit::snake(&sdl)));
3230 let door = Door::Similar.name(field);
3231 let arity = wide_signature();
3232 let numbers = self.answer_numbers(&elected.field);
3233 // TWO of them, because the door takes two and a `Connected` is not `Clone`. Both carry the
3234 // MOUNT's own manager, which the mint below hands back beside the corpus.
3235 let handle = self.wire_handle(ty);
3236 let mint = self.wire_corpus(
3237 field,
3238 Some(&elected.ty),
3239 engine,
3240 ty,
3241 &format_ident!("__ingraph_slot"),
3242 &format_ident!("__ingraph_connection"),
3243 );
3244 let own = quote_spanned! {ty.span()=> #connected::new(__ingraph_connection, ())};
3245 let scope = quote_spanned! {ty.span()=> #connected::new(__ingraph_connection, ())};
3246 let (floor, options) = (
3247 format_ident!("__ingraph_floor"),
3248 format_ident!("__ingraph_options"),
3249 );
3250 let floorless = format!(
3251 "`{sdl}` needs a floor in `{engine_word}`'s own score currency — write \
3252 `engine: {{ {engine_word}: {{ floor: … }} }}`. There is no number this framework could put \
3253 there instead: a score's DIRECTION belongs to the engine that measures in it, so a zero is \
3254 neutral for a similarity and prunes the whole corpus for a distance.",
3255 engine_word = engine.word,
3256 );
3257 let doc = leading(&format!(
3258 "The WHOLE UPSTREAM ENTITIES [`{index}`]'s `{field}` ranks nearest ONE ENTITY's own \
3259 `{field}`, in `{engine_word}` — the example itself excluded, and each neighbour wearing the \
3260 score and the ordinal its address carried.\n\nA neighbour whose row the system of record no \
3261 longer holds is absent, and the ordinal it held stays a hole.",
3262 engine_word = engine.word,
3263 ));
3264 let ctx = crate::method::wire_method(&format_ident!("ctx"));
3265 let (asked, chosen, first, depth) = (
3266 crate::method::wire_method(&format_ident!("key")),
3267 crate::method::wire_method(&format_ident!("engine")),
3268 crate::method::wire_method(&format_ident!("first")),
3269 crate::method::wire_method(&format_ident!("depth")),
3270 );
3271 let default = self
3272 .wire_first(GraphqlKind::AsyncGraphql, Some(field))
3273 .get();
3274 let default = syn::LitInt::new(&default.to_string(), field.span());
3275 quote! {
3276 #[doc = #doc]
3277 #[graphql(name = #sdl)]
3278 #arity
3279 async fn #method(
3280 &self,
3281 #ctx: &#ag::Context<'_>,
3282 #[graphql(name = "key")] #asked: <#example as #crossing>::Input,
3283 #[graphql(name = "engine")] #chosen: ::core::option::Option<#selector>,
3284 #[graphql(name = "first", default = #default)] #first: u32,
3285 #[graphql(name = "depth")] #depth: ::core::option::Option<u32>,
3286 ) -> #ag::Result<::std::vec::Vec<#hit<#entity, <#ty as #seam>::Score>>> {
3287 #numbers
3288 let __ingraph_example = <#example as #crossing>::cross(#asked)
3289 .map_err(|__ingraph_refusal| #refused_address(&__ingraph_refusal))?;
3290 let (#floor, #options) = match #chosen {
3291 ::core::option::Option::Some(#selector::#variant(ref __ingraph_named)) => (
3292 ::core::option::Option::map(__ingraph_named.floor(), ::core::clone::Clone::clone),
3293 __ingraph_named.options(),
3294 ),
3295 ::core::option::Option::None => (
3296 ::core::option::Option::None,
3297 ::core::option::Option::None,
3298 ),
3299 };
3300 let ::core::option::Option::Some(#floor) = #floor else {
3301 return ::core::result::Result::Err(#ag::Error::new(#floorless));
3302 };
3303 #mint
3304 let __ingraph_door = #ag::Context::data::<#sql_door<#db>>(#ctx)?;
3305 let __ingraph_ranked: ::std::vec::Vec<#ranked<_, _>> = #index::#door::<#handle>(
3306 &mut __ingraph_slot,
3307 #own,
3308 #scope,
3309 &__ingraph_example,
3310 #floor,
3311 __ingraph_fetch,
3312 #options,
3313 )
3314 .await
3315 .map_err(|__ingraph_refusal| {
3316 #ag::Error::new(::std::string::ToString::to_string(&__ingraph_refusal))
3317 })?;
3318 let mut __ingraph_gather = #gather::<#row, #db>::new(#sql_door::pool(__ingraph_door));
3319 let __ingraph_filled = #fill(
3320 __ingraph_ranked,
3321 &mut __ingraph_gather,
3322 ::core::option::Option::None,
3323 ::core::num::NonZeroUsize::get(__ingraph_page),
3324 )
3325 .await
3326 .map_err(|__ingraph_refusal| #refused(&__ingraph_refusal))?;
3327 ::core::iter::Iterator::collect(::core::iter::Iterator::map(
3328 ::std::vec::Vec::into_iter(__ingraph_filled),
3329 |__ingraph_hit| {
3330 let (__ingraph_score, __ingraph_rank, __ingraph_row) =
3331 #ranked::into_components(__ingraph_hit);
3332 ::core::result::Result::map_err(
3333 ::core::result::Result::map(
3334 <#entity as ::core::convert::TryFrom<#row>>::try_from(__ingraph_row),
3335 |__ingraph_entity| #hit::new(__ingraph_score, __ingraph_rank, __ingraph_entity),
3336 ),
3337 |__ingraph_refusal| #refused_row(&__ingraph_refusal),
3338 )
3339 },
3340 ))
3341 }
3342 }
3343 }
3344
3345 /// **THE FOLD ONE SET ROAD RUNS UNDER**, resolved into `__ingraph_fold` and named in
3346 /// `__ingraph_fold_name` — the deployment's installed policy, or this election's own.
3347 ///
3348 /// ```text
3349 /// FoldDoor<Lance, ShotsByClip> installed at launch → the deployment's
3350 /// semantics(fold = "app::Mine") written at the election → Shots::fold_by_clip()
3351 /// neither → Sum, which is what that accessor is
3352 /// ```
3353 ///
3354 /// # The REQUEST is not in that chain, and its absence is the ruling
3355 ///
3356 /// A fold changes what the answer MEANS — `sum` rewards a result that answered many query vectors
3357 /// adequately, `max` one that answered a single vector perfectly — so a client able to swap it per
3358 /// query is a client able to make two answers of one corpus that cannot be compared against each
3359 /// other. No argument is emitted for it, and a request arm stays purely additive on the day one is
3360 /// ruled: it would be a new `@oneOf` input beside `engine`, not a change to anything written here.
3361 ///
3362 /// # The two arms are ONE `&dyn`, and that is what keeps the door monomorphized once
3363 ///
3364 /// The two folds are two TYPES — one erased behind the door's `Arc`, one the concrete type the
3365 /// election declared — so a `match` handing each straight to the door would emit the whole
3366 /// resolver body twice for a choice made once per request. Coercing both to
3367 /// `&dyn FoldSemantics<Score>` costs one virtual call PER ENTITY at the fold and one body; the
3368 /// borrow folds through `FoldSemantics for &F`, so the door beneath is the same statically
3369 /// dispatched door either way.
3370 ///
3371 /// The elected fold is bound to a LOCAL first because the `&dyn` borrows it: `fold_by_<field>()`
3372 /// answers by value, and a temporary inside the match arm would not outlive the `await` below.
3373 fn fold_binding(&self, elected: &Elected, engine: &Engine) -> proc_macro2::TokenStream {
3374 let krate = &self.krate;
3375 let seam = framework(krate, &["store"], "VectorEngine");
3376 let semantics = framework(krate, &["retrieve"], "FoldSemantics");
3377 let door = framework(krate, &["graphql"], "FoldDoor");
3378 let lookup = framework(krate, &["graphql"], "installed_fold");
3379 let index = &self.index;
3380 let ty = engine
3381 .resource
3382 .as_ref()
3383 .expect("a plain road names a typed engine");
3384 let marker = elected_marker(self.base(), &elected.field);
3385 let elected_fold = fold_accessor(&elected.field);
3386 let ctx = crate::method::wire_method(&format_ident!("ctx"));
3387 quote! {
3388 let __ingraph_elected_fold = #index::#elected_fold();
3389 let __ingraph_fold: &dyn #semantics<<#ty as #seam>::Score> =
3390 match #lookup::<#ty, #marker>(#ctx) {
3391 ::core::option::Option::Some(__ingraph_door) => #door::semantics(__ingraph_door),
3392 ::core::option::Option::None => &__ingraph_elected_fold,
3393 };
3394 // THE NAME, read off the resolved fold rather than off either arm — so a refusal names what
3395 // actually folded, and the two arms cannot report differently about themselves.
3396 let __ingraph_fold_name =
3397 <dyn #semantics<<#ty as #seam>::Score>>::name(__ingraph_fold);
3398 }
3399 }
3400
3401 /// **THE BY-EXAMPLE SET ROAD's QUERY FIELD** — one election's EXAMPLE KEY in, the entities whose
3402 /// own set best answers the example's whole set out, without the example.
3403 ///
3404 /// ```text
3405 /// shotsSimilarByClipKeys(key: …) → [KeyframeKeyFoldedMatch!]!
3406 /// score the FOLD's answer over m streams
3407 /// streams { score ordinal } one nullable slot per member of the example's own set
3408 /// node { … }
3409 /// ```
3410 ///
3411 /// # It is [`similar_leg`](Self::similar_leg) at the OTHER LABEL, and the name does not move
3412 ///
3413 /// Same field, same argument, same engine arm, same `first`/`depth` rows, same rename seat. What
3414 /// differs is the door — `retrieve_similar_by_<field>_with` — and therefore the ANSWER, which
3415 /// carries `m` per-stream sightings where the unit road carries one rank. See
3416 /// [`answer_road`](Self::answer_road) for why the label picks the door and for the runtime refusal
3417 /// this ends.
3418 ///
3419 /// # The `m` IS THE DEPLOYMENT'S OWN DATA, and there is no guard on it
3420 ///
3421 /// The streams a set road walks come from the example's stored set, so their number is whatever
3422 /// the pipeline wrote for that entity rather than anything a request stated. A protective word
3423 /// over it would be a bound on a deployment's own corpus, which is not a thing a request can
3424 /// inflate. The road where that protection HAS a question to answer is the one asked with `m`
3425 /// vectors a CLIENT sends, and it is minted there: `streams = N` is spent in
3426 /// [`points_binding`](Self::points_binding), which only the question legs bind, and no leg on this
3427 /// road emits a count at all.
3428 ///
3429 /// # THE FLOOR IS THE ELEMENT'S, unchanged, and there is none in the folded currency
3430 ///
3431 /// The engine arm's `floor` row cuts each of the `m` per-vector walks, exactly as it cuts the one
3432 /// walk of the unit road. There is no floor on the folded score and there is no seat for one: a
3433 /// sum of `m` cosines is in a third currency that no engine reports and no author could calibrate.
3434 ///
3435 /// # AN EMPTY EXAMPLE SET IS REFUSED BY NAME
3436 ///
3437 /// `set.rs`'s own law surfacing — *a set query with no query vectors asks nothing*, which is what
3438 /// `FoldedQuery::of` answers `None` for. The door reaches it as `Unindexed` from the group read, and
3439 /// this leg is where it becomes a sentence naming the field, the argument and the election, rather
3440 /// than the store-shaped refusal a client cannot act on.
3441 fn similar_set_leg(
3442 &self,
3443 tier: &crate::fuse::Tier<'_>,
3444 elected: &Elected,
3445 engine: &Engine,
3446 ) -> proc_macro2::TokenStream {
3447 let IndexModel { krate, index, .. } = self;
3448 let ag = framework(krate, &[], "async_graphql");
3449 let seam = framework(krate, &["store"], "VectorEngine");
3450 let hit = framework(krate, &["graphql"], "FoldedMatch");
3451 let crossed = framework(krate, &["graphql"], "folded_matches");
3452 let crossing = framework(krate, &["graphql"], "ToGraphqlInput");
3453 let refused_address = framework(krate, &["graphql"], "refused_address");
3454 let folded = framework(krate, &["retrieve"], "Folded");
3455 let own_refusal = framework(krate, &["retrieve"], "OwnReadError");
3456 let connected = framework(krate, &["store"], "Connected");
3457 let field = &elected.field;
3458 let ty = engine
3459 .resource
3460 .as_ref()
3461 .expect("a plain road names a typed engine");
3462 let selector = tier
3463 .slot_selector(elected)
3464 .expect("a typed election mints its engine selector");
3465 let variant = format_ident!("{}", {
3466 use heck::ToUpperCamelCase as _;
3467 engine.word.to_string().to_upper_camel_case()
3468 });
3469 let key = wire_key_name();
3470 let example = example_key_name();
3471 let sdl = self.field_name(elected, Field::Similar);
3472 let method = crate::method::wire_method(&format_ident!("{}", crate::emit::snake(&sdl)));
3473 let door = Door::SimilarSet.name(field);
3474 let arity = wide_signature();
3475 let numbers = self.answer_numbers(&elected.field);
3476 let fold = self.fold_binding(elected, engine);
3477 // TWO of them, because the door takes two and a `Connected` is not `Clone`. Both carry the
3478 // MOUNT's own manager, which the mint below hands back beside the corpus.
3479 let handle = self.wire_handle(ty);
3480 let mint = self.wire_corpus(
3481 field,
3482 Some(&elected.ty),
3483 engine,
3484 ty,
3485 &format_ident!("__ingraph_slot"),
3486 &format_ident!("__ingraph_connection"),
3487 );
3488 let own = quote_spanned! {ty.span()=> #connected::new(__ingraph_connection, ())};
3489 let scope = quote_spanned! {ty.span()=> #connected::new(__ingraph_connection, ())};
3490 let (floor, options) = (
3491 format_ident!("__ingraph_floor"),
3492 format_ident!("__ingraph_options"),
3493 );
3494 let floorless = format!(
3495 "`{sdl}` needs a floor in `{engine_word}`'s own score currency — write \
3496 `engine: {{ {engine_word}: {{ floor: … }} }}`. The floor cuts each of the query set's own \
3497 walks, at the grain one pair of vectors is scored in; there is no floor on the folded score, \
3498 which is in a currency no engine reports.",
3499 engine_word = engine.word,
3500 );
3501 let empty = format!(
3502 "`{sdl}` was asked with `key`, and that entity's `{field}` set is empty — a set query with no \
3503 query vectors asks nothing, so there is no question here to answer. Index the entity's \
3504 `{field}` and ask again.",
3505 );
3506 let doc = leading(&format!(
3507 "The addresses [`{index}`]'s `{field}` SET ranks nearest ONE ENTITY's own `{field}` SET, in \
3508 `{engine_word}` — the example itself excluded.\n\nEach of the example's own vectors is asked \
3509 as its own query, and a FOLD is what turns those `m` answers into one score. Every hit \
3510 carries what each of those streams said, under `streams`, in the order the example holds its \
3511 vectors.\n\n{fold}",
3512 engine_word = engine.word,
3513 fold = fold_note(&elected.field, Asked::Example),
3514 ));
3515 let ctx = crate::method::wire_method(&format_ident!("ctx"));
3516 let (asked, chosen, first, depth) = (
3517 crate::method::wire_method(&format_ident!("key")),
3518 crate::method::wire_method(&format_ident!("engine")),
3519 crate::method::wire_method(&format_ident!("first")),
3520 crate::method::wire_method(&format_ident!("depth")),
3521 );
3522 let default = self
3523 .wire_first(GraphqlKind::AsyncGraphql, Some(field))
3524 .get();
3525 let default = syn::LitInt::new(&default.to_string(), field.span());
3526 quote! {
3527 #[doc = #doc]
3528 #[graphql(name = #sdl)]
3529 #arity
3530 async fn #method(
3531 &self,
3532 #ctx: &#ag::Context<'_>,
3533 #[graphql(name = "key")] #asked: <#example as #crossing>::Input,
3534 #[graphql(name = "engine")] #chosen: ::core::option::Option<#selector>,
3535 #[graphql(name = "first", default = #default)] #first: u32,
3536 #[graphql(name = "depth")] #depth: ::core::option::Option<u32>,
3537 ) -> #ag::Result<::std::vec::Vec<#hit<#key, <#ty as #seam>::Score>>> {
3538 #numbers
3539 let __ingraph_example = <#example as #crossing>::cross(#asked)
3540 .map_err(|__ingraph_refusal| #refused_address(&__ingraph_refusal))?;
3541 let (#floor, #options) = match #chosen {
3542 ::core::option::Option::Some(#selector::#variant(ref __ingraph_named)) => (
3543 ::core::option::Option::map(__ingraph_named.floor(), ::core::clone::Clone::clone),
3544 __ingraph_named.options(),
3545 ),
3546 ::core::option::Option::None => (
3547 ::core::option::Option::None,
3548 ::core::option::Option::None,
3549 ),
3550 };
3551 let ::core::option::Option::Some(#floor) = #floor else {
3552 return ::core::result::Result::Err(#ag::Error::new(#floorless));
3553 };
3554 #mint
3555 #fold
3556 let mut __ingraph_folded: ::std::vec::Vec<#folded<_, _>> = #index::#door::<#handle, _>(
3557 &mut __ingraph_slot,
3558 #own,
3559 #scope,
3560 &__ingraph_example,
3561 #floor,
3562 __ingraph_fold,
3563 __ingraph_fetch,
3564 // THE PER-STREAM DEPTH IS THE DOOR'S OWN DEFAULT, which is the fetch above: `depth` is
3565 // the FETCH on this family's wire and there is one such row, so passing it twice would be
3566 // one number wearing two names. The door resolves `None` to its own `limit`, so this is
3567 // byte-for-byte what a second spelling would compute.
3568 ::core::option::Option::None,
3569 #options,
3570 )
3571 .await
3572 .map_err(|__ingraph_refusal| match __ingraph_refusal {
3573 // THE EMPTY SET, named: the group read answers `Unindexed` for a column holding nothing,
3574 // and at THIS road that is a question with no query vectors rather than a missing row.
3575 #own_refusal::Unindexed => #ag::Error::new(#empty),
3576 __ingraph_refusal => #ag::Error::new(::std::format!(
3577 "`{}` folded under `{}` and the road refused: {}",
3578 #sdl,
3579 __ingraph_fold_name,
3580 __ingraph_refusal,
3581 )),
3582 })?;
3583 // THE PAGE, cut after the fold — `depth` bought the FETCH and `first` is what a client asked
3584 // to read. The fold's own budget counts ENTITIES, so the two numbers differ wherever the
3585 // floor pruned a stream or the example consumed one of its own hits.
3586 ::std::vec::Vec::truncate(
3587 &mut __ingraph_folded,
3588 ::core::num::NonZeroUsize::get(__ingraph_page),
3589 );
3590 ::core::result::Result::Ok(#crossed(
3591 ::core::iter::Iterator::map(
3592 ::std::vec::Vec::into_iter(__ingraph_folded),
3593 |__ingraph_hit| {
3594 let __ingraph_key = ::core::clone::Clone::clone(#folded::node_ref(&__ingraph_hit));
3595 #folded::map_node(
3596 __ingraph_hit,
3597 <#key as ::core::convert::From<_>>::from(__ingraph_key),
3598 )
3599 },
3600 ),
3601 ))
3602 }
3603 }
3604 }
3605
3606 /// **THE BY-EXAMPLE SET ROAD, HYDRATED** — one entity's address in, its set-neighbours' whole rows
3607 /// out, the example itself excluded.
3608 ///
3609 /// [`similar_set_leg`](Self::similar_set_leg)'s every measurement holds, and
3610 /// [`hydrated_leg`](Self::hydrated_leg)'s: the row is the fork point, the pool is the surface
3611 /// `Send` admits, the page is cut at the fill loop, and the three refusals cross under their three
3612 /// words. What is new is the CARRY — `folded_filled` is `filled` at this answer's arity, and it
3613 /// moves the folded score and every per-stream sighting onto the entity found under the key.
3614 ///
3615 /// A neighbour whose row the system of record no longer holds drops out, and the ordinals its
3616 /// slots carried stay holes in the streams they came from — which is the same shape tier B already
3617 /// leaves in a `rank`.
3618 fn similar_set_hydrated_leg(
3619 &self,
3620 tier: &crate::fuse::Tier<'_>,
3621 elected: &Elected,
3622 engine: &Engine,
3623 ) -> proc_macro2::TokenStream {
3624 let IndexModel { krate, index, .. } = self;
3625 let ag = framework(krate, &[], "async_graphql");
3626 let seam = framework(krate, &["store"], "VectorEngine");
3627 let hit = framework(krate, &["graphql"], "FoldedMatch");
3628 let sql_door = framework(krate, &["graphql"], "SqlDoor");
3629 let crossing = framework(krate, &["graphql"], "ToGraphqlInput");
3630 let refused = framework(krate, &["graphql"], "refused");
3631 let refused_row = framework(krate, &["graphql"], "refused_row");
3632 let refused_address = framework(krate, &["graphql"], "refused_address");
3633 let gather = framework(krate, &["retrieve"], "SqlPooledGather");
3634 let fill = framework(krate, &["retrieve"], "folded_filled");
3635 let folded = framework(krate, &["retrieve"], "Folded");
3636 let own_refusal = framework(krate, &["retrieve"], "OwnReadError");
3637 let connected = framework(krate, &["store"], "Connected");
3638 let field = &elected.field;
3639 let ty = engine
3640 .resource
3641 .as_ref()
3642 .expect("a plain road names a typed engine");
3643 let selector = tier
3644 .slot_selector(elected)
3645 .expect("a typed election mints its engine selector");
3646 let variant = format_ident!("{}", {
3647 use heck::ToUpperCamelCase as _;
3648 engine.word.to_string().to_upper_camel_case()
3649 });
3650 let example = example_key_name();
3651 let (db, row, entity) = hydration_names();
3652 let sdl = self.field_name(elected, Field::SimilarHydrated);
3653 let method = crate::method::wire_method(&format_ident!("{}", crate::emit::snake(&sdl)));
3654 let door = Door::SimilarSet.name(field);
3655 let arity = wide_signature();
3656 let numbers = self.answer_numbers(&elected.field);
3657 let fold = self.fold_binding(elected, engine);
3658 // TWO of them, because the door takes two and a `Connected` is not `Clone`. Both carry the
3659 // MOUNT's own manager, which the mint below hands back beside the corpus.
3660 let handle = self.wire_handle(ty);
3661 let mint = self.wire_corpus(
3662 field,
3663 Some(&elected.ty),
3664 engine,
3665 ty,
3666 &format_ident!("__ingraph_slot"),
3667 &format_ident!("__ingraph_connection"),
3668 );
3669 let own = quote_spanned! {ty.span()=> #connected::new(__ingraph_connection, ())};
3670 let scope = quote_spanned! {ty.span()=> #connected::new(__ingraph_connection, ())};
3671 let (floor, options) = (
3672 format_ident!("__ingraph_floor"),
3673 format_ident!("__ingraph_options"),
3674 );
3675 let floorless = format!(
3676 "`{sdl}` needs a floor in `{engine_word}`'s own score currency — write \
3677 `engine: {{ {engine_word}: {{ floor: … }} }}`. The floor cuts each of the query set's own \
3678 walks, at the grain one pair of vectors is scored in; there is no floor on the folded score, \
3679 which is in a currency no engine reports.",
3680 engine_word = engine.word,
3681 );
3682 let empty = format!(
3683 "`{sdl}` was asked with `key`, and that entity's `{field}` set is empty — a set query with no \
3684 query vectors asks nothing, so there is no question here to answer. Index the entity's \
3685 `{field}` and ask again.",
3686 );
3687 let doc = leading(&format!(
3688 "The WHOLE UPSTREAM ENTITIES [`{index}`]'s `{field}` SET ranks nearest ONE ENTITY's own \
3689 `{field}` SET, in `{engine_word}` — the example itself excluded, and each neighbour wearing \
3690 the folded score and the per-stream sightings its address carried.\n\nA neighbour whose row \
3691 the system of record no longer holds is absent, and the ordinals it held stay \
3692 holes.\n\n{fold}",
3693 engine_word = engine.word,
3694 fold = fold_note(&elected.field, Asked::Example),
3695 ));
3696 let ctx = crate::method::wire_method(&format_ident!("ctx"));
3697 let (asked, chosen, first, depth) = (
3698 crate::method::wire_method(&format_ident!("key")),
3699 crate::method::wire_method(&format_ident!("engine")),
3700 crate::method::wire_method(&format_ident!("first")),
3701 crate::method::wire_method(&format_ident!("depth")),
3702 );
3703 let default = self
3704 .wire_first(GraphqlKind::AsyncGraphql, Some(field))
3705 .get();
3706 let default = syn::LitInt::new(&default.to_string(), field.span());
3707 quote! {
3708 #[doc = #doc]
3709 #[graphql(name = #sdl)]
3710 #arity
3711 async fn #method(
3712 &self,
3713 #ctx: &#ag::Context<'_>,
3714 #[graphql(name = "key")] #asked: <#example as #crossing>::Input,
3715 #[graphql(name = "engine")] #chosen: ::core::option::Option<#selector>,
3716 #[graphql(name = "first", default = #default)] #first: u32,
3717 #[graphql(name = "depth")] #depth: ::core::option::Option<u32>,
3718 ) -> #ag::Result<::std::vec::Vec<#hit<#entity, <#ty as #seam>::Score>>> {
3719 #numbers
3720 let __ingraph_example = <#example as #crossing>::cross(#asked)
3721 .map_err(|__ingraph_refusal| #refused_address(&__ingraph_refusal))?;
3722 let (#floor, #options) = match #chosen {
3723 ::core::option::Option::Some(#selector::#variant(ref __ingraph_named)) => (
3724 ::core::option::Option::map(__ingraph_named.floor(), ::core::clone::Clone::clone),
3725 __ingraph_named.options(),
3726 ),
3727 ::core::option::Option::None => (
3728 ::core::option::Option::None,
3729 ::core::option::Option::None,
3730 ),
3731 };
3732 let ::core::option::Option::Some(#floor) = #floor else {
3733 return ::core::result::Result::Err(#ag::Error::new(#floorless));
3734 };
3735 #mint
3736 let __ingraph_door = #ag::Context::data::<#sql_door<#db>>(#ctx)?;
3737 #fold
3738 let __ingraph_folded: ::std::vec::Vec<#folded<_, _>> = #index::#door::<#handle, _>(
3739 &mut __ingraph_slot,
3740 #own,
3741 #scope,
3742 &__ingraph_example,
3743 #floor,
3744 __ingraph_fold,
3745 __ingraph_fetch,
3746 ::core::option::Option::None,
3747 #options,
3748 )
3749 .await
3750 .map_err(|__ingraph_refusal| match __ingraph_refusal {
3751 #own_refusal::Unindexed => #ag::Error::new(#empty),
3752 __ingraph_refusal => #ag::Error::new(::std::format!(
3753 "`{}` folded under `{}` and the road refused: {}",
3754 #sdl,
3755 __ingraph_fold_name,
3756 __ingraph_refusal,
3757 )),
3758 })?;
3759 let mut __ingraph_gather = #gather::<#row, #db>::new(#sql_door::pool(__ingraph_door));
3760 let __ingraph_filled = #fill(
3761 __ingraph_folded,
3762 &mut __ingraph_gather,
3763 ::core::option::Option::None,
3764 ::core::num::NonZeroUsize::get(__ingraph_page),
3765 )
3766 .await
3767 .map_err(|__ingraph_refusal| #refused(&__ingraph_refusal))?;
3768 // THE ONE CROSSING, and it is the record resolver's own: the row raises onto the wire
3769 // through the conversion its declaration wrote. The folded score and every slot are read off
3770 // the hit they belong to and never assembled by hand — `map_node` is the one move.
3771 ::core::iter::Iterator::collect(::core::iter::Iterator::map(
3772 ::std::vec::Vec::into_iter(__ingraph_filled),
3773 |__ingraph_hit| {
3774 let (__ingraph_score, __ingraph_streams, __ingraph_row) =
3775 #folded::into_components(__ingraph_hit);
3776 ::core::result::Result::map_err(
3777 ::core::result::Result::map(
3778 <#entity as ::core::convert::TryFrom<#row>>::try_from(__ingraph_row),
3779 |__ingraph_entity| <#hit<_, _> as ::core::convert::From<_>>::from(
3780 #folded::new(__ingraph_score, __ingraph_streams, __ingraph_entity),
3781 ),
3782 ),
3783 |__ingraph_refusal| #refused_row(&__ingraph_refusal),
3784 )
3785 },
3786 ))
3787 }
3788 }
3789 }
3790
3791 /// **THE SET ROAD'S QUESTION FIELD** — `m` POINTS a client sent, walked as `m` streams and folded
3792 /// into one ranking of addresses.
3793 ///
3794 /// ```text
3795 /// shotsByClipsKeys(question: { coordinates: [[…], […]] }) → [KeyframeKeyFoldedMatch!]!
3796 /// score the FOLD's answer over m streams
3797 /// streams { score ordinal } one nullable slot per point the request sent
3798 /// node { … }
3799 /// ```
3800 ///
3801 /// # It is [`keys_leg`](Self::keys_leg) at the OTHER LABEL, and the name does not move
3802 ///
3803 /// Same field, same `question:` argument, same engine arm, same `first`/`depth` rows, same rename
3804 /// seat. What differs is the DOOR — `retrieve_keys_by_<field>_with` — and therefore the shape of
3805 /// what is asked and what comes back: a list of points in, `m` per-stream sightings out. The label
3806 /// picks it, exactly as it already picks the by-example door; see
3807 /// [`answer_road`](Self::answer_road) for the routing.
3808 ///
3809 /// This is the road whose absence [`similar_set_leg`](Self::similar_set_leg)'s note used to point
3810 /// at — *the `_with` road asked with `m` vectors a CLIENT sends* — and it is where the protection
3811 /// that note deferred now lives.
3812 ///
3813 /// # The `m` IS THE REQUEST'S, which is the whole difference from the by-example twin
3814 ///
3815 /// The by-example road reads its streams out of an example's stored set, so its `m` is the
3816 /// deployment's own data and carries no guard. Here a client states `m`, so the declaration may
3817 /// bound it: [`points_binding`](Self::points_binding) emits `streams = N`'s refusal, and a request
3818 /// past the guard is refused naming the count rather than cut down to fit.
3819 ///
3820 /// # NOTHING IS EXCLUDED, because there is no example to exclude
3821 ///
3822 /// The by-example road drops the example from its own answer per stream. A question road has no
3823 /// address in hand at all, so every owner the engine reports is a legitimate answer — the door
3824 /// spends `owner_best` where its twin spends `owner_best_excluding`, and this leg states the
3825 /// difference rather than compensating for it.
3826 ///
3827 /// # THE FLOOR IS THE ELEMENT'S, and AN EMPTY LIST IS REFUSED BY NAME
3828 ///
3829 /// Both are [`similar_set_leg`](Self::similar_set_leg)'s word for word: the engine arm's `floor`
3830 /// row cuts each of the `m` per-vector walks and there is none in the folded currency, and
3831 /// `FoldedQuery::new` answers [`None`] for an empty list — *a set query with no query vectors asks
3832 /// nothing* — which this leg turns into a sentence naming the field and the argument.
3833 fn set_keys_leg(
3834 &self,
3835 tier: &crate::fuse::Tier<'_>,
3836 elected: &Elected,
3837 engine: &Engine,
3838 ) -> proc_macro2::TokenStream {
3839 let IndexModel { krate, index, .. } = self;
3840 let ag = framework(krate, &[], "async_graphql");
3841 let seam = framework(krate, &["store"], "VectorEngine");
3842 let hit = framework(krate, &["graphql"], "FoldedMatch");
3843 let crossed = framework(krate, &["graphql"], "folded_matches");
3844 let folded = framework(krate, &["retrieve"], "Folded");
3845 let set_query = framework(krate, &["retrieve"], "FoldedQuery");
3846 let connected = framework(krate, &["store"], "Connected");
3847 let field = &elected.field;
3848 let ty = engine
3849 .resource
3850 .as_ref()
3851 .expect("a plain road names a typed engine");
3852 let selector = tier
3853 .slot_selector(elected)
3854 .expect("a typed election mints its engine selector");
3855 let variant = format_ident!("{}", {
3856 use heck::ToUpperCamelCase as _;
3857 engine.word.to_string().to_upper_camel_case()
3858 });
3859 let key = wire_key_name();
3860 let question = self.question_name(tier, elected);
3861 let sdl = self.field_name(elected, Field::Keys);
3862 let method = crate::method::wire_method(&format_ident!("{}", crate::emit::snake(&sdl)));
3863 let door = Door::Set.name(field);
3864 let arity = wide_signature();
3865 let numbers = self.answer_numbers(&elected.field);
3866 let points = self.points_binding(&question, elected, &sdl);
3867 let fold = self.fold_binding(elected, engine);
3868 let handle = self.wire_handle(ty);
3869 let mint = self.wire_corpus(
3870 field,
3871 Some(&elected.ty),
3872 engine,
3873 ty,
3874 &format_ident!("__ingraph_slot"),
3875 &format_ident!("__ingraph_connection"),
3876 );
3877 let scope = quote_spanned! {ty.span()=> #connected::new(__ingraph_connection, ())};
3878 let (floor, options) = (
3879 format_ident!("__ingraph_floor"),
3880 format_ident!("__ingraph_options"),
3881 );
3882 let floorless = format!(
3883 "`{sdl}` needs a floor in `{engine_word}`'s own score currency — write \
3884 `engine: {{ {engine_word}: {{ floor: … }} }}`. The floor cuts each of the question's own \
3885 walks, at the grain one pair of vectors is scored in; there is no floor on the folded score, \
3886 which is in a currency no engine reports.",
3887 engine_word = engine.word,
3888 );
3889 let empty = format!(
3890 "`{sdl}` was asked with no query vectors — a set query with no query vectors asks nothing, so \
3891 there is no question here to answer. Name at least one point under \
3892 `question: {{ coordinates: [[…]] }}`.",
3893 );
3894 let doc = leading(&format!(
3895 "The addresses [`{index}`]'s `{field}` SET ranks nearest a whole QUESTION SET, in \
3896 `{engine_word}`.\n\nEach point the request sent is asked as its own query, and a FOLD is what \
3897 turns those `m` answers into one score. Every hit carries what each of those streams said, \
3898 under `streams`, in the order the request wrote its points.\n\n{fold}",
3899 engine_word = engine.word,
3900 fold = fold_note(
3901 &elected.field,
3902 Asked::Points(self.declared_streams(Some(&elected.field))),
3903 ),
3904 ));
3905 let ctx = crate::method::wire_method(&format_ident!("ctx"));
3906 let (asked, chosen, first, depth) = (
3907 crate::method::wire_method(&format_ident!("question")),
3908 crate::method::wire_method(&format_ident!("engine")),
3909 crate::method::wire_method(&format_ident!("first")),
3910 crate::method::wire_method(&format_ident!("depth")),
3911 );
3912 let default = self
3913 .wire_first(GraphqlKind::AsyncGraphql, Some(field))
3914 .get();
3915 let default = syn::LitInt::new(&default.to_string(), field.span());
3916 quote! {
3917 #[doc = #doc]
3918 #[graphql(name = #sdl)]
3919 #arity
3920 async fn #method(
3921 &self,
3922 #ctx: &#ag::Context<'_>,
3923 #[graphql(name = "question")] #asked: #question,
3924 #[graphql(name = "engine")] #chosen: ::core::option::Option<#selector>,
3925 #[graphql(name = "first", default = #default)] #first: u32,
3926 #[graphql(name = "depth")] #depth: ::core::option::Option<u32>,
3927 ) -> #ag::Result<::std::vec::Vec<#hit<#key, <#ty as #seam>::Score>>> {
3928 #numbers
3929 #points
3930 let (#floor, #options) = match #chosen {
3931 ::core::option::Option::Some(#selector::#variant(ref __ingraph_named)) => (
3932 ::core::option::Option::map(__ingraph_named.floor(), ::core::clone::Clone::clone),
3933 __ingraph_named.options(),
3934 ),
3935 ::core::option::Option::None => (
3936 ::core::option::Option::None,
3937 ::core::option::Option::None,
3938 ),
3939 };
3940 let ::core::option::Option::Some(#floor) = #floor else {
3941 return ::core::result::Result::Err(#ag::Error::new(#floorless));
3942 };
3943 // THE EMPTY QUESTION, named — and the CONSTRUCTOR is what names it: `FoldedQuery::new` answers
3944 // `None` for an empty list, so the law lives at the type and this leg spends it rather than
3945 // restating it as a length test of its own.
3946 let ::core::option::Option::Some(__ingraph_query) =
3947 #set_query::new(__ingraph_points, #floor)
3948 else {
3949 return ::core::result::Result::Err(#ag::Error::new(#empty));
3950 };
3951 #mint
3952 #fold
3953 let mut __ingraph_folded: ::std::vec::Vec<#folded<_, _>> = #index::#door::<#handle, _>(
3954 &mut __ingraph_slot,
3955 #scope,
3956 &__ingraph_query,
3957 __ingraph_fold,
3958 __ingraph_fetch,
3959 // THE PER-STREAM DEPTH IS THE DOOR'S OWN DEFAULT, which is the fetch above — the
3960 // by-example twin's line, and its reason unchanged: `depth` is the FETCH on this family's
3961 // wire and there is one such row, so passing it twice would be one number wearing two
3962 // names.
3963 ::core::option::Option::None,
3964 #options,
3965 )
3966 .await
3967 .map_err(|__ingraph_refusal| #ag::Error::new(::std::format!(
3968 "`{}` folded under `{}` and the road refused: {}",
3969 #sdl,
3970 __ingraph_fold_name,
3971 __ingraph_refusal,
3972 )))?;
3973 // THE PAGE, cut after the fold — `depth` bought the FETCH and `first` is what a client asked
3974 // to read. The fold's own budget counts ENTITIES, so the two numbers differ wherever the
3975 // floor pruned a stream.
3976 ::std::vec::Vec::truncate(
3977 &mut __ingraph_folded,
3978 ::core::num::NonZeroUsize::get(__ingraph_page),
3979 );
3980 ::core::result::Result::Ok(#crossed(
3981 ::core::iter::Iterator::map(
3982 ::std::vec::Vec::into_iter(__ingraph_folded),
3983 |__ingraph_hit| {
3984 let __ingraph_key = ::core::clone::Clone::clone(#folded::node_ref(&__ingraph_hit));
3985 #folded::map_node(
3986 __ingraph_hit,
3987 <#key as ::core::convert::From<_>>::from(__ingraph_key),
3988 )
3989 },
3990 ),
3991 ))
3992 }
3993 }
3994 }
3995
3996 /// **THE SET ROAD'S QUESTION FIELD, HYDRATED** — `m` points in, the neighbours' whole rows out,
3997 /// each wearing the folded score and every per-stream sighting.
3998 ///
3999 /// [`set_keys_leg`](Self::set_keys_leg)'s every measurement holds, and
4000 /// [`similar_set_hydrated_leg`](Self::similar_set_hydrated_leg)'s: the row is the fork point, the
4001 /// pool is the surface `Send` admits, the page is cut at the fill loop, and `folded_filled` is what
4002 /// moves the folded score and every slot onto the entity found under the key.
4003 ///
4004 /// It is mounted for its twin's reason and unmounted for the same one: a declaration wearing the
4005 /// head's `keys` word has an ENTITY upstream and no store for this tier to read rows out of.
4006 fn set_hydrated_leg(
4007 &self,
4008 tier: &crate::fuse::Tier<'_>,
4009 elected: &Elected,
4010 engine: &Engine,
4011 ) -> proc_macro2::TokenStream {
4012 let IndexModel { krate, index, .. } = self;
4013 let ag = framework(krate, &[], "async_graphql");
4014 let seam = framework(krate, &["store"], "VectorEngine");
4015 let hit = framework(krate, &["graphql"], "FoldedMatch");
4016 let sql_door = framework(krate, &["graphql"], "SqlDoor");
4017 let refused = framework(krate, &["graphql"], "refused");
4018 let refused_row = framework(krate, &["graphql"], "refused_row");
4019 let gather = framework(krate, &["retrieve"], "SqlPooledGather");
4020 let fill = framework(krate, &["retrieve"], "folded_filled");
4021 let folded = framework(krate, &["retrieve"], "Folded");
4022 let set_query = framework(krate, &["retrieve"], "FoldedQuery");
4023 let connected = framework(krate, &["store"], "Connected");
4024 let field = &elected.field;
4025 let ty = engine
4026 .resource
4027 .as_ref()
4028 .expect("a plain road names a typed engine");
4029 let selector = tier
4030 .slot_selector(elected)
4031 .expect("a typed election mints its engine selector");
4032 let variant = format_ident!("{}", {
4033 use heck::ToUpperCamelCase as _;
4034 engine.word.to_string().to_upper_camel_case()
4035 });
4036 let (db, row, entity) = hydration_names();
4037 let question = self.question_name(tier, elected);
4038 let sdl = self.field_name(elected, Field::Hydrated);
4039 let method = crate::method::wire_method(&format_ident!("{}", crate::emit::snake(&sdl)));
4040 let door = Door::Set.name(field);
4041 let arity = wide_signature();
4042 let numbers = self.answer_numbers(&elected.field);
4043 let points = self.points_binding(&question, elected, &sdl);
4044 let fold = self.fold_binding(elected, engine);
4045 let handle = self.wire_handle(ty);
4046 let mint = self.wire_corpus(
4047 field,
4048 Some(&elected.ty),
4049 engine,
4050 ty,
4051 &format_ident!("__ingraph_slot"),
4052 &format_ident!("__ingraph_connection"),
4053 );
4054 let scope = quote_spanned! {ty.span()=> #connected::new(__ingraph_connection, ())};
4055 let (floor, options) = (
4056 format_ident!("__ingraph_floor"),
4057 format_ident!("__ingraph_options"),
4058 );
4059 let floorless = format!(
4060 "`{sdl}` needs a floor in `{engine_word}`'s own score currency — write \
4061 `engine: {{ {engine_word}: {{ floor: … }} }}`. The floor cuts each of the question's own \
4062 walks, at the grain one pair of vectors is scored in; there is no floor on the folded score, \
4063 which is in a currency no engine reports.",
4064 engine_word = engine.word,
4065 );
4066 let empty = format!(
4067 "`{sdl}` was asked with no query vectors — a set query with no query vectors asks nothing, so \
4068 there is no question here to answer. Name at least one point under \
4069 `question: {{ coordinates: [[…]] }}`.",
4070 );
4071 let doc = leading(&format!(
4072 "The WHOLE UPSTREAM ENTITIES [`{index}`]'s `{field}` SET ranks nearest a whole QUESTION SET, \
4073 in `{engine_word}` — each neighbour wearing the folded score and the per-stream sightings its \
4074 address carried.\n\nA neighbour whose row the system of record no longer holds is absent, and \
4075 the ordinals it held stay holes.\n\n{fold}",
4076 engine_word = engine.word,
4077 fold = fold_note(
4078 &elected.field,
4079 Asked::Points(self.declared_streams(Some(&elected.field))),
4080 ),
4081 ));
4082 let ctx = crate::method::wire_method(&format_ident!("ctx"));
4083 let (asked, chosen, first, depth) = (
4084 crate::method::wire_method(&format_ident!("question")),
4085 crate::method::wire_method(&format_ident!("engine")),
4086 crate::method::wire_method(&format_ident!("first")),
4087 crate::method::wire_method(&format_ident!("depth")),
4088 );
4089 let default = self
4090 .wire_first(GraphqlKind::AsyncGraphql, Some(field))
4091 .get();
4092 let default = syn::LitInt::new(&default.to_string(), field.span());
4093 quote! {
4094 #[doc = #doc]
4095 #[graphql(name = #sdl)]
4096 #arity
4097 async fn #method(
4098 &self,
4099 #ctx: &#ag::Context<'_>,
4100 #[graphql(name = "question")] #asked: #question,
4101 #[graphql(name = "engine")] #chosen: ::core::option::Option<#selector>,
4102 #[graphql(name = "first", default = #default)] #first: u32,
4103 #[graphql(name = "depth")] #depth: ::core::option::Option<u32>,
4104 ) -> #ag::Result<::std::vec::Vec<#hit<#entity, <#ty as #seam>::Score>>> {
4105 #numbers
4106 #points
4107 let (#floor, #options) = match #chosen {
4108 ::core::option::Option::Some(#selector::#variant(ref __ingraph_named)) => (
4109 ::core::option::Option::map(__ingraph_named.floor(), ::core::clone::Clone::clone),
4110 __ingraph_named.options(),
4111 ),
4112 ::core::option::Option::None => (
4113 ::core::option::Option::None,
4114 ::core::option::Option::None,
4115 ),
4116 };
4117 let ::core::option::Option::Some(#floor) = #floor else {
4118 return ::core::result::Result::Err(#ag::Error::new(#floorless));
4119 };
4120 let ::core::option::Option::Some(__ingraph_query) =
4121 #set_query::new(__ingraph_points, #floor)
4122 else {
4123 return ::core::result::Result::Err(#ag::Error::new(#empty));
4124 };
4125 #mint
4126 let __ingraph_door = #ag::Context::data::<#sql_door<#db>>(#ctx)?;
4127 #fold
4128 let __ingraph_folded: ::std::vec::Vec<#folded<_, _>> = #index::#door::<#handle, _>(
4129 &mut __ingraph_slot,
4130 #scope,
4131 &__ingraph_query,
4132 __ingraph_fold,
4133 __ingraph_fetch,
4134 ::core::option::Option::None,
4135 #options,
4136 )
4137 .await
4138 .map_err(|__ingraph_refusal| #ag::Error::new(::std::format!(
4139 "`{}` folded under `{}` and the road refused: {}",
4140 #sdl,
4141 __ingraph_fold_name,
4142 __ingraph_refusal,
4143 )))?;
4144 let mut __ingraph_gather = #gather::<#row, #db>::new(#sql_door::pool(__ingraph_door));
4145 let __ingraph_filled = #fill(
4146 __ingraph_folded,
4147 &mut __ingraph_gather,
4148 ::core::option::Option::None,
4149 ::core::num::NonZeroUsize::get(__ingraph_page),
4150 )
4151 .await
4152 .map_err(|__ingraph_refusal| #refused(&__ingraph_refusal))?;
4153 ::core::iter::Iterator::collect(::core::iter::Iterator::map(
4154 ::std::vec::Vec::into_iter(__ingraph_filled),
4155 |__ingraph_hit| {
4156 let (__ingraph_score, __ingraph_streams, __ingraph_row) =
4157 #folded::into_components(__ingraph_hit);
4158 ::core::result::Result::map_err(
4159 ::core::result::Result::map(
4160 <#entity as ::core::convert::TryFrom<#row>>::try_from(__ingraph_row),
4161 |__ingraph_entity| <#hit<_, _> as ::core::convert::From<_>>::from(
4162 #folded::new(__ingraph_score, __ingraph_streams, __ingraph_entity),
4163 ),
4164 ),
4165 |__ingraph_refusal| #refused_row(&__ingraph_refusal),
4166 )
4167 },
4168 ))
4169 }
4170 }
4171 }
4172
4173 /// The TWO NUMBERS every answer leg resolves before it touches a door — the fetch depth and the
4174 /// page — with the edge-zero law as the one early return.
4175 ///
4176 /// Written once because both roads spend it identically and a chain written twice is a chain that
4177 /// can drift at one of them.
4178 fn answer_numbers(&self, field: &syn::Ident) -> proc_macro2::TokenStream {
4179 let depth = framework(&self.krate, &["retrieve"], "route_depth");
4180 // TWO COPIES OF ONE WALL, and it is the borrow rather than two facts: the token is
4181 // `Option::as_ref(&NonZeroU32::new(N))`, whose temporary lives to the end of the statement it
4182 // sits in, so the two `let`s below cannot share one.
4183 let (wall, again) = (self.wall(Some(field)), self.wall(Some(field)));
4184 let first = crate::method::wire_method(&format_ident!("first"));
4185 let written = crate::method::wire_method(&format_ident!("depth"));
4186 quote! {
4187 // THE EDGE-ZERO LAW, and it is the same line as the widening: the door's currency admits no
4188 // zero, so `first: 0` is not a smaller question but no question at all — answered here,
4189 // before any door, any slot lookup and any engine call.
4190 let ::core::option::Option::Some(__ingraph_budget) = ::core::num::NonZeroU32::new(#first)
4191 else {
4192 return ::core::result::Result::Ok(::std::vec::Vec::new());
4193 };
4194 let __ingraph_budget = ::core::result::Result::unwrap_or(
4195 <::core::num::NonZeroUsize as ::core::convert::TryFrom<::core::num::NonZeroU32>>::try_from(
4196 __ingraph_budget,
4197 ),
4198 ::core::num::NonZeroUsize::MAX,
4199 );
4200 let __ingraph_fetch = #depth(
4201 ::core::option::Option::map(
4202 ::core::option::Option::and_then(#written, ::core::num::NonZeroU32::new),
4203 |__ingraph_asked| ::core::result::Result::unwrap_or(
4204 <::core::num::NonZeroUsize as ::core::convert::TryFrom<
4205 ::core::num::NonZeroU32,
4206 >>::try_from(__ingraph_asked),
4207 ::core::num::NonZeroUsize::MAX,
4208 ),
4209 ),
4210 #wall,
4211 __ingraph_budget,
4212 );
4213 // THE PAGE is the ask with NO edge — `min(first, wall)` — which is the same law read with
4214 // nothing written at the request: what a client may read is what it asked for, inside the
4215 // wall it may never ask past.
4216 let __ingraph_page = #depth(::core::option::Option::None, #again, __ingraph_budget);
4217 }
4218 }
4219
4220 /// THE POINT a request named, width-checked against the election's own projection.
4221 ///
4222 /// The refusal names the FIELD and BOTH numbers, which is the whole reason the check is here
4223 /// rather than in the input's `parse`: a GraphQL list carries no width, so nothing below this can
4224 /// know that four coordinates were asked of a 768-wide column.
4225 ///
4226 /// A SET election's question road binds [`points_binding`](Self::points_binding) instead — the
4227 /// same check per point, with the offending index named — and the two are exclusive, the label
4228 /// having already chosen which door the leg calls.
4229 fn point_binding(&self, asked: &syn::Ident, elected: &Elected) -> proc_macro2::TokenStream {
4230 let embedding = framework(&self.krate, &["storage"], "Embedding");
4231 let ag = framework(&self.krate, &[], "async_graphql");
4232 let question = crate::method::wire_method(&format_ident!("question"));
4233 let field = elected.field.to_string();
4234 let (width, space, element) = answer_geometry(elected);
4235 quote! {
4236 let #question = match #question {
4237 #asked::Coordinates(__ingraph_written) => __ingraph_written,
4238 };
4239 let __ingraph_given = ::std::vec::Vec::len(&#question);
4240 let ::core::option::Option::Some(__ingraph_point) =
4241 <#embedding<#element, { #width }, #space>>::new(::std::sync::Arc::from(#question))
4242 else {
4243 return ::core::result::Result::Err(#ag::Error::new(::std::format!(
4244 "`{field}` embeds at {width} coordinates and this question carries {given}",
4245 field = #field,
4246 width = #width,
4247 given = __ingraph_given,
4248 )));
4249 };
4250 }
4251 }
4252
4253 /// THE `m` POINTS a request named, each width-checked, bound to `__ingraph_points` — and the
4254 /// declared stream guard, where one was written.
4255 ///
4256 /// [`point_binding`](Self::point_binding)'s twin one list deeper, and every word of that one's
4257 /// note holds per point: a GraphQL list carries no width, so nothing below this can know that four
4258 /// coordinates were asked of a 768-wide column.
4259 ///
4260 /// # The refusal names WHICH point, which is the whole reason the loop is written out
4261 ///
4262 /// A request carrying `m` lists has `m` chances to get the width wrong, and a sentence naming the
4263 /// field and both numbers would leave the author to find the offender by bisection. The index is
4264 /// the position in the list the client itself wrote, so it is a number they can act on.
4265 ///
4266 /// # The GUARD is emitted only where a declaration wrote one, and it REFUSES
4267 ///
4268 /// `streams = N` — see [`Numbers::streams`] for the protection-tier reading and
4269 /// [`declared_streams`](Self::declared_streams) for the two-tier chain. Past the guard the request
4270 /// is refused whole and never cut down to fit: dropping query vectors answers a different question
4271 /// under the same name, which is the ruled refuse-don't-chunk law read at `m`. Where no tier wrote
4272 /// a guard nothing at all is emitted, so an unguarded road is byte-for-byte what it was before the
4273 /// word existed.
4274 ///
4275 /// The EMPTINESS is deliberately NOT checked here: `FoldedQuery::new` answers [`None`] for an empty
4276 /// list and the leg spends that, so *a set query with no query vectors asks nothing* keeps ONE
4277 /// authority.
4278 fn points_binding(
4279 &self,
4280 asked: &syn::Ident,
4281 elected: &Elected,
4282 sdl: &str,
4283 ) -> proc_macro2::TokenStream {
4284 let embedding = framework(&self.krate, &["storage"], "Embedding");
4285 let ag = framework(&self.krate, &[], "async_graphql");
4286 let question = crate::method::wire_method(&format_ident!("question"));
4287 let field = elected.field.to_string();
4288 let (width, space, element) = answer_geometry(elected);
4289 let guard = match self.declared_streams(Some(&elected.field)) {
4290 Some(cap) => {
4291 let past = format!(
4292 "`{sdl}` admits at most {cap} query vectors and this question carries {{asked}} — \
4293 `streams = {cap}` is what this declaration lets ONE request spend. The question is not \
4294 cut down to fit: dropping query vectors answers a different question under the same \
4295 name, so one past the guard is refused whole. Ask it in batches of {cap}.",
4296 cap = cap.get(),
4297 );
4298 let cap = syn::LitInt::new(&cap.get().to_string(), elected.field.span());
4299 quote! {
4300 if __ingraph_asked > #cap {
4301 return ::core::result::Result::Err(#ag::Error::new(::std::format!(
4302 #past,
4303 asked = __ingraph_asked,
4304 )));
4305 }
4306 }
4307 }
4308 None => proc_macro2::TokenStream::new(),
4309 };
4310 quote! {
4311 let #question = match #question {
4312 #asked::Coordinates(__ingraph_written) => __ingraph_written,
4313 };
4314 let __ingraph_asked = ::std::vec::Vec::len(&#question);
4315 #guard
4316 let mut __ingraph_points = ::std::vec::Vec::with_capacity(__ingraph_asked);
4317 for (__ingraph_at, __ingraph_written) in
4318 ::core::iter::Iterator::enumerate(::std::vec::Vec::into_iter(#question))
4319 {
4320 let __ingraph_given = ::std::vec::Vec::len(&__ingraph_written);
4321 let ::core::option::Option::Some(__ingraph_point) =
4322 <#embedding<#element, { #width }, #space>>::new(::std::sync::Arc::from(__ingraph_written))
4323 else {
4324 return ::core::result::Result::Err(#ag::Error::new(::std::format!(
4325 "`{field}` embeds at {width} coordinates and query vector {at} of this question \
4326 carries {given}",
4327 field = #field,
4328 width = #width,
4329 at = __ingraph_at,
4330 given = __ingraph_given,
4331 )));
4332 };
4333 ::std::vec::Vec::push(&mut __ingraph_points, __ingraph_point);
4334 }
4335 }
4336 }
4337
4338 /// **THE FANNED ROAD's ANSWER FAMILY** — one object per leg, the union over them, and the hit that
4339 /// carries a fused root with its whole provenance.
4340 ///
4341 /// # Why a UNION and not one object with a nullable score per leg
4342 ///
4343 /// A sighting IS one leg's — the fold produced it by reading that leg's ranking — and each leg
4344 /// scores in its own engine's currency, which crosses AS ITSELF. A product with `deep: Float` beside
4345 /// `shallow: Float` would publish a shape where both could be set, neither could, and the two
4346 /// currencies had been flattened into one; the sum publishes the fact.
4347 ///
4348 /// # The FOLD's own numbers are `Float` at every arm, and that is not an inconsistency
4349 ///
4350 /// `contribution` is `weight × 1/(k + rank)` and the hit's `score` is their sum — the FRAMEWORK's
4351 /// arithmetic over ordinals rather than any engine's measurement — so they are one type however
4352 /// many currencies met. [`Sighting`](https://docs.rs/ingraph) states the same split one layer down.
4353 fn fused_answer(
4354 &self,
4355 tier: &crate::fuse::Tier<'_>,
4356 elected: &Elected,
4357 legs: &[&Engine],
4358 ) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
4359 use heck::ToUpperCamelCase as _;
4360
4361 let IndexModel {
4362 vis, krate, index, ..
4363 } = self;
4364 let ag = framework(krate, &[], "async_graphql");
4365 let shelf = crate::emit::vendored(krate, "async_graphql");
4366 let seam = framework(krate, &["store"], "VectorEngine");
4367 let transformer = framework(krate, &["transform"], "Transformer");
4368 let face = framework(krate, &["transform"], "Graphql");
4369 let output = framework(krate, &["transform"], "GraphqlOutput");
4370 let upstream = &self.source.node;
4371 let field = &elected.field;
4372 let stem = tier.stem(elected);
4373 let union = format_ident!("{stem}Sighting");
4374 let hit = format_ident!("{stem}FusedKeyMatch");
4375 let engines = format_ident!("{stem}Engines");
4376 let key = wire_key_name();
4377 let members: Vec<syn::Ident> = legs
4378 .iter()
4379 .map(|engine| {
4380 format_ident!(
4381 "{stem}{}Sighting",
4382 engine.word.to_string().to_upper_camel_case()
4383 )
4384 })
4385 .collect();
4386 let variants: Vec<syn::Ident> = legs
4387 .iter()
4388 .map(|engine| format_ident!("{}", engine.word.to_string().to_upper_camel_case()))
4389 .collect();
4390 let scores: Vec<proc_macro2::TokenStream> = legs
4391 .iter()
4392 .map(|engine| {
4393 let ty = engine
4394 .resource
4395 .as_ref()
4396 .expect("a fanned road types every leg");
4397 quote!(<#ty as #seam>::Score)
4398 })
4399 .collect();
4400
4401 // THE ENGINES PRODUCT — one row per leg, each holding that leg's OWN `{floor, options}` package.
4402 //
4403 // A PRODUCT where the selector beside it is a SUM, and the two shapes say two different things:
4404 // the `@oneOf` selector picks ONE leg to read directly, and this names them ALL because the
4405 // fused road walks them all and every one of them needs a floor in its own currency. Built
4406 // through the tier's own package emitter, so its factory chain, its readers and its input face
4407 // are the ones every other package in this family has.
4408 let engines_package = tier.packages().package(
4409 &engines,
4410 &format!(
4411 "The per-leg knobs a FUSED retrieve over [`{index}`]'s `{field}` runs under — one row per \
4412 store the field is written to, each holding that store's own floor and per-query knobs.\n\n\
4413 Every row is the requester's, and the floor is the one this framework cannot default: a \
4414 score's direction belongs to the engine that measures in it."
4415 ),
4416 &legs
4417 .iter()
4418 .map(|engine| {
4419 crate::fuse::Row::new(
4420 &engine.word,
4421 {
4422 let package = tier.engine_input(&stem, engine);
4423 quote!(#package)
4424 },
4425 &format!("`{}` leg", engine.word),
4426 )
4427 })
4428 .collect::<Vec<_>>(),
4429 );
4430
4431 let sighting_docs = members.iter().zip(legs).map(|(member, engine)| {
4432 let doc = leading(&format!(
4433 "What the `{word}` store said about a fused root of [`{index}`]'s `{field}` — its own \
4434 score, its own ordinal, and what that ordinal contributed to the fused score.",
4435 word = engine.word,
4436 ));
4437 let ty = engine
4438 .resource
4439 .as_ref()
4440 .expect("a fanned road types every leg");
4441 let score = quote!(<#ty as #seam>::Score);
4442 let members = crate::emit::substrate();
4443 quote! {
4444 #[doc = #doc]
4445 #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
4446 #vis struct #member {
4447 #members score: #score,
4448 #members ordinal: ::core::primitive::u64,
4449 #members contribution: ::core::primitive::f64,
4450 }
4451
4452 #[automatically_derived]
4453 impl #member {
4454 #[doc = " One sighting, in the order the fold hands its three numbers over."]
4455 #[must_use]
4456 #[inline]
4457 #vis const fn new(
4458 score: #score,
4459 ordinal: ::core::primitive::u64,
4460 contribution: ::core::primitive::f64,
4461 ) -> Self {
4462 Self { score, ordinal, contribution }
4463 }
4464
4465 #[doc = " The score this store gave the root, in this store's own currency."]
4466 #[must_use]
4467 #[inline]
4468 #vis const fn score_ref(&self) -> &#score {
4469 &self.score
4470 }
4471
4472 #[doc = " The 1-based ordinal this store gave the root in its own stream."]
4473 #[must_use]
4474 #[inline]
4475 #vis const fn ordinal(&self) -> ::core::primitive::u64 {
4476 self.ordinal
4477 }
4478
4479 #[doc = " The weighted term that ordinal added to the fused score."]
4480 #[must_use]
4481 #[inline]
4482 #vis const fn contribution(&self) -> ::core::primitive::f64 {
4483 self.contribution
4484 }
4485 }
4486 }
4487 });
4488
4489 let union_doc = leading(&format!(
4490 "WHICH of [`{index}`]'s `{field}` stores saw a fused root, and what it said — one arm per leg \
4491 the answer can name."
4492 ));
4493 let hit_doc = leading(&format!(
4494 "One fused address of [`{index}`]'s `{field}`: where it landed, what the fold scored it, and \
4495 every store that put it there.\n\nThe evidence is CONTRIBUTION-ORDERED — the biggest mover \
4496 first — which is the order the fold itself produced."
4497 ));
4498 let substrate = crate::emit::substrate();
4499 let declared = quote! {
4500 #engines_package
4501
4502 #(#sighting_docs)*
4503
4504 #[doc = #union_doc]
4505 #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
4506 #vis enum #union {
4507 #(#variants(#members),)*
4508 }
4509
4510 // NO `PartialEq`: the row carries the UPSTREAM's address object, which is a wire projection
4511 // and derives none — and a derive here would make this type's faces depend on a decision
4512 // another declaration's emission made. The two rows that ARE comparable carry their own.
4513 #[doc = #hit_doc]
4514 #[derive(::core::fmt::Debug, ::core::clone::Clone)]
4515 #vis struct #hit {
4516 #substrate key:
4517 <<<#upstream as #transformer>::Graphql as #face>::Output as #output>::Key,
4518 #substrate score: ::core::primitive::f64,
4519 #substrate evidence: ::std::vec::Vec<#union>,
4520 }
4521
4522 #[automatically_derived]
4523 impl #hit {
4524 #[doc = " One fused hit, in the order the fold hands its three parts over."]
4525 #[must_use]
4526 #[inline]
4527 #vis const fn new(
4528 key: <<<#upstream as #transformer>::Graphql as #face>::Output as #output>::Key,
4529 score: ::core::primitive::f64,
4530 evidence: ::std::vec::Vec<#union>,
4531 ) -> Self {
4532 Self { key, score, evidence }
4533 }
4534
4535 #[doc = " The address, borrowed."]
4536 #[must_use]
4537 #[inline]
4538 #vis const fn key_ref(
4539 &self,
4540 ) -> &<<<#upstream as #transformer>::Graphql as #face>::Output as #output>::Key {
4541 &self.key
4542 }
4543
4544 #[doc = " The FUSED score — comparable against the other rows of this answer and nothing else."]
4545 #[must_use]
4546 #[inline]
4547 #vis const fn score(&self) -> ::core::primitive::f64 {
4548 self.score
4549 }
4550
4551 #[doc = " Every store that saw this root, biggest mover first."]
4552 #[must_use]
4553 #[inline]
4554 #vis fn evidence(&self) -> &[#union] {
4555 &self.evidence
4556 }
4557 }
4558 };
4559
4560 let member_faces = members
4561 .iter()
4562 .zip(&scores)
4563 .zip(legs)
4564 .map(|((member, score), engine)| {
4565 let sdl = tier.packages().sdl(member);
4566 let word = &engine.word;
4567 let doc = format!("What the `{word}` store said about this root.");
4568 let (score_method, ordinal, contribution) = (
4569 crate::method::wire_method(&format_ident!("score")),
4570 crate::method::wire_method(&format_ident!("ordinal")),
4571 crate::method::wire_method(&format_ident!("contribution")),
4572 );
4573 quote! {
4574 #[doc = #doc]
4575 #[#ag::Object(crate = #shelf, name = #sdl)]
4576 impl #member {
4577 #[graphql(name = "score")]
4578 async fn #score_method(&self) -> &#score {
4579 #member::score_ref(self)
4580 }
4581
4582 #[graphql(name = "ordinal")]
4583 async fn #ordinal(&self) -> ::core::primitive::u64 {
4584 #member::ordinal(self)
4585 }
4586
4587 #[graphql(name = "contribution")]
4588 async fn #contribution(&self) -> ::core::primitive::f64 {
4589 #member::contribution(self)
4590 }
4591 }
4592 }
4593 });
4594
4595 let union_sdl = tier.packages().sdl(&union);
4596 let hit_sdl = tier.packages().sdl(&hit);
4597 // THE ROW WORD IS `node`, which is the Match family's across every tier — see
4598 // `ingraph::graphql::Match`, whose Rust field has carried the word since the type was written.
4599 // The METHOD is named for the row it publishes and the FIELD keeps the Rust noun it holds, which
4600 // is the same split the hand-written face draws.
4601 let (node_method, score_method, evidence_method) = (
4602 crate::method::wire_method(&format_ident!("node")),
4603 crate::method::wire_method(&format_ident!("score")),
4604 crate::method::wire_method(&format_ident!("evidence")),
4605 );
4606 let hit_face_doc = "One fused result: the address, the fused score, and every store that put it \
4607 there.";
4608 let face = quote! {
4609 #(#member_faces)*
4610
4611 // THE UNION, written out. `#[derive(Union)]` is unreachable from an emission: a derive is
4612 // written ON the declaration, the declaration is ungated so that a build with no wire binding
4613 // still compiles, and `#[cfg_attr]` cannot bridge the two — that predicate asks whether the
4614 // DECLARING crate has a feature called `async-graphql`, which is a different manifest.
4615 #[automatically_derived]
4616 impl #ag::resolver_utils::ContainerType for #union {
4617 async fn resolve_field(
4618 &self,
4619 _ctx: &#ag::Context<'_>,
4620 ) -> #ag::ServerResult<::core::option::Option<#ag::Value>> {
4621 ::core::result::Result::Ok(::core::option::Option::None)
4622 }
4623
4624 fn collect_all_fields<'__ingraph_seen>(
4625 &'__ingraph_seen self,
4626 __ingraph_ctx: &#ag::ContextSelectionSet<'__ingraph_seen>,
4627 __ingraph_fields: &mut #ag::resolver_utils::Fields<'__ingraph_seen>,
4628 ) -> #ag::ServerResult<()> {
4629 match self {
4630 #(Self::#variants(__ingraph_arm) => #ag::resolver_utils::ContainerType::collect_all_fields(
4631 __ingraph_arm,
4632 __ingraph_ctx,
4633 __ingraph_fields,
4634 ),)*
4635 }
4636 }
4637 }
4638
4639 #[automatically_derived]
4640 impl #ag::OutputType for #union {
4641 fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
4642 ::std::borrow::Cow::Borrowed(#union_sdl)
4643 }
4644
4645 fn introspection_type_name(&self) -> ::std::borrow::Cow<'static, ::core::primitive::str> {
4646 match self {
4647 #(Self::#variants(_) => <#members as #ag::OutputType>::type_name(),)*
4648 }
4649 }
4650
4651 fn create_type_info(
4652 __ingraph_registry: &mut #ag::registry::Registry,
4653 ) -> ::std::string::String {
4654 __ingraph_registry.create_output_type::<Self, _>(
4655 #ag::registry::MetaTypeId::Union,
4656 |__ingraph_registry| {
4657 #(<#members as #ag::OutputType>::create_type_info(__ingraph_registry);)*
4658 #ag::registry::MetaType::Union {
4659 name: ::std::string::String::from(#union_sdl),
4660 description: ::core::option::Option::None,
4661 possible_types: {
4662 let mut __ingraph_arms = #ag::indexmap::IndexSet::new();
4663 #(__ingraph_arms.insert(::std::borrow::Cow::into_owned(
4664 <#members as #ag::OutputType>::type_name(),
4665 ));)*
4666 __ingraph_arms
4667 },
4668 visible: ::core::option::Option::None,
4669 inaccessible: false,
4670 tags: ::std::vec::Vec::new(),
4671 rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
4672 directive_invocations: ::std::vec::Vec::new(),
4673 }
4674 },
4675 )
4676 }
4677
4678 async fn resolve(
4679 &self,
4680 __ingraph_ctx: &#ag::ContextSelectionSet<'_>,
4681 _field: &#ag::Positioned<#ag::parser::types::Field>,
4682 ) -> #ag::ServerResult<#ag::Value> {
4683 #ag::resolver_utils::resolve_container(__ingraph_ctx, self).await
4684 }
4685 }
4686
4687 #[automatically_derived]
4688 impl #ag::UnionType for #union {}
4689
4690 #[doc = #hit_face_doc]
4691 #[#ag::Object(crate = #shelf, name = #hit_sdl)]
4692 impl #hit {
4693 #[graphql(name = "node")]
4694 async fn #node_method(&self) -> &#key {
4695 #hit::key_ref(self)
4696 }
4697
4698 #[graphql(name = "score")]
4699 async fn #score_method(&self) -> ::core::primitive::f64 {
4700 #hit::score(self)
4701 }
4702
4703 #[graphql(name = "evidence")]
4704 async fn #evidence_method(&self) -> &[#union] {
4705 #hit::evidence(self)
4706 }
4707 }
4708 };
4709 (declared, face)
4710 }
4711
4712 /// **THE FUSED ROAD's QUERY FIELD** — one question, every store the field is written to, one
4713 /// leaderboard.
4714 ///
4715 /// The floors are per LEG and per CURRENCY, which is why the argument is a product rather than the
4716 /// `@oneOf` selector: the fused road walks every leg, and two stores holding one field score in
4717 /// two units that do not convert. The selector's road — read ONE named leg directly — is not
4718 /// published here; it is the same door with `options.engine` set, and it belongs to the round that
4719 /// gives this field its fuse options.
4720 fn fused_leg(
4721 &self,
4722 tier: &crate::fuse::Tier<'_>,
4723 elected: &Elected,
4724 legs: &[&Engine],
4725 ) -> proc_macro2::TokenStream {
4726 use heck::ToUpperCamelCase as _;
4727
4728 let IndexModel { krate, index, .. } = self;
4729 let ag = framework(krate, &[], "async_graphql");
4730 let marker = framework(krate, &["election"], "EmbeddingMarker");
4731 let connected = framework(krate, &["store"], "Connected");
4732 let fused = framework(krate, &["retrieve"], "Fused");
4733 let fused_score = framework(krate, &["retrieve"], "FusedScore");
4734 let sighting = framework(krate, &["retrieve"], "Sighting");
4735 let field = &elected.field;
4736 let ty = &elected.ty;
4737 let stem = tier.stem(elected);
4738 let question = self.question_name(tier, elected);
4739 let engines_ty = format_ident!("{stem}Engines");
4740 let union = format_ident!("{stem}Sighting");
4741 let hit = format_ident!("{stem}FusedKeyMatch");
4742 let evidence = tier.slot_evidence_name(elected);
4743 let asked_package = tier.route_question(elected);
4744 let key = wire_key_name();
4745 let door = Door::FusedLegs.name(field);
4746 let sdl = self.field_name(elected, Field::Fused);
4747 let method = crate::method::wire_method(&format_ident!("{}", crate::emit::snake(&sdl)));
4748 let arity = wide_signature();
4749 let numbers = self.answer_numbers(&elected.field);
4750 let point = self.point_binding(&question, elected);
4751 let engines: Vec<&syn::Path> = legs
4752 .iter()
4753 .map(|engine| {
4754 engine
4755 .resource
4756 .as_ref()
4757 .expect("a fanned road types every leg")
4758 })
4759 .collect();
4760 // ONE HANDLE PER LEG — what the fused door's engine parameters are. A leg names a MOUNT and the
4761 // door is bounded on a read face, so every parameter is the CORPUS type that mount mints.
4762 let handles: Vec<proc_macro2::TokenStream> =
4763 engines.iter().map(|ty| self.wire_handle(ty)).collect();
4764 let variants: Vec<syn::Ident> = legs
4765 .iter()
4766 .map(|engine| format_ident!("{}", engine.word.to_string().to_upper_camel_case()))
4767 .collect();
4768 let members: Vec<syn::Ident> = legs
4769 .iter()
4770 .map(|engine| {
4771 format_ident!(
4772 "{stem}{}Sighting",
4773 engine.word.to_string().to_upper_camel_case()
4774 )
4775 })
4776 .collect();
4777 let ctx = crate::method::wire_method(&format_ident!("ctx"));
4778 let seats = legs.iter().enumerate().map(|(at, engine)| {
4779 let engine_ty = engines[at];
4780 let reader = &engine.word;
4781 let (floor, options, slot, connection) = (
4782 format_ident!("__ingraph_floor_{}", engine.word),
4783 format_ident!("__ingraph_options_{}", engine.word),
4784 format_ident!("__ingraph_slot_{}", engine.word),
4785 format_ident!("__ingraph_connection_{}", engine.word),
4786 );
4787 let mint = self.wire_corpus(
4788 field,
4789 Some(&elected.ty),
4790 engine,
4791 engine_ty,
4792 &slot,
4793 &connection,
4794 );
4795 let floorless = format!(
4796 "`{sdl}` needs a floor in `{reader}`'s own score currency — write \
4797 `engines: {{ {reader}: {{ floor: … }} }}`. Every leg of a fused read states its own, \
4798 because two stores holding one field score in two units that do not convert, and there is \
4799 no number this framework could put there instead: a score's DIRECTION belongs to the \
4800 engine that measures in it."
4801 );
4802 let seat = crate::method::wire_method(&format_ident!("engines"));
4803 quote! {
4804 let (#floor, #options) = match #seat.#reader() {
4805 ::core::option::Option::Some(__ingraph_named) => (
4806 // `Option::map` OVER `Option::cloned`: the latter is inherent on BOTH `Option<&T>` and
4807 // `Option<&mut T>`, so a path call is `E0034` at a span the author cannot edit.
4808 ::core::option::Option::map(__ingraph_named.floor(), ::core::clone::Clone::clone),
4809 __ingraph_named.options(),
4810 ),
4811 ::core::option::Option::None => (
4812 ::core::option::Option::None,
4813 ::core::option::Option::None,
4814 ),
4815 };
4816 let ::core::option::Option::Some(#floor) = #floor else {
4817 return ::core::result::Result::Err(#ag::Error::new(#floorless));
4818 };
4819 #mint
4820 }
4821 });
4822 let arguments = legs.iter().enumerate().map(|(at, engine)| {
4823 let engine_ty = engines[at];
4824 let (floor, options, slot, connection) = (
4825 format_ident!("__ingraph_floor_{}", engine.word),
4826 format_ident!("__ingraph_options_{}", engine.word),
4827 format_ident!("__ingraph_slot_{}", engine.word),
4828 format_ident!("__ingraph_connection_{}", engine.word),
4829 );
4830 // THE SCOPE, per leg — `keys_leg`'s own measurement, and the same span discipline. Each leg
4831 // carries ITS OWN mount's manager, two legs of a fan being two resources, and the READ SCOPE
4832 // is still the unit: an engine whose scope is not the unit is `E0308` on the
4833 // `resource = "…"` path its author wrote.
4834 let scope = quote_spanned! {engine_ty.span()=>
4835 #connected::new(#connection, ())
4836 };
4837 quote! {
4838 &mut #slot,
4839 #scope,
4840 #floor,
4841 #options,
4842 }
4843 });
4844 let default = self
4845 .wire_first(GraphqlKind::AsyncGraphql, Some(field))
4846 .get();
4847 let default = syn::LitInt::new(&default.to_string(), field.span());
4848 let doc = leading(&format!(
4849 "The addresses [`{index}`]'s `{field}` ranks nearest a question, across every store it is \
4850 written to at once — one leaderboard, joined by reciprocal rank fusion."
4851 ));
4852 let (asked, seat, first, depth) = (
4853 crate::method::wire_method(&format_ident!("question")),
4854 crate::method::wire_method(&format_ident!("engines")),
4855 crate::method::wire_method(&format_ident!("first")),
4856 crate::method::wire_method(&format_ident!("depth")),
4857 );
4858 quote! {
4859 #[doc = #doc]
4860 #[graphql(name = #sdl)]
4861 #arity
4862 async fn #method(
4863 &self,
4864 #ctx: &#ag::Context<'_>,
4865 #[graphql(name = "question")] #asked: #question,
4866 #[graphql(name = "engines")] #seat: #engines_ty,
4867 #[graphql(name = "first", default = #default)] #first: u32,
4868 #[graphql(name = "depth")] #depth: ::core::option::Option<u32>,
4869 ) -> #ag::Result<::std::vec::Vec<#hit>> {
4870 #numbers
4871 #point
4872 #(#seats)*
4873 // THE CARRIER, reached through `Into` rather than by assuming the declaration's own item IS
4874 // an `Embedding`: the framework's row converts reflexively, and a third-party carrier joins
4875 // by writing one `From` — which is the openness the election family is built on.
4876 let __ingraph_carried: <#ty as #marker>::Item =
4877 ::core::convert::Into::into(__ingraph_point);
4878 let __ingraph_asked = #asked_package::new().with_coordinates(__ingraph_carried);
4879 let mut __ingraph_fused = #index::#door::<#(#handles),*>(
4880 #(#arguments)*
4881 // NO FUSE OPTIONS: this field publishes the plain leaderboard, so the weights, the flavour
4882 // and the per-leg edges are the declaration's own. The seat exists on the door and is
4883 // filled by the round that gives this field its options package.
4884 ::core::option::Option::None,
4885 &__ingraph_asked,
4886 __ingraph_fetch,
4887 )
4888 .await
4889 .map_err(|__ingraph_refusal| {
4890 #ag::Error::new(::std::string::ToString::to_string(&__ingraph_refusal))
4891 })?;
4892 ::std::vec::Vec::truncate(
4893 &mut __ingraph_fused,
4894 ::core::num::NonZeroUsize::get(__ingraph_page),
4895 );
4896 ::core::result::Result::Ok(::core::iter::Iterator::collect(
4897 ::core::iter::Iterator::map(
4898 ::std::vec::Vec::into_iter(__ingraph_fused),
4899 |__ingraph_row| {
4900 let (__ingraph_score, __ingraph_root, __ingraph_evidence) =
4901 #fused::into_components(__ingraph_row);
4902 #hit::new(
4903 <#key as ::core::convert::From<_>>::from(__ingraph_root),
4904 #fused_score::get(&__ingraph_score),
4905 ::core::iter::Iterator::collect(::core::iter::Iterator::map(
4906 ::std::vec::Vec::into_iter(__ingraph_evidence),
4907 |__ingraph_seen| {
4908 let (__ingraph_contribution, __ingraph_ordinal, __ingraph_leg) =
4909 #sighting::into_components(__ingraph_seen);
4910 match __ingraph_leg {
4911 #(#evidence::#variants(__ingraph_at) => #union::#variants(
4912 #members::new(__ingraph_at, __ingraph_ordinal, __ingraph_contribution),
4913 ),)*
4914 }
4915 },
4916 )),
4917 )
4918 },
4919 ),
4920 ))
4921 }
4922 }
4923 }
4924
4925 /// THE ARTIFACT-FAMILY BRIDGE — this declaration's own facts, written into a TYPE so that an
4926 /// entity's wire face can project them off a path.
4927 ///
4928 /// # Why a type and not a token read
4929 ///
4930 /// The fields that serve this family live on the OUTPUT OBJECT of the entity its objects are
4931 /// derived from, and that object is written by that entity's expansion. This one cannot reach it
4932 /// — a second `#[Object]` block on one type is `E0119` three times over — and that one cannot read
4933 /// this declaration, two derives being blind to each other. So the crossing is a trait: the
4934 /// entity's `locate(…)` word gives its expansion this family's PATH, and everything it needs is a
4935 /// projection off it.
4936 ///
4937 /// # What is emitted, and what is deliberately left for somebody else to write
4938 ///
4939 /// | impl | when | why |
4940 /// |---|---|---|
4941 /// | `BlobArtifact` | every artifact family | slot, upstream and the type-level suffix are all this declaration's |
4942 /// | `ArtifactSuffix` | every artifact family | the `extension` word's six forms, resolved |
4943 /// | `ArtifactStore` | the family named a store `ingraph` SHIPS | it is the only store this crate can spell |
4944 /// | `ArtifactData` | that, and the family wrote `data` | reading takes the store, so the capability needs one |
4945 ///
4946 /// The last two are absent for a family whose store word is bound at a GRAPH ROOT, and the absence
4947 /// is the openness rather than a gap: a root's `engines(…)` is written where the program is
4948 /// assembled, and no declaration's expansion can see one. `ArtifactStore`'s own
4949 /// `on_unimplemented` names both roads, and the second — implement it for the family — is a
4950 /// two-screen impl that this crate's `artifact_bridge` vantage writes in full.
4951 ///
4952 /// # The SLOT is minted from the declaration's name, snake-cased — unless a word said otherwise
4953 ///
4954 /// The convention every durable name a declaration mints already takes — `RecordModel::table_name`
4955 /// defaults a table this way and `Slot::name` says so out loud — so an artifact family's directory
4956 /// is `thumbnail` for a `Thumbnail`. It was recorded as a NAMING DECISION with an escape named:
4957 /// *the alternative (a word on the head) is additive the day somebody wants a slot that is not the
4958 /// type's name*. That day came, and the word is [`IndexModel::slot`]. The default is untouched, so
4959 /// nothing already stored moves.
4960 fn artifact_bridge(&self) -> proc_macro2::TokenStream {
4961 if self.kind != NodeKind::Blob {
4962 return proc_macro2::TokenStream::new();
4963 }
4964 use heck::ToSnakeCase as _;
4965
4966 let IndexModel { index, krate, .. } = self;
4967 let artifact = framework(krate, &["record"], "BlobArtifact");
4968 let slot_name = framework(krate, &["slot"], "SlotName");
4969 let source = &self.source.node;
4970 // THE DECLARED NAME OR THE CONVENTION, and the convention is what every family written before
4971 // the word arrived is stored under — which is why the word is additive rather than a migration.
4972 let slot = self
4973 .slot
4974 .as_ref()
4975 .map_or_else(|| index.to_string().to_snake_case(), syn::LitStr::value);
4976 let statik = match self.extension.as_ref().and_then(Extension::statik) {
4977 Some(suffix) => quote!(::core::option::Option::Some(#suffix)),
4978 None => quote!(::core::option::Option::None),
4979 };
4980 let suffix = self.artifact_suffix();
4981 let store = self.artifact_store();
4982 quote! {
4983 #[automatically_derived]
4984 impl #artifact for #index {
4985 type Upstream = #source;
4986
4987 const SLOT: &'static #slot_name = #slot_name::new(#slot);
4988 const SUFFIX: ::core::option::Option<&'static ::core::primitive::str> = #statik;
4989 }
4990
4991 #suffix
4992 #store
4993 }
4994 }
4995
4996 /// THE SIX FORMS, resolved — `ArtifactSuffix`, in whichever of its two shapes this family's
4997 /// `extension` word calls for.
4998 ///
4999 /// # Two column-less forms take the BLANKET, and it is their implementation rather than a stub
5000 ///
5001 /// `extension = "png"` and the omitted form both answer off the type, so the trait's own default
5002 /// body — `Self::SUFFIX`, mapped — already IS them. The impl is written over EVERY row
5003 /// (`impl<__INGRAPH_ROW__> ArtifactSuffix<__INGRAPH_ROW__>`), which costs nothing and buys the
5004 /// thing that matters: the family binds for a caller's row whatever that row turns out to be, so
5005 /// an upstream with no wire face is never asked for one.
5006 ///
5007 /// # Four COLUMN forms take one impl, at the row they actually read
5008 ///
5009 /// The row is `<Upstream as Graphql>::Output` — the hydrated object a resolver is holding — and
5010 /// the read is a DIRECT MEMBER read, for the reason this file's projections already are: an
5011 /// accessor is spelled four ways depending on what the declaration asked for, and the member's
5012 /// name is the one spelling that does not vary. A column the upstream does not expose is `E0609`
5013 /// at the emitted read, and an upstream with NO wire face is `E0277` on `Graphql` — both at the
5014 /// declaration, which is where the column form's own law says the value has to be: *`from` names a
5015 /// column the locate-field resolver already holds hydrated.*
5016 ///
5017 /// # The order inside the body is the two fences' own
5018 ///
5019 /// `variants` is an INPUT fence and `any_of` an OUTPUT one, so the body checks the value, renders,
5020 /// and then checks the rendering — which is exactly what makes a `with` hook compose with both.
5021 /// The hook eats the COLUMN VALUE and never the row, which is what lets ONE function serve the
5022 /// write lane and this face at once.
5023 ///
5024 /// The enum road renders through the column type's own `as_str()` — the storage textual form
5025 /// `#[derive(ingraph::Enum)]` emits — and the string road through `AsRef<str>`. A type answering
5026 /// neither is `E0599`/`E0277` at the emitted call, at the span its author wrote.
5027 fn artifact_suffix(&self) -> proc_macro2::TokenStream {
5028 let IndexModel { index, krate, .. } = self;
5029 let face = framework(krate, &["record"], "ArtifactSuffix");
5030 let Some(column) = self.extension.as_ref().and_then(Extension::column) else {
5031 let row = format_ident!("__INGRAPH_ROW__");
5032 return quote! {
5033 #[automatically_derived]
5034 impl<#row> #face<#row> for #index {}
5035 };
5036 };
5037 let unfenced = framework(krate, &["record"], "UnfencedSuffix");
5038 let graphql = framework(krate, &["transform"], "Graphql");
5039 let source = &self.source.node;
5040 let field = column.source.field();
5041 let family = index.to_string();
5042 let named = field.to_string();
5043 // The COLUMN VALUE, read by member and borrowed once — every road below reads this binding, so
5044 // the read happens in one place whichever of the four the declaration took.
5045 let value = quote_spanned!(field.span()=> &__ingraph_row.#field);
5046 let enumerated = column.source.enumerated().is_some();
5047 // WHAT THE ROW HELD, as text, for a refusal. The enum road has to render before it can report,
5048 // which is why this is not simply the value: a vocabulary enum's `Debug` is a Rust spelling and
5049 // its `as_str` is the one a declaration wrote.
5050 let found = if enumerated {
5051 quote!(::std::string::ToString::to_string(__ingraph_value.as_str()))
5052 } else {
5053 quote!(::std::string::ToString::to_string(
5054 ::core::convert::AsRef::<::core::primitive::str>::as_ref(__ingraph_value)
5055 ))
5056 };
5057 // THE INPUT FENCE — the enum road's subset, as PATTERNS. Emitting the variant as a pattern is
5058 // what makes rustc verify it EXISTS, at the string literal that named it: the expansion
5059 // prefix-checked the path against `from`'s type and can check nothing more, so the other half is
5060 // bought by referring to it.
5061 let input = (!column.variants.is_empty()).then(|| {
5062 let patterns: Vec<proc_macro2::TokenStream> = column
5063 .variants
5064 .iter()
5065 .map(|variant| match variant.parse::<syn::Path>() {
5066 Ok(path) => quote_spanned!(variant.span()=> #path),
5067 // Unreachable through the derive, which parses the same literal to prefix-check it. A
5068 // second front end that did not would get its refusal from rustc rather than a panic here.
5069 Err(refusal) => refusal.to_compile_error(),
5070 })
5071 .collect();
5072 let admitted = column.variants.iter().map(syn::LitStr::value);
5073 quote! {
5074 const __INGRAPH_VARIANTS__: &[&::core::primitive::str] = &[#(#admitted),*];
5075 if !::core::matches!(__ingraph_value, #(#patterns)|*) {
5076 return ::core::result::Result::Err(
5077 #unfenced::new(#family, #named, __INGRAPH_VARIANTS__, #found),
5078 );
5079 }
5080 }
5081 });
5082 // THE RENDER, in the three shapes the roads take.
5083 let render = match &column.with {
5084 Some(hook) => quote_spanned!(hook.span()=> #hook(__ingraph_value)),
5085 None if enumerated => quote!(__ingraph_value.as_str()),
5086 None => quote!(::core::convert::AsRef::<::core::primitive::str>::as_ref(
5087 __ingraph_value
5088 )),
5089 };
5090 // THE OUTPUT FENCE — which SUFFIXES this family says it produces. Required on the string road
5091 // and optional on the enum one, so its absence here is the declaration's own answer.
5092 let output = (!column.any_of.is_empty()).then(|| {
5093 let admitted = column.any_of.iter().map(syn::LitStr::value);
5094 quote! {
5095 const __INGRAPH_ANY_OF__: &[&::core::primitive::str] = &[#(#admitted),*];
5096 if !<[&::core::primitive::str]>::contains(
5097 __INGRAPH_ANY_OF__,
5098 &&*__ingraph_suffix,
5099 ) {
5100 return ::core::result::Result::Err(#unfenced::new(
5101 #family,
5102 #named,
5103 __INGRAPH_ANY_OF__,
5104 ::std::string::ToString::to_string(&*__ingraph_suffix),
5105 ));
5106 }
5107 }
5108 });
5109 let row = quote!(<#source as #graphql>::Output);
5110 quote! {
5111 #[automatically_derived]
5112 impl #face<#row> for #index {
5113 fn suffix(
5114 __ingraph_row: &#row,
5115 ) -> ::core::result::Result<
5116 ::core::option::Option<::std::borrow::Cow<'_, ::core::primitive::str>>,
5117 #unfenced,
5118 > {
5119 let __ingraph_value = #value;
5120 #input
5121 let __ingraph_suffix: ::std::borrow::Cow<'_, ::core::primitive::str> =
5122 ::core::convert::Into::into(#render);
5123 #output
5124 ::core::result::Result::Ok(::core::option::Option::Some(__ingraph_suffix))
5125 }
5126 }
5127 }
5128 }
5129
5130 /// WHERE THE OBJECTS LIVE — `ArtifactStore` and, under the `data` word, `ArtifactData`, for a
5131 /// family that named a store this crate can SPELL.
5132 ///
5133 /// # `fs` is the only word, and that is a measurement rather than a shape
5134 ///
5135 /// `EngineKind` is the SHIPPED table, and `ingraph` ships exactly one artifact store. A word
5136 /// outside it is bound at a graph root, which no expansion can see, so nothing here could name its
5137 /// type — and closing the vocabulary to fix that would be the framework deciding which stores may
5138 /// serve a wire field. The family writes the impl instead, and reaches every field the shipped one
5139 /// does.
5140 ///
5141 /// # It goes through the KEY-ONLY door, not through `AsyncLocate`
5142 ///
5143 /// `LocalFsBlob::address` and `::fetch` take the key's own walk and the suffix and nothing else.
5144 /// The `AsyncLocate` verb beside them reaches the same funnel through a supertrait that projects
5145 /// `BlobRecord` — a payload face this expansion does not emit, and cannot emit without ruling
5146 /// WHICH of a family's declared fields is the payload. The narrower door is the funnel at the
5147 /// bound it actually has, so the bridge needs no such ruling.
5148 ///
5149 /// # THIS BODY IS PURE ADDRESSING, and no layer here goes looking
5150 ///
5151 /// `locate` is a RENDER at every grain: the capability's own law says a locate which secretly
5152 /// stats is the *`get` that throws its bytes away* it exists instead of, and this layer keeps it
5153 /// rather than spending a syscall of its own one storey up. The division is **addressing here,
5154 /// PRESENCE AT USE**, and the reason is that a presence answer expires the instant it is produced
5155 /// — a `Some` can 404 by the time a client fetches, a `None` can exist by then — so every consumer
5156 /// handles absence at use ANYWAY, and a per-row `stat` buys an unreliable hint while writing the
5157 /// 404 handling twice.
5158 ///
5159 /// The seam's `Option` is untouched and its clause still reads exactly right: *each impl draws its
5160 /// own split, because only the store knows what it is able to know*. A store whose presence IS a
5161 /// row column answers `None` honestly and for free; fs and network stores answer `Some(rendered)`
5162 /// and say so. `required` on a locate position remains the SDL promotion, and its
5163 /// `None`-conversion is reachable on the stores that can produce one.
5164 ///
5165 /// Recorded plainly, because it is what a deployment on fs will observe: a bare locate position
5166 /// never nulls here. The placeholder UX rides `onerror` on the client, or the data road, which
5167 /// finds the absence for free and un-expired.
5168 ///
5169 /// # `ArtifactData` is emitted UNDER THE WORD, and that is the whole of what the word buys
5170 ///
5171 /// Presence at the type layer: a family that wrote `data` has the impl and a family that did not
5172 /// has none, so a field asking for bytes is `E0277` naming the family and the word rather than a
5173 /// null on the wire.
5174 fn artifact_store(&self) -> proc_macro2::TokenStream {
5175 let IndexModel { index, krate, .. } = self;
5176 if !self
5177 .stores
5178 .iter()
5179 .any(|engine| engine.shipped() == Some(EngineKind::Fs))
5180 {
5181 return proc_macro2::TokenStream::new();
5182 }
5183 let artifact = framework(krate, &["record"], "BlobArtifact");
5184 let store_face = framework(krate, &["record"], "ArtifactStore");
5185 let data_face = framework(krate, &["record"], "ArtifactData");
5186 let transformer = framework(krate, &["transform"], "Transformer");
5187 let construction = framework(krate, &["store"], "BlobStore");
5188 let fs_store = framework(krate, &["store"], "LocalFsStore");
5189 let fs_error = framework(krate, &["store"], "LocalFsBlobError");
5190 let address = framework(krate, &["store"], "blob_address");
5191 let location = framework(krate, &["store"], "BlobLocation");
5192 let source = &self.source.node;
5193 let key = quote!(<#source as #transformer>::Key);
5194 // The handle is minted per call and that is what it is FOR: `AsyncBlobStore::blob` is sync and
5195 // infallible on both faces because a per-slot handle is stateless, so minting one costs a
5196 // `Utf8Bytes` clone and reaching for a cached one would be a lifetime for no gain.
5197 let handle = quote! {
5198 let __ingraph_handle = <#fs_store as #construction>::blob(
5199 __ingraph_store,
5200 ::core::convert::AsRef::<::core::primitive::str>::as_ref(<Self as #artifact>::SLOT),
5201 );
5202 };
5203 let data = self.data.then(|| {
5204 quote! {
5205 #[automatically_derived]
5206 impl #data_face for #index {
5207 fn read(
5208 __ingraph_store: &Self::Store,
5209 __ingraph_key: &#key,
5210 __ingraph_suffix: ::core::option::Option<&::core::primitive::str>,
5211 ) -> impl ::core::future::Future<
5212 Output = ::core::result::Result<
5213 ::core::option::Option<Self::Payload>,
5214 Self::Error,
5215 >,
5216 > + ::core::marker::Send {
5217 #handle
5218 // A RESOLVED future, which is what a filesystem honestly hands an async caller: the read
5219 // is a blocking syscall and it has already happened by the time this is awaited. It is
5220 // the shipped `AsyncBlobEngine` face's own shape, reached through the key-only door.
5221 //
5222 // The ABSENCE is the backend's, unwrapped by nothing here: `fetch` already tells a miss
5223 // from a fault, so this body carries the answer through rather than drawing the split a
5224 // second time.
5225 ::core::future::ready(__ingraph_handle.fetch(
5226 #fs_store::root(__ingraph_store),
5227 __ingraph_key,
5228 __ingraph_suffix,
5229 ))
5230 }
5231 }
5232 }
5233 });
5234 quote! {
5235 #[automatically_derived]
5236 impl #store_face for #index {
5237 type Store = #fs_store;
5238 type Location = #location;
5239 type Payload = ::std::vec::Vec<u8>;
5240 type Error = #fs_error;
5241
5242 fn locate(
5243 __ingraph_store: &Self::Store,
5244 __ingraph_key: &#key,
5245 __ingraph_suffix: ::core::option::Option<&::core::primitive::str>,
5246 ) -> ::core::result::Result<::core::option::Option<Self::Location>, Self::Error> {
5247 #handle
5248 let __ingraph_path = __ingraph_handle.address(
5249 #fs_store::root(__ingraph_store),
5250 __ingraph_key,
5251 __ingraph_suffix,
5252 )?;
5253 // THE RENDER IS THE WHOLE BODY. A root this store cannot render an address out of refuses
5254 // here, and it refuses whether or not anything was ever written — a refusal that arrived
5255 // only once something HAD been written would be a deployment fault hiding until the day
5256 // the pipeline succeeds.
5257 let __ingraph_address = #address(&__ingraph_path)?;
5258 // `Some`, ALWAYS, and for this store that is the honest answer rather than a shortcut: a
5259 // filesystem address is presence-blind and a `stat` beside it buys an answer that expires
5260 // the instant it is produced. The seam's `Option` is spent by the backends that CAN
5261 // answer presence for free and un-expiring — a store holding it as a row column — and
5262 // under fs absence is discovered where it cannot expire: the data road finds it in the
5263 // read itself, and a client's own GET finds it at the fetch.
5264 ::core::result::Result::Ok(::core::option::Option::Some(
5265 #location::new(__ingraph_address),
5266 ))
5267 }
5268 }
5269
5270 #data
5271 }
5272 }
5273
5274 /// **LAYER TWO's DECLARATION HALF** — one `Describe<R>` per TARGET this declaration's legs point
5275 /// at, and the `Habitats` impl a graph root's launch drives it through.
5276 ///
5277 /// ```ignore
5278 /// impl Describe<crate::Ft> for Media { // the corpora Media owns in Ft
5279 /// const BLUEPRINT: &'static [SlotSchema] = &[
5280 /// SlotSchema::of(SlotName::new("media__title__lexical"), &[SlotColumn::text("title")], false),
5281 /// SlotSchema::of(SlotName::new("media__body__lexical"), &[SlotColumn::text("body")], true),
5282 /// ];
5283 /// }
5284 /// impl Habitats for Media {
5285 /// const UNBOUND: &'static [UnboundCorpus] = &[…]; // the legs that pointed at nothing
5286 /// const TARGETS: &'static [fn() -> ResourceDemand] = &[ResourceDemand::of::<crate::Ft>];
5287 /// fn make(creation) { creation.habitat::<crate::Ft, Selected<{…SYNC}>, Self>().await }
5288 /// }
5289 /// ```
5290 ///
5291 /// # `TARGETS` and `make` are ONE list read twice
5292 ///
5293 /// The same grouped-by-path rows: the const says WHICH targets this declaration mounts, so a
5294 /// launch can build them before the walk runs, and the body says what to make in each. They cannot
5295 /// drift because neither is written by hand — a leg that grew a `resource = "…"` adds a row to
5296 /// both, and a leg that lost one moves to `UNBOUND` and leaves both.
5297 ///
5298 /// # ONE IMPL PER TARGET, and the grouping is what makes it one
5299 ///
5300 /// Two elections pointing at the SAME resource are two corpora in ONE mount, so they are two rows
5301 /// of one blueprint rather than two impls — which they have to be, `Describe<R>` admitting one impl
5302 /// per `(type, target)` pair and a second being `E0119`. The legs are grouped by the resource path
5303 /// as WRITTEN, since that is the only spelling this expansion has: two different paths naming one
5304 /// type would be two impls and the compiler's own refusal, which is the honest place for it.
5305 ///
5306 /// # The TARGET is the RESOURCE and never the engine
5307 ///
5308 /// `Describe<crate::Ft>` and not `Describe<TantivyFulltext>`. Two deployments' tantivy stores are
5309 /// two resource types, so keying the habitat on the ENGINE would collapse them into one and make a
5310 /// second mount unaddressable — the same grain the mount seam and the slot name are already on.
5311 ///
5312 /// # What the blueprint carries, and what it deliberately does not
5313 ///
5314 /// The NAME is the slot marker's own, so the corpus a boot creates and the corpus a read opens
5315 /// cannot be given two answers. The COLUMN is the elected field under the column language's own
5316 /// door — text for a searched field, bytes for a coordinate one, which is what those values are at
5317 /// a storage boundary. The `stored` posture is the declaration's word. A per-slot KNOB is none of
5318 /// those and is not here: a tokenizer is a value a DEPLOYMENT decides at boot, and it reaches the
5319 /// visitor's own table instead.
5320 ///
5321 /// A VECTOR corpus carries its WIDTH beside them, projected off the elected field's own type —
5322 /// the same projection the geometry bindings make, in const position where it belongs.
5323 ///
5324 /// # A BLOB declaration emits the `Habitats` impl and NO blueprint
5325 ///
5326 /// It elects nothing, so there is no `(field × label)` slot for a leg to point at and no target
5327 /// for a `resource = "…"` to name. Its family's own home vocabulary exists
5328 /// ([`Layout`](../../ingraph/struct.Layout.html)) and is written by hand until the artifact grammar
5329 /// grows a pointing word — stated rather than half-emitted, which is this crate's standing posture
5330 /// for a word nothing spends.
5331 fn habitats(&self) -> proc_macro2::TokenStream {
5332 let IndexModel { index, krate, .. } = self;
5333 let describe = framework(krate, &["schema"], "Describe");
5334 let habitats = framework(krate, &["drive"], "Habitats");
5335 let unbound = framework(krate, &["drive"], "UnboundCorpus");
5336 let slot_name = framework(krate, &["slot"], "SlotName");
5337 let creation = framework(krate, &["drive"], "Creation");
5338 let launch_error = framework(krate, &["drive"], "LaunchError");
5339 let selected = framework(krate, &["operator"], "Selected");
5340 let declared = framework(krate, &["resource"], "DeclaredResource");
5341 let base = self.base();
5342
5343 // The KIND's own row: what a home looks like here, and which resource facet an unpointed corpus
5344 // needs. A blob has neither, which is what makes its whole emission the empty impl.
5345 let Some(resource_kind) = (match self.kind {
5346 NodeKind::Fulltext => Some(quote!(Documents)),
5347 NodeKind::Vector => Some(quote!(Coordinates)),
5348 _ => None,
5349 }) else {
5350 return quote! {
5351 #[automatically_derived]
5352 impl #habitats for #index {}
5353 };
5354 };
5355 let kind = framework(krate, &["resource"], "ResourceKind");
5356
5357 // ONE ROW PER LEG, grouped by the resource path as written — insertion-ordered, so the emission
5358 // is stable and diffable exactly as the slot markers are.
5359 let mut pointed: Vec<(syn::Path, Vec<proc_macro2::TokenStream>)> = Vec::new();
5360 let mut unpointed: Vec<proc_macro2::TokenStream> = Vec::new();
5361 for declared_field in &self.engines {
5362 let field = &declared_field.field;
5363 let column = self.slot_column(field);
5364 for engine in &declared_field.engines {
5365 let slot = crate::engine::Slot {
5366 field: field.clone(),
5367 engine: engine.word.clone(),
5368 };
5369 let name = slot.name(base);
5370 let Some(resource) = engine.resource.as_ref() else {
5371 unpointed.push(quote! {
5372 #unbound::new(#slot_name::new(#name), #kind::#resource_kind)
5373 });
5374 continue;
5375 };
5376 let row = self.blueprint_row(&slot, &name, engine.stored, &column);
5377 // Grouped by the path AS WRITTEN, which is the only spelling this expansion has: two
5378 // different paths naming one type would be two impls and `E0119`, which is the honest place
5379 // for that refusal — a macro that tried to resolve them would be resolving types.
5380 let written = quote!(#resource).to_string();
5381 match pointed
5382 .iter_mut()
5383 .find(|(path, _)| quote!(#path).to_string() == written)
5384 {
5385 Some((_, rows)) => rows.push(row),
5386 None => pointed.push((resource.clone(), vec![row])),
5387 }
5388 }
5389 }
5390
5391 let blueprint = self.blueprint_type();
5392 // SPANNED AT THE WORD, per the projection law this file already keeps: the impl's own
5393 // obligation is `R: Habitat`, and an unspanned one reports it at the ATTRIBUTE — a caret on
5394 // something the author cannot edit. At the path, `E0276`/`E0277` land on the very token that
5395 // named the target.
5396 let describes = pointed.iter().map(|(resource, rows)| {
5397 quote_spanned! {resource.span()=>
5398 #[automatically_derived]
5399 impl #describe<#resource> for #index {
5400 const BLUEPRINT: #blueprint = &[#(#rows,)*];
5401 }
5402 }
5403 });
5404 let steps = pointed.iter().map(|(resource, _)| {
5405 quote! {
5406 #creation::habitat::<
5407 #resource,
5408 #selected<{ <#resource as #declared>::SYNC }>,
5409 Self,
5410 >(__ingraph_creation).await?;
5411 }
5412 });
5413 // EMITTED ONLY WHERE THERE IS A STEP: a declaration whose legs all pointed at nothing takes the
5414 // trait's own empty default rather than carrying a body whose parameter nothing reads.
5415 let make = (!pointed.is_empty()).then(|| {
5416 quote! {
5417 fn make(
5418 __ingraph_creation: &mut #creation<'_>,
5419 ) -> impl ::core::future::Future<
5420 Output = ::core::result::Result<(), #launch_error>,
5421 > {
5422 async move {
5423 #(#steps)*
5424 ::core::result::Result::Ok(())
5425 }
5426 }
5427 }
5428 });
5429 let unbound_rows = (!unpointed.is_empty()).then(|| {
5430 quote! {
5431 const UNBOUND: &'static [#unbound] = &[#(#unpointed,)*];
5432 }
5433 });
5434 // THE MOUNTS this declaration asks for. A leg that named a target is what makes the deployment
5435 // mount it, and the launch has no other way to learn it: a search resolver holds the same
5436 // `Shared<R>` a landing node does and appears in no list the launch reads. Spanned at the path
5437 // for the `describes` rows' reason — the obligation here is `R: AsyncResource`, and the caret
5438 // belongs on the token that named it.
5439 let demand = framework(krate, &["resource"], "ResourceDemand");
5440 let mounts = pointed.iter().map(|(resource, _)| {
5441 quote_spanned! {resource.span()=>
5442 #demand::of::<#resource>
5443 }
5444 });
5445 let targets = (!pointed.is_empty()).then(|| {
5446 quote! {
5447 const TARGETS: &'static [fn() -> #demand] = &[#(#mounts,)*];
5448 }
5449 });
5450
5451 quote! {
5452 #(#describes)*
5453
5454 #[automatically_derived]
5455 impl #habitats for #index {
5456 #unbound_rows
5457 #targets
5458 #make
5459 }
5460 }
5461 }
5462
5463 /// ONE BLUEPRINT ROW — the corpus one leg owns, in whichever vocabulary its kind describes homes
5464 /// in.
5465 fn blueprint_row(
5466 &self,
5467 declared: &crate::engine::Slot,
5468 name: &str,
5469 stored: bool,
5470 column: &proc_macro2::TokenStream,
5471 ) -> proc_macro2::TokenStream {
5472 let krate = &self.krate;
5473 let slot_name = framework(krate, &["slot"], "SlotName");
5474 let field = &declared.field;
5475 match self.kind {
5476 NodeKind::Vector => {
5477 let spec = framework(krate, &["transform"], "SlotSpec");
5478 let width = self
5479 .embeddings
5480 .iter()
5481 .find(|elected| &elected.field == field)
5482 .map(|elected| {
5483 let ty = &elected.ty;
5484 let shape = framework(krate, &["election"], "EmbeddingShape");
5485 let embedding = framework(krate, &["election"], "EmbeddingMarker");
5486 quote_spanned!(field.span()=> <<#ty as #embedding>::Item as #shape>::WIDTH)
5487 });
5488 quote! {
5489 #spec::new(#slot_name::new(#name), &[#column], #width)
5490 }
5491 }
5492 _ => {
5493 let schema = framework(krate, &["transform"], "SlotSchema");
5494 // THE ROSTER TRAVELS WITH THE ROW, read off the slot's own seam rather than restated. A slot
5495 // maker is handed a blueprint and nothing else — it has no slot TYPE to project a `Lanes`
5496 // impl off — and it has to know how many partitions to shape the home for. Naming the seam
5497 // is what keeps the two one fact: an unfanned slot's `LANES` is the default roster of one,
5498 // which is the value `SlotSchema` already holds without this call.
5499 let lanes = framework(krate, &["lane"], "Lanes");
5500 let marker = declared.marker(self.base());
5501 quote! {
5502 #schema::of(#slot_name::new(#name), &[#column], #stored)
5503 .fanned(<#marker as #lanes>::LANES)
5504 }
5505 }
5506 }
5507 }
5508
5509 /// The BLUEPRINT TYPE this kind's targets answer with — the associated type a `Describe<R>` impl's
5510 /// const is written at, and the one a resource's own `Habitat` states.
5511 fn blueprint_type(&self) -> proc_macro2::TokenStream {
5512 let krate = &self.krate;
5513 match self.kind {
5514 NodeKind::Vector => {
5515 let spec = framework(krate, &["transform"], "SlotSpec");
5516 quote!(&'static [#spec])
5517 }
5518 _ => {
5519 let schema = framework(krate, &["transform"], "SlotSchema");
5520 quote!(&'static [#schema])
5521 }
5522 }
5523 }
5524
5525 /// ONE ELECTED FIELD as a blueprint COLUMN — its own name, under the door of the column language
5526 /// its values cross by.
5527 ///
5528 /// TEXT for a searched field, whose road produced text by construction; BYTES for a coordinate
5529 /// one, which is what a vector is at a storage boundary and the language's own floor. The WIDTH is
5530 /// not restated here — it is [`SlotSpec`](../../ingraph/struct.SlotSpec.html)'s own member, and two
5531 /// homes for one fact are free to disagree.
5532 fn slot_column(&self, field: &syn::Ident) -> proc_macro2::TokenStream {
5533 let krate = &self.krate;
5534 let column = framework(krate, &["transform"], "SlotColumn");
5535 let name = field.to_string();
5536 match self.kind {
5537 NodeKind::Vector => {
5538 let door = framework(krate, &["store"], "ColumnDoor");
5539 quote!(#column::new(#name, #door::Bytes))
5540 }
5541 _ => quote!(#column::text(#name)),
5542 }
5543 }
5544
5545 /// EVERY slot this declaration names — one per `(elected field × declared engine)`, in declared
5546 /// order.
5547 ///
5548 /// The set the storage plumbing is keyed by, and the answer to *how many corpora does this
5549 /// declaration own*. It is EMPTY for a declaration whose elections named no engine, which is the
5550 /// portable case: the slots exist, and which engines they are opened on is the deployment's.
5551 #[must_use]
5552 pub fn slots(&self) -> Vec<Slot> {
5553 self.engines.iter().flat_map(FieldEngines::slots).collect()
5554 }
5555
5556 /// ONE ZERO-SIZED MARKER PER SLOT, at MODULE SCOPE — the `(field × engine)` pairing carried as a
5557 /// type.
5558 ///
5559 /// # Why a type rather than the name alone
5560 ///
5561 /// `SlotHandle<E, T>` brands a handle with the slot it was opened for, and the brand is what stops
5562 /// a write landing in another slot's corpus — the class whose repair is a reindex rather than a
5563 /// code change. Before this round `T` was the DECLARATION, because a declaration was a slot. It is
5564 /// `(field × engine)` now, so the brand is these markers: two engines holding one field are two
5565 /// types, and a handle opened on one cannot be passed to the other's door.
5566 ///
5567 /// At MODULE SCOPE for [`elections`](Self::elections)' reason, and it is the same reason: a
5568 /// deployment names one when it opens a handle, so the name has to be spellable from the scope the
5569 /// declaration was written in.
5570 ///
5571 /// # The impl naming a CONCRETE engine rides that engine's gate; the marker does not
5572 ///
5573 /// The MEASURED law of the record side, applied here: only what names a concrete type may be
5574 /// gated, because a shut gate deletes it. The marker itself and its slot name are facts of the
5575 /// DECLARATION and exist in every build — a deployment compiling no engine at all still has the
5576 /// names its declaration minted, and a party that asks for the binding is the one that gets
5577 /// `E0277`.
5578 fn slot_markers(&self) -> proc_macro2::TokenStream {
5579 let IndexModel {
5580 index, vis, krate, ..
5581 } = self;
5582 let slot = framework(krate, &["store"], "Slot");
5583 let slot_name = framework(krate, &["slot"], "SlotName");
5584 // THE MARKER MOVES WITH THE BASE AND THE DURABLE NAME DOES NOT, which is the one asymmetry in
5585 // this file worth reading twice. A `rename` is a RUST word: it moves types a declaring scope
5586 // holds. The durable slot name is a STORAGE identity — the corpus this pairing owns — and
5587 // moving it with a Rust rename would silently repoint a live index. The word for that one is
5588 // the storage side's, and it is not this.
5589 let base = self.base();
5590 let markers = self.slots().into_iter().map(|declared| {
5591 let marker = declared.marker(base);
5592 let name = declared.name(index);
5593 let field = declared.field.to_string();
5594 let engine = declared.engine.to_string();
5595 let doc = leading(&format!(
5596 "The `{field}` × `{engine}` SLOT of [`{index}`] — the corpus that pairing owns, as a type. \
5597 A handle opened on it is branded with this marker and cannot be handed to another slot's \
5598 door.",
5599 ));
5600 let lanes = self.lane_bindings(&marker, &declared);
5601 quote! {
5602 #[doc = #doc]
5603 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5604 #vis struct #marker;
5605
5606 #[automatically_derived]
5607 impl #slot for #marker {
5608 type Of = #index;
5609
5610 const SLOT: &'static #slot_name = #slot_name::new(#name);
5611 const FIELD: &'static ::core::primitive::str = #field;
5612 const ENGINE: &'static ::core::primitive::str = #engine;
5613 }
5614
5615 #lanes
5616 }
5617 });
5618 quote!(#(#markers)*)
5619 }
5620
5621 /// **THE LANE SEAM ONE FULL-TEXT SLOT PUBLISHES** — its roster, its probe currency, and the
5622 /// per-word assertions that refuse a roster claiming one word twice.
5623 ///
5624 /// ```ignore
5625 /// impl Lanes for MediaBodyTantivy {
5626 /// const LANES: &'static [Lane] = &[
5627 /// Lane::of(LaneIdent::new("zh")).accepting(&[LaneIdent::new("cmn")]),
5628 /// Lane::of(LaneIdent::new("rest")).catch_all(),
5629 /// ];
5630 /// }
5631 /// impl LanedStore for MediaBodyTantivy { type Probe = String; }
5632 /// const _: () = assert!(!lane_claim_repeats(<MediaBodyTantivy as Lanes>::LANES, 1), "…");
5633 /// ```
5634 ///
5635 /// # FULL-TEXT ONLY, and refused BY NAME elsewhere
5636 ///
5637 /// A lane exists because a full-text field has ONE tokenizer and an immutable schema. A knn
5638 /// indexes coordinates, which no analyzer reads, and an artifact store holds bytes — so neither
5639 /// kind has a lane story, and the grammar refuses the word on both by name rather than emitting a
5640 /// roster nothing could spend.
5641 ///
5642 /// # An UNFANNED slot STILL PUBLISHES THE SEAM
5643 ///
5644 /// The impl is emitted whether or not `lanes(…)` was written, and where it was not the body is
5645 /// EMPTY — the trait's own default, which is one lane keyed `und`. That is presence-is-enablement
5646 /// stated in the emission: an unfanned corpus IS a fanned one whose roster has a single entry, so
5647 /// a reader over `S: Lanes` takes every full-text slot there is and nothing anywhere carries an
5648 /// *is this fanned* fork. Nothing about the CORPUS changes — one lane is one field, named `body`,
5649 /// tokenized by tantivy's `default`, which is the schema this backend has always built.
5650 ///
5651 /// # The COLLISION AUDIT is spent HERE, at the declaration
5652 ///
5653 /// The ruling asks for a folded collision to be a COMPILE-TIME refusal, and this is that call
5654 /// site: one `const` item per word the roster claims, each asserting the word was not claimed by
5655 /// an EARLIER position, and one more per catch-all. The relation is the framework's own —
5656 /// `lane_claim_repeats` reads this crate's ONE fold — so a declaration, a boot walk and a
5657 /// downstream's test cannot come to disagree about what a collision is.
5658 ///
5659 /// One item PER WORD rather than one per roster, because that is what buys the sentence: a
5660 /// constant cannot FORMAT a message, so the message is written HERE where the spelling is known,
5661 /// and the span is the word's own — a roster with `zh_hant` beside `zhHant` puts the caret on the
5662 /// SECOND one, which is the one its author can delete.
5663 fn lane_bindings(
5664 &self,
5665 marker: &syn::Ident,
5666 declared: &crate::engine::Slot,
5667 ) -> proc_macro2::TokenStream {
5668 let IndexModel { krate, index, .. } = self;
5669 if self.kind != NodeKind::Fulltext {
5670 return proc_macro2::TokenStream::new();
5671 }
5672 let Some(engine) = self.declared_engine(declared) else {
5673 return proc_macro2::TokenStream::new();
5674 };
5675 let lanes_trait = framework(krate, &["lane"], "Lanes");
5676 let laned = framework(krate, &["lane"], "LanedStore");
5677 let lane = framework(krate, &["lane"], "Lane");
5678 let ident = framework(krate, &["lane"], "LaneIdent");
5679 let repeats = framework(krate, &["lane"], "lane_claim_repeats");
5680 let catches_again = framework(krate, &["lane"], "lane_catch_all_repeats");
5681 let field = &declared.field;
5682 let word = &declared.engine;
5683
5684 let roster = (!engine.lanes.is_empty()).then(|| {
5685 let rows = engine.lanes.iter().map(|row| {
5686 let key = row.key.to_string();
5687 let accepting = (!row.accepts.is_empty()).then(|| {
5688 let accepts = row.accepts.iter().map(ToString::to_string);
5689 quote!(.accepting(&[#(#ident::new(#accepts),)*]))
5690 });
5691 let catches = row.catch_all.as_ref().map(|_| quote!(.catch_all()));
5692 // SPANNED AT THE KEY, per this file's projection law: what a row can earn is reported at the
5693 // word its author wrote rather than at the attribute.
5694 quote_spanned!(row.key.span()=> #lane::of(#ident::new(#key)) #accepting #catches)
5695 });
5696 quote! {
5697 const LANES: &'static [#lane] = &[#(#rows,)*];
5698 }
5699 });
5700
5701 // ONE ASSERTION PER CLAIMED WORD, counted out against the roster's own FLAT claim positions —
5702 // each lane's key, then that lane's aliases, which is exactly the order `lane_claim` addresses.
5703 let mut at = 0usize;
5704 let mut audits = proc_macro2::TokenStream::new();
5705 for (lane_at, row) in engine.lanes.iter().enumerate() {
5706 for claimed in row.claims() {
5707 let word_at = at;
5708 let why = format!(
5709 "the word `{claimed}` is claimed twice in `{index}`'s `{field}` × `{word}` lanes — a \
5710 lane's key and every alias it accepts fold through ONE relation, so `{claimed}`, its \
5711 hyphenated spelling and its cased spellings are ONE word. Rename it or drop the second \
5712 claim: two lanes claiming one tag is a document filed by list order"
5713 );
5714 audits.extend(quote_spanned! {claimed.span()=>
5715 const _: () = ::core::assert!(
5716 !#repeats(<#marker as #lanes_trait>::LANES, #word_at),
5717 #why
5718 );
5719 });
5720 at += 1;
5721 }
5722 if let Some(catches) = row.catch_all.as_ref() {
5723 let key = &row.key;
5724 let why = format!(
5725 "lane `{key}` is declared the catch-all in `{index}`'s `{field}` × `{word}` lanes, and an \
5726 EARLIER lane already is — a roster declares exactly one, because two would make *which \
5727 stranger goes where* depend on the order the lanes happen to be written in"
5728 );
5729 audits.extend(quote_spanned! {catches.span()=>
5730 const _: () = ::core::assert!(
5731 !#catches_again(<#marker as #lanes_trait>::LANES, #lane_at),
5732 #why
5733 );
5734 });
5735 }
5736 }
5737
5738 quote! {
5739 #[automatically_derived]
5740 impl #lanes_trait for #marker {
5741 #roster
5742 }
5743
5744 #[automatically_derived]
5745 impl #laned for #marker {
5746 // A full-text lane is asked with TEXT — the query string that lane's own analyzer parses —
5747 // so this is what a router wired to this slot must answer in, and anything else is `E0271`
5748 // at the seat. OWNED, because a fan hands back a `Vec` of probes that outlive the question
5749 // they were split from.
5750 type Probe = ::std::string::String;
5751 }
5752
5753 #audits
5754 }
5755 }
5756
5757 /// The LEG one slot was minted from — the `(field × engine)` pairing read back off the model.
5758 ///
5759 /// A slot is minted from a leg and then carried as a pair of idents, so the leg is FOUND rather
5760 /// than threaded through every caller: the lists are a declaration's own length, the walk happens
5761 /// once at expansion time, and the alternative is a second copy of every leg's facts inside a
5762 /// name.
5763 fn declared_engine(&self, declared: &crate::engine::Slot) -> Option<&crate::engine::Engine> {
5764 self
5765 .engines
5766 .iter()
5767 .find(|elected| elected.field == declared.field)?
5768 .engines
5769 .iter()
5770 .find(|engine| engine.word == declared.engine)
5771 }
5772
5773 /// WHAT THIS INDEX EMITS, stated for the downstream declarations that cannot see it.
5774 ///
5775 /// A derived index declares no products — its message is the entry it holds, which is the
5776 /// declared struct — so the row is the sole-product pair every one-product node carries. It is
5777 /// here for the same reason it is on a record: a `subscribe(upstream(node = "…"))` names an index
5778 /// as readily as it names anything else, and the payload it projects is `<Index as Emits>::Out`.
5779 fn emits_binding(&self) -> proc_macro2::TokenStream {
5780 let IndexModel { index, krate, .. } = self;
5781 let emits = framework(krate, &["operator"], "Emits");
5782 let sole = framework(krate, &["operator"], "SoleProduct");
5783 quote! {
5784 #[automatically_derived]
5785 impl #emits for #index {
5786 type Out = Self;
5787 }
5788
5789 #[automatically_derived]
5790 impl #sole for #index {}
5791 }
5792 }
5793
5794 /// The `fanout` WRITE LANE — one door per marked field, writing every engine that field declared.
5795 ///
5796 /// # Why the DEFAULT case emits nothing, and that is the mirror rather than a gap
5797 ///
5798 /// Single-write needs no door. The record side needs `insert_postgres` beside `insert_sqlite`
5799 /// because the ROW TYPE is what picks the database and a caller cannot name it — *the method NAME
5800 /// is where the database is chosen and the type parameter is where the driver is.* Here the slot
5801 /// is already named by the HANDLE: `SlotHandle<E, TitleTantivy>` is branded, so
5802 /// `handle.upsert_document(…)` writes that slot and no other, and an emitted wrapper would add a
5803 /// second spelling of a choice already made. The mirror is exact and its economy is real.
5804 ///
5805 /// A FAN is the case no existing door covers: writing one message to several slots at once, whose
5806 /// engines are different types with different contexts and different errors. So `fanout` emits and
5807 /// the default does not, which is also the honest reading of the marker — it is an increment, and
5808 /// what it increments is visible in the expansion.
5809 ///
5810 /// # The legs are SEQUENTIAL and the first refusal stops the fan
5811 ///
5812 /// See [`Refused`](crate::engine) for why no leg is rolled back: the engines are independent
5813 /// stores sharing no transaction, and inventing one would be this crate deciding a durability
5814 /// question that is the deployment's. What the caller is told is which leg refused, which says
5815 /// exactly which stores took the write.
5816 ///
5817 /// # At MODULE SCOPE rather than in the anonymous `const`
5818 ///
5819 /// The door is spelled by a DEPLOYMENT — it is the write lane's own call — so it goes where the
5820 /// retrieve pair goes and for the retrieve pair's reason. Its parameters name the slot markers,
5821 /// which are at module scope too.
5822 fn fanouts(&self) -> proc_macro2::TokenStream {
5823 let IndexModel {
5824 index, vis, krate, ..
5825 } = self;
5826 // TWO PATHS where there used to be one, and the split is the engine cutover in BOTH families:
5827 // the CONNECTION is a base seat and the scope, the entry and the verb are the WRITE FACE's, so a
5828 // qualified path has to name whichever trait actually declares the member.
5829 let (base, face, verb) = match self.kind {
5830 NodeKind::Fulltext => (
5831 framework(krate, &["store"], "FulltextEngine"),
5832 framework(krate, &["store"], "AsyncFulltextWrite"),
5833 format_ident!("upsert_document"),
5834 ),
5835 NodeKind::Vector => (
5836 framework(krate, &["store"], "VectorEngine"),
5837 framework(krate, &["store"], "AsyncVectorWrite"),
5838 format_ident!("upsert_vector"),
5839 ),
5840 // A `blob` elects nothing, so it declares no engine and has nothing to fan.
5841 _ => return proc_macro2::TokenStream::new(),
5842 };
5843 let brand = framework(krate, &["store"], "SlotHandle");
5844 let connected = framework(krate, &["store"], "Connected");
5845 let refused = framework(krate, &["store"], "Refused");
5846
5847 let doors = self
5848 .engines
5849 .iter()
5850 .filter(|declared| declared.fanout)
5851 .map(|declared| {
5852 let field = &declared.field;
5853 let door = fan_door(field);
5854 let legs: Vec<Leg> = declared
5855 .slots()
5856 .into_iter()
5857 .enumerate()
5858 .map(|(at, slot)| Leg {
5859 engine: format_ident!("__INGRAPH_ENGINE_{at}__"),
5860 handle: format_ident!("__ingraph_slot_{at}"),
5861 scope: format_ident!("__ingraph_scope_{at}"),
5862 doc: format_ident!("__ingraph_doc_{at}"),
5863 marker: slot.marker(self.base()),
5864 word: slot.engine.to_string(),
5865 })
5866 .collect();
5867
5868 let parameters = legs.iter().map(|leg| {
5869 let Leg {
5870 engine,
5871 handle,
5872 scope,
5873 doc,
5874 marker,
5875 ..
5876 } = leg;
5877 quote! {
5878 #handle: &mut #brand<#engine, #marker>,
5879 #scope: #connected<
5880 '_,
5881 <#engine as #base>::Connection,
5882 <#engine as #face>::WriteContext<'_>,
5883 >,
5884 #doc: <#engine as #face>::Doc,
5885 }
5886 });
5887 let bounds = legs.iter().map(|Leg { engine, .. }| quote!(#engine: #face));
5888 let names = legs.iter().map(|Leg { engine, .. }| engine);
5889 let error = refusal_type(&legs, &refused, &base);
5890 let writes = legs.iter().enumerate().map(|(at, leg)| {
5891 let Leg {
5892 handle, scope, doc, ..
5893 } = leg;
5894 let wrap = refusal_arm(at, legs.len(), &refused);
5895 quote! {
5896 #handle.#verb(#scope, #doc).await.map_err(#wrap)?;
5897 }
5898 });
5899 let words = legs
5900 .iter()
5901 .map(|Leg { word, .. }| format!("`{word}`"))
5902 .collect::<Vec<_>>()
5903 .join(", ");
5904 let doc = leading(&format!(
5905 "Write one entry to EVERY engine `{field}` declared — {words}.\n\n`{field}` is marked \
5906 `fanout`, so all of its engines are live at once: this writes each in declared order and \
5907 stops at the first refusal, naming the leg that gave it. Without the marker the engines \
5908 are portability and a deployment writes through the one slot it opened.",
5909 ));
5910 quote! {
5911 #[doc = #doc]
5912 #[allow(clippy::too_many_arguments)]
5913 #vis async fn #door<#(#names),*>(
5914 #(#parameters)*
5915 ) -> ::core::result::Result<(), #error>
5916 where
5917 #(#bounds),*
5918 {
5919 #(#writes)*
5920 ::core::result::Result::Ok(())
5921 }
5922 }
5923 })
5924 .collect::<Vec<_>>();
5925
5926 if doors.is_empty() {
5927 return proc_macro2::TokenStream::new();
5928 }
5929 quote! {
5930 #[automatically_derived]
5931 impl #index {
5932 #(#doors)*
5933 }
5934 }
5935 }
5936
5937 /// ONE ZERO-SIZED MARKER PER ELECTION, at MODULE SCOPE — the column carried as a type.
5938 ///
5939 /// The markers cannot move inside the anonymous `const` the rest of the expansion lives in, and
5940 /// the reason is what they are FOR: a lane names one — `SlotLane<E, SegmentPair,
5941 /// SegmentPairByImageEmbedding>` — so the name has to be spellable from the scope the declaration was
5942 /// written in. Everything inside that const is reachable only by the expansion itself.
5943 ///
5944 /// Each carries the declaration's own visibility, exactly as the retrieve methods do, and for the
5945 /// same reason: a wiring site in another module is where the marker is spent, so a marker less
5946 /// visible than the method it selects would leave that method uncallable through the lane.
5947 ///
5948 /// # It is emitted PER ELECTION and not per declaration, which is the whole ruling
5949 ///
5950 /// The alternative was one marker for the declaration with the column bound at construction, and
5951 /// that is what does not refuse anything: two lanes of one type, differing in a value, are
5952 /// interchangeable at every wiring site. N markers make the two lanes N TYPES, and a door typed
5953 /// for one rejects the other where the two were joined.
5954 ///
5955 /// A `blob` or `fulltext` declaration emits nothing here, and for two different reasons. A `blob`
5956 /// elects nothing at all — it is addressed rather than ranked. A `fulltext` elects, but what a
5957 /// marker would be parameterized BY does not exist: the vector marker carries a `VectorColumn`,
5958 /// and a full-text engine is asked for a slot and a string with no column between them. What a
5959 /// full-text election gets instead is its SLOT markers — see
5960 /// [`slot_markers`](Self::slot_markers), which both kinds get and which is the per-field grain the
5961 /// engine grammar supplies.
5962 fn elections(&self) -> proc_macro2::TokenStream {
5963 let IndexModel {
5964 index, vis, krate, ..
5965 } = self;
5966 let elected = framework(krate, &["store"], "Elected");
5967 let column = framework(krate, &["store"], "VectorColumn");
5968 let base = self.base();
5969 let markers = self.embeddings.iter().map(|Elected { field, .. }| {
5970 let marker = elected_marker(base, field);
5971 let name = field.to_string();
5972 let doc = leading(&format!(
5973 "The `{name}` ELECTION of [`{index}`], as a type — what a lane serving that column is \
5974 parameterized by, and what `retrieve_by_{name}` answers from.",
5975 ));
5976 quote! {
5977 #[doc = #doc]
5978 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5979 #vis struct #marker;
5980
5981 #[automatically_derived]
5982 impl #elected<#index> for #marker {
5983 const COLUMN: #column = #column::new(#name);
5984 }
5985 }
5986 });
5987 quote!(#(#markers)*)
5988 }
5989
5990 /// `impl VectorRecord` — EVERY elected field, projected under its own column, and every fact read
5991 /// through the election family rather than off a token.
5992 ///
5993 /// Emitted for the vector kind and for neither of the others, which is the word's own asymmetry:
5994 /// the other two elect nothing and have no coordinates to hand anybody.
5995 ///
5996 /// # What each member is, and where the fact came from
5997 ///
5998 /// - **`Element`** is `<<F as EmbeddingMarker>::Item as EmbeddingShape>::Element` for the FIRST
5999 /// election's own field type. The width is NOT restated: it is a fact of the field's type, and
6000 /// [`VectorRecord`] deliberately has no `const DIM` for the same reason two homes for one fact
6001 /// are free to disagree.
6002 /// - **`vectors`** yields one `(column, coordinates)` pair per `embedding`-labelled election, in
6003 /// declared order, and nothing else. This is the whole payload posture made mechanical — a
6004 /// declaration's UNELECTED embedding-typed fields are reachable through their own accessors and
6005 /// are named nowhere on this path, so no knn can see one through ANY column.
6006 /// - **`vector_sets`** yields `(column, ordinal, coordinates)` once per MEMBER of every
6007 /// `list(embedding)` election, ordinals running `0..n` in `members()` order — and it is emitted
6008 /// only where a set election exists, a declaration with none keeping the trait's empty default.
6009 /// The two methods partition the elections: a column reported by one is never reported by the
6010 /// other, so *what is stored under this column* has one answer and the shape is read off which
6011 /// face answered.
6012 /// - **`Filter`** is `()`, the empty product this crate uses for a face a declaration does not
6013 /// have. What a search over this index may be scoped BY is the engine block's to state and that
6014 /// grammar has not arrived; `()` is the no-scope case, which a face lowers to no predicate at
6015 /// all rather than to a filter nobody wrote.
6016 ///
6017 /// # ONE WALK for both faces, and the label decides only which one reports it
6018 ///
6019 /// Both are written over `EmbeddingMarker::members`, which yields one member for a single election
6020 /// and the whole set for a set one. So there is no unwrap on this path and no partial function to
6021 /// get wrong: a single election is a set of one, mechanically, and the difference between the two
6022 /// faces is exactly whether an ordinal rides beside the coordinates.
6023 ///
6024 /// # ONE element across N elections, and rustc is what says so
6025 ///
6026 /// A slot is opened at one element, so N columns of one slot are N columns of one element. The
6027 /// front end does not check it, and could not: the elections' types are opaque tokens here, and
6028 /// what they DENOTE is the compiler's. So `Element` is the first election's projection and every
6029 /// pair is spanned at ITS OWN election field: a second election at a disagreeing element is
6030 /// `E0308` on the FIELD the author marked, not somewhere inside an expansion.
6031 fn vector_record(&self) -> proc_macro2::TokenStream {
6032 let Some(first) = self.embeddings.first() else {
6033 return proc_macro2::TokenStream::new();
6034 };
6035 let index = &self.index;
6036 let record = framework(&self.krate, &["record"], "VectorRecord");
6037 let column = framework(&self.krate, &["store"], "VectorColumn");
6038 let marker = framework(&self.krate, &["election"], "EmbeddingMarker");
6039 let shape = framework(&self.krate, &["election"], "EmbeddingShape");
6040 let first = &first.ty;
6041 let element = quote!(<<#first as #marker>::Item as #shape>::Element);
6042 // CHAINED rather than arrayed, on both faces: each election contributes a different opaque
6043 // iterator type, so there is no array of a common item to build. Every chain link is the same
6044 // tuple, which is what keeps the item type one.
6045 let singles = self
6046 .embeddings
6047 .iter()
6048 .filter(|elected| !elected.label.is_set())
6049 .map(|Elected { field, ty, .. }| {
6050 let name = field.to_string();
6051 // SPANNED AT THE ELECTION, which is what puts a disagreeing element's `E0308` and a missing
6052 // impl's `E0277` on the word the author wrote rather than on a token of this emitter's.
6053 quote_spanned!(field.span()=> .chain(
6054 <#ty as #marker>::members(&self.#field)
6055 .map(|__ingraph_member| (
6056 #column::new(#name),
6057 <<#ty as #marker>::Item as #shape>::coordinates(__ingraph_member),
6058 ))
6059 ))
6060 })
6061 .collect::<Vec<_>>();
6062 let sets = self
6063 .embeddings
6064 .iter()
6065 .filter(|elected| elected.label.is_set())
6066 .map(|Elected { field, ty, .. }| {
6067 let name = field.to_string();
6068 // `(0u32..).zip(…)` rather than `.enumerate()`, so the ORDINAL is minted at its own width
6069 // with no cast: a `usize as u32` in emitted code would be a lint an author never wrote and a
6070 // truncation nobody could reach.
6071 quote_spanned!(field.span()=> .chain(
6072 (0u32..)
6073 .zip(<#ty as #marker>::members(&self.#field))
6074 .map(|(__ingraph_at, __ingraph_member)| (
6075 #column::new(#name),
6076 __ingraph_at,
6077 <<#ty as #marker>::Item as #shape>::coordinates(__ingraph_member),
6078 ))
6079 ))
6080 })
6081 .collect::<Vec<_>>();
6082 // Emitted only where a set election exists, so a declaration that has none keeps the trait's own
6083 // default — the empty stream, which is what *no set members* means — and its expansion says
6084 // nothing about a face it does not have.
6085 let vector_sets = if sets.is_empty() {
6086 proc_macro2::TokenStream::new()
6087 } else {
6088 quote! {
6089 #[inline]
6090 fn vector_sets(&self)
6091 -> impl ::core::iter::Iterator<Item = (#column, u32, &[Self::Element])>
6092 {
6093 ::core::iter::empty() #(#sets)*
6094 }
6095 }
6096 };
6097 quote! {
6098 #[automatically_derived]
6099 impl #record for #index {
6100 type Element = #element;
6101 type Filter = ();
6102
6103 #[inline]
6104 fn vectors(&self) -> impl ::core::iter::Iterator<Item = (#column, &[Self::Element])> {
6105 ::core::iter::empty() #(#singles)*
6106 }
6107
6108 #vector_sets
6109 }
6110 }
6111 }
6112
6113 /// THE DECLARED FOLD, one accessor per SET election — what
6114 /// `semantics(fold = "…")` is spent on.
6115 ///
6116 /// # A word parsed into a model nothing spends is a promise rather than a rule
6117 ///
6118 /// This grammar's own standard, applied to its newest word. The `_with` door takes the fold BY
6119 /// VALUE and dispatches it statically, so what a declaration-level default can be is a way to
6120 /// SPELL it: `Clip::fold_by_frames()` hands back the fold this election declared, or the shipped
6121 /// [`Sum`] where it declared none, and the ruled chain reads as one line at the call —
6122 /// `…_with(…, Clip::fold_by_frames(), 10)` for the declaration's, anything else for the query's.
6123 ///
6124 /// # Constructed through [`Default`], which is the bound the word asks for
6125 ///
6126 /// The emission holds a PATH and no value, so the only way to build one is a trait every
6127 /// implementation can derive. A type that folds but cannot be defaulted is `E0277` here, naming
6128 /// the path its author wrote — and the shipped citizens carry it for exactly this reason.
6129 ///
6130 /// Emitted for a SET election alone: a single embedding has one best per query vector, so there is
6131 /// nothing to fold and no door to fold it at.
6132 fn declared_folds(&self) -> proc_macro2::TokenStream {
6133 let IndexModel { vis, krate, .. } = self;
6134 let shipped = |citizen| framework(krate, &["retrieve"], citizen);
6135 let folds = self
6136 .embeddings
6137 .iter()
6138 .filter(|elected| elected.label.is_set())
6139 .map(|elected| {
6140 let field = &elected.field;
6141 let name = fold_accessor(field);
6142 // The SHORTHAND resolves HERE, which is the one place that knows where the shelf is: a word
6143 // names a framework citizen and a path names the declaring crate's own type, and both arrive
6144 // at the same `Default` construction below.
6145 let fold = match &elected.fold {
6146 None | Some(Fold::Sum) => shipped("Sum"),
6147 Some(Fold::Max) => shipped("Max"),
6148 Some(Fold::Custom(path)) => quote!(#path),
6149 };
6150 let doc = leading(&format!(
6151 "The fold `{field}`'s set door takes when the caller has no other — this election's \
6152 DECLARED default, or the framework's `Sum` where it declared none.",
6153 ));
6154 let chain = leading(
6155 "The ruled chain is *query explicit > declaration > shipped*, and this is the middle \
6156 step written out: a caller that wants its own fold passes it, and one that wants this \
6157 election's passes this.",
6158 );
6159 let wire = leading(
6160 "THE WIRE'S CHAIN IS SHORTER BY ITS FIRST STEP: a request never chooses a fold, so the \
6161 emitted set road reads *installed at launch > this accessor*, and this is what it falls \
6162 to. The two chains differ because the callers do — a Rust caller states its own \
6163 question, and a client asks one the deployment decided the meaning of.",
6164 );
6165 quote_spanned! {field.span()=>
6166 #[doc = #doc]
6167 #[doc = ""]
6168 #[doc = #chain]
6169 #[doc = ""]
6170 #[doc = #wire]
6171 #[must_use]
6172 #[inline]
6173 #vis fn #name() -> #fold {
6174 <#fold as ::core::default::Default>::default()
6175 }
6176 }
6177 })
6178 .collect::<Vec<_>>();
6179 if folds.is_empty() {
6180 return proc_macro2::TokenStream::new();
6181 }
6182 let index = &self.index;
6183 quote! {
6184 #[allow(dead_code)]
6185 impl #index {
6186 #(#folds)*
6187 }
6188 }
6189 }
6190
6191 /// THE FROM-ROADS — one `FulltextRoad` impl per full-text SLOT, and one bare demand per elected
6192 /// field that named no engine.
6193 ///
6194 /// # This is where `searchable`'s CHECK is, and it is a bound rather than a table
6195 ///
6196 /// The marker elects a field and says nothing about its type, because the front end has no type
6197 /// to say anything about — and the one check a parser could make is a spelling allowlist, which
6198 /// false-refuses `SmolStr`, a newtype, an alias and `Vec<String>` alike. So the check is
6199 /// *A FROM-ROAD EXISTS*, and it is asked HERE, where rustc can answer it: the identity road
6200 /// demands `Searchable` (blanket over `AsRef<str>`), the shorthands demand a walk whose items are
6201 /// text, and a declared conversion demands a function of the right shape. A field with no road is
6202 /// `E0277` at its OWN TYPE TOKEN — `quote_spanned` puts it there — carrying `Searchable`'s
6203 /// `on_unimplemented` note, which teaches the three roads by name.
6204 ///
6205 /// Neither of the two answers that were on the table: not *no check* (a `searchable` field that
6206 /// cannot be read as text would reach the write lane and fail there, or worse, index nothing),
6207 /// and not a syntactic allowlist (a false refusal, which this crate calls a defect of its own).
6208 ///
6209 /// # A field with no ENGINE still gets one
6210 ///
6211 /// An election naming no engine is the PORTABLE case — legal, and it means the deployment says
6212 /// which engine. There is no slot to hang an impl on, so the demand is emitted bare. Without it a
6213 /// portable declaration would be the one place the check does not run, and *portable* would
6214 /// quietly mean *unchecked*.
6215 ///
6216 /// # UNGATED, because nothing here names a concrete engine
6217 ///
6218 /// The record side's law is that only what spells a concrete type may ride a feature gate, since
6219 /// a shut gate DELETES what it wraps. A road names a sink, a trait and the declaration's own
6220 /// field — no engine type appears — so these impls exist in a build that compiled no backend at
6221 /// all, which is also the only way the portable case could be checked.
6222 fn roads(&self) -> proc_macro2::TokenStream {
6223 if self.kind != NodeKind::Fulltext {
6224 return proc_macro2::TokenStream::new();
6225 }
6226 let IndexModel { index, krate, .. } = self;
6227 let writer = framework(krate, &["document"], "BoxWriter");
6228 let road = framework(krate, &["store"], "FulltextRoad");
6229 // `Of` is the SUPERTRAIT's — a road is one more fact about a slot, and the SLOT is what says
6230 // which declaration it belongs to. Spelled `<Self as Slot>::Of` and not `Self::Of`, which is
6231 // `E0576` inside an impl of the subtrait.
6232 let slot = framework(krate, &["store"], "Slot");
6233 let mut emitted = proc_macro2::TokenStream::new();
6234 for declared in &self.engines {
6235 if !self.searchable.contains(&declared.field) {
6236 continue;
6237 }
6238 // THE PORTABLE CASE. `engines` carries one entry per ELECTED field whether or not it named an
6239 // engine, so *named none* is the entry with an EMPTY list rather than a missing entry.
6240 if declared.engines.is_empty() {
6241 let body = self.road_body(&declared.field, &Road::Identity);
6242 emitted.extend(quote! {
6243 const _: () = {
6244 #[allow(dead_code)]
6245 fn road(entry: &#index, into: &mut #writer) {
6246 #body
6247 }
6248 };
6249 });
6250 continue;
6251 }
6252 for engine in &declared.engines {
6253 let marker = Slot {
6254 field: declared.field.clone(),
6255 engine: engine.word.clone(),
6256 }
6257 .marker(self.base());
6258 let stored = engine.stored;
6259 let error = if engine.road.fallible() {
6260 crate::model::boxed_error()
6261 } else {
6262 quote!(::core::convert::Infallible)
6263 };
6264 let body = self.road_body(&declared.field, &engine.road);
6265 emitted.extend(quote! {
6266 #[automatically_derived]
6267 impl #road for #marker {
6268 const STORED: bool = #stored;
6269
6270 type Error = #error;
6271
6272 fn write(
6273 entry: &<Self as #slot>::Of,
6274 into: &mut #writer,
6275 ) -> ::core::result::Result<(), <Self as #road>::Error> {
6276 #body
6277 ::core::result::Result::Ok(())
6278 }
6279 }
6280 });
6281 }
6282 }
6283 emitted
6284 }
6285
6286 /// ONE ROAD's body — the call the declaration's word picks, spanned at the FIELD'S OWN TYPE so a
6287 /// bound it does not satisfy is reported there.
6288 ///
6289 /// [`Conversion::apply`](crate::model::Conversion) is deliberately NOT reused: it builds a
6290 /// one-argument call (`f(value)`), and a full-text converter takes the SINK first —
6291 /// `fn(&mut BoxWriter, &Field)` — because the segmentation has to survive, which a returned
6292 /// `String` destroys. Same family, same two spellings, same escape; a different arity, written
6293 /// out.
6294 fn road_body(&self, field: &syn::Ident, road: &Road) -> proc_macro2::TokenStream {
6295 let IndexModel { krate, .. } = self;
6296 let writer = framework(krate, &["document"], "BoxWriter");
6297 let searchable = framework(krate, &["document"], "Searchable");
6298 // The declared type carries the span every refusal about this road lands at. A field the model
6299 // has no column for cannot arise — `searchable` is read off the same walk that built them — and
6300 // the fallback keeps that impossibility from being a panic.
6301 let at = self
6302 .fields
6303 .iter()
6304 .find(|column| column.name == *field)
6305 .map_or_else(|| field.span(), |column| column.ty.span());
6306 match road {
6307 Road::Identity => {
6308 quote_spanned!(at=> #searchable::write(&entry.#field, into);)
6309 }
6310 Road::Join(separator) => {
6311 quote_spanned!(at=> #writer::push_joined(into, &entry.#field, #separator);)
6312 }
6313 Road::Multi => {
6314 quote_spanned!(at=> #writer::push_each(into, &entry.#field);)
6315 }
6316 Road::Declared(Conversion::Default | Conversion::Infallible(_)) => {
6317 let Road::Declared(Conversion::Infallible(path)) = road else {
6318 // `Conversion::Default` never reaches a `Declared` road — a block that named no function
6319 // took `Road::Identity`, which is a different road rather than a missing one.
6320 return quote_spanned!(at=> #searchable::write(&entry.#field, into););
6321 };
6322 quote_spanned!(at=> #path(into, &entry.#field);)
6323 }
6324 Road::Declared(Conversion::Fallible(fallible)) => {
6325 let path = &fallible.path;
6326 match &fallible.escape {
6327 // A plain `?`, so the slot's boxed refusal absorbs the function's through `From` — and a
6328 // pair that cannot is `E0277` AT THE `?`, naming that function's error.
6329 None => quote_spanned!(at=> #path(into, &entry.#field)?;),
6330 Some(escape) => quote_spanned! {at=>
6331 ::core::result::Result::map_err(#path(into, &entry.#field), #escape)?;
6332 },
6333 }
6334 }
6335 }
6336 }
6337
6338 /// THE LABEL AUDITS — one per election, holding the field's own type to what its label claimed.
6339 ///
6340 /// # Why the claim is audited at all
6341 ///
6342 /// The label is what the EXPANSION reads: it decides which faces are written above and which doors
6343 /// are grown below, and a macro cannot resolve a type to check it. The marker is what RUSTC reads.
6344 /// One fact with two readers is the shape that drifts, so the emission states the label's claim as
6345 /// a bound and lets the compiler settle it.
6346 ///
6347 /// A field labelled `embedding` whose type carries a set is `E0277` HERE — at the span of the
6348 /// election word its author wrote — with a sentence naming both sides. The same holds the other
6349 /// way round, and between them the label cannot lie.
6350 ///
6351 /// `const _: fn() = elects_one::<TheField>;` is the shape every audit in this crate takes.
6352 fn label_audits(&self) -> proc_macro2::TokenStream {
6353 // EVERY labelled field, elected or not. A label on payload is accepted — see
6354 // [`labelled`](IndexModel::labelled) — and accepted is not unexamined: the claim is the same
6355 // claim, so it meets the same compiler.
6356 let elected = self
6357 .embeddings
6358 .iter()
6359 .map(|elected| (&elected.field, &elected.ty, elected.label));
6360 let payload = self
6361 .labelled
6362 .iter()
6363 .map(|labelled| (&labelled.field, &labelled.ty, labelled.label));
6364 let audits = elected.chain(payload).map(|(field, ty, label)| {
6365 let audit = framework(&self.krate, &["election"], label.audit());
6366 quote_spanned!(field.span()=> const _: fn() = #audit::<#ty>;)
6367 });
6368 quote!(#(#audits)*)
6369 }
6370
6371 /// THE KIND AUDITS — one per POINTING leg, holding the resource it named to the kind of seam this
6372 /// declaration writes.
6373 ///
6374 /// # The first of the three binding laws, and the only one a declaration can settle alone
6375 ///
6376 /// *Named → kind-verified.* A leg writing `resource = "crate::Ft"` names a type this expansion
6377 /// cannot resolve, so the claim is stated as a BOUND and rustc settles it: a vector election
6378 /// pointed at a full-text store is `E0277` naming `VectorEngine`, and the caret sits on the path
6379 /// its author wrote. The other two laws are the DEPLOYMENT's — a sole default, and the refusal
6380 /// that lists candidates — and both need the resource catalog, which is a graph root away.
6381 ///
6382 /// # Why it is emitted where the projections already run
6383 ///
6384 /// The `floor` and `options` rows of a leg's query package are `<Ft as FulltextEngine>::Score` and
6385 /// `::SearchOptions`, which refuse a wrong kind on their own. Two things they do not do:
6386 ///
6387 /// 1. **they land nowhere useful.** A projection sits inside a package row the author never
6388 /// wrote, so the refusal is reported at the whole attribute. This is `quote_spanned!` at the
6389 /// path, so the caret sits on the word — which is what *at the word* asks for, and the only
6390 /// part of the law a reader ever sees;
6391 /// 2. **they belong to the wire.** The package is the question layer's and the kind law is the
6392 /// resource axis's, so a round that changes what the wire mints must not be able to take the
6393 /// check away with it.
6394 ///
6395 /// A COVERAGE argument was drafted for a third reason and WITHDRAWN: every shape measured — set
6396 /// elections, fanned legs, `rrf = false` legs, declarations with no GraphQL skin — mints the seat
6397 /// and therefore projects anyway. The two above are the whole of it.
6398 ///
6399 /// # The bound is the BASE, never a face
6400 ///
6401 /// Verifying a kind must not drag in a verb obligation — a store that holds documents is a
6402 /// full-text resource whether or not this deployment also writes through it — which is what the
6403 /// verb-free base is for. Faces are the per-slot handle's, one grain down.
6404 ///
6405 /// # `blob` points at nothing, and that is the grammar rather than an omission
6406 ///
6407 /// An artifact family elects nothing and its store blocks claim no pointing word: an artifact is
6408 /// ADDRESSED rather than ranked, so it mints no package for a floor to sit in and has no kind
6409 /// question to ask. The arm answers nothing rather than guessing a seam for it.
6410 fn resource_audits(&self) -> proc_macro2::TokenStream {
6411 let audit = match self.kind {
6412 NodeKind::Fulltext => framework(&self.krate, &["store"], "holds_documents"),
6413 NodeKind::Vector => framework(&self.krate, &["store"], "holds_coordinates"),
6414 NodeKind::Operator
6415 | NodeKind::Entity
6416 | NodeKind::Record
6417 | NodeKind::Aggregate
6418 | NodeKind::Blob => {
6419 return proc_macro2::TokenStream::new();
6420 }
6421 };
6422 let audits = self
6423 .engines
6424 .iter()
6425 .flat_map(|declared| declared.engines.iter())
6426 .filter_map(|engine| engine.resource.as_ref())
6427 .map(|resource| quote_spanned!(resource.span()=> const _: fn() = #audit::<#resource>;));
6428 quote!(#(#audits)*)
6429 }
6430
6431 /// THE MOUNT SEAM this declaration's kind reads a resource through — `None` on a kind that mounts
6432 /// nothing.
6433 ///
6434 /// One function, so the two places that name the seam — the WIRE MINT below and the HANDLE the
6435 /// emitted Rust door is turbofished with — cannot come to name two different traits.
6436 fn mount_seam(&self) -> Option<proc_macro2::TokenStream> {
6437 match self.kind {
6438 NodeKind::Fulltext => Some(framework(&self.krate, &["store"], "FulltextMount")),
6439 NodeKind::Vector => Some(framework(&self.krate, &["store"], "VectorMount")),
6440 NodeKind::Operator
6441 | NodeKind::Entity
6442 | NodeKind::Record
6443 | NodeKind::Aggregate
6444 | NodeKind::Blob => None,
6445 }
6446 }
6447
6448 /// THE PER-SLOT HANDLE a pointed resource mints — what an emitted Rust door's engine parameter is.
6449 ///
6450 /// The RESOURCE is the mount and the HANDLE is what wears the read faces, so a door bounded
6451 /// `E: AsyncFulltextRead` is spelled with this and never with the resource itself. Spanned at the
6452 /// path the author wrote, so a resource of the wrong kind — one with no mount seam of this family
6453 /// — is `E0277` on the word rather than inside an expansion.
6454 fn wire_handle(&self, resource: &syn::Path) -> proc_macro2::TokenStream {
6455 let mount = self
6456 .mount_seam()
6457 .expect("a retrieving kind mounts its resources");
6458 quote_spanned!(resource.span()=> <#resource as #mount>::Handle)
6459 }
6460
6461 /// THE WIRE MINT — one election's CORPUS, out of the request's own citizens.
6462 ///
6463 /// ```ignore
6464 /// let (mut __ingraph_slot, __ingraph_connection) =
6465 /// search_slot::<app::Ft, Media>(ctx, "title", <MediaTitleLexical as Slot>::SLOT)?;
6466 /// ```
6467 ///
6468 /// # Three facts, and each of them moved here from somewhere it did not belong
6469 ///
6470 /// The CITIZEN is `Shared<R>` — the resource a launch built — rather than a per-pairing door an
6471 /// application installed, because a leg POINTS at a resource and that is the type this expansion
6472 /// can name. The SLOT NAME is read off the marker this declaration already mints, so the corpus a
6473 /// read opens and the corpus a write lands in have ONE home. And the CONNECTION comes back beside
6474 /// the handle, because a minted handle is stateless and reaches its index back through the mount's
6475 /// own manager — the value an emitted resolver had no way to build while all it held was an
6476 /// engine.
6477 ///
6478 /// A VECTOR corpus takes its width beside the name, per the two mount seams' one difference, and
6479 /// the width is projected off the ELECTED FIELD's own type — the same projection the geometry
6480 /// bindings make, spelled inline because this position is an expression rather than a const
6481 /// argument.
6482 fn wire_corpus(
6483 &self,
6484 field: &syn::Ident,
6485 elected: Option<&syn::Type>,
6486 engine: &Engine,
6487 resource: &syn::Path,
6488 slot: &syn::Ident,
6489 connection: &syn::Ident,
6490 ) -> proc_macro2::TokenStream {
6491 let IndexModel { krate, index, .. } = self;
6492 let ctx = crate::method::wire_method(&format_ident!("ctx"));
6493 let word = field.to_string();
6494 let brand = crate::engine::Slot {
6495 field: field.clone(),
6496 engine: engine.word.clone(),
6497 }
6498 .marker(self.base());
6499 let marker = framework(krate, &["store"], "Slot");
6500 let (door, width) = match (self.kind, elected) {
6501 (NodeKind::Vector, Some(ty)) => {
6502 let shape = framework(krate, &["election"], "EmbeddingShape");
6503 let embedding = framework(krate, &["election"], "EmbeddingMarker");
6504 (
6505 framework(krate, &["graphql"], "vector_slot"),
6506 Some(quote_spanned! {field.span()=>
6507 , <<#ty as #embedding>::Item as #shape>::WIDTH
6508 }),
6509 )
6510 }
6511 _ => (framework(krate, &["graphql"], "search_slot"), None),
6512 };
6513 quote! {
6514 let (mut #slot, #connection) = #door::<#resource, #index>(
6515 #ctx,
6516 #word,
6517 <#brand as #marker>::SLOT #width,
6518 )?;
6519 }
6520 }
6521
6522 /// The RETRIEVE face, written TWICE — once with a span around each door's body and once without.
6523 ///
6524 /// The G6 instrument clause, reaching the query path's own doors. `emit::query`'s three crossing
6525 /// entries and these are ONE mechanism: a door that leaves this process is a door whose duration a
6526 /// trace wants, and the retrieve faces are where an application asks the framework a question. See
6527 /// [`observed`](Self::observed) for why the entry is written twice rather than carrying an
6528 /// attribute, and [`retrieve_half`](Self::retrieve_half) for what the doors are.
6529 ///
6530 /// A kind that answers no retrieve emits NEITHER half rather than two empty gates, and the test is
6531 /// the emission itself — `blob` returns nothing from the half below, so one `is_empty` keeps the
6532 /// decision about which kinds retrieve in the ONE place that already makes it.
6533 fn retrieve(&self) -> proc_macro2::TokenStream {
6534 let watched = self.retrieve_half(true);
6535 if watched.is_empty() {
6536 return watched;
6537 }
6538 let plain = self.retrieve_half(false);
6539 let gate = framework(&self.krate, &["gate"], "if_tracing");
6540 let ungated = framework(&self.krate, &["gate"], "if_no_tracing");
6541 quote! {
6542 #gate! { #watched }
6543 #ungated! { #plain }
6544 }
6545 }
6546
6547 /// THE FUSED DOORS — `vector_fuse` and `vector_fuse_similar`, over the tier's own routes.
6548 ///
6549 /// Emitted per the ADDITIVE DOOR LAW ([`Doors`](crate::fuse::Doors)), which is decided in exactly
6550 /// one place and read here: a tier with two or more routes of one modality gets that modality's
6551 /// door, a mixed tier also gets `fuse`, and every per-kind door beside them goes on emitting. At
6552 /// the INDEX grain the law resolves to one of the three — a full-text declaration is one route
6553 /// however many fields it elects, and a declaration's KIND is its modality, so `fulltext_fuse` and
6554 /// the mixed `fuse` have no route set to fuse here and their home is the root.
6555 ///
6556 /// # Every route is asked through the door it already had
6557 ///
6558 /// The fused doors reach `retrieve_keys_by_<field>` and `retrieve_similar_by_<field>` and nothing
6559 /// else — no second query path, no floor of their own, no walk of their own. What they add is the
6560 /// three facts a fold needs and a single route has no use for: WHICH routes to ask (the question
6561 /// chain's participation rule), how much each one's opinion counts (`Route::weight`), and what
6562 /// arithmetic joins them (`FusionOptions`).
6563 ///
6564 /// # The question chain is resolved HERE, and only its COORDINATES half can run
6565 ///
6566 /// `asked`'s law — 自问 > 层问 > 父问 — is what decides a route's question, and `participates` is
6567 /// what turns *no resolvable question* into a structural absence rather than an empty answer. Both
6568 /// are spent below over the `coordinates` seat, which is the half a door can act on: a route
6569 /// holding its own coordinates needs no tower.
6570 ///
6571 /// The TEXT half is resolved and NOT run, and the reason is a measurement rather than a choice: a
6572 /// text question becomes coordinates by walking that election's own `ask` chain, whose hops are
6573 /// types the declaration named — so a door running the text chain would take one type parameter
6574 /// per route, and its arity would be the declaration's rather than the grammar's. That is the
6575 /// tower-fanout design and it is unruled, so this door asks in coordinates and the text chain is
6576 /// carried.
6577 ///
6578 /// # A route whose example is UNINDEXED is absent rather than fatal
6579 ///
6580 /// In `vector_fuse_similar` the example comes from the entity's own stored vectors, per route. An
6581 /// entity indexed in one column and not another is ordinary — that is what a multi-election
6582 /// declaration is FOR — so `Unindexed` from one route drops that route out of the fold, exactly as
6583 /// a missing question does, and every other refusal propagates.
6584 fn fused_half(&self, observed: bool) -> proc_macro2::TokenStream {
6585 use heck::ToUpperCamelCase as _;
6586
6587 let doors = self.tier().doors();
6588 if !doors.vector {
6589 return proc_macro2::TokenStream::new();
6590 }
6591 let IndexModel {
6592 index, vis, krate, ..
6593 } = self;
6594 let key = self.key();
6595 // The BASE carries the vocabulary and the READ FACE carries the lease, so a projection names
6596 // whichever of the two declares the member it asks for; the bound names the face, which implies
6597 // the base. The row names NEITHER — `Field` is engine-blind, which is what the column language
6598 // bought and what makes this bound one word instead of one per engine.
6599 let face = framework(krate, &["store"], "VectorEngine");
6600 let lease = framework(krate, &["store"], "AsyncVectorRead");
6601 let row = framework(krate, &["store"], "Field");
6602 let brand = framework(krate, &["store"], "SlotHandle");
6603 let connected = framework(krate, &["store"], "Connected");
6604 let embedding = framework(krate, &["storage"], "Embedding");
6605 let marker = framework(krate, &["election"], "EmbeddingMarker");
6606 let vector_query = framework(krate, &["retrieve"], "VectorQuery");
6607 let fused = framework(krate, &["retrieve"], "Fused");
6608 let rooted = framework(krate, &["retrieve"], "Rooted");
6609 let route = framework(krate, &["retrieve"], "Route");
6610 let depth = framework(krate, &["retrieve"], "route_depth");
6611 let flavour = framework(krate, &["retrieve"], "FusionOptions");
6612 let fusion = framework(krate, &["retrieve"], "Fusion");
6613 let participates = framework(krate, &["retrieve"], "participates");
6614 let weighted = framework(krate, &["retrieve"], "fuse_weighted");
6615 let refused = framework(krate, &["retrieve"], "OwnReadError");
6616 let join = framework(krate, &["retrieve"], self.dedup.join());
6617 let admits = self.dedup.admits();
6618
6619 let tier = self.tier();
6620 let evidence = tier.evidence_name();
6621 let refusal = tier.fused_error_name();
6622 let options = tier.options_name().expect("a vector tier retrieves");
6623 let question = tier.question_name().expect("a vector tier retrieves");
6624 let routes: Vec<&Elected> = tier.fused_routes().collect();
6625
6626 // ONE ROUTE'S OWN NAMES — its engine parameter, the three values it is asked with, and the two
6627 // projections off that engine. Every list below is in route order and read in lock-step, which
6628 // is what keeps a route's engine, slot, scope and floor from drifting apart across the four
6629 // places they are spelled.
6630 let engines: Vec<syn::Ident> = routes
6631 .iter()
6632 .map(|elected| crate::fuse::engine_param(&elected.field))
6633 .collect();
6634 let slots: Vec<syn::Ident> = routes
6635 .iter()
6636 .map(|elected| format_ident!("{}_slot", elected.field))
6637 .collect();
6638 let scopes: Vec<syn::Ident> = routes
6639 .iter()
6640 .map(|elected| format_ident!("{}_scope", elected.field))
6641 .collect();
6642 let owns: Vec<syn::Ident> = routes
6643 .iter()
6644 .map(|elected| format_ident!("{}_own", elected.field))
6645 .collect();
6646 let floors: Vec<syn::Ident> = routes
6647 .iter()
6648 .map(|elected| format_ident!("{}_floor", elected.field))
6649 .collect();
6650 // THE KNOB SEAT, one per route and beside that route's own floor — for the FLOOR's exact reason,
6651 // stated one member over. A route's knobs are `<T as VectorEngine>::SearchOptions` where `T` is
6652 // the type the DECLARATION named; this door's are `<__INGRAPH_ENGINE_<F>__ as …>::SearchOptions`,
6653 // and nothing proves the two are one type. So the request package's `engine` seat cannot be read
6654 // into a generic call here, and the knobs travel positionally exactly as the floors do.
6655 let knob_seats: Vec<syn::Ident> = routes
6656 .iter()
6657 .map(|elected| format_ident!("{}_options", elected.field))
6658 .collect();
6659 let knobs: Vec<proc_macro2::TokenStream> = engines
6660 .iter()
6661 .map(|engine| quote!(::core::option::Option<&<#engine as #face>::SearchOptions>))
6662 .collect();
6663 let scores: Vec<proc_macro2::TokenStream> = engines
6664 .iter()
6665 .map(|engine| quote!(<#engine as #face>::Score))
6666 .collect();
6667 let refusals: Vec<proc_macro2::TokenStream> = engines
6668 .iter()
6669 .map(|engine| quote!(<#engine as #face>::Error))
6670 .collect();
6671 let variants: Vec<syn::Ident> = routes
6672 .iter()
6673 .map(|elected| format_ident!("{}", elected.field.to_string().to_upper_camel_case()))
6674 .collect();
6675
6676 // ONE ROUTE's edge facts, read the same way in both doors: the weight a parent believes about
6677 // it, whether the parent walked it at all, and HOW DEEP to ask it — the third fact, resolved
6678 // through the framework's own law, which caps the ask against the DECLARED wall and falls to the
6679 // caller's budget where the request named no depth.
6680 let edges = routes.iter().map(|elected| {
6681 let field = &elected.field;
6682 let package = tier.route_options(elected);
6683 let wall = self.wall(::core::option::Option::Some(field));
6684 quote! {
6685 let __ingraph_route = ::core::option::Option::and_then(options, #options::#field);
6686 let __ingraph_enabled = ::core::option::Option::map_or(
6687 __ingraph_route,
6688 #route::<#package>::DEFAULT_ENABLED,
6689 #route::enabled,
6690 );
6691 let __ingraph_weight = ::core::option::Option::map_or(
6692 __ingraph_route,
6693 #route::<#package>::DEFAULT_WEIGHT,
6694 #route::weight,
6695 );
6696 let __ingraph_ceiling = #depth(
6697 ::core::option::Option::and_then(__ingraph_route, #route::depth),
6698 // THE DECLARED CEILING, which is the only ceiling there is: a wall is written in the
6699 // DECLARATION and never on a request, so nothing is read out of the package here. The
6700 // word ARRIVED with the number tiers and this is the argument it fills — `None` still,
6701 // and byte-for-byte the old tokens, where no tier of this declaration wrote one.
6702 #wall,
6703 limit,
6704 );
6705 }
6706 });
6707
6708 let asks = routes
6709 .iter()
6710 .enumerate()
6711 .zip(edges)
6712 .map(|((at, elected), edge)| {
6713 let field = &elected.field;
6714 let (width, space) = self.geometry(elected);
6715 let variant = &variants[at];
6716 let engine = &engines[at];
6717 let slot = &slots[at];
6718 let scope = &scopes[at];
6719 let floor = &floors[at];
6720 let knob = &knob_seats[at];
6721 let asked = tier.route_question(elected);
6722 let keys = Door::Keys.name(field);
6723 let point = quote!(#embedding<<#engine as #face>::Element, #width, #space>);
6724 quote! {
6725 {
6726 #edge
6727 let __ingraph_own = ::core::option::Option::and_then(
6728 #question::#field(question),
6729 #asked::coordinates,
6730 );
6731 if #participates(__ingraph_enabled, __ingraph_own) {
6732 let __ingraph_coordinates: #point = ::core::convert::Into::into(
6733 ::core::clone::Clone::clone(
6734 __ingraph_own.expect("a participating route resolved a question"),
6735 ),
6736 );
6737 let __ingraph_query = #vector_query::new(
6738 __ingraph_coordinates,
6739 ::core::clone::Clone::clone(&#floor),
6740 );
6741 let __ingraph_ranked = Self::#keys::<#engine>(
6742 #slot,
6743 ::core::clone::Clone::clone(&#scope),
6744 &__ingraph_query,
6745 __ingraph_ceiling,
6746 #knob,
6747 )
6748 .await
6749 .map_err(#refusal::#variant)?;
6750 __ingraph_members.push((
6751 __ingraph_weight,
6752 ::core::iter::Iterator::collect::<::std::vec::Vec<_>>(
6753 ::core::iter::Iterator::map(
6754 ::std::vec::Vec::into_iter(__ingraph_ranked),
6755 |__ingraph_hit| {
6756 let (__ingraph_score, __ingraph_rank, __ingraph_key) =
6757 __ingraph_hit.into_components();
6758 #rooted::new(
6759 __ingraph_key,
6760 __ingraph_rank,
6761 #evidence::#variant(__ingraph_score),
6762 )
6763 },
6764 ),
6765 ),
6766 ));
6767 }
6768 }
6769 }
6770 });
6771
6772 let examples = routes.iter().enumerate().map(|(at, elected)| {
6773 let field = &elected.field;
6774 let package = tier.route_options(elected);
6775 let variant = &variants[at];
6776 let engine = &engines[at];
6777 let slot = &slots[at];
6778 let scope = &scopes[at];
6779 let own = &owns[at];
6780 let floor = &floors[at];
6781 let knob = &knob_seats[at];
6782 let similar = Door::Similar.name(field);
6783 let wall = self.wall(::core::option::Option::Some(field));
6784 quote! {
6785 {
6786 let __ingraph_route = ::core::option::Option::and_then(options, #options::#field);
6787 let __ingraph_enabled = ::core::option::Option::map_or(
6788 __ingraph_route,
6789 #route::<#package>::DEFAULT_ENABLED,
6790 #route::enabled,
6791 );
6792 let __ingraph_weight = ::core::option::Option::map_or(
6793 __ingraph_route,
6794 #route::<#package>::DEFAULT_WEIGHT,
6795 #route::weight,
6796 );
6797 let __ingraph_ceiling = #depth(
6798 ::core::option::Option::and_then(__ingraph_route, #route::depth),
6799 // THE DECLARED CEILING, which is the only ceiling there is: a wall is written in the
6800 // DECLARATION and never on a request, so nothing is read out of the package here. The
6801 // word ARRIVED with the number tiers and this is the argument it fills — `None` still,
6802 // and byte-for-byte the old tokens, where no tier of this declaration wrote one.
6803 #wall,
6804 limit,
6805 );
6806 if __ingraph_enabled {
6807 // AN UNINDEXED ROUTE IS ABSENT, not fatal: an entity held in one column and not another
6808 // is what a multi-election declaration is for. Every other refusal propagates, and the
6809 // ENGINE arm names the route it came from — the widening's whole point.
6810 match Self::#similar::<#engine>(
6811 #slot,
6812 ::core::clone::Clone::clone(&#own),
6813 ::core::clone::Clone::clone(&#scope),
6814 key,
6815 ::core::clone::Clone::clone(&#floor),
6816 __ingraph_ceiling,
6817 #knob,
6818 )
6819 .await
6820 {
6821 ::core::result::Result::Ok(__ingraph_ranked) => {
6822 __ingraph_members.push((
6823 __ingraph_weight,
6824 ::core::iter::Iterator::collect::<::std::vec::Vec<_>>(
6825 ::core::iter::Iterator::map(
6826 ::std::vec::Vec::into_iter(__ingraph_ranked),
6827 |__ingraph_hit| {
6828 let (__ingraph_score, __ingraph_rank, __ingraph_key) =
6829 __ingraph_hit.into_components();
6830 #rooted::new(
6831 __ingraph_key,
6832 __ingraph_rank,
6833 #evidence::#variant(__ingraph_score),
6834 )
6835 },
6836 ),
6837 ),
6838 ));
6839 }
6840 ::core::result::Result::Err(#refused::Unindexed) => {}
6841 ::core::result::Result::Err(#refused::Engine(__ingraph_refusal)) => {
6842 return ::core::result::Result::Err(
6843 #refused::Engine(#refusal::#variant(__ingraph_refusal)),
6844 );
6845 }
6846 ::core::result::Result::Err(#refused::Several { held }) => {
6847 return ::core::result::Result::Err(#refused::Several { held });
6848 }
6849 ::core::result::Result::Err(#refused::Width { declared, stored }) => {
6850 return ::core::result::Result::Err(#refused::Width { declared, stored });
6851 }
6852 }
6853 }
6854 }
6855 }
6856 });
6857
6858 let resolved = quote! {
6859 let __ingraph_fusion = ::core::option::Option::map_or(
6860 ::core::option::Option::and_then(options, #options::fusion),
6861 <#fusion as ::core::default::Default>::default(),
6862 #flavour::fusion,
6863 );
6864 };
6865 let fuse_door = format_ident!("vector_fuse");
6866 let similar_door = format_ident!("vector_fuse_similar");
6867 let answer = quote!(::std::vec::Vec<#fused<#key, #evidence<#(#scores,)*>>>);
6868 let coordinate_bounds = routes.iter().enumerate().map(|(at, elected)| {
6869 let (width, space) = self.geometry(elected);
6870 let engine = &engines[at];
6871 let ty = &elected.ty;
6872 quote! {
6873 <#ty as #marker>::Item: ::core::clone::Clone
6874 + ::core::convert::Into<#embedding<<#engine as #face>::Element, #width, #space>>
6875 }
6876 });
6877 // THE PER-ROUTE OBLIGATIONS, one group per route: the engine is one, the key addresses it, its
6878 // currency clones and its read scope clones. Each is stated against THAT route's engine, which
6879 // is what a single `__INGRAPH_ENGINE__` was quietly collapsing into one obligation.
6880 let seams = engines.iter().map(|engine| {
6881 quote! {
6882 #engine: #lease,
6883 #key: #row + #admits + ::core::clone::Clone,
6884 <#engine as #face>::Score: ::core::clone::Clone,
6885 <#engine as #lease>::ReadContext<'__ingraph_scope>: ::core::clone::Clone,
6886 }
6887 });
6888 let similar_seams = seams.clone();
6889 let fuse_params = routes.iter().enumerate().map(|(at, _)| {
6890 let engine = &engines[at];
6891 let slot = &slots[at];
6892 let scope = &scopes[at];
6893 let floor = &floors[at];
6894 let knob = &knob_seats[at];
6895 let seat = &knobs[at];
6896 quote! {
6897 #slot: &mut #brand<#engine, Self>,
6898 #scope: #connected<'__ingraph_scope, <#engine as #face>::Connection,
6899 <#engine as #lease>::ReadContext<'__ingraph_scope>>,
6900 #floor: <#engine as #face>::Score,
6901 #knob: #seat,
6902 }
6903 });
6904 let similar_params = routes.iter().enumerate().map(|(at, _)| {
6905 let engine = &engines[at];
6906 let slot = &slots[at];
6907 let scope = &scopes[at];
6908 let own = &owns[at];
6909 let floor = &floors[at];
6910 let knob = &knob_seats[at];
6911 let seat = &knobs[at];
6912 quote! {
6913 #slot: &mut #brand<#engine, Self>,
6914 #own: #connected<'__ingraph_scope, <#engine as #face>::Connection,
6915 <#engine as #lease>::ReadContext<'__ingraph_scope>>,
6916 #scope: #connected<'__ingraph_scope, <#engine as #face>::Connection,
6917 <#engine as #lease>::ReadContext<'__ingraph_scope>>,
6918 #floor: <#engine as #face>::Score,
6919 #knob: #seat,
6920 }
6921 });
6922 let fuse_body = self.observed(
6923 observed,
6924 &fuse_door,
6925 quote! {
6926 #resolved
6927 let mut __ingraph_members = ::std::vec::Vec::new();
6928 #(#asks)*
6929 ::core::result::Result::Ok(
6930 #weighted::<_, _, #join<#key>>(__ingraph_members, __ingraph_fusion)
6931 )
6932 },
6933 );
6934 let similar_body = self.observed(
6935 observed,
6936 &similar_door,
6937 quote! {
6938 #resolved
6939 let mut __ingraph_members = ::std::vec::Vec::new();
6940 #(#examples)*
6941 ::core::result::Result::Ok(
6942 #weighted::<_, _, #join<#key>>(__ingraph_members, __ingraph_fusion)
6943 )
6944 },
6945 );
6946 let fuse_doc = leading(&format!(
6947 "FUSED, VECTOR — every one of [`{index}`]'s vector routes asked at once, their rankings \
6948 joined by reciprocal rank fusion. Answers in THIS tier's own key.",
6949 ));
6950 let law = leading(
6951 "Beside the per-election doors and never instead of them: a caller asking one column still \
6952 calls that column's own pair. What this adds is the four facts a fold needs and one route \
6953 has no use for — WHICH routes to ask (a route with no resolvable question is structurally \
6954 absent, and one the parent disabled is not walked), how much each one's opinion counts, HOW \
6955 DEEP to ask each of them, and what arithmetic joins them.",
6956 );
6957 let depths = leading(
6958 "PER-ROUTE DEPTH, spent at each route's own fetch: a route's `Route.depth` is what this door \
6959 hands that route's `knn`, falling back to `limit` where the request named none, and CAPPED \
6960 by the declaration's own ceiling wherever one is declared. Asymmetric engines therefore each \
6961 get their own number — which is the point, since RRF is sum-family and a candidate pool \
6962 deeper than the answer is the ordinary shape. A `depth` below `limit` is legal, and a \
6963 `depth` above the wall is capped rather than refused: the request's number is a preference \
6964 and the declaration's is protection.",
6965 );
6966 let hetero = leading(
6967 "ONE ENGINE PARAMETER PER ROUTE, and one slot, one read scope, one FLOOR and one set of \
6968 KNOBS beside each — because a floor is a number in ONE engine's currency and its knobs are \
6969 written in ONE engine's vocabulary, and two routes held in two stores have two of each. The \
6970 homogeneous tier names the same engine in every position, which is the DEGENERATE case of \
6971 this signature rather than a second door.",
6972 );
6973 let knobs_doc = leading(
6974 "PER-ROUTE KNOBS, spent at each route's own crossing and read by nothing here: \
6975 `<field>_options` is handed to that route's tier-A door verbatim, and a route given none \
6976 runs under its engine's own defaults.",
6977 );
6978 let knobs_wall = leading(
6979 "They are POSITIONAL for the FLOOR's reason, one member over. The request package's `engine` \
6980 seat holds `<T as VectorEngine>::SearchOptions` for the type the DECLARATION named — a \
6981 concrete type — where this door's parameter is that projection off a generic engine, and \
6982 nothing proves the two are one. So a generic door cannot read the seat's knobs into its own \
6983 call, and what a caller holds concretely it hands in positionally.",
6984 );
6985 let knobs_borrow = leading(
6986 "BORROWED, which is what makes a fan free: one request value reaches every route with no \
6987 copy taken, and no route's package is cloned to be spent. No door of this family states a \
6988 `Clone` obligation about the knobs.",
6989 );
6990 let currency = leading(
6991 "No score of any route enters the fusion — only the ORDINAL its engine gave the hit — which \
6992 is what lets routes whose currencies were never compared be fused at all. Each route's own \
6993 score rides out as EVIDENCE instead, in that route's own currency.",
6994 );
6995 let similar_doc = leading(&format!(
6996 "FUSED, VECTOR, BY EXAMPLE — what else is near THIS entity, according to every one of \
6997 [`{index}`]'s vector routes at once. The key is this tier's own at every level, and each \
6998 route reaches its own stored vectors through its own by-example door.",
6999 ));
7000 let absence = leading(
7001 "A route holding nothing for this entity drops OUT of the fold rather than refusing the \
7002 whole answer: an entity indexed in one column and not another is what a multi-election \
7003 declaration is for. Every other refusal — a width the declaration does not state, several \
7004 vectors where it elected one, the engine's own — propagates, the engine's own wearing the \
7005 name of the route that spoke it.",
7006 );
7007 quote! {
7008 #[doc = #fuse_doc]
7009 #[doc = ""]
7010 #[doc = #law]
7011 #[doc = ""]
7012 #[doc = #depths]
7013 #[doc = ""]
7014 #[doc = #hetero]
7015 #[doc = ""]
7016 #[doc = #knobs_doc]
7017 #[doc = ""]
7018 #[doc = #knobs_wall]
7019 #[doc = ""]
7020 #[doc = #knobs_borrow]
7021 #[doc = ""]
7022 #[doc = #currency]
7023 #[allow(clippy::too_many_arguments)]
7024 #vis async fn #fuse_door<'__ingraph_scope, #(#engines),*>(
7025 #(#fuse_params)*
7026 options: ::core::option::Option<&#options>,
7027 question: &#question,
7028 limit: ::core::num::NonZeroUsize,
7029 ) -> ::core::result::Result<#answer, #refusal<#(#refusals,)*>>
7030 where
7031 #(#seams)*
7032 #(#coordinate_bounds,)*
7033 {
7034 #fuse_body
7035 }
7036
7037 #[doc = #similar_doc]
7038 #[doc = ""]
7039 #[doc = #absence]
7040 #[doc = ""]
7041 #[doc = #depths]
7042 #[doc = ""]
7043 #[doc = #hetero]
7044 #[doc = ""]
7045 #[doc = #knobs_doc]
7046 #[doc = ""]
7047 #[doc = #knobs_wall]
7048 #[doc = ""]
7049 #[doc = #knobs_borrow]
7050 #[doc = ""]
7051 #[doc = #currency]
7052 #[allow(clippy::too_many_arguments)]
7053 #vis async fn #similar_door<'__ingraph_scope, #(#engines),*>(
7054 #(#similar_params)*
7055 key: &#key,
7056 options: ::core::option::Option<&#options>,
7057 limit: ::core::num::NonZeroUsize,
7058 ) -> ::core::result::Result<#answer, #refused<#refusal<#(#refusals,)*>>>
7059 where
7060 #(#similar_seams)*
7061 {
7062 #similar_body
7063 }
7064 }
7065 }
7066
7067 /// THE MINI FUSE DOORS — `vector_fuse_by_<field>` and `vector_fuse_similar_by_<field>`, over ONE
7068 /// fanned election's legs.
7069 ///
7070 /// # The fractal, one level down
7071 ///
7072 /// A fanned field carries the tier's whole fusion kit onto one field: its LEGS are its routes, its
7073 /// slot package is a mini `FuseOptions`, and this is the door that spends them. Everything the
7074 /// tier door does over the fields a declaration elected, this does over the stores ONE field is
7075 /// written to — the same fold, the same ordinals, the same evidence shape.
7076 ///
7077 /// # ONE QUESTION, and that is the deliberate asymmetry
7078 ///
7079 /// The tier door takes a question package per route, because two elections are two spaces. The
7080 /// legs are ONE field's coordinates in several stores, so there is one question and every leg is
7081 /// asked it — which is why the question package of a fanned slot has no per-leg row, and why this
7082 /// signature takes one `question` where the tier's takes a tree.
7083 ///
7084 /// The asymmetry does not reach the KNOBS: a leg's `Route` carries its own weight and its own
7085 /// DEPTH, resolved exactly as a tier route's is, so the legs share a question and disagree about
7086 /// how deep to answer it.
7087 ///
7088 /// # The SELECTOR is read here and nowhere else
7089 ///
7090 /// `engine` absent picks the FUSED road: every participating leg is walked and their ordinals are
7091 /// folded. `engine` present picks ONE leg and reads it directly, answering the SAME shape — the
7092 /// evidence enum with a single variant filled. There is no second door and no second answer type,
7093 /// which is the whole of what *addressability* costs.
7094 ///
7095 /// A leg a `resource =` word made addressable but `rrf = false` took out of the leaderboard is
7096 /// reachable ONLY by the selector, and is skipped on the fused road. A participating leg with no
7097 /// `resource =` word is the reverse: folded, and unnameable.
7098 ///
7099 /// # The floors are POSITIONAL, and the seat's own floor is not spent
7100 ///
7101 /// The selector's variants each carry a `floor` in their engine's own `Score` — a CONCRETE type,
7102 /// projected off the path the declaration wrote. This door's floor is
7103 /// `<__INGRAPH_ENGINE_<LEG>__ as VectorEngine>::Score`, a generic. Nothing proves the two are one
7104 /// type, so the seat's floor cannot be read into a generic door's call and the positional floor is
7105 /// what is spent. Same posture as the tier door's, and the same posture `options` has carried
7106 /// since β4b.
7107 fn fanned_half(&self, observed: bool) -> proc_macro2::TokenStream {
7108 let tier = self.tier();
7109 let slots: Vec<proc_macro2::TokenStream> = tier
7110 .fanned_slots()
7111 .map(|elected| self.fanned_slot_doors(observed, elected))
7112 .collect();
7113 quote!(#(#slots)*)
7114 }
7115
7116 /// ONE fanned election's pair of mini fuse doors — see [`fanned_half`](Self::fanned_half).
7117 fn fanned_slot_doors(&self, observed: bool, elected: &Elected) -> proc_macro2::TokenStream {
7118 use heck::ToUpperCamelCase as _;
7119
7120 let IndexModel { vis, krate, .. } = self;
7121 let key = self.key();
7122 // The BASE carries the vocabulary and the READ FACE carries the lease, so a projection names
7123 // whichever of the two declares the member it asks for; the bound names the face, which implies
7124 // the base. The row names NEITHER — `Field` is engine-blind, which is what the column language
7125 // bought and what makes this bound one word instead of one per engine.
7126 let face = framework(krate, &["store"], "VectorEngine");
7127 let lease = framework(krate, &["store"], "AsyncVectorRead");
7128 let row = framework(krate, &["store"], "Field");
7129 let brand = framework(krate, &["store"], "SlotHandle");
7130 let connected = framework(krate, &["store"], "Connected");
7131 let embedding = framework(krate, &["storage"], "Embedding");
7132 let marker = framework(krate, &["election"], "EmbeddingMarker");
7133 let vector_query = framework(krate, &["retrieve"], "VectorQuery");
7134 let fused = framework(krate, &["retrieve"], "Fused");
7135 let rooted = framework(krate, &["retrieve"], "Rooted");
7136 let route = framework(krate, &["retrieve"], "Route");
7137 let depth = framework(krate, &["retrieve"], "route_depth");
7138 let flavour = framework(krate, &["retrieve"], "FusionOptions");
7139 let fusion = framework(krate, &["retrieve"], "Fusion");
7140 let participates = framework(krate, &["retrieve"], "participates");
7141 let weighted = framework(krate, &["retrieve"], "fuse_weighted");
7142 let refused = framework(krate, &["retrieve"], "OwnReadError");
7143 let join = framework(krate, &["retrieve"], self.dedup.join());
7144 let admits = self.dedup.admits();
7145
7146 let tier = self.tier();
7147 let field = &elected.field;
7148 let legs = tier.slot_legs(elected);
7149 let options = tier.route_options(elected);
7150 let asked = tier.route_question(elected);
7151 let evidence = tier.slot_evidence_name(elected);
7152 let refusal = tier.slot_error_name(elected);
7153 let selector = tier.slot_selector(elected);
7154 let (width, space) = self.geometry(elected);
7155 let keys = Door::Keys.name(field);
7156 let similar = Door::Similar.name(field);
7157 let fuse_door = Door::FusedLegs.name(field);
7158 let similar_door = Door::FusedLegsSimilar.name(field);
7159
7160 // ONE LEG'S OWN NAMES, in written order and read in lock-step — the same discipline the tier
7161 // door's route lists are under, at the grain where a route is a STORE.
7162 let engines: Vec<syn::Ident> = legs
7163 .iter()
7164 .map(|engine| crate::fuse::engine_param(&engine.word))
7165 .collect();
7166 let variants: Vec<syn::Ident> = legs
7167 .iter()
7168 .map(|engine| format_ident!("{}", engine.word.to_string().to_upper_camel_case()))
7169 .collect();
7170 let handles: Vec<syn::Ident> = legs
7171 .iter()
7172 .map(|engine| format_ident!("{}_slot", engine.word))
7173 .collect();
7174 let scopes: Vec<syn::Ident> = legs
7175 .iter()
7176 .map(|engine| format_ident!("{}_scope", engine.word))
7177 .collect();
7178 let owns: Vec<syn::Ident> = legs
7179 .iter()
7180 .map(|engine| format_ident!("{}_own", engine.word))
7181 .collect();
7182 let floors: Vec<syn::Ident> = legs
7183 .iter()
7184 .map(|engine| format_ident!("{}_floor", engine.word))
7185 .collect();
7186 // ONE LEG'S KNOBS, beside its floor and named after the WORD its declaration wrote — the tier
7187 // door's own seat one grain down, and positional for the same measured reason.
7188 let knob_seats: Vec<syn::Ident> = legs
7189 .iter()
7190 .map(|engine| format_ident!("{}_options", engine.word))
7191 .collect();
7192 let knobs: Vec<proc_macro2::TokenStream> = engines
7193 .iter()
7194 .map(|engine| quote!(::core::option::Option<&<#engine as #face>::SearchOptions>))
7195 .collect();
7196 let scores: Vec<proc_macro2::TokenStream> = engines
7197 .iter()
7198 .map(|engine| quote!(<#engine as #face>::Score))
7199 .collect();
7200 let refusals: Vec<proc_macro2::TokenStream> = engines
7201 .iter()
7202 .map(|engine| quote!(<#engine as #face>::Error))
7203 .collect();
7204
7205 // THE SELECTOR, read ONCE at the head of each body — `None` where the slot typed no leg, in
7206 // which case every gate below collapses to the edge fact alone.
7207 let chosen = selector
7208 .as_ref()
7209 .map_or_else(proc_macro2::TokenStream::new, |_| {
7210 quote! {
7211 let __ingraph_chosen = ::core::option::Option::and_then(options, #options::engine);
7212 }
7213 });
7214
7215 // ONE LEG's gate and edge facts. A PARTICIPANT reads its `Route` seat; a typed non-participant
7216 // has no seat to read and is reachable only by being named.
7217 let edge = |at: usize| {
7218 let engine = legs[at];
7219 let variant = &variants[at];
7220 let named = selector.as_ref().map(|selector| {
7221 quote!(
7222 ::core::matches!(__ingraph_chosen, ::core::option::Option::Some(#selector::#variant(_)))
7223 )
7224 });
7225 if engine.rrf {
7226 let leg = tier.slot_leg_options(elected, engine);
7227 let word = &engine.word;
7228 // The FUSED road's gate is the parent's edge fact; the SELECTOR road's is the name. A
7229 // request that named ANOTHER leg does not walk this one even though it participates.
7230 let gate = named.map_or_else(
7231 || quote!(let __ingraph_walk = __ingraph_enabled;),
7232 |named| {
7233 quote! {
7234 let __ingraph_walk = if ::core::option::Option::is_some(&__ingraph_chosen) {
7235 #named
7236 } else {
7237 __ingraph_enabled
7238 };
7239 }
7240 },
7241 );
7242 let wall = self.wall(::core::option::Option::Some(&elected.field));
7243 quote! {
7244 let __ingraph_route = ::core::option::Option::and_then(options, #options::#word);
7245 let __ingraph_enabled = ::core::option::Option::map_or(
7246 __ingraph_route,
7247 #route::<#leg>::DEFAULT_ENABLED,
7248 #route::enabled,
7249 );
7250 let __ingraph_weight = ::core::option::Option::map_or(
7251 __ingraph_route,
7252 #route::<#leg>::DEFAULT_WEIGHT,
7253 #route::weight,
7254 );
7255 let __ingraph_ceiling = #depth(
7256 ::core::option::Option::and_then(__ingraph_route, #route::depth),
7257 // THE DECLARED CEILING, which is the only ceiling there is: a wall is written in the
7258 // DECLARATION and never on a request, so nothing is read out of the package here. The
7259 // word ARRIVED with the number tiers and this is the argument it fills — `None` still,
7260 // and byte-for-byte the old tokens, where no tier of this declaration wrote one.
7261 #wall,
7262 limit,
7263 );
7264 #gate
7265 }
7266 } else {
7267 let named =
7268 named.expect("a leg outside the leaderboard is in the walk only if it is typed");
7269 quote! {
7270 // NO `Route` SEAT: this leg is outside the leaderboard, so its parent holds no edge facts
7271 // about it — no weight, no depth. It is walked only when a request NAMES it, and then it
7272 // is the whole answer: the weight is the neutral one and the depth is the caller's own
7273 // budget, there being no fold to ask it deeper for.
7274 let __ingraph_weight = #route::<()>::DEFAULT_WEIGHT;
7275 let __ingraph_ceiling = limit;
7276 let __ingraph_walk = #named;
7277 }
7278 }
7279 };
7280
7281 let asks = (0..legs.len()).map(|at| {
7282 let edge = edge(at);
7283 let engine = &engines[at];
7284 let variant = &variants[at];
7285 let handle = &handles[at];
7286 let scope = &scopes[at];
7287 let floor = &floors[at];
7288 let knob = &knob_seats[at];
7289 let point = quote!(#embedding<<#engine as #face>::Element, #width, #space>);
7290 quote! {
7291 {
7292 #edge
7293 // THE ONE QUESTION, read per leg because each leg converts it into its OWN engine's
7294 // element type. `participates` is the tier door's own predicate, reached rather than
7295 // restated: no resolvable question is a structural absence at both grains.
7296 let __ingraph_own = #asked::coordinates(question);
7297 if #participates(__ingraph_walk, __ingraph_own) {
7298 let __ingraph_coordinates: #point = ::core::convert::Into::into(
7299 ::core::clone::Clone::clone(
7300 __ingraph_own.expect("a walked leg resolved the slot's question"),
7301 ),
7302 );
7303 let __ingraph_query = #vector_query::new(
7304 __ingraph_coordinates,
7305 ::core::clone::Clone::clone(&#floor),
7306 );
7307 let __ingraph_ranked = Self::#keys::<#engine>(
7308 #handle,
7309 ::core::clone::Clone::clone(&#scope),
7310 &__ingraph_query,
7311 __ingraph_ceiling,
7312 #knob,
7313 )
7314 .await
7315 .map_err(#refusal::#variant)?;
7316 __ingraph_members.push((
7317 __ingraph_weight,
7318 ::core::iter::Iterator::collect::<::std::vec::Vec<_>>(
7319 ::core::iter::Iterator::map(
7320 ::std::vec::Vec::into_iter(__ingraph_ranked),
7321 |__ingraph_hit| {
7322 let (__ingraph_score, __ingraph_rank, __ingraph_key) =
7323 __ingraph_hit.into_components();
7324 #rooted::new(
7325 __ingraph_key,
7326 __ingraph_rank,
7327 #evidence::#variant(__ingraph_score),
7328 )
7329 },
7330 ),
7331 ),
7332 ));
7333 }
7334 }
7335 }
7336 });
7337
7338 let examples = (0..legs.len()).map(|at| {
7339 let edge = edge(at);
7340 let engine = &engines[at];
7341 let variant = &variants[at];
7342 let handle = &handles[at];
7343 let scope = &scopes[at];
7344 let own = &owns[at];
7345 let floor = &floors[at];
7346 let knob = &knob_seats[at];
7347 quote! {
7348 {
7349 #edge
7350 if __ingraph_walk {
7351 // AN UNINDEXED LEG IS ABSENT, not fatal — one store holding this entity and another
7352 // not is exactly what a fan is for. Every other refusal propagates, the engine's own
7353 // wearing the name of the STORE that spoke it.
7354 match Self::#similar::<#engine>(
7355 #handle,
7356 ::core::clone::Clone::clone(&#own),
7357 ::core::clone::Clone::clone(&#scope),
7358 key,
7359 ::core::clone::Clone::clone(&#floor),
7360 __ingraph_ceiling,
7361 #knob,
7362 )
7363 .await
7364 {
7365 ::core::result::Result::Ok(__ingraph_ranked) => {
7366 __ingraph_members.push((
7367 __ingraph_weight,
7368 ::core::iter::Iterator::collect::<::std::vec::Vec<_>>(
7369 ::core::iter::Iterator::map(
7370 ::std::vec::Vec::into_iter(__ingraph_ranked),
7371 |__ingraph_hit| {
7372 let (__ingraph_score, __ingraph_rank, __ingraph_key) =
7373 __ingraph_hit.into_components();
7374 #rooted::new(
7375 __ingraph_key,
7376 __ingraph_rank,
7377 #evidence::#variant(__ingraph_score),
7378 )
7379 },
7380 ),
7381 ),
7382 ));
7383 }
7384 ::core::result::Result::Err(#refused::Unindexed) => {}
7385 ::core::result::Result::Err(#refused::Engine(__ingraph_refusal)) => {
7386 return ::core::result::Result::Err(
7387 #refused::Engine(#refusal::#variant(__ingraph_refusal)),
7388 );
7389 }
7390 ::core::result::Result::Err(#refused::Several { held }) => {
7391 return ::core::result::Result::Err(#refused::Several { held });
7392 }
7393 ::core::result::Result::Err(#refused::Width { declared, stored }) => {
7394 return ::core::result::Result::Err(#refused::Width { declared, stored });
7395 }
7396 }
7397 }
7398 }
7399 }
7400 });
7401
7402 let resolved = quote! {
7403 let __ingraph_fusion = ::core::option::Option::map_or(
7404 ::core::option::Option::and_then(options, #options::fusion),
7405 <#fusion as ::core::default::Default>::default(),
7406 #flavour::fusion,
7407 );
7408 };
7409 let answer = quote!(::std::vec::Vec<#fused<#key, #evidence<#(#scores,)*>>>);
7410 let seams = engines.iter().map(|engine| {
7411 quote! {
7412 #engine: #lease,
7413 #key: #row + #admits + ::core::clone::Clone,
7414 <#engine as #face>::Score: ::core::clone::Clone,
7415 <#engine as #lease>::ReadContext<'__ingraph_scope>: ::core::clone::Clone,
7416 }
7417 });
7418 let similar_seams = seams.clone();
7419 let ty = &elected.ty;
7420 let coordinate_bounds = engines.iter().map(|engine| {
7421 quote! {
7422 <#ty as #marker>::Item: ::core::clone::Clone
7423 + ::core::convert::Into<#embedding<<#engine as #face>::Element, #width, #space>>
7424 }
7425 });
7426 let fuse_params = (0..legs.len()).map(|at| {
7427 let engine = &engines[at];
7428 let handle = &handles[at];
7429 let scope = &scopes[at];
7430 let floor = &floors[at];
7431 let knob = &knob_seats[at];
7432 let seat = &knobs[at];
7433 quote! {
7434 #handle: &mut #brand<#engine, Self>,
7435 #scope: #connected<'__ingraph_scope, <#engine as #face>::Connection,
7436 <#engine as #lease>::ReadContext<'__ingraph_scope>>,
7437 #floor: <#engine as #face>::Score,
7438 #knob: #seat,
7439 }
7440 });
7441 let similar_params = (0..legs.len()).map(|at| {
7442 let engine = &engines[at];
7443 let handle = &handles[at];
7444 let scope = &scopes[at];
7445 let own = &owns[at];
7446 let floor = &floors[at];
7447 let knob = &knob_seats[at];
7448 let seat = &knobs[at];
7449 quote! {
7450 #handle: &mut #brand<#engine, Self>,
7451 #own: #connected<'__ingraph_scope, <#engine as #face>::Connection,
7452 <#engine as #lease>::ReadContext<'__ingraph_scope>>,
7453 #scope: #connected<'__ingraph_scope, <#engine as #face>::Connection,
7454 <#engine as #lease>::ReadContext<'__ingraph_scope>>,
7455 #floor: <#engine as #face>::Score,
7456 #knob: #seat,
7457 }
7458 });
7459 let fuse_body = self.observed(
7460 observed,
7461 &fuse_door,
7462 quote! {
7463 #chosen
7464 #resolved
7465 let mut __ingraph_members = ::std::vec::Vec::new();
7466 #(#asks)*
7467 ::core::result::Result::Ok(
7468 #weighted::<_, _, #join<#key>>(__ingraph_members, __ingraph_fusion)
7469 )
7470 },
7471 );
7472 let similar_body = self.observed(
7473 observed,
7474 &similar_door,
7475 quote! {
7476 #chosen
7477 #resolved
7478 let mut __ingraph_members = ::std::vec::Vec::new();
7479 #(#examples)*
7480 ::core::result::Result::Ok(
7481 #weighted::<_, _, #join<#key>>(__ingraph_members, __ingraph_fusion)
7482 )
7483 },
7484 );
7485 let fuse_doc = leading(&format!(
7486 "FUSED, FANNED SLOT — every store `{field}` is written to asked at once with the SAME \
7487 question, their rankings joined by reciprocal rank fusion.",
7488 ));
7489 let fractal = leading(
7490 "The tier's own door one level down: a fanned field's LEGS are its routes, so this is the \
7491 same fold over the stores one field lives in rather than over the fields a declaration \
7492 elected. It stands beside the per-election pair and never instead of it.",
7493 );
7494 let one_question = leading(
7495 "ONE QUESTION for every leg, which is the fan's deliberate asymmetry: the legs are one \
7496 field's coordinates in several stores, so there is nothing per-leg to ask. What IS per-leg \
7497 is the parent's own `Route.depth`, which is what this door hands that leg's `knn`. A leg the \
7498 declaration left out of the leaderboard has no `Route` seat to carry one and takes the \
7499 caller's budget whole.",
7500 );
7501 let per_leg_knobs = leading(
7502 "The ENGINE's own per-query knobs are per-leg too, and `<word>_options` is the seat: two \
7503 stores holding one field speak two vocabularies, so there is no package both could take. \
7504 Each is handed to that leg's tier-A door verbatim and BORROWED — one question, several \
7505 stores, no copy — and a leg given none runs under its engine's defaults. Positional for the \
7506 floor's own reason: the seat's knobs are the concrete type the declaration NAMED, and this \
7507 door's are that projection off a generic engine.",
7508 );
7509 let selector_doc = leading(
7510 "The `engine` seat picks the ROAD. Absent, the fused one: every leg the declaration left in \
7511 the leaderboard is walked. Present, a single-leg direct read of the leg it names — answering \
7512 the SAME shape, with one variant of the evidence filled, so a client that switches roads \
7513 parses the same answer.",
7514 );
7515 let similar_doc = leading(&format!(
7516 "FUSED, FANNED SLOT, BY EXAMPLE — what else is near THIS entity's `{field}`, according to \
7517 every store it is written to at once.",
7518 ));
7519 let absence = leading(
7520 "A store holding nothing for this entity drops OUT of the fold rather than refusing the whole \
7521 answer. Every other refusal propagates, the engine's own wearing the name of the store that \
7522 spoke it.",
7523 );
7524 quote! {
7525 #[doc = #fuse_doc]
7526 #[doc = ""]
7527 #[doc = #fractal]
7528 #[doc = ""]
7529 #[doc = #one_question]
7530 #[doc = ""]
7531 #[doc = #per_leg_knobs]
7532 #[doc = ""]
7533 #[doc = #selector_doc]
7534 #[allow(clippy::too_many_arguments)]
7535 #vis async fn #fuse_door<'__ingraph_scope, #(#engines),*>(
7536 #(#fuse_params)*
7537 options: ::core::option::Option<&#options>,
7538 question: &#asked,
7539 limit: ::core::num::NonZeroUsize,
7540 ) -> ::core::result::Result<#answer, #refusal<#(#refusals,)*>>
7541 where
7542 #(#seams)*
7543 #(#coordinate_bounds,)*
7544 {
7545 #fuse_body
7546 }
7547
7548 #[doc = #similar_doc]
7549 #[doc = ""]
7550 #[doc = #fractal]
7551 #[doc = ""]
7552 #[doc = #absence]
7553 #[doc = ""]
7554 #[doc = #per_leg_knobs]
7555 #[doc = ""]
7556 #[doc = #selector_doc]
7557 #[allow(clippy::too_many_arguments)]
7558 #vis async fn #similar_door<'__ingraph_scope, #(#engines),*>(
7559 #(#similar_params)*
7560 key: &#key,
7561 options: ::core::option::Option<&#options>,
7562 limit: ::core::num::NonZeroUsize,
7563 ) -> ::core::result::Result<#answer, #refused<#refusal<#(#refusals,)*>>>
7564 where
7565 #(#similar_seams)*
7566 {
7567 #similar_body
7568 }
7569 }
7570 }
7571
7572 /// THE FUSED-READ IMPL — the `keys` verb a fused read asks this member through.
7573 ///
7574 /// # The MODALITY MARKER that used to ride here is gone
7575 ///
7576 /// Until 2026-08-19 this emission also wrote `impl VectorFusable for …` (or the full-text twin),
7577 /// free at the index grain because a declaration's KIND is its modality. What DEMANDED it — a
7578 /// graph root's `fuse(vector)` / `fuse(fulltext)` trim — had already retired with the root's own
7579 /// typed doors, and no round after it wrote the bound: the recipe layer LISTS its members, so
7580 /// there is no typed door for a trim to select. A capability nobody demands is a trait in a
7581 /// prelude, so both markers and this impl went together. The verb below is unaffected — it was
7582 /// always ONE trait for both modalities, which is what lets a mixed door reach every member
7583 /// through one projection.
7584 ///
7585 /// # ONE ENGINE PER MEMBER at this seat, and the member's own heterogeneity is still reachable
7586 ///
7587 /// The impl is generic over one `E`: a fused read's routes are its MEMBERS, so the currency law at
7588 /// that grain is one engine parameter per member exactly as the index grain's is one per route. A
7589 /// member whose own routes are held by DIFFERENT engines is still asked through its own
7590 /// `vector_fuse`, which takes one engine each; widening this seat would mean a consumer's
7591 /// signature naming a member's route count, which is the wall the projection exists to keep.
7592 ///
7593 /// # `Ctx` is one `(slot, scope, floor, options)` seat per ASKING POSITION the member's top door has
7594 ///
7595 /// Named inside this impl and nowhere else — a root spells `<M as AsyncFusedRead<E>>::Ctx<'_>` and
7596 /// learns nothing about a slot. The last two ride here for ONE reason, and it is the reason the
7597 /// floor already rode here: both are written in the ENGINE's own vocabulary — `Score` and
7598 /// `SearchOptions` — and a root holds this member's package by PROJECTION, so there is no row it
7599 /// could read either out of. What a caller holds concretely it hands in through the seat; what the
7600 /// root can name it hands in through `options`. The list is the emission's own:
7601 ///
7602 /// | this member | its top door | `Ctx` |
7603 /// |---|---|---|
7604 /// | ≥ 2 fused routes | `vector_fuse` | one seat per route |
7605 /// | 1 fused route | that route's `retrieve_keys_by_<field>` | one seat |
7606 /// | a full-text subject | `retrieve_keys` | one seat |
7607 /// | a vector tier whose only election is a SET | — | no impl at all |
7608 ///
7609 /// The last row is the presence law reaching this seam: a set election is no route of its own tier
7610 /// (see [`crate::fuse::Tier::doors`]), so a declaration electing nothing else has nothing a
7611 /// parent's fold could read an ordinal from, and it does not implement the capability. A root
7612 /// naming it is `E0277` rather than a member that silently contributes nothing.
7613 ///
7614 /// # What `keys` hands up, per route count
7615 ///
7616 /// | routes | `Evidence` | the ordinal a parent reads |
7617 /// |---|---|---|
7618 /// | one | `<E as …>::Score` | the ENGINE's raw ordinal, untouched |
7619 /// | several | `Vec<<Index>FusedEvidence<…>>` | this member's own FUSED position, 1-based |
7620 ///
7621 /// The second row is the fractal's own sentence — *each child fusing its own routes and entering
7622 /// its parent as one* — and it is the one place in this pipeline where an ordinal is MINTED. It is
7623 /// lawful exactly where a set election's is not: the number comes from an ORDER a fold authored,
7624 /// where a set election's `m` streams have no order between them to author one from. A member's
7625 /// own weights and fusion flavour are spent producing it, which is what makes them reachable from
7626 /// a root at all.
7627 ///
7628 /// # A question nobody asked is a STRUCTURAL ABSENCE
7629 ///
7630 /// A member whose seat in the root's question package is empty answers the empty list rather than
7631 /// its whole corpus — `participates`' law, read at the member grain, so a root asking two of its
7632 /// three members does not silently ask the third.
7633 fn capability(&self) -> proc_macro2::TokenStream {
7634 let IndexModel { index, krate, .. } = self;
7635 let tier = self.tier();
7636 let (Some(options), Some(question)) = (tier.options_name(), tier.question_name()) else {
7637 return proc_macro2::TokenStream::new();
7638 };
7639 // THREE ROWS, and the third is the engine cutover: `lease` is the trait that declares the read
7640 // scope and `face` the one that declares the vocabulary. The ROW is neither's — `Field` is
7641 // engine-blind, one impl per TYPE, so BOTH families now spell the same one word where each used
7642 // to spell its own engine-keyed trait. A FOURTH row named the modality marker until 2026-08-19.
7643 let (face, lease, row) = match self.kind {
7644 NodeKind::Fulltext => (
7645 framework(krate, &["store"], "FulltextEngine"),
7646 framework(krate, &["store"], "AsyncFulltextRead"),
7647 framework(krate, &["store"], "Field"),
7648 ),
7649 NodeKind::Vector => (
7650 framework(krate, &["store"], "VectorEngine"),
7651 framework(krate, &["store"], "AsyncVectorRead"),
7652 framework(krate, &["store"], "Field"),
7653 ),
7654 NodeKind::Operator
7655 | NodeKind::Entity
7656 | NodeKind::Record
7657 | NodeKind::Aggregate
7658 | NodeKind::Blob => {
7659 return proc_macro2::TokenStream::new();
7660 }
7661 };
7662 let seam = framework(krate, &["retrieve"], "AsyncFusedRead");
7663 let depth = framework(krate, &["retrieve"], "route_depth");
7664 let engine = format_ident!("__INGRAPH_ENGINE__");
7665 let key = self.key();
7666 let brand = framework(krate, &["store"], "SlotHandle");
7667 let connected = framework(krate, &["store"], "Connected");
7668 let rooted = framework(krate, &["retrieve"], "Rooted");
7669 let admits = self.dedup.admits();
7670 let participates = framework(krate, &["retrieve"], "participates");
7671 let routes: Vec<&Elected> = tier.fused_routes().collect();
7672 if self.kind == NodeKind::Vector && routes.is_empty() {
7673 return proc_macro2::TokenStream::new();
7674 }
7675 let seats = routes.len().max(1);
7676 // ONE ASKING POSITION: the slot, the read scope, the FLOOR and the KNOBS. The last two ride here
7677 // for one reason — both are written in the ENGINE's own vocabulary, and a root holds this
7678 // member's package by PROJECTION and can read no row out of it. So neither can arrive through
7679 // `options`, and both arrive through the seat a root hands down whole without naming its parts.
7680 let seat = quote! {
7681 (
7682 &'__ingraph_ctx mut #brand<#engine, Self>,
7683 #connected<'__ingraph_ctx, <#engine as #face>::Connection,
7684 <#engine as #lease>::ReadContext<'__ingraph_ctx>>,
7685 <#engine as #face>::Score,
7686 ::core::option::Option<&'__ingraph_ctx <#engine as #face>::SearchOptions>,
7687 )
7688 };
7689 // ONE SEAT IS THE TUPLE ITSELF. A one-element tuple is a legal type and an ugly call — `((a, b,
7690 // c, d),)` at every single-route member, which is most of them — so the wrapper appears exactly
7691 // where there is something to wrap.
7692 let seats_list: Vec<proc_macro2::TokenStream> = (0..seats).map(|_| seat.clone()).collect();
7693 let ctx = if seats == 1 {
7694 seat.clone()
7695 } else {
7696 quote!((#(#seats_list,)*))
7697 };
7698 let slots: Vec<syn::Ident> = (0..seats)
7699 .map(|at| format_ident!("__ingraph_slot_{at}"))
7700 .collect();
7701 let scopes: Vec<syn::Ident> = (0..seats)
7702 .map(|at| format_ident!("__ingraph_scope_{at}"))
7703 .collect();
7704 let floors: Vec<syn::Ident> = (0..seats)
7705 .map(|at| format_ident!("__ingraph_floor_{at}"))
7706 .collect();
7707 let knob_seats: Vec<syn::Ident> = (0..seats)
7708 .map(|at| format_ident!("__ingraph_options_{at}"))
7709 .collect();
7710 let destructure = if seats == 1 {
7711 let slot = &slots[0];
7712 let scope = &scopes[0];
7713 let floor = &floors[0];
7714 let knob = &knob_seats[0];
7715 quote!(let (#slot, #scope, #floor, #knob) = ctx;)
7716 } else {
7717 quote!(let (#((#slots, #scopes, #floors, #knob_seats),)*) = ctx;)
7718 };
7719 // The RANKED-TO-ROOTED mapping, written once: the engine's own ordinal rides out untouched and
7720 // the score becomes this member's evidence.
7721 let carried = quote! {
7722 ::core::iter::Iterator::collect(::core::iter::Iterator::map(
7723 ::std::vec::Vec::into_iter(__ingraph_ranked),
7724 |__ingraph_hit| {
7725 let (__ingraph_score, __ingraph_rank, __ingraph_key) = __ingraph_hit.into_components();
7726 #rooted::new(__ingraph_key, __ingraph_rank, __ingraph_score)
7727 },
7728 ))
7729 };
7730 let first_slot = &slots[0];
7731 let first_scope = &scopes[0];
7732 let first_floor = &floors[0];
7733 let first_knobs = &knob_seats[0];
7734
7735 let (evidence, refusal, body) = if routes.len() > 1 {
7736 let fused_evidence = tier.evidence_name();
7737 let fused_error = tier.fused_error_name();
7738 let door = format_ident!("vector_fuse");
7739 let scores = (0..routes.len()).map(|_| quote!(<#engine as #face>::Score));
7740 let errors = (0..routes.len()).map(|_| quote!(<#engine as #face>::Error));
7741 let engines = (0..routes.len()).map(|_| quote!(#engine));
7742 let handed = (0..routes.len()).map(|at| {
7743 let slot = &slots[at];
7744 let scope = &scopes[at];
7745 let floor = &floors[at];
7746 let knob = &knob_seats[at];
7747 quote!(#slot, #scope, #floor, #knob,)
7748 });
7749 // THE NESTED EVIDENCE IS THIS MEMBER'S OWN SIGHTING LIST, WHOLE (Q3b + #296-L2). A parent's
7750 // variant holds what the child's fold answered, and what a fold answers is now a list of
7751 // sightings — the member's evidence beside the term each of them contributed. Unwrapping to
7752 // the bare evidence here would strip the number at exactly the seam the wire union publishes
7753 // it at.
7754 let sighting = framework(krate, &["retrieve"], "Sighting");
7755 (
7756 quote!(::std::vec::Vec<#sighting<#fused_evidence<#(#scores,)*>>>),
7757 quote!(#fused_error<#(#errors,)*>),
7758 quote! {
7759 #destructure
7760 let __ingraph_fused = Self::#door::<#(#engines),*>(
7761 #(#handed)*
7762 options,
7763 question,
7764 limit,
7765 )
7766 .await?;
7767 // THE MINTED ORDINAL, and the one place this pipeline mints one. It is a POSITION in an
7768 // order this member's own fold AUTHORED — which is exactly the condition a set election
7769 // lacks, and why that case is excluded from the walk rather than given a number.
7770 ::core::result::Result::Ok(
7771 ::core::iter::Iterator::collect(::core::iter::Iterator::map(
7772 ::core::iter::Iterator::enumerate(::std::vec::Vec::into_iter(__ingraph_fused)),
7773 |(__ingraph_at, __ingraph_row)| {
7774 let (_, __ingraph_root, __ingraph_seen) = __ingraph_row.into_components();
7775 #rooted::new(__ingraph_root, (__ingraph_at as u64) + 1, __ingraph_seen)
7776 },
7777 )),
7778 )
7779 },
7780 )
7781 } else if self.kind == NodeKind::Fulltext {
7782 let door = format_ident!("retrieve_keys");
7783 let query = framework(krate, &["retrieve"], "FulltextQuery");
7784 // THE UNSUFFIXED SUBJECT has no election to name, so the wall it is capped by is the
7785 // CONTAINER's alone — which is the whole chain at this grain rather than a step of it.
7786 let wall = self.wall(::core::option::Option::None);
7787 (
7788 quote!(<#engine as #face>::Score),
7789 quote!(<#engine as #face>::Error),
7790 quote! {
7791 #destructure
7792 // NO EDGE AT THIS GRAIN, and that is the fractal rather than a gap: the parent already
7793 // spent its `Route`'s depth against its own budget before it called, so what arrives as
7794 // `limit` IS this edge's number. What is left to resolve is this declaration's own.
7795 let __ingraph_ceiling = #depth(
7796 ::core::option::Option::None,
7797 // THE DECLARED CEILING, which is the only ceiling there is: a wall is written in the
7798 // DECLARATION and never on a request, so nothing is read out of the package here. The
7799 // word ARRIVED with the number tiers and this is the argument it fills — `None` still,
7800 // and byte-for-byte the old tokens, where no tier of this declaration wrote one.
7801 #wall,
7802 limit,
7803 );
7804 let __ingraph_question = match #question::question(question) {
7805 ::core::option::Option::Some(__ingraph_text) => __ingraph_text,
7806 ::core::option::Option::None => {
7807 return ::core::result::Result::Ok(::std::vec::Vec::new());
7808 }
7809 };
7810 let __ingraph_query = #query::new(
7811 ::std::string::String::clone(__ingraph_question),
7812 #first_floor,
7813 );
7814 let __ingraph_ranked = Self::#door::<#engine>(
7815 #first_slot,
7816 #first_scope,
7817 &__ingraph_query,
7818 __ingraph_ceiling,
7819 #first_knobs,
7820 )
7821 .await?;
7822 ::core::result::Result::Ok(#carried)
7823 },
7824 )
7825 } else {
7826 let elected = routes[0];
7827 let field = &elected.field;
7828 let (width, space) = self.geometry(elected);
7829 let embedding = framework(krate, &["storage"], "Embedding");
7830 let vector_query = framework(krate, &["retrieve"], "VectorQuery");
7831 let route = framework(krate, &["retrieve"], "Route");
7832 let door = Door::Keys.name(field);
7833 let package = tier.route_options(elected);
7834 let asked = tier.route_question(elected);
7835 // A FANNED route takes the caller's own budget and does NOT read its edge's depth, where a
7836 // flat leaf does. That asymmetry is INHERITED rather than chosen here: the read used to be one
7837 // `route_depth` call whose middle argument was the leaf package's `ceiling` row, and a mini
7838 // tier has no such row, so the whole call was skipped for a fan and the edge went with it. The
7839 // wall law retired that row, which leaves the skip standing on nothing — whether a fanned
7840 // route's own `Route::depth` should now be spent is a LETTER rather than a guess, and until it
7841 // is answered the behaviour here is unmoved.
7842 let flat = !tier
7843 .fanned_slots()
7844 .any(|fanned| fanned.field == elected.field);
7845 // WHERE THE ROUTE'S OWN PACKAGE IS. A tier electing ONE field IS its route — the binding table
7846 // hands the leaf up, and `options` already IS it. A tier electing several hands up its own
7847 // fuse package, so the route is one seat inside it and is reached through the same `Route`
7848 // edge the tier door reads. Both are possible with a single FUSED route: a set election is no
7849 // route of its tier, so a two-election tier may have exactly one.
7850 let nested = self.embeddings.len() > 1;
7851 let read = if nested {
7852 let ceiling = flat.then(|| {
7853 let wall = self.wall(::core::option::Option::Some(field));
7854 quote! {
7855 let __ingraph_ceiling = #depth(
7856 ::core::option::Option::and_then(__ingraph_route, #route::depth),
7857 // THE DECLARED CEILING, which is the only ceiling there is: a wall is written in the
7858 // DECLARATION and never on a request, so nothing is read out of the package here. The
7859 // word ARRIVED with the number tiers and this is the argument it fills — `None` still,
7860 // and byte-for-byte the old tokens, where no tier of this declaration wrote one.
7861 #wall,
7862 limit,
7863 );
7864 }
7865 });
7866 let budget = ceiling
7867 .is_none()
7868 .then(|| quote!(let __ingraph_ceiling = limit;));
7869 quote! {
7870 let __ingraph_route = ::core::option::Option::and_then(options, #options::#field);
7871 let __ingraph_enabled = ::core::option::Option::map_or(
7872 __ingraph_route,
7873 #route::<#package>::DEFAULT_ENABLED,
7874 #route::enabled,
7875 );
7876 #ceiling
7877 #budget
7878 let __ingraph_own = ::core::option::Option::and_then(
7879 #question::#field(question),
7880 #asked::coordinates,
7881 );
7882 if !#participates(__ingraph_enabled, __ingraph_own) {
7883 return ::core::result::Result::Ok(::std::vec::Vec::new());
7884 }
7885 let __ingraph_own = __ingraph_own.expect("a participating route resolved a question");
7886 }
7887 } else {
7888 let ceiling = if flat {
7889 let wall = self.wall(::core::option::Option::Some(field));
7890 quote! {
7891 let __ingraph_ceiling = #depth(
7892 ::core::option::Option::None,
7893 // THE DECLARED CEILING, which is the only ceiling there is: a wall is written in the
7894 // DECLARATION and never on a request, so nothing is read out of the package here. The
7895 // word ARRIVED with the number tiers and this is the argument it fills — `None` still,
7896 // and byte-for-byte the old tokens, where no tier of this declaration wrote one.
7897 #wall,
7898 limit,
7899 );
7900 }
7901 } else {
7902 quote!(let __ingraph_ceiling = limit;)
7903 };
7904 quote! {
7905 #ceiling
7906 let __ingraph_own = match #question::coordinates(question) {
7907 ::core::option::Option::Some(__ingraph_at) => __ingraph_at,
7908 ::core::option::Option::None => {
7909 return ::core::result::Result::Ok(::std::vec::Vec::new());
7910 }
7911 };
7912 }
7913 };
7914 (
7915 quote!(<#engine as #face>::Score),
7916 quote!(<#engine as #face>::Error),
7917 quote! {
7918 #destructure
7919 #read
7920 let __ingraph_coordinates: #embedding<
7921 <#engine as #face>::Element, #width, #space
7922 > = ::core::convert::Into::into(::core::clone::Clone::clone(__ingraph_own));
7923 let __ingraph_query = #vector_query::new(__ingraph_coordinates, #first_floor);
7924 let __ingraph_ranked = Self::#door::<#engine>(
7925 #first_slot,
7926 #first_scope,
7927 &__ingraph_query,
7928 __ingraph_ceiling,
7929 #first_knobs,
7930 )
7931 .await?;
7932 ::core::result::Result::Ok(#carried)
7933 },
7934 )
7935 };
7936
7937 // THE OBLIGATIONS, which are the member's own doors' restated once — a root that names this
7938 // member inherits them at its own call rather than learning them.
7939 let coordinates = routes.iter().map(|elected| {
7940 let (width, space) = self.geometry(elected);
7941 let ty = &elected.ty;
7942 let marker = framework(krate, &["election"], "EmbeddingMarker");
7943 let embedding = framework(krate, &["storage"], "Embedding");
7944 quote! {
7945 <#ty as #marker>::Item: ::core::clone::Clone
7946 + ::core::convert::Into<#embedding<<#engine as #face>::Element, #width, #space>>
7947 }
7948 });
7949 let coordinates: Vec<proc_macro2::TokenStream> = match self.kind {
7950 NodeKind::Vector => coordinates.collect(),
7951 _ => Vec::new(),
7952 };
7953 // THE CLONE IS THE FUSED DOOR'S OWN, and it is asked for only where that door is reached: the
7954 // tier door clones one read scope per route, and a member with one route never does. Stating it
7955 // unconditionally would keep an engine whose scope is a lease out of every root, for a call it
7956 // does not make.
7957 let scoped = (routes.len() > 1).then(|| {
7958 quote! {
7959 for<'__ingraph_scope> <#engine as #lease>::ReadContext<'__ingraph_scope>:
7960 ::core::clone::Clone,
7961 }
7962 });
7963 let doc = leading(&format!(
7964 "[`{index}`] answers this modality's fused query — the capability this declaration's KIND \
7965 states, and the verb a fused read asks it through.",
7966 ));
7967 quote! {
7968 const _: () = {
7969 #[doc = #doc]
7970 #[automatically_derived]
7971 impl<#engine> #seam<#engine> for #index
7972 where
7973 #engine: #lease,
7974 #key: #row + #admits + ::core::clone::Clone,
7975 <#engine as #face>::Score: ::core::clone::Clone,
7976 #scoped
7977 #(#coordinates,)*
7978 {
7979 // The GAT's own outlives clauses, RESTATED — the trait owns them and an impl may not add
7980 // one, so the impl repeats exactly what the trait declared.
7981 // The GAT's own outlives clause, RESTATED — the trait owns it and an impl may not add
7982 // one, so the impl repeats exactly what the trait declared. The two PROJECTIONS a borrowed
7983 // scope needs follow from it by rustc's own projection-outlives rule, which is why the
7984 // trait names one clause rather than three it could not spell over an unbounded engine.
7985 type Ctx<'__ingraph_ctx>
7986 = #ctx
7987 where
7988 #engine: '__ingraph_ctx;
7989 type Error = #refusal;
7990 type Evidence = #evidence;
7991 type Root = #key;
7992
7993 fn keys<'__ingraph_ctx>(
7994 ctx: Self::Ctx<'__ingraph_ctx>,
7995 options: ::core::option::Option<&#options>,
7996 question: &#question,
7997 limit: ::core::num::NonZeroUsize,
7998 ) -> impl ::core::future::Future<
7999 Output = ::core::result::Result<
8000 ::std::vec::Vec<#rooted<Self::Root, Self::Evidence>>,
8001 Self::Error,
8002 >,
8003 >
8004 where
8005 #engine: '__ingraph_ctx,
8006 {
8007 async move { #body }
8008 }
8009 }
8010 };
8011 }
8012 }
8013
8014 /// ONE ELECTION's width and space, as PROJECTIONS off the field's own type.
8015 ///
8016 /// Both used to be tokens this crate read out of the field's spelling. They are now
8017 /// `<<F as EmbeddingMarker>::Item as EmbeddingShape>::WIDTH` and `::Space`, which is the same two
8018 /// facts arriving from the only party that can know them.
8019 ///
8020 /// Three things come free with the move. An ALIAS works, because a bound resolves what a peel
8021 /// could not. The SPACE stops being an [`Option`]: the parameter defaults to `Anon`, so a field
8022 /// that named no space projects `Anon` and the emission no longer decides whether to spell a
8023 /// third argument. And a ZERO WIDTH is `E0080` wherever the const is reached, because the
8024 /// projection reads `Embedding::DIM` rather than `N`.
8025 ///
8026 /// The width is BRACED because it is a const argument built from a path: a bare qualified path is
8027 /// not one, and the braces are what put it in const-expression position. Nothing generic enters
8028 /// it — the field's type is the declaration's own, concrete — so no unstable const machinery is
8029 /// involved.
8030 fn geometry(&self, elected: &Elected) -> (syn::Ident, syn::Ident) {
8031 geometry(elected)
8032 }
8033
8034 /// THE GEOMETRY BINDINGS — one `const` and one `type` per election, projecting the field's width
8035 /// and its space out of the election family ONCE.
8036 ///
8037 /// # Why the projections are bound to a name rather than written where they are spent
8038 ///
8039 /// The width lands in CONST-ARGUMENT position, where a qualified path is not a legal const
8040 /// argument and a braced block is. Two braced blocks of identical text are two ANONYMOUS
8041 /// CONSTANTS, and rustc will not match a `where` clause carrying one against an obligation
8042 /// carrying the other — the ask road, whose bound and whose call both name the elected width, is
8043 /// where that shows up as *the trait bound is not satisfied* on the road's own hop. Measured, then
8044 /// bound: one const, named, and every position refers to the SAME one.
8045 ///
8046 /// The space has no such rule and is bound beside it anyway: the pair reads as one fact, and a
8047 /// signature naming two short idents is a signature a person can read.
8048 ///
8049 /// They live inside the expansion's anonymous `const`, so nothing of this is nameable from the
8050 /// declaring scope.
8051 fn geometry_bindings(&self) -> proc_macro2::TokenStream {
8052 let marker = framework(&self.krate, &["election"], "EmbeddingMarker");
8053 let shape = framework(&self.krate, &["election"], "EmbeddingShape");
8054 let bound = self.embeddings.iter().map(|elected| {
8055 let (width, space) = geometry(elected);
8056 let ty = &elected.ty;
8057 let at = elected.field.span();
8058 // SPANNED AT THE ELECTION, which is what puts a missing impl's `E0277` on the word the author
8059 // wrote rather than on a token of this emitter's.
8060 quote_spanned! {at=>
8061 #[allow(non_upper_case_globals)]
8062 const #width: usize = <<#ty as #marker>::Item as #shape>::WIDTH;
8063 #[allow(dead_code, non_camel_case_types)]
8064 type #space = <<#ty as #marker>::Item as #shape>::Space;
8065 }
8066 });
8067 quote!(#(#bound)*)
8068 }
8069
8070 /// ONE HALF of the retrieve face: two inherent methods PER SUBJECT, and no trait over any of them.
8071 ///
8072 /// # A full-text index has ONE subject and an embedding index has one PER ELECTION
8073 ///
8074 /// The full-text kind emits `retrieve_keys` / `retrieve` — the WHOLE-SUBJECT pair, asking `All` —
8075 /// and one `retrieve_keys_by_<field>` / `retrieve_by_<field>` pair per elected field beside it,
8076 /// each minting a one-column `FulltextSubset`. The unsuffixed pair used to be the whole family
8077 /// because there was nowhere to put a suffixed one's answer; the seam takes the subset now, so
8078 /// there is. It STAYS because `All` and `These([field])` are two questions: `All` is whatever the
8079 /// SLOT holds, and a slot may hold columns the declaration never elected. The vector pair is
8080 /// `retrieve_keys_by_<field>` / `retrieve_by_<field>`, UNIFORMLY — one pair per election,
8081 /// including where a declaration elects exactly one. There is no unsuffixed alias for the
8082 /// single-election case: a name whose spelling depended on the CARDINALITY of the declaration
8083 /// would move the day a second `knn` arrived, breaking every caller of a method nobody edited,
8084 /// which is the same silent-shift argument that makes the marker mandatory.
8085 ///
8086 /// # Why inherent and not a `Retrieve<Q>`
8087 ///
8088 /// Everything that differs between two retrieve-capable nodes is EMITTED — the upstream entity a
8089 /// tier-B answer holds, the filter type its store takes, the dedup mechanism its key admits — so a
8090 /// unifying trait would be generic over all of it and would name nothing shared. What IS shared is
8091 /// the framework's own core, which both methods delegate to. A trait minted OVER these methods, if
8092 /// the fused cross-index query ever needs one, is a pure widening.
8093 ///
8094 /// # What each method is generic over, and why none of it could be a concrete name
8095 ///
8096 /// - **The ENGINE.** A declaration names its engines by WORD, and a word is bound to a type by
8097 /// the deployment rather than here — shipped words under their own feature, everyone else's at
8098 /// the graph root. So the seam is the parameter and the caller passes its handle, which is the
8099 /// record side's own division read onto this axis: the SLOT is where the engine is chosen and the
8100 /// type parameter is where the handle is. It also has to be: a build may have no engine compiled
8101 /// at all.
8102 /// - **The STORE.** Tier B gathers the UPSTREAM's rows, and the upstream's row types belong to
8103 /// another expansion this one cannot see. Naming a dialect would be worse than impossible: a
8104 /// derived index declares no database, so an emission reaching `sqlx` would make this
8105 /// declaration fail to compile in a build with no SQL family at all. The seam is `AsyncGather`,
8106 /// which is ungated, and the framework's `SqlGather` is what a SQL caller passes.
8107 ///
8108 /// # THE TYPED READ IS HERE, because A′ took it off the engine
8109 ///
8110 /// Neither engine face names a record: each answers with its OWN addresses, in its own vocabulary,
8111 /// and the read back into `<Upstream as Transformer>::Key` is this emission's act — which is the
8112 /// whole content of *the emission owns the typing*. Two lines carry it, one pair per family:
8113 ///
8114 /// - `#key: Field` on the `where` clause, which is the KEY's structure impl — one `write`/`read`
8115 /// pair per column, in the key's own order, and ENGINE-BLIND on both arms;
8116 /// - `retrieve::keyed::<E, #key>(hits)?` / `retrieve::vector_keyed::<E, #key>(hits)?`, the
8117 /// framework's shared walk over it.
8118 ///
8119 /// A key column whose type has no row at all is `E0277` naming it — *`f64: Field` is not
8120 /// satisfied* — at the retrieve call. It names ONE thing where the retired per-engine rows named
8121 /// two, and that is the language having one fewer axis rather than a weaker refusal: a row is
8122 /// written once per TYPE and reaches every engine, so *this type does not cross* is now the whole
8123 /// of what can be wrong.
8124 ///
8125 /// # It is emitted for BOTH RETRIEVING KINDS, and what was in the way was a WORD
8126 ///
8127 /// The wall went first, and it was never the last thing standing: `VectorDb::knn` carried
8128 /// `where R: VectorRecord + Transformer`, and requiring an absent impl on an inherent method of a
8129 /// CONCRETE type is `E0277` — *add `#![feature(trivial_bounds)]`* — at a span inside an expansion
8130 /// its author cannot edit. A′'s R-free `VectorEngine` has no such `where` at all. What remained
8131 /// was not a bound but a FACT the declaration had no way to state: WHICH field of it is the
8132 /// embedding. `#[ingraph(knn)]` states it, so the vector arm below reads the marked field and
8133 /// nothing is picked on anybody's behalf.
8134 ///
8135 /// `blob` still answers no retrieve, and that absence is permanent rather than pending: an
8136 /// artifact family is ADDRESSED, not ranked, so there is no hit stream for a tier A to collapse.
8137 ///
8138 /// # The two flavours differ in three lines, and share the rest
8139 ///
8140 /// The engine face, the query type and the engine CALL — a string against coordinates. Everything
8141 /// after the hits exist is the same code reached through the same core, which is what
8142 /// *the pipeline is flavour-blind* means stated as an emission rather than as prose. Tier B is
8143 /// identical on both: it takes keys and gathers rows, and by then a knn and a search have produced
8144 /// the same thing.
8145 ///
8146 /// The vector query carries the declaration's WIDTH — `VectorQuery<E::Element, E::Score, #N>`,
8147 /// with `N` read off THIS election's field type — so asking a 768-wide column with a 384-wide
8148 /// embedding is `E0308` at the call, and two elections of different widths take their own. Its
8149 /// element and score are the ENGINE's, since it is the engine's `knn` that consumes the one and
8150 /// reports the other.
8151 ///
8152 /// It carries the SPACE the same way and from the same place: a field declared
8153 /// `Embedding<f32, 768, Clip>` emits `VectorQuery<…, 768, Clip>`, so a query built in another
8154 /// space is `E0308` at the call for the mismatch a width cannot see, and a field that named no
8155 /// space emits the three-argument form its default already means.
8156 ///
8157 /// The ELECTION SELECTOR rides beside it and is not a parameter: `knn` is asked for THIS method's
8158 /// own `VectorColumn`, minted `const` from the field its `knn` marker elected. So which column
8159 /// answers is a fact of the METHOD rather than an argument a caller could get wrong, and the pair
8160 /// of suffixed names is the whole of the choice a caller makes.
8161 ///
8162 /// # An election LABELLED `list(embedding)` grows a THIRD door
8163 ///
8164 /// `retrieve_keys_by_<field>_with`, beside the pair and never instead of it: `m` query vectors and
8165 /// a `FoldSemantics` in, one score per ENTITY out. It differs from the pair in three ways and each
8166 /// is forced:
8167 ///
8168 /// - it answers in `Folded` rather than `Ranked`, because the FOLD authors the answer's order —
8169 /// there are `m` engine streams and no order between them, so no ordinal is minted ACROSS them
8170 /// and each stream's own rides in that stream's slot;
8171 /// - it names the SCOPE's lifetime, because the scope is CLONED once per query vector and the
8172 /// `Clone` bound has to be written about a lifetime the signature can spell;
8173 /// - it is TIER A only. The pair's tier B is unchanged and still answers the single-vector
8174 /// question with whole entities.
8175 ///
8176 /// The pair itself needs nothing: at one query vector the set road IS the pair's road, the
8177 /// per-owner collapse being the dedup stage the pair already runs. And the door is gated on the
8178 /// LABEL rather than on a bound, so a single election has no `_with` door at all — a true absence
8179 /// rather than a seat nobody can sit in.
8180 ///
8181 /// # The DEDUP word is spent here and nowhere else
8182 ///
8183 /// It picks the membership type the delegation names, which picks the bound the method's `where`
8184 /// clause carries. A key that cannot satisfy it is `E0277` at the CALL — which is where the
8185 /// mismatch actually is, the key being the upstream's rather than this declaration's. The set door
8186 /// spends it TWICE — once for the collapse's membership and once for the fold's accumulator — and
8187 /// the two are the same word's two rows.
8188 ///
8189 /// # `#[allow(dead_code)]`
8190 ///
8191 /// The methods sit in the anonymous `const` with the rest of the expansion, so a declaration that
8192 /// never retrieves would otherwise warn in its own `-D warnings` build about code its author did
8193 /// not write.
8194 ///
8195 /// # THE BY-KEY DOORS: `get_<field>` is the read, and the similar door is sugar over it
8196 ///
8197 /// `get_<field>(slot, own, &key)` answers *what did you store for THIS entity in this column* —
8198 /// the entity's own embedding, CHECKED against the elected field's own type. It is the by-key
8199 /// read raised to door grade, and it is where every judgment about a stored vector is spent:
8200 /// the seam answers a SET, this election declared ONE, so none is `Unindexed`, several is
8201 /// `Several { held }` rather than a pick nobody made, and a width the declaration does not state
8202 /// is `Width { declared, stored }` rather than a value the type is lying about. ONE engine call,
8203 /// so ONE read scope, and NO `Admits` bound: nothing here builds a dedup membership.
8204 ///
8205 /// `retrieve_similar_by_<field>` answers *what else is near THIS entity*, given the entity's key
8206 /// rather than coordinates. Its whole body is the ruled recipe — **fetch own set → query with it
8207 /// → exclude self** — and every step of it is a call to something already here: `get_<field>`
8208 /// above, the same `knn` the raw pair calls, the same address read, the same walk. The one thing
8209 /// it does that no existing line did is start that walk's dedup membership with the example
8210 /// ALREADY SEEN, which is what makes the exclusion leave the example's raw-stream ordinal as a
8211 /// HOLE and makes `limit` count neighbours. **The arity and the width are not restated here**:
8212 /// the example arrives through the door above, so the three judgments have ONE authority and the
8213 /// refusal rides `?` undecorated.
8214 ///
8215 /// Both are emitted per ELECTION, like the pair, and conditional on nothing a declaration writes:
8216 /// the by-key read is a capability of the seam, so any elected column can be asked. There is no
8217 /// tier-B twin — the ruling names two doors and both are `retrieve_keys_*` — and no FOLD either:
8218 /// a fold is what turns `m` per-query numbers into one, and both of these ask with a single
8219 /// vector. The set door beside them is where a fold is spent.
8220 ///
8221 /// # ALL SIX DOORS ARE INSTRUMENTED, and the `entry` field is what tells them apart
8222 ///
8223 /// `observed` decides whether each body wears a span. Every method here crosses to an engine —
8224 /// tier A directly, tier B through tier A, an `ask` road through the hops before either, the get
8225 /// door in one crossing of its own, and the similar door through that one plus a `knn` — so
8226 /// instrumenting some of them would need a rule nobody has written, which is the query face's own
8227 /// answer one family over. The nesting a trace then shows is the composition it IS: a road inside
8228 /// a tier B inside a tier A, a get inside a similar, each door named by its own `entry`.
8229 fn retrieve_half(&self, observed: bool) -> proc_macro2::TokenStream {
8230 let IndexModel {
8231 index, vis, krate, ..
8232 } = self;
8233 let upstream = &self.source.node;
8234 let key = self.key();
8235
8236 let engine = format_ident!("__INGRAPH_ENGINE__");
8237 let store = format_ident!("__INGRAPH_STORE__");
8238
8239 // THE THREE LINES THE FLAVOURS DIFFER IN, decided once: which seam the methods project through,
8240 // what a query IS, and how the engine is asked. `blob` decides nothing and answers nothing —
8241 // an artifact family is addressed rather than ranked, which is why its arm is an early return
8242 // and not a third row here.
8243 //
8244 // The BRAND is not among them: `SlotHandle` is a struct rather than a trait and is engine-kind
8245 // agnostic, so the door each flavour goes through is branded by the same path.
8246 let (face, lease, row, keyed) = match self.kind {
8247 NodeKind::Fulltext => (
8248 framework(krate, &["store"], "FulltextEngine"),
8249 framework(krate, &["store"], "AsyncFulltextRead"),
8250 framework(krate, &["store"], "Field"),
8251 framework(krate, &["retrieve"], "keyed"),
8252 ),
8253 NodeKind::Vector => (
8254 framework(krate, &["store"], "VectorEngine"),
8255 framework(krate, &["store"], "AsyncVectorRead"),
8256 framework(krate, &["store"], "Field"),
8257 framework(krate, &["retrieve"], "vector_keyed"),
8258 ),
8259 _ => return proc_macro2::TokenStream::new(),
8260 };
8261 // A FOURTH LINE the flavours differ in, and it is the engine cutover rather than a new idea:
8262 // the LEASE is declared by the read face now and the VOCABULARY by the base, so a projection
8263 // names whichever of the two owns the member.
8264 //
8265 // The ROW is the one line that stopped differing. Both families' engine-keyed row traits are
8266 // deleted, so `#key: Field` is what both arms emit — one impl per TYPE, reaching every engine
8267 // there is.
8268
8269 let brand = framework(krate, &["store"], "SlotHandle");
8270 let connected = framework(krate, &["store"], "Connected");
8271 let gather = framework(krate, &["retrieve"], "AsyncGather");
8272 let ranked = framework(krate, &["retrieve"], "Ranked");
8273 let refusal = framework(krate, &["retrieve"], "RetrieveError");
8274 let membership = framework(krate, &["retrieve"], self.dedup.membership());
8275 let ranked_keys = framework(krate, &["retrieve"], "ranked_keys");
8276 let filled = framework(krate, &["retrieve"], "filled");
8277 let admits = self.dedup.admits();
8278 // THE KNOB SEAT, spelled once for every searching door of this half — the engine's own
8279 // per-query vocabulary, BORROWED, so a fan hands one request value to every leg with no copy.
8280 // It is the LAST positional because the seam's own verbs put it last: what precedes it are the
8281 // universal facts (subject, query, k) and what it holds is the backend's business alone.
8282 let knobs = quote!(::core::option::Option<&<#engine as #face>::SearchOptions>);
8283 let knobs_doc = leading(
8284 "`options` is the request's OWN per-query knobs, handed to the engine verb verbatim — this \
8285 door reads none of it, defaults none of it and substitutes nothing for it. `None` runs under \
8286 the engine's own defaults, which is what every caller got before the seat existed.",
8287 );
8288 let knobs_borrow = leading(
8289 "It is BORROWED rather than owned, which is what lets one request value reach every route of \
8290 a fold with no copy: a fused door holds one package and hands the same reference down each \
8291 leg. No door of this family states a `Clone` obligation about it.",
8292 );
8293 let forwarded_doc = leading(
8294 "It FORWARDS them to its tier A unchanged, which is what makes the seat reach a hydrated \
8295 answer at all: this door is one hop above the crossing rather than a second caller with \
8296 defaults of its own, and a wire resolver rides THIS door for the whole entities it \
8297 publishes. `None` is still the engine's own defaults — the difference is that a request \
8298 naming knobs now has somewhere to put them.",
8299 );
8300 let own_read_note = leading(
8301 "The knobs reach the SEARCH and not the by-key read: a door making both crossings spends \
8302 `options` on the one the seam takes them for, and the address read has no such seat to \
8303 spend them into.",
8304 );
8305 let streams_knobs = leading(
8306 "ONE package for all `m` streams, and the borrow is what makes that free: the `m` calls are \
8307 one question asked in `m` places, so there is one set of knobs to run them under and no \
8308 copy of it is taken. A per-stream package would be a knob per DATA-BORN vector, which is \
8309 not a thing a request can name.",
8310 );
8311
8312 let pairs = self.subjects().into_iter().map(|subject| {
8313 let Subject {
8314 keys,
8315 whole,
8316 about,
8317 grain,
8318 } = &subject;
8319 let election = match grain {
8320 Grain::Election(elected) => Some(*elected),
8321 Grain::Whole | Grain::Column(_) => None,
8322 };
8323 let (query, ask) = match grain {
8324 // The WHOLE full-text subject: the query is a string against whatever grammar the engine
8325 // has, and the subset is the word that asks over everything the slot holds.
8326 Grain::Whole => {
8327 let query = framework(krate, &["retrieve"], "FulltextQuery");
8328 let subset = framework(krate, &["store"], "FulltextSubset");
8329 (
8330 quote!(#query<<#engine as #face>::Score>),
8331 quote!(search(
8332 slot,
8333 scope,
8334 #subset::All,
8335 query.text(),
8336 limit,
8337 options,
8338 )),
8339 )
8340 }
8341 // ONE SEARCHABLE FIELD: the same query type, narrowed by a subset this method MINTS. The
8342 // list is a `const` item rather than a `&[…]` temporary so the slice is `'static` and the
8343 // future holds no array across its await.
8344 Grain::Column(field) => {
8345 let name = field.to_string();
8346 let query = framework(krate, &["retrieve"], "FulltextQuery");
8347 let subset = framework(krate, &["store"], "FulltextSubset");
8348 let column = framework(krate, &["store"], "FulltextColumn");
8349 (
8350 quote!(#query<<#engine as #face>::Score>),
8351 quote! {
8352 search(
8353 slot,
8354 scope,
8355 #subset::These({
8356 const __INGRAPH_COLUMNS: &[#column] = &[#column::new(#name)];
8357 __INGRAPH_COLUMNS
8358 }),
8359 query.text(),
8360 limit,
8361 options,
8362 )
8363 },
8364 )
8365 }
8366 // An ELECTION's subject: the query carries THIS column's width, and the engine is told which
8367 // column answers by a `VectorColumn` this method mints rather than takes.
8368 Grain::Election(elected) => {
8369 let (width, space) = self.geometry(elected);
8370 let name = elected.field.to_string();
8371 let query = framework(krate, &["retrieve"], "VectorQuery");
8372 let column = framework(krate, &["store"], "VectorColumn");
8373 (
8374 quote!(#query<<#engine as #face>::Element, <#engine as #face>::Score, #width, #space>),
8375 quote!(knn(
8376 slot,
8377 scope,
8378 #column::new(#name),
8379 query.coordinates(),
8380 limit,
8381 options,
8382 )),
8383 )
8384 }
8385 };
8386 // THE TWO BY-KEY DOORS, emitted for every election and conditional on nothing — a declaration
8387 // that elected a column can always be asked *what did you store for this entity* and *what
8388 // else is near it*, the by-key read being a capability of the SEAM rather than of a declared
8389 // word. They sit beside the raw pair rather than replacing anything: a caller holding
8390 // coordinates still calls the pair, and these two are for the caller holding a KEY.
8391 //
8392 // The GET door is emitted FIRST because the similar door is written in terms of it, and every
8393 // judgment about what an engine stored for a key is spent inside it exactly once.
8394 let by_key = election.map_or_else(proc_macro2::TokenStream::new, |elected| {
8395 let (width, space) = self.geometry(elected);
8396 let name = elected.field.to_string();
8397 let column = framework(krate, &["store"], "VectorColumn");
8398 let embedding = framework(krate, &["storage"], "Embedding");
8399 let vector_query = framework(krate, &["retrieve"], "VectorQuery");
8400 let addressed = framework(krate, &["retrieve"], "vector_addressed");
8401 let excluding = framework(krate, &["retrieve"], "ranked_keys_excluding");
8402 let refused = framework(krate, &["retrieve"], "OwnReadError");
8403 let own_door = Door::Own.name(&elected.field);
8404 let door = Door::Similar.name(&elected.field);
8405 let input = quote!(#embedding::<<#engine as #face>::Element, #width, #space>);
8406 // THE ANSWER SHAPE IS THE ELECTION'S LABEL, decided HERE and nowhere else. A unit election
8407 // declared ONE embedding, so the door answers one and several is a refusal; a `list`
8408 // election declared a SET, so the door answers the whole group with its ordinals and
8409 // several is the point. One door, two answer shapes, and ZERO runtime judgment about which
8410 // — the label is read at expansion.
8411 let grouped = elected.label.is_set();
8412 let held = framework(krate, &["retrieve"], "Held");
8413 let answers = if grouped {
8414 quote!(#held<#input>)
8415 } else {
8416 quote!(#input)
8417 };
8418 let own_doc = leading(&format!(
8419 "BY KEY — this entity's OWN `{field}` {noun}, CHECKED against what the declaration says \
8420 it is. A READ, and not a search: nothing is ranked, scored or compared here.",
8421 field = elected.field,
8422 noun = if grouped {
8423 "set, whole"
8424 } else {
8425 "embedding"
8426 },
8427 ));
8428 let own_scope = leading(
8429 "ONE engine call and ONE read scope, which is the whole of what separates it from the \
8430 similar door below: this is the by-key read alone, so `own` is the only crossing there \
8431 is. No dedup membership is built either, so the declaration's own `dedup` word buys \
8432 this door no bound.",
8433 );
8434 let own_judgment = leading(if grouped {
8435 "IT IS WHERE THE WIDTH IS JUDGED, per member and against the elected field's own type. \
8436 The seam answers with a SET and this election DECLARED one, so the arity is not a \
8437 judgment here at all — what would be `Several` on a unit election is this door's \
8438 ordinary answer, and it comes back whole in `Held`, each member under the ordinal a set \
8439 query asked with it is attributed by. An empty column is `Unindexed`, which is a fact \
8440 about the caller's own argument rather than a set of zero."
8441 } else {
8442 "IT IS WHERE THE ARITY AND THE WIDTH ARE JUDGED, and the only place either is. The seam \
8443 answers with a SET, because one entity may hold several vectors in one column, and what \
8444 this election declared is a single embedding — so none is a named refusal, several is a \
8445 named refusal rather than one of them picked on the caller's behalf, and a stored \
8446 vector that is not the declared width is named rather than trusted. Every other door \
8447 needing this entity's own embedding comes through here, so all three are written ONCE."
8448 });
8449 let own_errors = leading(if grouped {
8450 "The engine's own refusal from the by-key read, or the KEY itself: a column holding \
8451 nothing for it, or a stored vector of the wrong width. `Several` cannot arise — a set \
8452 of several is what this election declared."
8453 } else {
8454 "The engine's own refusal from the by-key read, or the KEY itself: a column holding \
8455 nothing for it, one holding several vectors for it where this election declared one, or \
8456 a stored vector of the wrong width."
8457 });
8458 let doc = leading(&format!(
8459 "TIER A, BY EXAMPLE — the ranked, deduped KEYS nearest to `key`'s OWN `{field}`, WITHOUT \
8460 `key` itself.",
8461 field = elected.field,
8462 ));
8463 let recipe = leading(&format!(
8464 "Sugar over the pair above and not a second query path: it reads the example's own \
8465 embedding back through [`{own_door}`](Self::{own_door}), hands it to the same `knn`, \
8466 and excludes the example — which the pipeline does by starting its dedup membership \
8467 with `key` ALREADY SEEN, so the example consumes its own raw-stream ordinal (the rank \
8468 hole stays) and `limit` counts NEIGHBOURS rather than counting the example as one of \
8469 them.",
8470 ));
8471 let budget = leading(
8472 "`limit` is ALSO the `k` the engine is handed, and a BUDGET at both ends: an answer \
8473 one short of it is ordinary, because the example occupies one of the fetched hits \
8474 whenever it is among them — the same class of shortening a floor drop causes from the \
8475 other end, and never a silent widening.",
8476 );
8477 let scopes = leading(
8478 "TWO read scopes, because the door makes TWO engine calls and a `Connected` is \
8479 deliberately not `Clone` — a scope may be a lease. `own` is the by-key read's and \
8480 `scope` is the `knn`'s; both borrow the same connection-manager, which is where an \
8481 engine's searcher actually lives.",
8482 );
8483 let errors = leading(&format!(
8484 "Everything [`{own_door}`](Self::{own_door}) refuses about the EXAMPLE, carried through \
8485 undecorated, plus the engine's own refusal from the `knn` and from the address read \
8486 after it.",
8487 ));
8488 // THE ARITY WALK, one per answer shape and picked at EMISSION. Both spend the SAME width
8489 // crossing against the elected field's own type — nothing an engine hands back has been
8490 // through that constructor, so this is where the drift is catchable at all — and they differ
8491 // in exactly what the LABEL says they differ in: how many values the declaration promised.
8492 let arity = if grouped {
8493 quote! {
8494 if ::std::vec::Vec::is_empty(&__ingraph_held) {
8495 return ::core::result::Result::Err(#refused::Unindexed);
8496 }
8497 let mut __ingraph_members = ::std::vec::Vec::with_capacity(__ingraph_held.len());
8498 for __ingraph_stored in __ingraph_held {
8499 let __ingraph_width = __ingraph_stored.len();
8500 match #input::new(::std::sync::Arc::from(__ingraph_stored)) {
8501 ::core::option::Option::Some(__ingraph_point) => {
8502 __ingraph_members.push(__ingraph_point);
8503 }
8504 ::core::option::Option::None => {
8505 return ::core::result::Result::Err(#refused::Width {
8506 declared: #input::DIM,
8507 stored: __ingraph_width,
8508 });
8509 }
8510 }
8511 }
8512 // THE ORDER IS THE ENGINE'S, unreordered — which is what makes the ordinal a `Held`
8513 // carries the same number a `Folded` asked with this set is subscripted by.
8514 ::core::result::Result::Ok(#held::new(
8515 ::std::vec::Vec::into_boxed_slice(__ingraph_members),
8516 ))
8517 }
8518 } else {
8519 quote! {
8520 let mut __ingraph_held = __ingraph_held;
8521 // The ARITY is spent HERE and only here: the seam answers with a SET because one entity
8522 // may hold several vectors in one column, and what this declaration elected is a single
8523 // `Embedding` — so one is taken, none is named, and several is named rather than having
8524 // one of them picked on the caller's behalf.
8525 let __ingraph_stored = match __ingraph_held.len() {
8526 0 => return ::core::result::Result::Err(#refused::Unindexed),
8527 1 => ::std::vec::Vec::remove(&mut __ingraph_held, 0),
8528 count => return ::core::result::Result::Err(#refused::Several { held: count }),
8529 };
8530 let __ingraph_width = __ingraph_stored.len();
8531 match #input::new(::std::sync::Arc::from(__ingraph_stored)) {
8532 ::core::option::Option::Some(__ingraph_point) => {
8533 ::core::result::Result::Ok(__ingraph_point)
8534 }
8535 ::core::option::Option::None => ::core::result::Result::Err(#refused::Width {
8536 declared: #input::DIM,
8537 stored: __ingraph_width,
8538 }),
8539 }
8540 }
8541 };
8542 // HOW THE SINGLE-VECTOR BY-EXAMPLE DOOR TAKES ITS EXAMPLE, which is the ARITY question the
8543 // group read handed back. A unit election's `get_` already answers one. A SET election's
8544 // answers the whole group — and this door asks with ONE vector by construction, so the
8545 // arity judgment lives HERE for the set case rather than in a door whose declaration says
8546 // several are ordinary. What was `Several` before the split is `Several` still; it is
8547 // simply refused where the arity is actually needed.
8548 //
8549 // The `_with` twin beside it is the door a set election is FOR, and it asks with all `m`.
8550 let example = if grouped {
8551 quote! {
8552 let __ingraph_group = Self::#own_door::<#engine>(slot, own, key).await?;
8553 let mut __ingraph_members =
8554 ::std::vec::Vec::from(#held::into_members(__ingraph_group));
8555 let example = match __ingraph_members.len() {
8556 1 => ::std::vec::Vec::remove(&mut __ingraph_members, 0),
8557 count => return ::core::result::Result::Err(#refused::Several { held: count }),
8558 };
8559 }
8560 } else {
8561 quote!(let example = Self::#own_door::<#engine>(slot, own, key).await?;)
8562 };
8563 let own_body = self.observed(
8564 observed,
8565 &own_door,
8566 quote! {
8567 let address = #addressed::<#engine, #key>(key);
8568 let __ingraph_held = #brand::get_vectors(slot, own, #column::new(#name), &address)
8569 .await
8570 .map_err(#refused::Engine)?;
8571 #arity
8572 },
8573 );
8574 let body = self.observed(
8575 observed,
8576 &door,
8577 quote! {
8578 // THE EXAMPLE COMES THROUGH THE DOOR ABOVE, which is what makes this one sugar: the
8579 // WIDTH is judged there, so nothing here restates it and the refusal rides `?`
8580 // unchanged.
8581 #example
8582 let query = #vector_query::new(example, floor);
8583 let hits = #brand::knn(
8584 slot,
8585 scope,
8586 #column::new(#name),
8587 query.coordinates(),
8588 limit,
8589 options,
8590 )
8591 .await
8592 .map_err(#refused::Engine)?;
8593 let hits = #keyed::<#engine, #key>(hits).map_err(#refused::Engine)?;
8594 ::core::result::Result::Ok(#excluding::<_, _, #membership<#key>>(
8595 hits,
8596 query.floor(),
8597 ::core::num::NonZeroUsize::get(limit),
8598 key,
8599 ))
8600 },
8601 );
8602 quote! {
8603 #[doc = #own_doc]
8604 #[doc = ""]
8605 #[doc = #own_scope]
8606 #[doc = ""]
8607 #[doc = #own_judgment]
8608 #[doc = ""]
8609 #[doc = " # Errors"]
8610 #[doc = ""]
8611 #[doc = #own_errors]
8612 #vis async fn #own_door<#engine>(
8613 slot: &mut #brand<#engine, Self>,
8614 own: #connected<'_, <#engine as #face>::Connection,
8615 <#engine as #lease>::ReadContext<'_>>,
8616 key: &#key,
8617 ) -> ::core::result::Result<#answers, #refused<<#engine as #face>::Error>>
8618 where
8619 #engine: #lease,
8620 #key: #row,
8621 {
8622 #own_body
8623 }
8624
8625 #[doc = #doc]
8626 #[doc = ""]
8627 #[doc = #recipe]
8628 #[doc = ""]
8629 #[doc = #budget]
8630 #[doc = ""]
8631 #[doc = #scopes]
8632 #[doc = ""]
8633 #[doc = " # Errors"]
8634 #[doc = ""]
8635 #[doc = #errors]
8636 #[doc = ""]
8637 #[doc = #knobs_doc]
8638 #[doc = ""]
8639 #[doc = #knobs_borrow]
8640 #[doc = ""]
8641 #[doc = #own_read_note]
8642 #[allow(clippy::too_many_arguments)]
8643 #vis async fn #door<#engine>(
8644 slot: &mut #brand<#engine, Self>,
8645 own: #connected<'_, <#engine as #face>::Connection,
8646 <#engine as #lease>::ReadContext<'_>>,
8647 scope: #connected<'_, <#engine as #face>::Connection,
8648 <#engine as #lease>::ReadContext<'_>>,
8649 key: &#key,
8650 floor: <#engine as #face>::Score,
8651 limit: ::core::num::NonZeroUsize,
8652 options: #knobs,
8653 ) -> ::core::result::Result<
8654 ::std::vec::Vec<#ranked<#key, <#engine as #face>::Score>>,
8655 #refused<<#engine as #face>::Error>,
8656 >
8657 where
8658 #engine: #lease,
8659 #key: #row + #admits,
8660 {
8661 #body
8662 }
8663 }
8664 });
8665 // THE SET DOOR, beside the pair above and never instead of it — emitted only for an election
8666 // whose LABEL states a set. Everything it needs is in scope here for the ask road's reason:
8667 // the three roads answer about one column and differ in what they are given.
8668 let set_door = election.map_or_else(proc_macro2::TokenStream::new, |elected| {
8669 // THE LABEL is the gate, and it is the whole gate: a declaration that wrote `embedding` has
8670 // no `_with` door at all, which is a TRUE ABSENCE rather than a door standing behind a bound
8671 // nobody can satisfy.
8672 if !elected.label.is_set() {
8673 return proc_macro2::TokenStream::new();
8674 }
8675 let (width, space) = self.geometry(elected);
8676 let name = elected.field.to_string();
8677 let with = Door::Set.name(&elected.field);
8678 let column = framework(krate, &["store"], "VectorColumn");
8679 let folded = framework(krate, &["retrieve"], "Folded");
8680 let set_query = framework(krate, &["retrieve"], "FoldedQuery");
8681 let fold_semantics = framework(krate, &["retrieve"], "FoldSemantics");
8682 let sightings = framework(krate, &["retrieve"], "Sightings");
8683 let owner_best = framework(krate, &["retrieve"], "owner_best");
8684 let set_scored = framework(krate, &["retrieve"], "set_scored");
8685 let accumulator = framework(krate, &["retrieve"], self.dedup.accumulator());
8686 let fold = format_ident!("__INGRAPH_FOLD__");
8687 let doc = leading(&format!(
8688 "TIER A, SET-SIMILARITY — the entities whose `{field}` SET best answers `m` query \
8689 vectors at once. Each vector's own best match in an entity's set is found first, and \
8690 `fold` is how those `m` bests become ONE score.",
8691 field = elected.field,
8692 ));
8693 let shape_note = leading(
8694 "It answers in `Folded` rather than in `Ranked`, and `limit` counts ENTITIES. The FOLD \
8695 authors this answer's order — there are `m` engine streams and no order between them — \
8696 so no ordinal is minted ACROSS them, and each stream's own ordinal is carried in that \
8697 stream's slot instead. The pair above stays the door for the single-vector question, and \
8698 asking this one with a single vector is that same question: every fold agrees at \
8699 `m = 1`, down to the one rank the slots then carry.",
8700 );
8701 let fold_note = leading(
8702 "The fold is a TYPE rather than a word — `Sum`, `Max` and `Weighted` are the three this \
8703 framework ships, and a fourth is one impl. It is taken by value and dispatched \
8704 statically, so a fold nobody here has heard of costs this door nothing.",
8705 );
8706 let raw_depth = leading(
8707 "`depth` is HOW DEEP EACH OF THE `m` STREAMS FETCHES, and `limit` still counts the \
8708 ENTITIES the fold answers with — two bounds at two grains, neither able to widen the \
8709 other. Absent, each stream fetches `limit`, which is byte-for-byte what this door did \
8710 before the knob existed.\n\nIt is a DOOR PARAMETER rather than an edge fact for the \
8711 by-example twin's reason, which covers this door word for word: the streams are \
8712 DATA-BORN — `m` vectors a caller brought, where the twin's `m` come out of an example's \
8713 stored set — so there is no declared route for a `Route` seat to hang on either way. A \
8714 `depth` BELOW `limit` is legal and is not refused: every number here is a ceiling rather \
8715 than a promise.\n\nWHY it is worth a number of its own: the fold reads `m` per-entity \
8716 bests, and a sum-family fold depends on positions no single stream's top slice \
8717 determines — so fetching deeper than the answer is wide is the pattern, and the VALUE is \
8718 the caller's rather than one this door could invent. Inflating `limit` and truncating \
8719 afterwards is not the same request: it distorts the answer contract to smuggle in a pool \
8720 size.",
8721 );
8722 // THE BY-EXAMPLE TWIN, the fourth door a set election gets and the one the spec's §6
8723 // measurement found missing. It stands to `retrieve_similar_by_<field>` exactly as the door
8724 // above stands to `retrieve_keys_by_<field>`: the same question, asked with `m` vectors.
8725 // THE DEPTH LAW, bound once for BOTH `_with` doors: the raw twin and the by-example one
8726 // resolve the same chain at the same grain, so a second binding would be a second place for
8727 // the path to drift.
8728 let stream_depth = framework(krate, &["retrieve"], "route_depth");
8729 let by_example = Door::SimilarSet.name(&elected.field);
8730 let similar = Door::Similar.name(&elected.field);
8731 let own_door = Door::Own.name(&elected.field);
8732 let embedding = framework(krate, &["storage"], "Embedding");
8733 let held = framework(krate, &["retrieve"], "Held");
8734 let refused = framework(krate, &["retrieve"], "OwnReadError");
8735 let best_excluding = framework(krate, &["retrieve"], "owner_best_excluding");
8736 let by_example_doc = leading(&format!(
8737 "TIER A, SET-SIMILARITY BY EXAMPLE — the entities whose `{field}` SET best answers \
8738 `key`'s OWN set, WITHOUT `key` itself.",
8739 field = elected.field,
8740 ));
8741 let by_example_recipe = leading(&format!(
8742 "The by-example recipe asked with `m` vectors instead of one — fetch own set, query with \
8743 EACH of them, exclude self, fold. The exclusion runs per stream rather than on the fused \
8744 answer, which is what keeps the example from contributing to its own neighbours' \
8745 sightings; filtering afterwards would answer a different ranking under the same name. \
8746 [`{similar}`](Self::{similar}) is the single-vector spelling of the same question.",
8747 ));
8748 let by_example_read = leading(&format!(
8749 "It reads the example's set through [`{own}`](Self::{own}), which on a SET election \
8750 answers the GROUP — the `m` vectors under the ordinals this door then asks them in. That \
8751 is one authority for the emptiness and one for the width, where the two used to be \
8752 written twice and could drift.",
8753 own = Door::Own.name(&elected.field),
8754 ));
8755 let by_example_depth = leading(
8756 "`depth` is HOW DEEP EACH OF THE `m` STREAMS FETCHES, and `limit` still counts the \
8757 ENTITIES the fold answers with — two bounds at two grains, neither able to widen the \
8758 other. Absent, each stream fetches `limit`, which is byte-for-byte what this door did \
8759 before the knob existed.\n\nIt is a DOOR PARAMETER rather than an edge fact because \
8760 these streams are DATA-BORN: the `m` of them come from the example's own stored set, so \
8761 there is no declared route to hang a `Route` seat on. A `depth` BELOW `limit` is legal \
8762 and is not refused — every number here is a ceiling rather than a promise, and a fold \
8763 handed shallower streams answers from what it was given.\n\nWHY it is worth a number \
8764 of its own: the fold is over `m` per-entity bests, and a sum-family fold reads positions \
8765 no single stream's top slice determines — so fetching deeper than the answer is wide is \
8766 the pattern, and the VALUE is the caller's rather than one this door could invent.",
8767 );
8768 let by_example_errors = leading(
8769 "The engine's own refusal from the by-key read, from any of the `m` knn calls or from \
8770 the address reads after them; `Unindexed` where the column holds nothing for `key`; and \
8771 `Width` where one of the stored vectors is not the declared width. `Several` cannot \
8772 arise — a set of several is what this door is for.",
8773 );
8774 // THE FOLD NAMES ITSELF ON THE SPAN, which is the first of the three places the
8775 // `FoldSemantics::name` row is spent: a trace of a set retrieve says WHICH arithmetic
8776 // authored the order it answered in, and that fork is otherwise invisible from outside —
8777 // two deployments running `sum` and `max` over one corpus produce two rankings and one
8778 // indistinguishable span. FULLY QUALIFIED because the fold is a type parameter and the
8779 // method call would be resolved against a bound rather than against a spelling.
8780 let fold_field = quote! {
8781 fold = <#fold as #fold_semantics<<#engine as #face>::Score>>::name(&fold),
8782 };
8783 let by_example_body = self.observed_with(
8784 observed,
8785 &by_example,
8786 fold_field,
8787 quote! {
8788 // THE EXAMPLE COMES THROUGH THE GROUP READ, which is what the set door's `get_` IS. The
8789 // walk that used to stand here — empty check, width crossing, per-member collect — was
8790 // that door's body written a second time, and the two could drift; now the emptiness
8791 // and the width have ONE authority and the refusal rides `?` undecorated.
8792 let __ingraph_example = Self::#own_door::<#engine>(slot, own, key).await?;
8793 // THE PER-STREAM DEPTH, resolved once for all `m` — the same law a `Route`'s own
8794 // depth resolves by, with no middle tier: a stream is DATA-BORN and has no declaration
8795 // to carry a ceiling. Absent, it is the fold's own budget, which is byte-for-byte what
8796 // every stream fetched before the seat existed.
8797 let __ingraph_depth = #stream_depth(depth, ::core::option::Option::None, limit);
8798 let mut __ingraph_bests =
8799 ::std::vec::Vec::with_capacity(#held::len(&__ingraph_example));
8800 for __ingraph_point in #held::members(&__ingraph_example) {
8801 let __ingraph_hits = #brand::knn(
8802 slot,
8803 ::core::clone::Clone::clone(&scope),
8804 #column::new(#name),
8805 #embedding::coordinates(__ingraph_point),
8806 __ingraph_depth,
8807 options,
8808 )
8809 .await
8810 .map_err(#refused::Engine)?;
8811 let __ingraph_hits =
8812 #keyed::<#engine, #key>(__ingraph_hits).map_err(#refused::Engine)?;
8813 __ingraph_bests.push(
8814 #best_excluding::<_, _, #membership<#key>>(__ingraph_hits, &floor, key)
8815 );
8816 }
8817 ::core::result::Result::Ok(#set_scored::<
8818 _, _, #accumulator<#key, #sightings<<#engine as #face>::Score>>, _
8819 >(__ingraph_bests, &fold, ::core::num::NonZeroUsize::get(limit)))
8820 },
8821 );
8822 quote! {
8823 #[doc = #doc]
8824 #[doc = ""]
8825 #[doc = #shape_note]
8826 #[doc = ""]
8827 #[doc = #fold_note]
8828 #[doc = ""]
8829 #[doc = #raw_depth]
8830 #[doc = ""]
8831 #[doc = #knobs_doc]
8832 #[doc = ""]
8833 #[doc = #streams_knobs]
8834 #[allow(clippy::too_many_arguments)]
8835 #vis async fn #with<'__ingraph_scope, #engine, #fold>(
8836 slot: &mut #brand<#engine, Self>,
8837 scope: #connected<'__ingraph_scope, <#engine as #face>::Connection,
8838 <#engine as #lease>::ReadContext<'__ingraph_scope>>,
8839 query: &#set_query<
8840 <#engine as #face>::Element, <#engine as #face>::Score, #width, #space
8841 >,
8842 fold: #fold,
8843 limit: ::core::num::NonZeroUsize,
8844 depth: ::core::option::Option<::core::num::NonZeroUsize>,
8845 options: #knobs,
8846 ) -> ::core::result::Result<
8847 ::std::vec::Vec<#folded<#key, <#engine as #face>::Score>>,
8848 <#engine as #face>::Error,
8849 >
8850 where
8851 #engine: #lease,
8852 #key: #row + #admits,
8853 #fold: #fold_semantics<<#engine as #face>::Score>,
8854 <#engine as #lease>::ReadContext<'__ingraph_scope>: ::core::clone::Clone,
8855 {
8856 // THE PER-STREAM DEPTH, resolved once for all `m` — the by-example twin's own line, at
8857 // the door that asks the same question with vectors a caller brought instead of vectors
8858 // an example held. There is no middle tier for the same reason there: a stream here is
8859 // DATA-BORN and has no declaration to carry a ceiling. Absent, it is the fold's own
8860 // budget, which is byte-for-byte what every stream fetched before the seat existed.
8861 let __ingraph_depth = #stream_depth(depth, ::core::option::Option::None, limit);
8862 let mut __ingraph_bests =
8863 ::std::vec::Vec::with_capacity(query.inputs().len());
8864 for __ingraph_coordinates in query.coordinates() {
8865 // The scope is CLONED per query vector: `knn` takes it by value, and `m` calls need
8866 // `m` of them. Read knobs are per-call by nature, and an engine whose read scope must
8867 // not be duplicated is absent from this door at compile time.
8868 //
8869 // `k` is EACH STREAM's ceiling, and the fold's `limit` counts ENTITIES: two bounds at
8870 // two grains, neither able to widen the other.
8871 let __ingraph_hits = #brand::knn(
8872 slot,
8873 ::core::clone::Clone::clone(&scope),
8874 #column::new(#name),
8875 __ingraph_coordinates,
8876 __ingraph_depth,
8877 options,
8878 ).await?;
8879 let __ingraph_hits = #keyed::<#engine, #key>(__ingraph_hits)?;
8880 __ingraph_bests.push(
8881 #owner_best::<_, _, #membership<#key>>(__ingraph_hits, query.floor())
8882 );
8883 }
8884 ::core::result::Result::Ok(#set_scored::<
8885 _, _, #accumulator<#key, #sightings<<#engine as #face>::Score>>, _
8886 >(__ingraph_bests, &fold, ::core::num::NonZeroUsize::get(limit)))
8887 }
8888
8889 #[doc = #by_example_doc]
8890 #[doc = ""]
8891 #[doc = #by_example_recipe]
8892 #[doc = ""]
8893 #[doc = #by_example_read]
8894 #[doc = ""]
8895 #[doc = #by_example_depth]
8896 #[doc = ""]
8897 #[doc = " # Errors"]
8898 #[doc = ""]
8899 #[doc = #by_example_errors]
8900 #[doc = ""]
8901 #[doc = #knobs_doc]
8902 #[doc = ""]
8903 #[doc = #streams_knobs]
8904 #[doc = ""]
8905 #[doc = #own_read_note]
8906 #[allow(clippy::too_many_arguments)]
8907 #vis async fn #by_example<'__ingraph_scope, #engine, #fold>(
8908 slot: &mut #brand<#engine, Self>,
8909 own: #connected<'_, <#engine as #face>::Connection,
8910 <#engine as #lease>::ReadContext<'_>>,
8911 scope: #connected<'__ingraph_scope, <#engine as #face>::Connection,
8912 <#engine as #lease>::ReadContext<'__ingraph_scope>>,
8913 key: &#key,
8914 floor: <#engine as #face>::Score,
8915 fold: #fold,
8916 limit: ::core::num::NonZeroUsize,
8917 depth: ::core::option::Option<::core::num::NonZeroUsize>,
8918 options: #knobs,
8919 ) -> ::core::result::Result<
8920 ::std::vec::Vec<#folded<#key, <#engine as #face>::Score>>,
8921 #refused<<#engine as #face>::Error>,
8922 >
8923 where
8924 #engine: #lease,
8925 #key: #row + #admits,
8926 #fold: #fold_semantics<<#engine as #face>::Score>,
8927 <#engine as #lease>::ReadContext<'__ingraph_scope>: ::core::clone::Clone,
8928 {
8929 #by_example_body
8930 }
8931 }
8932 });
8933 let keys_doc = leading(&format!(
8934 "TIER A — the ranked, deduped KEYS this {noun} matched{about}: the engine alone, no store \
8935 hop and no filter. `limit` is a BUDGET, and a short answer is legal.",
8936 noun = self.kind.noun(),
8937 ));
8938 let whole_doc = leading(&format!(
8939 "TIER B — the WHOLE upstream entities this {noun} matched{about}, in the ENGINE's order, \
8940 each wearing the score and the raw-stream rank of its key.",
8941 noun = self.kind.noun(),
8942 ));
8943 let keys_body = self.observed(
8944 observed,
8945 keys,
8946 quote! {
8947 let hits = #brand::#ask.await?;
8948 let hits = #keyed::<#engine, #key>(hits)?;
8949 // The walk's OWN truncation stays, and it is not a second ceiling: `k` bounds what the
8950 // engine FETCHES and this bounds what survives the floor and the dedup, which can only be
8951 // shorter. The walk counts SURVIVORS and takes a plain `usize` for it — a walk asked for
8952 // nothing is a legal call with an empty answer, where an ENGINE asked for nothing is not a
8953 // question at all — so the door's non-zero number is spent at this boundary.
8954 ::core::result::Result::Ok(#ranked_keys::<_, _, #membership<#key>>(
8955 hits,
8956 query.floor(),
8957 ::core::num::NonZeroUsize::get(limit),
8958 ))
8959 },
8960 );
8961 let whole_body = self.observed(
8962 observed,
8963 whole,
8964 quote! {
8965 // UNBOUNDED at tier A: the fill loop's own filter is what decides how many of the
8966 // above-floor keys become results, so a budget here would starve it. `NonZeroUsize::MAX` is
8967 // the honest spelling of *as many as exist* in the door family's own currency, and what an
8968 // engine does with a huge ceiling is that engine's business in its own storage — the seam
8969 // says so, and tantivy's `min(k, num_docs)` clamp is the reference.
8970 let ranked = match Self::#keys::<#engine>(
8971 slot,
8972 scope,
8973 query,
8974 ::core::num::NonZeroUsize::MAX,
8975 // FORWARDED VERBATIM: the knobs are the REQUEST's, and a hydrating door is one hop
8976 // above the seat rather than a second caller with defaults of its own. Reading,
8977 // defaulting or substituting anything here would be this door having an opinion about
8978 // an engine's own vocabulary.
8979 options,
8980 )
8981 .await
8982 {
8983 ::core::result::Result::Ok(ranked) => ranked,
8984 ::core::result::Result::Err(error) => {
8985 return ::core::result::Result::Err(#refusal::Engine(error));
8986 }
8987 };
8988 #filled(ranked, store, filter, ::core::num::NonZeroUsize::get(limit))
8989 .await
8990 .map_err(#refusal::Gather)
8991 },
8992 );
8993 quote! {
8994 #[doc = #keys_doc]
8995 #[doc = ""]
8996 #[doc = #knobs_doc]
8997 #[doc = ""]
8998 #[doc = #knobs_borrow]
8999 #vis async fn #keys<#engine>(
9000 slot: &mut #brand<#engine, Self>,
9001 scope: #connected<'_, <#engine as #face>::Connection,
9002 <#engine as #lease>::ReadContext<'_>>,
9003 query: &#query,
9004 limit: ::core::num::NonZeroUsize,
9005 options: #knobs,
9006 ) -> ::core::result::Result<
9007 ::std::vec::Vec<#ranked<#key, <#engine as #face>::Score>>,
9008 <#engine as #face>::Error,
9009 >
9010 where
9011 #engine: #lease,
9012 #key: #row + #admits,
9013 {
9014 #keys_body
9015 }
9016
9017 #[doc = #whole_doc]
9018 #[doc = ""]
9019 #[doc = #knobs_doc]
9020 #[doc = ""]
9021 #[doc = #forwarded_doc]
9022 #[allow(clippy::too_many_arguments)]
9023 #vis async fn #whole<#engine, #store>(
9024 slot: &mut #brand<#engine, Self>,
9025 scope: #connected<'_, <#engine as #face>::Connection,
9026 <#engine as #lease>::ReadContext<'_>>,
9027 store: &mut #store,
9028 query: &#query,
9029 filter: ::core::option::Option<&<#store as #gather<#key, #upstream>>::Filter>,
9030 limit: ::core::num::NonZeroUsize,
9031 options: #knobs,
9032 ) -> ::core::result::Result<
9033 ::std::vec::Vec<#ranked<#upstream, <#engine as #face>::Score>>,
9034 #refusal<
9035 <#engine as #face>::Error,
9036 <#store as #gather<#key, #upstream>>::Error,
9037 >,
9038 >
9039 where
9040 #engine: #lease,
9041 #store: #gather<#key, #upstream>,
9042 #key: #row + #admits,
9043 {
9044 #whole_body
9045 }
9046
9047 #by_key
9048
9049 #set_door
9050 }
9051 });
9052
9053 // THE FUSED DOORS ride the same impl and the same observation gate as the doors they call: a
9054 // trace of a fused retrieve is one span per route inside one span for the fold, which is the
9055 // composition it IS.
9056 let fused = self.fused_half(observed);
9057 // THE MINI FUSE DOORS ride beside them, for the same reason and one grain down: a fanned slot
9058 // is a tier whose routes are STORES, so its fold is one span per leg inside one for the fold.
9059 let fanned = self.fanned_half(observed);
9060 quote! {
9061 #[allow(dead_code)]
9062 impl #index {
9063 #(#pairs)*
9064
9065 #fused
9066
9067 #fanned
9068 }
9069 }
9070 }
9071
9072 /// ONE DOOR'S BODY, with a span around it or without — the G6 instrument clause, applied to the
9073 /// retrieve faces.
9074 ///
9075 /// The query face's own clause is `emit::query`'s `observed`, and everything that one states holds
9076 /// here word for word: `#[instrument]` cannot be reached from an expansion at all —
9077 /// `tracing-attributes` 0.1 declares no crate-path key and writes `::tracing::…`
9078 /// absolutely, and those paths resolve in the DECLARING crate, which names no tracing — so the
9079 /// span is opened by hand through the `macro_rules!` family, whose `$crate` follows the definition
9080 /// and lands on the shelf whatever path reached it. A `#[cfg_attr]` cannot stand in either: that
9081 /// predicate asks whether the declaring crate has a feature by that name. So the body is written
9082 /// twice and `if_tracing!`/`if_no_tracing!` keep exactly one.
9083 ///
9084 /// # It wraps the WHOLE body, and that is what the query face wraps too
9085 ///
9086 /// There the entry's body IS the crossing call, so the two readings coincide; here a door walks a
9087 /// road, reads an address, dedupes and gathers, and what a reader of `ingraph.query` is asking is
9088 /// how long the DOOR took. An `async move` block is what carries a multi-statement body into that
9089 /// position — its output is the method's own, so `?` and an early `return` mean inside it exactly
9090 /// what they meant before.
9091 ///
9092 /// # The LEVEL is `Info`, and it is the framework's default rather than a choice made here
9093 ///
9094 /// `span!` builds its metadata in a `static`, so the level has to be const-evaluable — which is
9095 /// why the query face reads the declaration's word at expansion time. A DERIVED INDEX writes no
9096 /// such word: `tracing(level = …)` is not in the vocabulary the derive's index front end admits —
9097 /// `upstream(…)`, `dedup(…)`, `embedding(…)` and `crate = "…"` are the whole of it — so there is
9098 /// nothing to read, and what these doors open at is the default a declaration that wrote no word
9099 /// gets. The day the word reaches this grammar, this line reads the model instead of the constant
9100 /// and nothing else moves.
9101 ///
9102 /// # The third field is `engine` where the query face's is `db`
9103 ///
9104 /// Both name what the door crossed to, and a full-text index is not a database. `record` and
9105 /// `entry` are the query face's own, unchanged, so one `ingraph.query` pane holds every emitted
9106 /// door and the `entry` field is what tells them apart.
9107 fn observed(
9108 &self,
9109 observed: bool,
9110 entry: &syn::Ident,
9111 body: proc_macro2::TokenStream,
9112 ) -> proc_macro2::TokenStream {
9113 if !observed {
9114 return body;
9115 }
9116 let instrument = framework(&self.krate, &["tracing"], "Instrument");
9117 let span = framework(&self.krate, &["tracing"], "span");
9118 let level = framework(&self.krate, &["tracing"], "Level");
9119 let constant = TracingLevel::Info.constant();
9120 let record = self.index.to_string();
9121 let entry = entry.to_string();
9122 let engine = self.kind.as_str();
9123 quote! {
9124 {
9125 use #instrument as _;
9126 async move { #body }
9127 .instrument(#span!(
9128 #level::#constant,
9129 "ingraph.query",
9130 record = #record,
9131 entry = #entry,
9132 engine = #engine,
9133 ))
9134 .await
9135 }
9136 }
9137 }
9138
9139 /// [`observed`](Self::observed) WITH ONE MORE FIELD, whose value is a RUNTIME expression rather
9140 /// than a constant — the set door's `fold`, and today nothing else.
9141 ///
9142 /// # It is a second function rather than a parameter on the first, and the SPAN IS HOISTED
9143 ///
9144 /// Two reasons, and the second is a measurement. The span above is built INSIDE `.instrument(…)`,
9145 /// which is evaluated after the `async move` block has already captured everything it moves — so a
9146 /// field reading the door's own `fold` parameter there is `E0382`, a use of a moved value. Binding
9147 /// the span first ends the borrow at the `let`, because `span!` records a `&str` field eagerly
9148 /// rather than holding it.
9149 ///
9150 /// The other reason is that the shape above must not move: every other door's expansion is pinned
9151 /// byte-for-byte by this module's tracing suite, and a hoist applied to all of them would be an
9152 /// unrelated diff in eleven emissions to buy a field one of them needs.
9153 fn observed_with(
9154 &self,
9155 observed: bool,
9156 entry: &syn::Ident,
9157 fields: proc_macro2::TokenStream,
9158 body: proc_macro2::TokenStream,
9159 ) -> proc_macro2::TokenStream {
9160 if !observed {
9161 return body;
9162 }
9163 let instrument = framework(&self.krate, &["tracing"], "Instrument");
9164 let span = framework(&self.krate, &["tracing"], "span");
9165 let level = framework(&self.krate, &["tracing"], "Level");
9166 let constant = TracingLevel::Info.constant();
9167 let record = self.index.to_string();
9168 let entry = entry.to_string();
9169 let engine = self.kind.as_str();
9170 quote! {
9171 {
9172 use #instrument as _;
9173 let __ingraph_span = #span!(
9174 #level::#constant,
9175 "ingraph.query",
9176 record = #record,
9177 entry = #entry,
9178 engine = #engine,
9179 #fields
9180 );
9181 async move { #body }.instrument(__ingraph_span).await
9182 }
9183 }
9184 }
9185
9186 /// The SUBJECTS this declaration answers under — one per pair of emitted retrieve methods.
9187 ///
9188 /// A full-text index has ONE unsuffixed pair plus one per searchable field; an embedding index has
9189 /// one per election, each named by the field its `knn` marker elected. The third kind reaches this
9190 /// nowhere: `blob` returns before it, an artifact family being addressed rather than ranked.
9191 ///
9192 /// # The full-text pairs, and why there are now N + 1 of them
9193 ///
9194 /// The unsuffixed pair used to be the whole family, and the reason was the seam: a per-field door
9195 /// would have to tell the engine which field answered, and `FulltextRead::search` took a slot, a
9196 /// scope and a string with nowhere to put the answer. That is the argument the grain ruling
9197 /// dissolved — the seam takes a [`FulltextSubset`] now — so the door family arrives, at VECTOR
9198 /// PARITY: `retrieve_keys_by_<field>` / `retrieve_by_<field>`, one pair per searchable field,
9199 /// minting a one-column subset the way the vector pair mints its own `VectorColumn`.
9200 ///
9201 /// The unsuffixed pair STAYS, and is not an alias for the single-field case. It asks
9202 /// `FulltextSubset::All`, which is a different question from *this field*: `All` is whatever the
9203 /// SLOT holds, and a slot may hold columns the declaration never elected. So one declaration
9204 /// electing one field emits both, and the two mean two things.
9205 ///
9206 /// The unsuffixed pair is emitted FIRST, which is what makes the vector kind's rule — a name whose
9207 /// spelling depends on the CARDINALITY of the declaration would move the day a second election
9208 /// arrived — hold on this side too: no full-text name moves when a field is elected, because the
9209 /// whole-subject pair was never one of the per-field ones.
9210 ///
9211 /// # WHAT THE FAN STILL WAITS ON, and why it did not hold the doors up
9212 ///
9213 /// A `fanout` field writes every declared engine at once, so a read that answered from ALL of its
9214 /// legs has to fan and FUSE them, and that is not built on either side of this face. What the
9215 /// per-field doors do instead is what the unsuffixed pair has always done: the ENGINE is a type
9216 /// parameter and the handle is the caller's, so which leg answers is the caller's own choice at
9217 /// the call rather than a winner this emission picked. The fan is the fused round's, it arrives
9218 /// for both pairs together, and it was never an argument about suffixes.
9219 fn subjects(&self) -> Vec<Subject<'_>> {
9220 if self.kind != NodeKind::Vector {
9221 let (keys, whole) = Door::pair(None);
9222 let mut subjects = vec![Subject {
9223 keys,
9224 whole,
9225 about: searched(&self.searchable),
9226 grain: Grain::Whole,
9227 }];
9228 subjects.extend(self.searchable.iter().map(|field| {
9229 let (keys, whole) = Door::pair(Some(field));
9230 Subject {
9231 keys,
9232 whole,
9233 about: format!(" in `{field}`"),
9234 grain: Grain::Column(field),
9235 }
9236 }));
9237 return subjects;
9238 }
9239 self
9240 .embeddings
9241 .iter()
9242 .map(|elected| {
9243 let field = &elected.field;
9244 let (keys, whole) = Door::pair(Some(field));
9245 Subject {
9246 keys,
9247 whole,
9248 about: format!(" in `{field}`"),
9249 grain: Grain::Election(elected),
9250 }
9251 })
9252 .collect()
9253 }
9254
9255 /// The index's OWN API: the constructor, the borrow of the key it carries, and one accessor
9256 /// family per declared field.
9257 ///
9258 /// A CONSTRUCTOR, which a record deliberately has none of, and the reason is the injection rather
9259 /// than a change of taste: this macro adds a field to the item its author wrote, so the struct
9260 /// literal an author would otherwise write no longer names every field and cannot be written at
9261 /// all. `new` is what replaces it, and the key comes first because it is the argument the
9262 /// declaration did not declare.
9263 ///
9264 /// `key_ref` and NO `key`. The by-value half is `Transformer::key`, emitted below; an inherent
9265 /// method of the same name would shadow it with a second spelling of one answer. The BORROW has no
9266 /// such twin — the trait hands a key back by value — and a document read to learn its key would
9267 /// otherwise clone one.
9268 ///
9269 /// Every field takes the MUTATORS, [`FieldsModel`](crate::fields::FieldsModel)'s rule for
9270 /// [`FieldsModel`](crate::fields::FieldsModel)'s reason: a record withholds them from the fields
9271 /// that bear identity, and no field here bears any. The key field takes none — it is the
9272 /// upstream's answer about which message this document is, and a document that could be re-keyed
9273 /// in place would be a document that could lie about where it came from.
9274 fn carrier(&self) -> proc_macro2::TokenStream {
9275 let IndexModel {
9276 index, vis, krate, ..
9277 } = self;
9278 let field = borrowed_key(&self.prefix);
9279 let key = self.key();
9280 let (names, types): (Vec<&syn::Ident>, Vec<&syn::Type>) = self
9281 .fields
9282 .iter()
9283 .map(|column| (&column.name, &column.ty))
9284 .unzip();
9285 let families = self.fields.iter().map(|column| {
9286 // A DERIVED INDEX's own fields carry no condition seat — the word is the record family's.
9287 column.methods(
9288 vis,
9289 krate,
9290 &format!("`{}` field of this [`{index}`]", column.name),
9291 true,
9292 &proc_macro2::TokenStream::new(),
9293 )
9294 });
9295 let new_doc = leading(&format!(
9296 "Construct {article} {noun} from the upstream key it carries and its own fields.",
9297 article = self.kind.article(),
9298 noun = self.kind.noun(),
9299 ));
9300 let key_doc = leading("The upstream key this document is addressed by, by reference.");
9301 let arity = wide_signature();
9302 quote! {
9303 impl #index {
9304 #[doc = #new_doc]
9305 #arity
9306 #[inline]
9307 #vis const fn new(#field: #key, #(#names: #types,)*) -> Self {
9308 Self { #field, #(#names,)* }
9309 }
9310
9311 #[doc = #key_doc]
9312 #[inline]
9313 #vis const fn key_ref(&self) -> &#key {
9314 &self.#field
9315 }
9316
9317 #(#families)*
9318 }
9319 }
9320 }
9321
9322 /// The ENTITY BINDING, every member of it a projection of the upstream's own.
9323 ///
9324 /// `Key` and `Lineage` are the upstream's verbatim, which is what *one document per upstream
9325 /// message* means: the document is that message, indexed, so it is addressed by that message's
9326 /// address and descends from that message's ancestors. Naming them through the upstream rather
9327 /// than copying its columns is also what keeps them true — re-keying the upstream re-keys every
9328 /// index over it, and a drift is a compile error rather than a convention.
9329 ///
9330 /// `Id` is read off the KEY rather than off the upstream, and the difference is which impl has to
9331 /// exist: `Identifiable::id_ref` is answered here by borrowing through the carried key, so what
9332 /// this expansion needs is that the key answers it. Every key a node macro emits does — the record
9333 /// emission writes `impl Identifiable for <Record>Key` beside the record's own — and an upstream
9334 /// whose key does not is `E0277` naming that key.
9335 ///
9336 /// `Record` and `Graphql` are both `()`, the empty product this crate uses for a face a
9337 /// declaration does not have. A derived index becomes no SQL row: its documents live in an engine
9338 /// of its own. Its wire face is a RANKING rather than a predicate — a different surface from the
9339 /// one `Graphql` describes — and binding `Self` for a face with no types behind it would be a
9340 /// claim nothing answers.
9341 ///
9342 /// The SUBSCRIPTION is not audited separately here, and needs no second item: `<Upstream as
9343 /// Transformer>::Key` is itself the bound, so a path naming nothing is `E0412` and a path naming
9344 /// something that is not a node is `E0277`, both at the string the author wrote. A record spells
9345 /// the audit out because its `subscribe = "…"` reaches no other emitted position.
9346 fn binding(&self) -> proc_macro2::TokenStream {
9347 let index = &self.index;
9348 let upstream = &self.source.node;
9349 let field = borrowed_key(&self.prefix);
9350 let key = self.key();
9351 let transformer = framework(&self.krate, &["transform"], "Transformer");
9352 let identifiable = framework(&self.krate, &["transform"], "Identifiable");
9353 quote! {
9354 #[automatically_derived]
9355 impl #identifiable for #index {
9356 type Id = <#key as #identifiable>::Id;
9357
9358 #[inline]
9359 fn id_ref(&self) -> &Self::Id {
9360 #identifiable::id_ref(&self.#field)
9361 }
9362 }
9363
9364 #[automatically_derived]
9365 impl #transformer for #index {
9366 type Key = #key;
9367 type Lineage = <#upstream as #transformer>::Lineage;
9368 type Record = ();
9369 type Graphql = ();
9370
9371 #[inline]
9372 fn key(&self) -> Self::Key {
9373 ::core::clone::Clone::clone(&self.#field)
9374 }
9375 }
9376 }
9377 }
9378
9379 /// **THE SUBSCRIBER** — the `subscribe` word's whole emission: a launchable node beside the
9380 /// declaration, which receives the upstream's messages over a real edge, projects them into this
9381 /// declaration's documents, lands those documents in this declaration's own corpora, and publishes
9382 /// them onward.
9383 ///
9384 /// EMPTY without the word, which is what makes subscription additive: the hand road's expansion is
9385 /// unchanged to the byte, and a deployment that fills its corpora itself keeps doing so.
9386 ///
9387 /// # WHY A SECOND TYPE — [`default_indexer_name`] carries the argument
9388 ///
9389 /// The declaration's value is a DOCUMENT and a node's value holds its `Shared<R>` mounts; one type
9390 /// cannot honestly be both. So the node is minted beside the document, and everything below is
9391 /// written on it.
9392 ///
9393 /// # THE BATCH IS THE DELIVERY, because the delivery is the only boundary there is
9394 ///
9395 /// A subscriber opens ONE batch per `accept`, queues every document of that delivery into it, and
9396 /// publishes before it answers. That is not a policy choice among several: `Payload` carries `One`
9397 /// and `Batch` and NOTHING ELSE — there is no end-of-stream punctuation in this layer's vocabulary
9398 /// — so a batch spanning more than one delivery would have no event that closes it, and a batch
9399 /// per ITEM would commit N times for a delivery the sender framed as one. The delivery is the
9400 /// frame the sender chose, and it is the frame the corpus takes.
9401 ///
9402 /// What a caller gets from this is the property the whole road exists for: when `accept` returns
9403 /// `Ok`, every document of that delivery is durable AND FINDABLE — see
9404 /// [`FulltextLane::publish`](https://docs.rs/ingraph), where the two are one act.
9405 ///
9406 /// # THE FATE OF A REFUSED WRITE IS THE DELIVERY'S, and the batch is rolled back under it
9407 ///
9408 /// A refusal anywhere in a batch discards that batch and returns `Err`, which
9409 /// [`Operator`](https://docs.rs/ingraph)'s own failure contract turns into a `DeadLettered` fate at
9410 /// this node. Nothing half-written survives the failure and no document is ever dropped in
9411 /// silence, which is the one outcome a write must not have — and the documents are NOT emitted
9412 /// either, so a refused delivery reaches no downstream.
9413 ///
9414 /// ACROSS corpora the guarantee stops at *whole or not at all*, and that is the topology's own
9415 /// answer rather than this emission's shortcoming: a declaration electing two fields writes two
9416 /// INDEPENDENT stores that share no transaction, so a refusal in the second leaves the first
9417 /// published. Inventing a rollback across them would be this expansion deciding a durability
9418 /// question that belongs to the deployment — the same statement the `fanout` door's own
9419 /// [`Refused`](crate::engine) note makes one seam over — and what the redelivery of a
9420 /// dead-lettered item costs is a repeat of an idempotent keyed replace.
9421 ///
9422 /// # THE DOCUMENTS ARE EMITTED AFTER THEY LAND, and the order is observable
9423 ///
9424 /// `emitter.emit` runs below the publish, so a downstream consumer of this node sees a document
9425 /// only once the corpus can answer for it. The reverse order would publish a document downstream
9426 /// that a search cannot find, which is the *read sees a partial entity* hazard moved one node
9427 /// earlier and made invisible.
9428 ///
9429 /// # THE RETRACTION SEAM, LEFT OPEN ON PURPOSE
9430 ///
9431 /// Every delivered item is an UPSERT here, and that is a statement about today's vocabulary rather
9432 /// than a claim about the world: `Payload` has no retraction variant, so a deletion cannot arrive
9433 /// and this body does not pretend to route one.
9434 ///
9435 /// What that leaves for the round which brings one is a SEAM rather than a rewrite. The walk is
9436 /// written over ITEMS — `into_items`, which is shape-agnostic — and matches no framework enum at
9437 /// all, so nothing here is an exhaustive match a new variant would have to break, and nothing here
9438 /// silently absorbs a variant it has never seen. The arm that carries a retraction lands in the
9439 /// document loop beside the upsert, and the engine act it needs is one more member on the write
9440 /// lane beside [`entry`](https://docs.rs/ingraph). Neither is written now, because a seam that is
9441 /// filled by guessing is worse than one that is empty and says so.
9442 fn subscriber(&self) -> proc_macro2::TokenStream {
9443 if !self.subscribe || self.kind != NodeKind::Fulltext {
9444 return proc_macro2::TokenStream::new();
9445 }
9446 let IndexModel {
9447 index, vis, krate, ..
9448 } = self;
9449 let node = crate::model::default_indexer_name(self.base());
9450 let upstream = &self.source.node;
9451
9452 // THE MOUNTS, grouped by the resource path AS WRITTEN — `habitats`' own grouping, for its own
9453 // reason: two spellings of one type would be two fields holding one `Shared`, and the emission
9454 // has no way to resolve them into one. One field per written path, in declaration order.
9455 let mut pointed: Vec<syn::Path> = Vec::new();
9456 let mut lanes: Vec<(usize, syn::Ident, &syn::Ident)> = Vec::new();
9457 for declared in &self.engines {
9458 if !self.searchable.contains(&declared.field) {
9459 continue;
9460 }
9461 for engine in &declared.engines {
9462 let Some(resource) = engine.resource.as_ref() else {
9463 continue;
9464 };
9465 let written = quote!(#resource).to_string();
9466 let at = pointed
9467 .iter()
9468 .position(|path| quote!(#path).to_string() == written)
9469 .unwrap_or_else(|| {
9470 pointed.push(resource.clone());
9471 pointed.len() - 1
9472 });
9473 let marker = crate::engine::Slot {
9474 field: declared.field.clone(),
9475 engine: engine.word.clone(),
9476 }
9477 .marker(self.base());
9478 lanes.push((at, marker, &declared.field));
9479 }
9480 }
9481 // A DECLARATION WHOSE LEGS POINT AT NOTHING has no node to mint: there is no store to open and
9482 // no mount to demand, so a subscriber would be a running node that lands nowhere. The word is
9483 // not refused for it — an unpointed leg is legal and means the deployment says instead — and
9484 // what it gets is the hand road it already had.
9485 if pointed.is_empty() {
9486 return proc_macro2::TokenStream::new();
9487 }
9488
9489 let mounts: Vec<syn::Ident> = (0..pointed.len())
9490 .map(|at| format_ident!("__ingraph_mount_{at}"))
9491 .collect();
9492 let shared = framework(krate, &["resource"], "Shared");
9493 let demand = framework(krate, &["resource"], "ResourceDemand");
9494 let resources = framework(krate, &["drive"], "Resources");
9495 let missing = framework(krate, &["drive"], "MissingResourceError");
9496 let constructor = framework(krate, &["drive"], "AsyncConstructor");
9497 let declared = framework(krate, &["drive"], "Declared");
9498 let effect = framework(krate, &["drive"], "Effect");
9499 let upstream_row = framework(krate, &["drive"], "Upstream");
9500 let unchanneled = framework(krate, &["drive"], "Unchanneled");
9501 let buffered = framework(krate, &["drive"], "Buffered");
9502 let downstream = framework(krate, &["drive"], "Downstream");
9503 let awaited = framework(krate, &["operator"], "Async");
9504 let context = framework(krate, &["drive"], "Context");
9505 let delivery = framework(krate, &["drive"], "Delivery");
9506 let item = framework(krate, &["drive"], "Item");
9507 let emitter = framework(krate, &["operator"], "Emitter");
9508 let operator = framework(krate, &["operator"], "AsyncOperator");
9509 let transformer = framework(krate, &["transform"], "Transformer");
9510 let identifiable = framework(krate, &["transform"], "Identifiable");
9511 let handle = framework(krate, &["store"], "SlotHandle");
9512 let mount = framework(krate, &["store"], "FulltextMount");
9513 let lane = framework(krate, &["store"], "FulltextLane");
9514 let road = framework(krate, &["store"], "FulltextRoad");
9515 let slot = framework(krate, &["store"], "Slot");
9516 let box_writer = framework(krate, &["document"], "BoxWriter");
9517 let connected = framework(krate, &["store"], "Connected");
9518 let refusal = framework(krate, &["store"], "IndexRefusal");
9519
9520 let named = quote!(#upstream).to_string();
9521 let node_doc = leading(&format!(
9522 "**THE SUBSCRIBER** [`{index}`] mints by wearing `subscribe` — the node a deployment mounts to \
9523 have this declaration's corpora filled for it.\n\nIt holds one mount per resource this \
9524 declaration's legs point at, receives [`{named}`]'s messages over the edge \
9525 `upstream(…)` named, and lands one document per message in each of this declaration's \
9526 corpora before publishing that document onward."
9527 ));
9528 let fields = mounts.iter().zip(&pointed).map(|(field, resource)| {
9529 let doc = leading(&format!(
9530 "The `{}` this node's corpora live in, built by the launch and reached at construction.",
9531 quote!(#resource)
9532 ));
9533 quote_spanned! {resource.span()=>
9534 #[doc = #doc]
9535 #field: #shared<#resource>
9536 }
9537 });
9538 let reaches = mounts.iter().zip(&pointed).map(|(field, resource)| {
9539 quote_spanned! {resource.span()=>
9540 #field: #resources::shared::<#resource>(__ingraph_resources)?
9541 }
9542 });
9543 let demands = pointed.iter().map(|resource| {
9544 quote_spanned! {resource.span()=>
9545 #demand::of::<#resource>
9546 }
9547 });
9548
9549 // ONE PROJECTION PER FIELD, in the DECLARATION's own order, which is the order `new` takes them
9550 // in. Read off `fields` rather than off the projection list so the two cannot drift: a field
9551 // whose entry is missing has already been refused, and the fallback keeps that refusal from
9552 // becoming a panic here.
9553 let projected = self.fields.iter().map(|column| {
9554 let name = &column.name;
9555 let from = self
9556 .source
9557 .projections
9558 .iter()
9559 .find(|projected| projected.field == *name)
9560 .map_or(name, |projected| &projected.from);
9561 quote_spanned!(from.span()=> ::core::clone::Clone::clone(&__ingraph_message.#from))
9562 });
9563
9564 let blocks = lanes.iter().map(|(at, marker, _)| {
9565 let held = &mounts[*at];
9566 let resource = &pointed[*at];
9567 // THE ENGINE, NAMED. Every lane call spells it rather than leaning on inference: `scope` and
9568 // `open` are answered through associated types alone, so a bare `_` leaves the solver with
9569 // `<_ as FulltextLane>::Batch == …` and nothing to unify it against. Spanned at the resource
9570 // path, so an engine with no lane is `E0277` on the word that chose it.
9571 let engine = quote_spanned!(resource.span()=> <#resource as #mount>::Handle);
9572 quote_spanned! {resource.span()=>
9573 {
9574 let __ingraph_mount = #shared::get(&self.#held);
9575 let __ingraph_connection = <#resource as #mount>::connection(__ingraph_mount);
9576 let __ingraph_slot = <#resource as #mount>::corpus(
9577 __ingraph_mount,
9578 <#marker as #slot>::SLOT.as_ref(),
9579 );
9580 let mut __ingraph_batch =
9581 <#engine as #lane>::open::<#marker>(&__ingraph_slot, __ingraph_connection)
9582 .map_err(#refusal::of)?;
9583 let mut __ingraph_corpus = #handle::<#engine, #index>::mint(__ingraph_slot);
9584 // THE QUEUE, and every refusal in it is the BATCH's: the loop stops at the first, the
9585 // batch is discarded whole below, and the delivery is dead-lettered rather than
9586 // half-landed.
9587 let __ingraph_queued: ::core::result::Result<(), Self::Error> = async {
9588 for __ingraph_document in &__ingraph_documents {
9589 let mut __ingraph_segments = #box_writer::new();
9590 <#marker as #road>::write(__ingraph_document, &mut __ingraph_segments)
9591 .map_err(#refusal::of)?;
9592 let __ingraph_entry = <#engine as #lane>::entry(
9593 #handle::engine(&__ingraph_corpus),
9594 #identifiable::id_ref(__ingraph_document),
9595 #index::key_ref(__ingraph_document),
9596 &__ingraph_segments,
9597 )
9598 .map_err(#refusal::of)?;
9599 #handle::upsert_document(
9600 &mut __ingraph_corpus,
9601 #connected::new(
9602 __ingraph_connection,
9603 <#engine as #lane>::scope(&mut __ingraph_batch),
9604 ),
9605 __ingraph_entry,
9606 )
9607 .await
9608 .map_err(#refusal::of)?;
9609 }
9610 ::core::result::Result::Ok(())
9611 }
9612 .await;
9613 match __ingraph_queued {
9614 ::core::result::Result::Ok(()) => <#engine as #lane>::publish(
9615 #handle::engine(&__ingraph_corpus),
9616 __ingraph_connection,
9617 __ingraph_batch,
9618 )
9619 .map_err(#refusal::of)?,
9620 ::core::result::Result::Err(__ingraph_refusal) => {
9621 <#engine as #lane>::discard(
9622 #handle::engine(&__ingraph_corpus),
9623 __ingraph_connection,
9624 __ingraph_batch,
9625 );
9626 return ::core::result::Result::Err(__ingraph_refusal);
9627 }
9628 }
9629 }
9630 }
9631 });
9632
9633 quote! {
9634 #[doc = #node_doc]
9635 #vis struct #node {
9636 #(#fields,)*
9637 }
9638
9639 #[automatically_derived]
9640 impl #constructor for #node {
9641 type Error = #missing;
9642 type Options = ();
9643
9644 fn with_options(
9645 __ingraph_resources: &#resources,
9646 (): (),
9647 ) -> impl ::core::future::Future<
9648 Output = ::core::result::Result<Self, <Self as #constructor>::Error>,
9649 > {
9650 async move {
9651 ::core::result::Result::Ok(Self {
9652 #(#reaches,)*
9653 })
9654 }
9655 }
9656 }
9657
9658 #[automatically_derived]
9659 impl #declared for #node {
9660 const EFFECT: #effect = #effect::Lands;
9661 const HOLDS_LANE: bool = true;
9662 const UPSTREAMS: &'static [#upstream_row] = &[#upstream_row::of::<#upstream>(#named)];
9663 const DEMANDS: &'static [fn() -> #demand] = &[#(#demands,)*];
9664
9665 type Channels = #unchanneled;
9666 type Options = ();
9667 type Mode = #awaited;
9668 type Pair = #buffered;
9669 type Wires<__INGRAPH_OUT__> = #downstream<__INGRAPH_OUT__>;
9670 // NO ATTRIBUTION, and there is no word here to write one with. This node is INJECTED rather
9671 // than declared — the `subscribe` word on a corpus mints it — and what it emits is the
9672 // DERIVED index document, which carries no `Attributes` impl for a projection to resolve
9673 // through. Its observations stay counter-grade, exactly as they were before the seat
9674 // existed.
9675 type Attribution<__INGRAPH_OUT__> = ();
9676 }
9677
9678 #[automatically_derived]
9679 impl #operator for #node {
9680 type In = #upstream;
9681 type Out = #index;
9682 type Error = #refusal;
9683
9684 fn accept(
9685 &mut self,
9686 _: &#context,
9687 __ingraph_delivery: #delivery<Self::In>,
9688 __ingraph_emitter: &mut #emitter<Self::Out>,
9689 ) -> impl ::core::future::Future<
9690 Output = ::core::result::Result<(), <Self as #operator>::Error>,
9691 > {
9692 async move {
9693 // EVERY DOCUMENT FIRST, before a single store is opened: a declaration with several
9694 // corpora writes each of them from the same set, and building per corpus would project
9695 // the same message once per engine.
9696 let mut __ingraph_documents = ::std::vec::Vec::new();
9697 for __ingraph_item in #delivery::into_items(__ingraph_delivery) {
9698 let __ingraph_message = #item::into_value(__ingraph_item);
9699 __ingraph_documents.push(#index::new(
9700 #transformer::key(&__ingraph_message),
9701 #(#projected,)*
9702 ));
9703 }
9704 // AN EMPTY DELIVERY OPENS NOTHING. A writer costs a lock and a thread, and a batch of
9705 // no documents publishes nothing — so the honest answer to one is to have done nothing.
9706 if !::std::vec::Vec::is_empty(&__ingraph_documents) {
9707 #(#blocks)*
9708 }
9709 // BELOW THE PUBLISH, which is the ordering this node's whole contract rests on: what
9710 // leaves here is findable in every corpus this declaration named.
9711 for __ingraph_document in __ingraph_documents {
9712 #emitter::emit(__ingraph_emitter, __ingraph_document);
9713 }
9714 ::core::result::Result::Ok(())
9715 }
9716 }
9717 }
9718 }
9719 }
9720
9721 /// One PROJECTION AUDIT per declared field: a function whose body reads the upstream field the
9722 /// declaration named, and whose return type is the index field's own.
9723 ///
9724 /// It is the whole mechanism by which `title = "speaker"` is checked. The body is spanned at the
9725 /// STRING the author wrote, so a field the upstream does not have is `E0609` there, one it will
9726 /// not show from this module is `E0616` there, and one whose type does not match is `E0308` there
9727 /// — each naming the upstream, none of them landing inside an expansion.
9728 ///
9729 /// DEAD BY CONSTRUCTION, and the `allow` says so: nothing calls these and nothing is meant to.
9730 /// They exist to be type-checked, which is what a macro that cannot see the upstream can do about
9731 /// the upstream. Calling one would make the audit a code path, and a code path is a thing that has
9732 /// to stay correct rather than a thing that has to compile.
9733 ///
9734 /// One function per FIELD, so the errors arrive one per mistake rather than collapsing into the
9735 /// first. Two sources projecting one field would collide on the name, which is exactly the
9736 /// position the frame law on [`borrowed_key`](crate::model::borrowed_key) reserves an index for.
9737 fn projections(&self) -> proc_macro2::TokenStream {
9738 let upstream = &self.source.node;
9739 let audits = self.source.projections.iter().map(|projected| {
9740 let Projected { field, from, ty } = projected;
9741 let name = format_ident!("__ig_project_{field}");
9742 let read = quote_spanned!(from.span()=> &value.#from);
9743 quote! {
9744 #[allow(dead_code)]
9745 fn #name(value: &#upstream) -> &#ty {
9746 #read
9747 }
9748 }
9749 });
9750 quote!(#(#audits)*)
9751 }
9752
9753 /// `<Upstream as Transformer>::Key` — the type of the carried field, and of everything read out of
9754 /// it.
9755 ///
9756 /// Written once here because four emitted positions spell it — the constructor's first parameter,
9757 /// `key_ref`'s return, `Transformer::Key` and the `Identifiable` it is projected through — and
9758 /// four hand-written copies is four places for the projection to drift.
9759 fn key(&self) -> proc_macro2::TokenStream {
9760 let upstream = &self.source.node;
9761 let transformer = framework(&self.krate, &["transform"], "Transformer");
9762 quote!(<#upstream as #transformer>::Key)
9763 }
9764
9765 /// γ′ — the ONE field this expansion adds to the item its author wrote.
9766 ///
9767 /// Minted here rather than at the front end that injects it, so that the name, the type and the
9768 /// visibility are decided by the code that also reads them back: `new` takes it, `key_ref` borrows
9769 /// it, the entity binding answers through it, and all four are above.
9770 ///
9771 /// `pub(crate)`, which is the stamp every other field of the declaration wears — see
9772 /// `ingraph-derive`'s `host` module — and no exception is carved for this one. The visibility
9773 /// convention is about a declaration's fields being read by the code emitted around them, and this
9774 /// field is the case that statement was written for.
9775 ///
9776 /// # Panics
9777 /// Never in practice: the tokens are this function's own, and the only way they fail to parse as a
9778 /// named field is a change to this line.
9779 #[must_use]
9780 pub fn carried_key(&self) -> syn::Field {
9781 use syn::parse::Parser as _;
9782
9783 let name = borrowed_key(&self.prefix);
9784 let key = self.key();
9785 syn::Field::parse_named
9786 .parse2(quote!(pub(crate) #name: #key))
9787 .expect("a named field")
9788 }
9789
9790 /// Every method this emission declares, in EMISSION ORDER, for the front end that has to refuse a
9791 /// collision before an expansion lands two of one name in a scope its author cannot edit.
9792 ///
9793 /// The FIXED names are here for the reason a declaration's derived ones are: a field called `key`
9794 /// reaches `key_ref`, and a `copy` field called `new` reaches `new`. Neither is a near miss — both
9795 /// are the emitted name exactly — so both are refused at the declaration rather than left to be a
9796 /// duplicate definition inside the expansion.
9797 ///
9798 /// # EVERY name, and the ones this used to miss are the reason it says so
9799 ///
9800 /// The list once held the constructor, the borrowed key and the accessor families, and the whole
9801 /// read-and-write surface below them was absent. Each absence was the same defect: a `copy` field
9802 /// called `fan_title` beside a `fanout`-marked `title` gives the index two `fan_title`, a field
9803 /// called `retrieve_keys` gives it two of those, and `E0592` reports each of them at
9804 /// `#[ingraph::fulltext(…)]` — a span the author cannot edit, in a message that never names the
9805 /// field. A table that knows about the accessors alone refuses the collisions it happens to have
9806 /// heard of and is silent about the rest, which reads as a rule that has been applied.
9807 ///
9808 /// # ONE OWNER, and an impl written inside the anonymous const is not a smaller scope
9809 ///
9810 /// Every method here lands on the DECLARATION's own type, which is why they all carry
9811 /// [`Owner::Record`]. The retrieve face is emitted inside the expansion's anonymous `const` and the
9812 /// fan door at module scope, and that difference buys nothing: an inherent impl is global whatever
9813 /// block it was written in, so the two impls' names share one namespace and collide with each other
9814 /// exactly as they collide with the carrier's.
9815 ///
9816 /// The order is the EMITTER's own walk — see [`emit`](Self::emit) — so a front end reporting a
9817 /// collision can name the earlier of the two as the one already there. It is pinned against the
9818 /// emission itself by `tests::the_enumeration_names_exactly_the_methods_the_emission_declares`,
9819 /// rather than maintained by hand.
9820 #[must_use]
9821 pub fn emitted_methods(&self) -> Vec<Emitted> {
9822 let mint = |name: syn::Ident, origin: Origin| Emitted {
9823 owner: Owner::Record,
9824 owner_name: self.index.clone(),
9825 name,
9826 origin,
9827 };
9828 // The FANS lead, because the emission writes them before the const the rest of it lives in.
9829 let mut emitted: Vec<Emitted> = self
9830 .fans()
9831 .map(|field| mint(fan_door(field), Origin::Fan(field.clone())))
9832 .collect();
9833 // The FUSE FAMILY next — the packages, questions and the column vocabulary the tier writes
9834 // between the fans and the carrier, rostered by the tier itself so the names and their
9835 // predicates live beside the emission.
9836 emitted.extend(
9837 self
9838 .tier()
9839 .emitted_methods()
9840 .into_iter()
9841 .map(|(on, name)| Emitted {
9842 owner: Owner::Fuse,
9843 owner_name: on.clone(),
9844 name: name.clone(),
9845 origin: Origin::Fuse(crate::method::FuseOrigin { on, member: name }),
9846 }),
9847 );
9848 emitted.push(mint(format_ident!("new"), Origin::Constructor));
9849 emitted.push(mint(format_ident!("key_ref"), Origin::BorrowedKey));
9850 emitted.extend(
9851 self
9852 .fields
9853 .iter()
9854 .flat_map(|column| column.emitted(Owner::Record, &self.index, true)),
9855 );
9856 // The DECLARED FOLDS, between the carrier and the retrieve face because that is where they are
9857 // written — one per SET election, which is the predicate `declared_folds` asks rather than a
9858 // second reading of it.
9859 emitted.extend(
9860 self
9861 .embeddings
9862 .iter()
9863 .filter(|elected| elected.label.is_set())
9864 .map(|elected| {
9865 mint(
9866 fold_accessor(&elected.field),
9867 Origin::Fold(elected.field.clone()),
9868 )
9869 }),
9870 );
9871 emitted.extend(
9872 self
9873 .retrieve_methods()
9874 .into_iter()
9875 .map(|(name, origin)| mint(name, origin)),
9876 );
9877 emitted
9878 }
9879
9880 /// The RETRIEVE face's names, in the order [`retrieve_half`](Self::retrieve_half) writes them —
9881 /// the doors of every subject, each subject's whole family before the next subject's.
9882 ///
9883 /// Split out for the reason the record's order-by methods are: the conditions differ from every
9884 /// other family's, and a walk this long inside one function would hide which of them is answered
9885 /// where. Each condition is asked HERE in the same form the emission asks it — a kind that answers
9886 /// no retrieve has no subjects at all, a by-key pair rides an election, the set door rides the
9887 /// LABEL and the asked pair rides a declared road.
9888 fn retrieve_methods(&self) -> Vec<(syn::Ident, Origin)> {
9889 let mut emitted = Vec::new();
9890 // The `blob` kind reaches no retrieve at all — an artifact family is addressed rather than
9891 // ranked — and `subjects` cannot say so on its own: it answers the unelected pair for every kind
9892 // that is not `vector`, which is what makes the full-text pair unsuffixed.
9893 if !self.seamed() {
9894 return emitted;
9895 }
9896 // THE FUSED DOORS lead the per-subject walk, because the emission writes them after it — the
9897 // roster's order is the emitter's own, and `retrieve_half` appends them to the impl.
9898 let mut fused = Vec::new();
9899 if self.tier().doors().vector {
9900 fused.push((
9901 format_ident!("vector_fuse"),
9902 Origin::Door(DoorOrigin {
9903 door: Door::Fused,
9904 election: None,
9905 }),
9906 ));
9907 fused.push((
9908 format_ident!("vector_fuse_similar"),
9909 Origin::Door(DoorOrigin {
9910 door: Door::FusedSimilar,
9911 election: None,
9912 }),
9913 ));
9914 }
9915 for subject in self.subjects() {
9916 // The audit's ELECTION is the door's SUFFIX: `None` reconstructs the unsuffixed pair and
9917 // `Some` a `_by_<field>` one, so a per-field full-text door answers its column exactly as a
9918 // vector door answers its election.
9919 let suffix = match subject.grain {
9920 Grain::Whole => None,
9921 Grain::Column(field) => Some(field.clone()),
9922 Grain::Election(elected) => Some(elected.field.clone()),
9923 };
9924 let door = |door: Door| {
9925 Origin::Door(DoorOrigin {
9926 door,
9927 election: suffix.clone(),
9928 })
9929 };
9930 emitted.push((subject.keys.clone(), door(Door::Keys)));
9931 emitted.push((subject.whole.clone(), door(Door::Whole)));
9932 let Grain::Election(elected) = subject.grain else {
9933 continue;
9934 };
9935 // The BY-KEY pair, conditional on nothing but the election itself — a declaration that elected
9936 // a column can always be asked what it stored for an entity and what else is near it.
9937 emitted.push((Door::Own.name(&elected.field), door(Door::Own)));
9938 emitted.push((Door::Similar.name(&elected.field), door(Door::Similar)));
9939 if elected.label.is_set() {
9940 emitted.push((Door::Set.name(&elected.field), door(Door::Set)));
9941 emitted.push((
9942 Door::SimilarSet.name(&elected.field),
9943 door(Door::SimilarSet),
9944 ));
9945 }
9946 }
9947 emitted.extend(fused);
9948 // THE MINI FUSE DOORS, last for the emitter's own reason — `retrieve_half` appends them after
9949 // the tier's, and the roster's order is the emission's. The condition is asked in the same form
9950 // the emission asks it: `fanned_slots`, which is two or more PARTICIPATING legs and not a set
9951 // election, read from the one place that decides it.
9952 for elected in self.tier().fanned_slots() {
9953 let field = elected.field.clone();
9954 let door = |door: Door| {
9955 Origin::Door(DoorOrigin {
9956 door,
9957 election: Some(field.clone()),
9958 })
9959 };
9960 emitted.push((Door::FusedLegs.name(&field), door(Door::FusedLegs)));
9961 emitted.push((
9962 Door::FusedLegsSimilar.name(&field),
9963 door(Door::FusedLegsSimilar),
9964 ));
9965 }
9966 emitted
9967 }
9968
9969 /// The fields that GET A FAN DOOR — every `fanout`-marked one, on a kind that has a write verb to
9970 /// fan.
9971 ///
9972 /// An enumeration naming a door the expansion does not write would refuse a declaration for a
9973 /// collision it could not have, which is why the kind is asked here at all.
9974 fn fans(&self) -> impl Iterator<Item = &syn::Ident> {
9975 self
9976 .engines
9977 .iter()
9978 .filter(|_| self.seamed())
9979 .filter(|declared| declared.fanout)
9980 .map(|declared| &declared.field)
9981 }
9982
9983 /// Whether this kind HAS AN ENGINE SEAM — the one predicate the fan door and the retrieve face are
9984 /// both conditional on.
9985 ///
9986 /// [`fanouts`](Self::fanouts) and [`retrieve_half`](Self::retrieve_half) each ask it as the `_`
9987 /// arm of a match that also picks the seam's trait paths and its write verb, so what is shared is
9988 /// the QUESTION and not the answer — a `blob` elects nothing, holds no corpus and therefore has
9989 /// neither door. Written once here so the two enumerations above ask it in one spelling, and
9990 /// pinned against the emitters by this module's `audits` suite: a kind that grew a seam and did
9991 /// not reach this predicate fails there.
9992 const fn seamed(&self) -> bool {
9993 matches!(self.kind, NodeKind::Fulltext | NodeKind::Vector)
9994 }
9995
9996 /// Every TYPE this emission declares into the DECLARING SCOPE, in EMISSION ORDER — the markers,
9997 /// which are the whole of what a derived index puts in the type namespace beside the item its
9998 /// author wrote.
9999 ///
10000 /// [`RecordModel::emitted_types`](crate::model::RecordModel::emitted_types)' argument, one family
10001 /// over: the front end refuses a declaration whose emitted types collide, and it asks HERE which
10002 /// those are rather than keeping a list of its own.
10003 ///
10004 /// # WHY a derived index needs this at all, when its markers are minted rather than named
10005 ///
10006 /// No word renames either of these, so the collisions are not a rename landing on a neighbour —
10007 /// they are the JOIN. A marker is `<Index><Field><Engine>` in upper camel case, and camel case has
10008 /// no separator: field `a` × engine `b_c` and field `a_b` × engine `c` both mint `<Index>ABC`.
10009 /// The election markers are `<Index>By<Field>` and stand in the same scope, so field `by` × engine
10010 /// `image` mints exactly the marker of an election on `image`.
10011 ///
10012 /// The durable slot NAME has the same three parts and does NOT have the problem — see
10013 /// [`Slot::name`](crate::engine::Slot::name), which joins with `__` for precisely this reason and
10014 /// is test-pinned.
10015 ///
10016 /// # The boundary-preserving JOIN was measured against the refusal, and lost on two counts
10017 ///
10018 /// **A TYPE cannot take that separator.** `<Index>__a__b_c` is not upper camel case, so every
10019 /// marker would arrive under `non_camel_case_types` in a crate that never wrote it — the cost
10020 /// [`one_storage_marker`](crate::model::one_storage_marker) already spends `allow`s on, paid here
10021 /// on names the WIRING spells rather than on a hidden one. And spell them it does:
10022 /// `SlotHandle<E, SearchDocumentTitleTantivy>` and the lanes over it are some eighty sites across
10023 /// this workspace, several of them `compile_fail` goldens whose text IS the assertion.
10024 ///
10025 /// **And it would not close the class.** The election markers camel-join too, so elections on
10026 /// `image_1` and `image1` mint one `<Index>ByImage1` whatever the slot markers do. A respelling
10027 /// buys one of the three collisions and leaves the other two live — under an error code that would
10028 /// then look handled, which is the failure the whole-fix constraint was written against.
10029 ///
10030 /// So the name stays and the collision is REFUSED at the declaration, which is the road that leaves
10031 /// the author's own tokens the thing that moves.
10032 ///
10033 /// # The INDEX's own name is not here, and cannot collide with one of these
10034 ///
10035 /// A record adds its own name to this list because a rename can land on it. Nothing here can:
10036 /// every marker is the index's name followed by at least one more camel-case segment, so
10037 /// `<Index>` itself is not in the set — and a name this enumeration invented would refuse a
10038 /// declaration for a clash that could not happen.
10039 ///
10040 /// The order is the emitter's own walk — elections, then slots — and it is pinned against the
10041 /// emission by `tests::the_enumeration_names_exactly_the_types_the_emission_declares`.
10042 #[must_use]
10043 pub fn emitted_types(&self) -> Vec<Declared> {
10044 let index = self.base();
10045 self
10046 .embeddings
10047 .iter()
10048 .map(|elected| Declared {
10049 name: elected_marker(index, &elected.field),
10050 role: Role::Election(elected.field.clone()),
10051 })
10052 .chain(self.slots().into_iter().map(|slot| Declared {
10053 name: slot.marker(index),
10054 role: Role::Slot(slot),
10055 }))
10056 .chain(
10057 self
10058 .tier()
10059 .emitted_types()
10060 .into_iter()
10061 .map(|name| Declared {
10062 name,
10063 role: Role::Fuse,
10064 }),
10065 )
10066 // THE QUERY UNIT, last and only where the declaration is dressed — a name in the declaring
10067 // scope is a name the collision refusals are measured against, whatever tier minted it.
10068 .chain(self.mounts().then(|| Declared {
10069 name: self.queries_name(),
10070 role: Role::Queries,
10071 }))
10072 // THE ANSWER FAMILY, after it and in the emitter's own walk — one question per road, and the
10073 // hit shapes a fanned road adds. Every one of them is a module-scope declaration OUTSIDE the
10074 // binding gate, which is what makes this enumeration able to name them at all: a type minted
10075 // inside a gate would be invisible here and visible to a declaring author.
10076 .chain(self.answer_names())
10077 .collect()
10078 }
10079
10080 /// EVERY TYPE the answer family lands, in the emitter's own walk — see
10081 /// [`answers`](Self::answers).
10082 fn answer_names(&self) -> Vec<Declared> {
10083 use heck::ToUpperCamelCase as _;
10084
10085 let tier = self.tier();
10086 let mut names = Vec::new();
10087 for (elected, road) in self.answer_roads() {
10088 let stem = tier.stem(elected);
10089 let role = Role::Answer(elected.field.clone());
10090 names.push(Declared {
10091 name: format_ident!("{stem}Question"),
10092 role: role.clone(),
10093 });
10094 if let AnswerRoad::Fanned(legs) = road {
10095 names.push(Declared {
10096 name: format_ident!("{stem}Engines"),
10097 role: role.clone(),
10098 });
10099 for engine in &legs {
10100 names.push(Declared {
10101 name: format_ident!(
10102 "{stem}{}Sighting",
10103 engine.word.to_string().to_upper_camel_case()
10104 ),
10105 role: role.clone(),
10106 });
10107 }
10108 names.push(Declared {
10109 name: format_ident!("{stem}Sighting"),
10110 role: role.clone(),
10111 });
10112 names.push(Declared {
10113 name: format_ident!("{stem}FusedKeyMatch"),
10114 role,
10115 });
10116 }
10117 }
10118 names
10119 }
10120
10121 /// What the field wrote, or [`None`] where it wrote nothing — the ELECTION tier's lookup.
10122 #[must_use]
10123 pub fn numbers_of(&self, field: &syn::Ident) -> Option<&FieldNumbers> {
10124 self
10125 .field_numbers
10126 .iter()
10127 .find(|written| &written.field == field)
10128 }
10129
10130 /// **THE WALL FOR ONE ROUTE** — the declared ceiling `route_depth` caps every fetch against.
10131 ///
10132 /// Two tiers and no third: the ELECTION's word where it wrote one, else the CONTAINER's. There is
10133 /// no framework default and there never will be one — an absent wall is the AUTHOR'S INFORMED
10134 /// OPENNESS (#293-B), and a number invented on their behalf would be the framework deciding what a
10135 /// deployment may afford.
10136 ///
10137 /// `field` is [`None`] at the grains that are not one election's — the full-text tier's unsuffixed
10138 /// subject — where the container's word is the whole chain.
10139 #[must_use]
10140 pub fn declared_ceiling(&self, field: Option<&syn::Ident>) -> Option<core::num::NonZeroU32> {
10141 field
10142 .and_then(|field| self.numbers_of(field))
10143 .and_then(|written| written.numbers.ceiling)
10144 .or(self.numbers.ceiling)
10145 }
10146
10147 /// **THE STREAM GUARD FOR ONE ELECTION** — how many query vectors one request may ask its `_with`
10148 /// road with, or [`None`] where no tier wrote a guard.
10149 ///
10150 /// [`declared_ceiling`](Self::declared_ceiling)'s twin on the other protective axis, resolved the
10151 /// same way and for the same reason: the ELECTION's word where it wrote one, else the CONTAINER's,
10152 /// and no third step — a word written closer to the door is the more specific statement of the same
10153 /// rule, and an unwritten guard is NO guard rather than a number this crate invented.
10154 ///
10155 /// It is spent in [`points_binding`](Self::points_binding) and nowhere else, which is the ruled
10156 /// scope: the guard is over an `m` a REQUEST states, and the only road asked with one is the
10157 /// `_with` question road.
10158 #[must_use]
10159 pub fn declared_streams(&self, field: Option<&syn::Ident>) -> Option<core::num::NonZeroU32> {
10160 field
10161 .and_then(|field| self.numbers_of(field))
10162 .and_then(|written| written.numbers.streams)
10163 .or(self.numbers.streams)
10164 }
10165
10166 /// **THE WALL, AS AN EMITTED `route_depth` READS IT** — the token that fills the second argument
10167 /// every fetch resolves through.
10168 ///
10169 /// `Option::as_ref` over a fresh `Option<NonZeroU32>` rather than a hoisted `const`, and the shape
10170 /// is the borrow's: the callee takes `Option<&NonZeroU32>`, the temporary lives to the end of the
10171 /// `let` statement the call sits in, and `route_depth` hands back an owned number — so nothing
10172 /// outlives the statement and no item has to be minted in the emitted body's scope.
10173 ///
10174 /// [`None`] where no tier declared one, which is the `::core::option::Option::None` every site
10175 /// spelled while the word did not exist — so a declaration that writes nothing expands to exactly
10176 /// the tokens it expanded to before, and the word is purely additive.
10177 #[must_use]
10178 pub fn wall(&self, field: Option<&syn::Ident>) -> proc_macro2::TokenStream {
10179 match self.declared_ceiling(field) {
10180 Some(wall) => {
10181 let wall = wall.get();
10182 quote! {
10183 ::core::option::Option::as_ref(&::core::num::NonZeroU32::new(#wall))
10184 }
10185 }
10186 None => quote!(::core::option::Option::None),
10187 }
10188 }
10189
10190 /// **THE WIRE DEFAULT** — the literal one election's `first:` argument publishes, resolved through
10191 /// the ruled chain and capped by the wall.
10192 ///
10193 /// ```text
10194 /// field-skin `first` → field `limit` → container-skin `first` → container `limit` → 20
10195 /// ```
10196 ///
10197 /// The order is Q6a's verbatim, and each step is the more specific statement of the same number:
10198 /// a skin's word beats the bones at its own tier because it is written closer to the schema, and a
10199 /// field's tier beats the container's because it is written closer to the door. [`FRAMEWORK_LIMIT`]
10200 /// is the floor of the chain rather than a default anybody writes.
10201 ///
10202 /// The WALL caps the answer, and that is not decoration: a default published above the ceiling
10203 /// would be a schema promising a page size the fetch silently cuts, which is the one thing an SDL
10204 /// literal must not be able to do.
10205 #[must_use]
10206 pub fn wire_first(&self, kind: GraphqlKind, field: Option<&syn::Ident>) -> core::num::NonZeroU32 {
10207 let at = field.and_then(|field| self.numbers_of(field));
10208 let asked = at
10209 .and_then(|written| written.skin(kind))
10210 .and_then(|skin| skin.first)
10211 .or_else(|| at.and_then(|written| written.numbers.limit))
10212 .or_else(|| {
10213 self
10214 .graphql
10215 .as_ref()
10216 .and_then(|block| block.skin(kind))
10217 .and_then(|skin| skin.first)
10218 })
10219 .or(self.numbers.limit)
10220 .unwrap_or(FRAMEWORK_LIMIT);
10221 match self.declared_ceiling(field) {
10222 Some(wall) => asked.min(wall),
10223 None => asked,
10224 }
10225 }
10226
10227 /// **THE POOL DEPTH** a fold's streams are fetched at when a request names none — the declared
10228 /// half of Q6b's chain.
10229 ///
10230 /// ```text
10231 /// (request depth) → field `depth` → container `depth` → the whole limit chain
10232 /// ```
10233 ///
10234 /// The first step is the REQUEST's and is therefore the resolver's, not a declaration's: what this
10235 /// answers is everything below it, which is what a resolver falls to when the request deferred.
10236 /// Falling to the limit chain rather than to a depth of its own is the same statement
10237 /// `Route::depth`'s `None` makes one grain up — *as deep as the answer is wide* — and it keeps an
10238 /// undepthed world byte-identical to the one before the knob existed.
10239 #[must_use]
10240 pub fn pool_depth(&self, kind: GraphqlKind, field: Option<&syn::Ident>) -> core::num::NonZeroU32 {
10241 let asked = field
10242 .and_then(|field| self.numbers_of(field))
10243 .and_then(|written| written.numbers.depth)
10244 .or(self.numbers.depth);
10245 match asked {
10246 Some(depth) => match self.declared_ceiling(field) {
10247 Some(wall) => depth.min(wall),
10248 None => depth,
10249 },
10250 // NO `min` REPEATED HERE: the limit chain has already been through the wall, and capping a
10251 // capped number twice is the same number.
10252 None => self.wire_first(kind, field),
10253 }
10254 }
10255}
10256
10257/// WHICH of an election's QUERY FIELDS a name is being asked for — a closed vocabulary of five, one
10258/// per road an election can mount and no more.
10259#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10260pub enum Field {
10261 /// `<index>By<Field>Keys` — one typed store, a QUESTION, ranked addresses.
10262 Keys,
10263 /// `<index>By<Field>` — the same question, HYDRATED: the upstream's whole entities.
10264 Hydrated,
10265 /// `<index>FusedBy<Field>Keys` — every store the field is written to, one leaderboard.
10266 Fused,
10267 /// `<index>SimilarBy<Field>Keys` — one typed store, an EXAMPLE KEY, ranked addresses without the
10268 /// example.
10269 Similar,
10270 /// `<index>SimilarBy<Field>` — the same example, HYDRATED: the neighbours' whole entities.
10271 SimilarHydrated,
10272}
10273
10274impl Field {
10275 /// Every road, in the order a refusal lists them — which is also the order the near-miss line
10276 /// measures a typo against, and the TIER ORDER of each pair: the keys rung first, its hydrated
10277 /// twin under it.
10278 ///
10279 /// [`RenamePiece::ALL`]'s twin one axis over, and the same law: the vocabulary and the reader are
10280 /// ONE list, so a word offered by a suggestion is a word the next compile reads.
10281 pub const ALL: [Self; 5] = [
10282 Self::Keys,
10283 Self::Hydrated,
10284 Self::Fused,
10285 Self::Similar,
10286 Self::SimilarHydrated,
10287 ];
10288
10289 /// The word a declaration writes to name this road's query field.
10290 #[must_use]
10291 pub const fn as_str(self) -> &'static str {
10292 match self {
10293 Self::Keys => "keys",
10294 Self::Hydrated => "hydrated",
10295 Self::Fused => "fused",
10296 Self::Similar => "similar",
10297 Self::SimilarHydrated => "similar_hydrated",
10298 }
10299 }
10300
10301 /// What a refusal calls the field this word is about — the half an author reading a sentence about
10302 /// their own typo needs, five roads being four more than anybody holds in their head.
10303 #[must_use]
10304 pub const fn what(self) -> &'static str {
10305 match self {
10306 Self::Keys => "the ranked addresses one typed store answers a question with",
10307 Self::Hydrated => "the same question answered with the upstream's whole entities",
10308 Self::Fused => "the one leaderboard every store this field is written to agrees on",
10309 Self::Similar => "the ranked addresses one typed store answers an EXAMPLE KEY with",
10310 Self::SimilarHydrated => "the same example answered with the neighbours' whole entities",
10311 }
10312 }
10313
10314 /// The road a path names, if it names one.
10315 #[must_use]
10316 pub fn of(path: &syn::Path) -> Option<Self> {
10317 Self::ALL
10318 .into_iter()
10319 .find(|road| path.is_ident(road.as_str()))
10320 }
10321
10322 /// The DERIVED name, before any declared word replaces it.
10323 ///
10324 /// Built from the declaration's rename-aware base rather than from its own ident, so
10325 /// `rename = "ShotSearch"` moves the field with the family — the same law every minted type name
10326 /// is under, at the one name that is a schema's rather than Rust's.
10327 ///
10328 /// # The shape is `{subject}{road?}By{election}{tier?}`, and the TIER NOUN is the law
10329 ///
10330 /// The user's ruling of 2026-08-16, uniform across all three families: **a keys-tier field wears
10331 /// the `Keys` noun, and the bare name is the hydrated twin's.** So the two slots are filled by two
10332 /// independent facts — the road word (`Fused`, `Similar`, or nothing for the question road) says
10333 /// WHICH road, and the tier noun says which TIER of it — and every road's pair of names differs by
10334 /// the noun alone.
10335 ///
10336 /// The fused road is the one that had to move: it published the bare name while no fused tier B
10337 /// existed to want it, which is a name that would have had to be renamed on the day one arrived.
10338 /// One rule over three families is what keeps that day from being a naming deadlock, and
10339 /// `{subject}FusedBy{election}` is now RESERVED rather than emitted.
10340 fn derived(self, base: &syn::Ident, field: &syn::Ident) -> String {
10341 use heck::{ToLowerCamelCase as _, ToUpperCamelCase as _};
10342
10343 let subject = base.to_string().to_lower_camel_case();
10344 let election = field.to_string().to_upper_camel_case();
10345 match self {
10346 Self::Keys => format!("{subject}By{election}Keys"),
10347 Self::Hydrated => format!("{subject}By{election}"),
10348 Self::Fused => format!("{subject}FusedBy{election}Keys"),
10349 Self::Similar => format!("{subject}SimilarBy{election}Keys"),
10350 Self::SimilarHydrated => format!("{subject}SimilarBy{election}"),
10351 }
10352 }
10353}
10354
10355/// The THREE PROJECTIONS one election's answer face binds — the width, the space and the element.
10356///
10357/// The `__…__` fence and the field spelled inside it, this crate's standing answer for every emitted
10358/// ident: two elections cannot mint one name and no declaration can collide with either. Distinct
10359/// from [`geometry`]'s pair on purpose — those live inside the expansion's OTHER anonymous const and
10360/// a name in one const is a name in one const.
10361fn answer_geometry(elected: &Elected) -> (syn::Ident, syn::Ident, syn::Ident) {
10362 let at = elected.field.span();
10363 let field = elected.field.to_string().to_uppercase();
10364 (
10365 format_ident!("__INGRAPH_ANSWER_WIDTH_{field}__", span = at),
10366 format_ident!("__INGRAPH_ANSWER_SPACE_{field}__", span = at),
10367 format_ident!("__INGRAPH_ANSWER_ELEMENT_{field}__", span = at),
10368 )
10369}
10370
10371/// **WHAT A CLIENT IS TOLD ABOUT THE FOLD** — the sentence both set legs publish, and the third of
10372/// the three places [`FoldSemantics::name`] is spent.
10373///
10374/// # The sentence cannot say WHICH fold ran, and it says so
10375///
10376/// SDL descriptions are built when the schema is compiled and the installed fold is a LAUNCH-time
10377/// fact, so a row naming the running fold would be a string the schema cannot know. What the
10378/// description can carry is the CHAIN — the deployment's seat, the election's word, and the citizen
10379/// both fall back to — plus where the running fold's own name is readable, which is the `fold` field
10380/// on this door's trace span. A dynamic wire row for it waits for an introspection home that does
10381/// not exist yet.
10382///
10383/// # And it says the request is not in the chain
10384///
10385/// A fold changes what the answer MEANS, so a client that read this sentence and looked for an
10386/// argument would be looking for a seat the ruling deliberately does not mint. Naming the absence is
10387/// cheaper for a schema reader than leaving it to be inferred from a field list.
10388///
10389/// [`FoldSemantics::name`]: ../../ingraph/retrieve/trait.FoldSemantics.html#tymethod.name
10390fn fold_note(field: &syn::Ident, asked: Asked) -> String {
10391 let m = match asked {
10392 Asked::Example => format!(
10393 "The `{field}` set is asked WHOLE: `m` is however many vectors the example holds, which is \
10394 this deployment's own data rather than anything a request states — so no number here bounds \
10395 it."
10396 ),
10397 Asked::Points(None) => format!(
10398 "`m` is however many points this request sent under `coordinates`, and this declaration wrote \
10399 no `streams` guard — so nothing here bounds it but the engine's own corpus. `{field}`'s \
10400 streams are walked one per point and folded once."
10401 ),
10402 Asked::Points(Some(guard)) => format!(
10403 "`m` is however many points this request sent under `coordinates`, and this declaration \
10404 admits at most {guard} of them: a question past that is REFUSED naming the count rather than \
10405 cut down to fit, because dropping query vectors answers a different question. `{field}`'s \
10406 streams are walked one per point and folded once.",
10407 guard = guard.get(),
10408 ),
10409 };
10410 format!(
10411 "WHICH FOLD runs is the DEPLOYMENT's and never the request's: it installs any `FoldSemantics` \
10412 for this pairing at launch, else this election's own `semantics(fold = …)` word answers, else \
10413 the framework's `Sum` — every query vector contributing its own \
10414 best. There is no argument for it here, because two answers of one corpus folded differently \
10415 cannot be compared against each other. The fold that actually ran names itself on this door's \
10416 `ingraph.query` span, under `fold`.\n\n{m}"
10417 )
10418}
10419
10420/// WHERE ONE SET ROAD'S `m` COMES FROM — which is what decides whether anything may bound it.
10421///
10422/// A vocabulary of two rather than a bool, because the second arm CARRIES the guard: the two facts a
10423/// reader of the published description needs are *who states `m`* and *what caps it*, and only one
10424/// of the two roads has an answer to the second.
10425#[derive(Debug, Clone, Copy)]
10426enum Asked {
10427 /// The example's own stored set — this deployment's data, which no request can inflate and no
10428 /// declared word bounds.
10429 Example,
10430 /// The points a REQUEST sent, with the declared `streams` guard over them where a tier wrote one.
10431 Points(Option<core::num::NonZeroU32>),
10432}
10433
10434/// The name the UPSTREAM's wire address is bound to inside an answer face's `const`.
10435///
10436/// One per declaration rather than one per election: every hit of every road carries the same
10437/// address, the upstream being the one thing a derived index draws from.
10438fn wire_key_name() -> syn::Ident {
10439 format_ident!("__INGRAPH_ANSWER_KEY__")
10440}
10441
10442/// The name the UPSTREAM's OWN key type is bound to inside an answer face's `const`.
10443///
10444/// [`wire_key_name`]'s twin at the other end of one address: that one is what a hit RENDERS into,
10445/// this one is what a by-example door TAKES — and the two are different types joined by a `From`,
10446/// which the plain road's crossing already spends. One per declaration for that one's reason.
10447fn example_key_name() -> syn::Ident {
10448 format_ident!("__INGRAPH_ANSWER_EXAMPLE__")
10449}
10450
10451/// The three names a HYDRATED road's projections are bound to — the upstream's database, its row in
10452/// that database, and the wire object that row raises into.
10453///
10454/// One per declaration, [`wire_key_name`]'s reason unchanged: every hydrated road of every election
10455/// reads the same upstream out of the same store. They are bound inside the `if_sqlx!` half alone —
10456/// see [`IndexModel::hydration_bindings`] — so a build without the SQL family has neither the names
10457/// nor anything that could resolve them.
10458fn hydration_names() -> (syn::Ident, syn::Ident, syn::Ident) {
10459 (
10460 format_ident!("__INGRAPH_ANSWER_DB__"),
10461 format_ident!("__INGRAPH_ANSWER_ROW__"),
10462 format_ident!("__INGRAPH_ANSWER_ENTITY__"),
10463 )
10464}
10465
10466/// ONE ELECTION's width and space, as the NAMES the expansion binds its projections to — see
10467/// [`IndexModel::geometry`], whose doc states the whole of it.
10468///
10469/// Free rather than a method because more than one emitter needs the same two tokens, so one home
10470/// keeps the spellings from drifting.
10471fn geometry(elected: &Elected) -> (syn::Ident, syn::Ident) {
10472 let at = elected.field.span();
10473 let field = elected.field.to_string().to_uppercase();
10474 (
10475 format_ident!("__INGRAPH_WIDTH_{field}__", span = at),
10476 format_ident!("__INGRAPH_SPACE_{field}__", span = at),
10477 )
10478}
10479
10480/// WHICH fields a full-text subject is about, as its doc line names them.
10481///
10482/// EMPTY for an empty set, which is the one case that never reaches a live emission — a full-text
10483/// declaration marking nothing is refused by name at the front end — and is reachable from a model
10484/// built by hand. An emission that read *every projection* here would be the dissolved posture
10485/// restated in the docs, so the sentence is built from the elections rather than from the fields.
10486fn searched(fields: &[syn::Ident]) -> String {
10487 if fields.is_empty() {
10488 return String::new();
10489 }
10490 format!(
10491 " in {}",
10492 fields
10493 .iter()
10494 .map(|field| format!("`{field}`"))
10495 .collect::<Vec<_>>()
10496 .join(", "),
10497 )
10498}
10499
10500/// ONE LEG of a `fanout` write — the names its parameters take, and the slot it writes.
10501///
10502/// A struct rather than a tuple, because six parallel `Vec`s over one index is exactly the shape
10503/// that drifts: the engine parameter, the three bindings and the marker have to describe ONE slot,
10504/// and here they are one value that cannot be zipped wrongly.
10505struct Leg {
10506 /// The engine TYPE PARAMETER this leg introduces.
10507 ///
10508 /// One per leg and never shared, which is the whole reason the fan is emitted rather than written
10509 /// generically: two engines are two types, and a signature that named one parameter twice would
10510 /// refuse the case the marker exists for.
10511 engine: syn::Ident,
10512 /// The branded handle's parameter name.
10513 handle: syn::Ident,
10514 /// The connection-and-write-context parameter's name.
10515 scope: syn::Ident,
10516 /// The entry's parameter name.
10517 doc: syn::Ident,
10518 /// The slot MARKER this leg's handle is branded with.
10519 marker: syn::Ident,
10520 /// The engine WORD, for the door's own doc line.
10521 word: String,
10522}
10523
10524/// The fan's error type: the legs' own errors, summed by right-nesting.
10525///
10526/// `Refused<A, Refused<B, C>>` for three legs, `A`'s own error for one. The nesting is the arity
10527/// mechanism — see [`Refused`](crate::engine) for why a wider enum per arity is refused — and this
10528/// is the one place its shape is decided, so the type a door returns and the arms
10529/// [`refusal_arm`] builds cannot disagree.
10530fn refusal_type(
10531 legs: &[Leg],
10532 refused: &proc_macro2::TokenStream,
10533 face: &proc_macro2::TokenStream,
10534) -> proc_macro2::TokenStream {
10535 let Some((first, rest)) = legs.split_first() else {
10536 // A fan with no leg is refused at the front end — `fanout` needs two engines to fan between —
10537 // so this is the shape of an unreachable model rather than a case.
10538 return quote!(::core::convert::Infallible);
10539 };
10540 let engine = &first.engine;
10541 let mine = quote!(<#engine as #face>::Error);
10542 if rest.is_empty() {
10543 return mine;
10544 }
10545 let theirs = refusal_type(rest, refused, face);
10546 quote!(#refused<#mine, #theirs>)
10547}
10548
10549/// The wrapper leg `at` of `legs` maps its error through, to reach [`refusal_type`]'s nesting.
10550///
10551/// `First` at its own depth, `Second` for every leg above it, and the LAST leg skips the `First`
10552/// because it is what the innermost `Second` already holds.
10553fn refusal_arm(
10554 at: usize,
10555 legs: usize,
10556 refused: &proc_macro2::TokenStream,
10557) -> proc_macro2::TokenStream {
10558 let binding = format_ident!("__ingraph_refused");
10559 let mut wrapped = if at + 1 == legs {
10560 quote!(#binding)
10561 } else {
10562 quote!(#refused::First(#binding))
10563 };
10564 for _ in 0..at {
10565 wrapped = quote!(#refused::Second(#wrapped));
10566 }
10567 quote!(|#binding| #wrapped)
10568}