Skip to main content

ingraph_codegen/
model.rs

1//! What a record means, once every rule has been checked — the shape [`crate::emit`] turns into
2//! tokens.
3//!
4//! A record's key is FLAT and it is `lineage ⊕ id`: the full path from the root, root-first, then
5//! the record's own id. Root-first is load-bearing rather than cosmetic: root attribution reads the
6//! leading column, and the blob address the key walks into nests its parents as directories, so a
7//! lineage-scoped removal is one prefix. [`Lineage::fields`] therefore preserves the order it was
8//! given.
9//!
10//! [`RecordModel`] is PLAIN: public fields, no constructor of its own, and nothing that parses. A
11//! derive builds one from a decorated declaration; `ingraph-compiler` will later build the same
12//! one from a manifest entry. Both reach the same emitter, and neither is this crate's business —
13//! which is also where VALIDATION lives, with whoever holds the source spans to report against.
14//!
15//! Emitted NAMES are resolved before they get here: the model says what each type is called, and
16//! the emitter does not decide. The convention those names default to lives here all the same
17//! ([`default_key_name`], [`default_lineage_name`]) so that every front end defaults alike rather
18//! than each keeping its own copy of the suffix rule.
19
20use core::fmt;
21
22use heck::ToSnakeCase as _;
23use quote::format_ident;
24use syn::ext::IdentExt as _;
25
26use crate::{
27  construct::{Build, Construction},
28  engine::Slot,
29  name::RustSafeName,
30  prefix::EmissionPrefix,
31};
32
33/// WHICH NODE a declaration is — one word per derive, carried past validation because the emission
34/// reads it too.
35///
36/// One node holds ONE storage and the MACRO IS the storage declaration, so the word answers both
37/// halves of that law at once: which storage family this declaration was allowed to name, and
38/// whether the emission mints the marker that makes a second one unspellable.
39///
40/// [`NodeKind::Operator`] is the base and every other kind is it plus a store, which is the order
41/// they are written in.
42///
43/// The last three are the DERIVED INDEXES, and what separates them from the RECORD FAMILY is not
44/// their storage but their KEY: each mints no `id` at all and carries its upstream's key instead,
45/// which is [`NodeKind::derives_its_key`] below. That is why they arrived with `upstream(…)` and
46/// could not have arrived before it — a kind with no way to name an upstream would have had no key
47/// to carry.
48///
49/// [`NodeKind::Entity`] and [`NodeKind::Record`] are the RECORD FAMILY's two upper rungs, and they
50/// differ in the storage essence alone: an entity bears an identity, an operator's whole compute
51/// surface and a WIRE FACE, and holds no rows. It is the tier the 22 declarations that wrote no
52/// storage block were already using without a word for it — measured on the way in — so it is the
53/// rowless path given its own macro rather than a new code path.
54///
55/// [`NodeKind::Aggregate`] is the record family's THIRD member and it names an upstream like a
56/// derived index does, which is why it sits between the two halves rather than in either. Its
57/// storage answers are the record's to the letter — rows, bare store words, a wire face, a key it
58/// mints — because its storage IS a record: the macro mints the `(group…, measure…)` row shape and
59/// hands it to the record pass, the `journal` pattern. What is its own is the GRAMMAR that fills
60/// those rows, and a grammar is not a storage fact.
61///
62/// That grammar has since ARRIVED and its EMISSION has not, which is the state worth stating rather
63/// than leaving a reader to infer: `#[ingraph::aggregate(…)]` mints [`NodeKind::Aggregate`], reads
64/// the whole declaration and refuses every rule it breaks by name — and then refuses an ACCEPTED one
65/// too, with a sentence saying the expansion that mounts the node is the task after it. So the word
66/// rows below are reached by an author's declaration now, and the only thing no caller reaches is an
67/// emission. They were answered before either half existed, and answered truthfully, because they
68/// are what the grammar got built AGAINST — a kind that reached a front end and only then discovered
69/// its own storage law would have been discovering it a task too late.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub enum NodeKind {
72  /// A graph node: it subscribes, it carries a watermark, and it owns no storage at all.
73  Operator,
74  /// An operator that PUBLISHES — an identity-bearing node with a wire face and no rows.
75  Entity,
76  /// An entity holding the META STORE — rows, in the databases its store words name.
77  Record,
78  /// A record whose rows are a declared FOLD over ONE upstream: one row per group, recomputed
79  /// WHOLE on every trigger.
80  ///
81  /// It consumes the upstream's TABLE rather than its messages, which is the whole safety
82  /// argument — duplicate delivery is normal operation here and an incremental count could not
83  /// inherit the keyed-replace theorem, so a trigger reads, groups, folds and upserts. Deletion
84  /// falls out of that for free.
85  Aggregate,
86  /// An operator holding a FULL-TEXT INDEX over an upstream's messages.
87  Fulltext,
88  /// An operator holding an EMBEDDING INDEX over an upstream's messages.
89  Vector,
90  /// An operator holding a FAMILY OF ARTIFACTS derived from an upstream's messages.
91  Blob,
92}
93
94impl NodeKind {
95  /// The MACRO that declares it — the word a refusal names when it sends an author to another
96  /// declaration, and the last segment of the attribute they write.
97  ///
98  /// The bare word rather than the whole attribute, because a refusal spells the two differently:
99  /// one names the macro (*declare them with the `vector` macro*) and one quotes what the author
100  /// typed (*`#[ingraph::operator]` supports structs only*).
101  #[must_use]
102  pub const fn as_str(self) -> &'static str {
103    match self {
104      Self::Operator => "operator",
105      Self::Entity => "entity",
106      Self::Record => "record",
107      Self::Aggregate => "aggregate",
108      Self::Fulltext => "fulltext",
109      Self::Vector => "vector",
110      Self::Blob => "blob",
111    }
112  }
113
114  /// What a refusal CALLS one of these — *record*, *operator*, *full-text index*.
115  ///
116  /// A front end's sentences are the same sentences whichever node broke the rule, so the noun is
117  /// the only part that varies and it lives with the vocabulary rather than being branched on in
118  /// each message.
119  #[must_use]
120  pub const fn noun(self) -> &'static str {
121    match self {
122      Self::Operator => "operator",
123      Self::Entity => "entity",
124      Self::Record => "record",
125      // The macro's own word reads as the noun, as the record family's other two do. The derived
126      // indexes need a second word because theirs are shorthands for a thing they are an index OF;
127      // an aggregate is not an index of anything.
128      Self::Aggregate => "aggregate",
129      Self::Fulltext => "full-text index",
130      Self::Vector => "embedding index",
131      Self::Blob => "artifact family",
132    }
133  }
134
135  /// [`NodeKind::noun`] in the plural, for the sentences that speak about the KIND rather than
136  /// about one declaration of it.
137  #[must_use]
138  pub const fn plural(self) -> &'static str {
139    match self {
140      Self::Operator => "operators",
141      Self::Entity => "entities",
142      Self::Record => "records",
143      Self::Aggregate => "aggregates",
144      Self::Fulltext => "full-text indexes",
145      Self::Vector => "embedding indexes",
146      Self::Blob => "artifact families",
147    }
148  }
149
150  /// The indefinite article [`NodeKind::noun`] takes.
151  ///
152  /// Here rather than at each message, and it is not pedantry: a sentence assembled with the wrong
153  /// one — *a operator* — is a refusal the reader trips over on their way to the rule, and the two
154  /// facts are one fact about the word.
155  #[must_use]
156  pub const fn article(self) -> &'static str {
157    match self {
158      Self::Operator | Self::Entity | Self::Aggregate | Self::Vector | Self::Blob => "an",
159      Self::Record | Self::Fulltext => "a",
160    }
161  }
162
163  /// The record-level BLOCK this node's own storage is declared in, or `None` for the kinds whose
164  /// storage is not a block at all.
165  ///
166  /// The WORD rather than a boolean, because the useful refusal is the inverse: every storage block
167  /// but this one is refused on this node, and a refusal that sends an author to the right
168  /// declaration has to map the word back to the derive that takes it.
169  ///
170  /// For the three derived indexes the word is the MACRO's own, which is the storage law read back:
171  /// `fulltext(…)` on anything else names an index that is a `fulltext` node, and on a `fulltext`
172  /// node it names that node's engines.
173  ///
174  /// **A RECORD ANSWERS `None`, and that is the unwrap read back.** Rows used to live inside
175  /// `persist(…)`; they are named BARE at the head now — `#[ingraph::record(sqlite, postgres)]` —
176  /// because storage is the record's ESSENCE and an essence does not wrap. So a record has no
177  /// storage block for anything to be refused against, and every block in this vocabulary is refused
178  /// on it. [`NodeKind::holds_rows`] is what asks the question this used to answer for a record.
179  #[must_use]
180  pub const fn storage_block(self) -> Option<&'static str> {
181    match self {
182      // An AGGREGATE answers `None` for a record's reason, arrived at the same way: its store words
183      // are bare at the head because its storage is a record's, so it has no block of its own and
184      // every block in this vocabulary is refused on it.
185      Self::Operator | Self::Entity | Self::Record | Self::Aggregate => None,
186      Self::Fulltext => Some("fulltext"),
187      Self::Vector => Some("vector"),
188      Self::Blob => Some("blob"),
189    }
190  }
191
192  /// Whether this node holds ROWS — the record family's top rung, and the only kind whose store
193  /// words sit bare at the head.
194  ///
195  /// Stated rather than derived from [`NodeKind::storage_block`], which no longer answers it: the
196  /// unwrap took the record's storage out of a block, so *has a block called `persist`* and *holds
197  /// rows* stopped being one question. Every refusal that used to compare the block name to
198  /// `"persist"` asks this instead.
199  ///
200  /// Written as an exhaustive MATCH rather than a `matches!` for [`NodeKind::stores`]' reason, and
201  /// the fourth kind is what made the difference visible: an aggregate holds rows, so silence here
202  /// would have refused its own store words at the head — the very words its grammar takes.
203  #[must_use]
204  pub const fn holds_rows(self) -> bool {
205    match self {
206      Self::Operator | Self::Entity | Self::Fulltext | Self::Vector | Self::Blob => false,
207      // The b1 ruling read back: an aggregate's storage IS a record's, so `sqlite` sits bare at its
208      // head exactly as it does at a record's, and `table`/`rename` are its to name.
209      Self::Record | Self::Aggregate => true,
210    }
211  }
212
213  /// The FIELD MARKER this kind elects its subject with, or `None` for a kind that elects nothing.
214  ///
215  /// `knn` on a `vector` and `searchable` on a `fulltext`, one law under two words: presence elects
216  /// the field, absence leaves it stored-not-indexed payload, and a declaration that marks none is
217  /// refused by name. A `blob` answers an ADDRESS rather than a ranking, so it has no subject to
218  /// elect and takes neither word; the record family declares no fields of this tier at all.
219  ///
220  /// The WORD rather than a boolean, for [`NodeKind::storage_block`]'s reason: the refusals that
221  /// spend this have to NAME the marker — the one a declaration should have written, and the one it
222  /// wrote on a kind that does not take it.
223  ///
224  /// # An AGGREGATE marks its fields and still answers `None`, which is a tier and not an oversight
225  ///
226  /// An aggregate's fields carry roles — one names a group column, one names a measure — so the
227  /// reflex is to spell one of those words here. It would be the wrong tier. What this word names is
228  /// the INDEX SUBJECT: the only reader is the derived-index grammar, and what it does with the
229  /// answer is decide which field grows a corpus, an engine leg and a resource binding. An aggregate
230  /// has none of those — its roles say which column is KEY and which is VALUE, which is the row
231  /// shape, and the row shape is the record family's tier. Answering a word here would enrol the
232  /// kind in the engine machinery on the strength of a spelling.
233  ///
234  /// The roles land in the grammar task, and their WORDS are that task's to settle against the house
235  /// register — the design leaves open which word the measure block takes and whether the block and
236  /// the field marker share one. Nothing here is spent on them, so nothing here can pre-empt it.
237  #[must_use]
238  pub const fn election(self) -> Option<&'static str> {
239    match self {
240      Self::Operator | Self::Entity | Self::Record | Self::Aggregate | Self::Blob => None,
241      Self::Fulltext => Some("searchable"),
242      Self::Vector => Some("knn"),
243    }
244  }
245
246  /// Whether this node's key is the UPSTREAM's rather than its own — the derived-index half of the
247  /// family.
248  ///
249  /// The definitional split, and the one that decides which model a declaration becomes: a node that
250  /// mints an `id` emits a `*Key` type of its own and reaches
251  /// [`RecordModel`], and one that carries an upstream's key emits neither and reaches
252  /// [`IndexModel`](crate::index::IndexModel). *The key is not its to mint* is the ruling, and this
253  /// is the word for it.
254  ///
255  /// Stated over the kinds rather than derived from [`NodeKind::storage_block`], because the two are
256  /// independent facts that happen to agree today: a record stores and mints, an operator does
257  /// neither, and a kind that stored without minting or minted without storing would be a coherent
258  /// thing to add.
259  ///
260  /// **An AGGREGATE names an upstream and still answers `false`**, which is the whole reason this
261  /// word is stated over kinds rather than read off the grammar. Naming an upstream is what the
262  /// derived indexes arrived with, so the shape looks like theirs; the KEY is not theirs. A derived
263  /// index carries the upstream's key because every one of its entries is an entry ABOUT one
264  /// upstream row. An aggregate's row is about a GROUP, and the group is a projection its own
265  /// declaration names — so the key it emits is its own, minted from the group columns, and it
266  /// reaches [`RecordModel`] like the rest of the record family. *The key is not its to mint* is not
267  /// true of it.
268  #[must_use]
269  pub const fn derives_its_key(self) -> bool {
270    match self {
271      Self::Operator | Self::Entity | Self::Record | Self::Aggregate => false,
272      Self::Fulltext | Self::Vector | Self::Blob => true,
273    }
274  }
275
276  /// Whether this kind may wear `graphql(…)` — the DRESSING axis, which crosses the storage one
277  /// rather than following it.
278  ///
279  /// A record and an entity both publish; an operator does not. That is the whole of what separates
280  /// the two rowless kinds, and it is a real separation rather than a spare word: a dressed rowless
281  /// node publishes its ADDRESS, which is what a search declaration over it projects through
282  /// (`<<<Upstream as Transformer>::Graphql as Graphql>::Output as GraphqlOutput>::Key`), and an
283  /// undressed one binds `Graphql = ()` for which that projection does not resolve. The KEYS tier of
284  /// every election over an entity stands on this word.
285  ///
286  /// The three derived indexes answer `false` here and take `graphql(…)` anyway: their block is
287  /// their own grammar's, read by [`crate::index`], and this predicate is `record_options`' alone.
288  ///
289  /// An AGGREGATE answers `true` and reaches the wire through the record publication path — the
290  /// storage sugar read forward, since a kind whose rows are a record's rows publishes them the way
291  /// a record does. Written as an exhaustive MATCH rather than a `matches!` for
292  /// [`NodeKind::stores`]' reason: this word gates whether `graphql(…)` is accepted at the head at
293  /// all, so a kind that took the answer by silence would have had its declared wire face refused.
294  #[must_use]
295  pub const fn dressable(self) -> bool {
296    match self {
297      Self::Operator | Self::Fulltext | Self::Vector | Self::Blob => false,
298      Self::Entity | Self::Record | Self::Aggregate => true,
299    }
300  }
301
302  /// Whether this kind's declared type is itself a MESSAGE — a value a producer GIVES on an edge,
303  /// and therefore a thing an acked give can be answered FOR.
304  ///
305  /// The `receipt = "…"` word's gate, and the whole of the re-key that put the word here: a receipt
306  /// is a property of what is GIVEN rather than of who receives it. One message asks one question
307  /// and every seat on the far end answers that same one, so the type belongs to the declaration
308  /// that MINTS the message — an `entity` is this framework's own word for that (*the message
309  /// node*), a `record` is an entity with rows, and an `aggregate` is a record whose rows are a
310  /// fold. All three declare a type that travels.
311  ///
312  /// The other four answer `false`, for two different reasons worth keeping apart. An OPERATOR is
313  /// the node family's BASE: it computes, it publishes no address, and what goes on its out-edge is
314  /// its `Operator::Out` rather than itself — there is no operator value on any wire to be given.
315  /// The three DERIVED INDEXES are indexes OF somebody else's messages and carry that upstream's
316  /// key, which [`NodeKind::derives_its_key`] is the word for — so a receipt declared on one would
317  /// be an answer to a question another declaration asked.
318  ///
319  /// Stated over the kinds as an exhaustive MATCH rather than derived from [`NodeKind::dressable`],
320  /// which happens to agree today: *publishes a wire address* and *is a message* are two facts, and
321  /// a kind that flowed without dressing would be a coherent thing to add.
322  #[must_use]
323  pub const fn mints_a_message(self) -> bool {
324    match self {
325      Self::Operator | Self::Fulltext | Self::Vector | Self::Blob => false,
326      Self::Entity | Self::Record | Self::Aggregate => true,
327    }
328  }
329
330  /// Whether this node holds a storage, and therefore whether its emission mints the one-storage
331  /// marker — see [`one_storage_marker`].
332  ///
333  /// It was DERIVED from [`NodeKind::storage_block`] while the two agreed, and the unwrap ended
334  /// that: a record's storage is no longer a block, so deriving this would have silently stopped
335  /// marking the kind whose marker matters most. Stated over the kinds, exhaustively, so a kind
336  /// added later cannot take an answer by silence.
337  ///
338  /// It is also the LANDING fact the convergence reads — `Effect::Lands` and the write lane beside
339  /// it, in [`emit::declared`](crate::emit) — and the ladder made that honest rather than only
340  /// preserving it. A record with no storage block used to answer `true` here, because the answer
341  /// was a fact about the KIND and every record's kind said it stored; so a declaration that named
342  /// nowhere still claimed a write lane it did not have, and the validate walk never called it the
343  /// pure leaf it was. A record now HAS a store by construction and an entity is the rowless rung,
344  /// so the two readings of this word have stopped being able to disagree.
345  #[must_use]
346  pub const fn stores(self) -> bool {
347    match self {
348      Self::Operator | Self::Entity => false,
349      // An AGGREGATE has a store by construction exactly as a record does — the row table its
350      // trigger upserts into — so it mints the one-storage marker and claims the write lane the
351      // convergence reads. Its lane is a WHOLE REWRITE per trigger rather than a row per message,
352      // which the landing fact does not distinguish and does not need to: what it says is that
353      // something lands here.
354      Self::Record | Self::Aggregate | Self::Fulltext | Self::Vector | Self::Blob => true,
355    }
356  }
357}
358
359/// A validated record: what it is called, what it emits, and every field it declares.
360#[derive(Debug, Clone)]
361pub struct RecordModel {
362  /// The EMISSION NAMESPACE this declaration's minted names wear.
363  ///
364  /// [`EmissionPrefix::INGRAPH`] for everything `ingraph`'s own front ends build, and a domain
365  /// framework's own mark for a model `mediagraph-codegen` or its successors build — see
366  /// [`crate::prefix`] for what the seat covers and why it is a field rather than a constant.
367  pub prefix: EmissionPrefix,
368  /// The record's own name — the declaration this model came from.
369  pub record: syn::Ident,
370  /// WHICH node this is — the derive it was written under.
371  ///
372  /// A MODEL fact rather than a parser one because the emission spends it: the one-storage marker
373  /// is minted for the kinds that store and for no other, and nothing else in the emitted output
374  /// could tell them apart.
375  pub kind: NodeKind,
376  /// How visible the record is — and therefore how visible each emitted type and each of its
377  /// fields is.
378  ///
379  /// Mirrored rather than fixed at `pub`: a private record whose key were public would have
380  /// leaked into its crate's public API without anyone writing it, and no one can widen a type
381  /// they did not declare.
382  pub vis: syn::Visibility,
383  /// Whether the declaration OPTED IN to the shutdown's goodbye — `teardown` on its own attribute.
384  ///
385  /// A fact about the VALUE a launch constructs rather than about anything emitted beside it: what
386  /// this node's `AsyncTeardown` impl says is the author's, and what the expansion does with the word is
387  /// demand that there be one. The launch entry's own emission reads it again, to enrol the built
388  /// value in the chain.
389  pub teardown: bool,
390  /// The MODE WORD, where the declaration wrote one — `async` on its own attribute, and the path
391  /// kept for its SPAN.
392  ///
393  /// A bare declaration is on the blocking face, so the absence is the ordinary state and `None` is
394  /// what says it. The word carries no value, which is why the presence alone is the whole fact —
395  /// but unlike [`teardown`](Self::teardown), which collapses to a `bool` the moment it is parsed,
396  /// this keeps the `syn::Path` all the way here ON PURPOSE: the audit it emits has to blame the
397  /// word, and a `bool` has no span for a caret to land on.
398  pub asynchronous: Option<syn::Path>,
399  /// The FACE WORD, where the declaration wrote one — `stream` on its own attribute, and the path
400  /// kept for its SPAN.
401  ///
402  /// A DIFFERENT AXIS from [`asynchronous`](Self::asynchronous), and the two multiply rather than
403  /// compete: this one picks the PAIR — [`Operator`]/[`AsyncOperator`] against
404  /// [`StreamOperator`]/[`AsyncStreamOperator`] — and that one picks which HALF of whichever pair
405  /// was chosen. So `stream` alone names the blocking streaming face and `stream, async` names the
406  /// awaited one, with no mode word of its own: the mode vocabulary already existed, and a second
407  /// spelling of it would be a second authority for one fact.
408  ///
409  /// The `syn::Path` is kept all the way here for [`asynchronous`](Self::asynchronous)'s reason: the
410  /// audit it emits has to blame the word, and a `bool` has no span for a caret to land on.
411  ///
412  /// [`Operator`]: https://docs.rs/ingraph/latest/ingraph/trait.Operator.html
413  /// [`AsyncOperator`]: https://docs.rs/ingraph/latest/ingraph/trait.AsyncOperator.html
414  /// [`StreamOperator`]: https://docs.rs/ingraph/latest/ingraph/trait.StreamOperator.html
415  /// [`AsyncStreamOperator`]: https://docs.rs/ingraph/latest/ingraph/trait.AsyncStreamOperator.html
416  pub streaming: Option<syn::Path>,
417  /// The KIND WORD, where the declaration wrote one — `autonomous` on its own attribute, and the
418  /// path kept for its SPAN.
419  ///
420  /// The PAIR axis's THIRD value, on [`streaming`](Self::streaming)'s own axis rather than beside
421  /// it: a declaration wears exactly one kind, so `autonomous` and `stream` are refused together
422  /// and the mode word multiplies with either — `autonomous` alone names the blocking autonomous
423  /// face and `autonomous, async` names the awaited one.
424  ///
425  /// What the word buys is a body that OWNS ITS OWN LOOP: select order, arm priority, intake
426  /// gating, batching, ack timing and internal workers are the node's rather than a driver's. The
427  /// `syn::Path` is kept all the way here for [`asynchronous`](Self::asynchronous)'s reason.
428  ///
429  /// [`AutonomousOperator`]: https://docs.rs/ingraph/latest/ingraph/trait.AutonomousOperator.html
430  /// [`AsyncAutonomousOperator`]: https://docs.rs/ingraph/latest/ingraph/trait.AsyncAutonomousOperator.html
431  pub autonomous: Option<syn::Path>,
432  /// Whether the declaration opted its outputs into the ROOT PROJECTION — `attributed` on its own
433  /// attribute.
434  ///
435  /// A `bool` rather than a kept `syn::Path`, on [`teardown`](Self::teardown)'s precedent and for
436  /// its reason: nothing this word emits blames the word back. What it writes is one member of the
437  /// facts trait, and a projection that cannot take a root out of this node's output is refused at
438  /// the MOUNT with the payload named — a caret on the word here would point at a declaration that
439  /// is not the one to fix.
440  ///
441  /// A SEPARATE axis from every word above it. The pair, the mode and the kind say what a body IS;
442  /// this says what the framework does with what the body EMITS, so it composes with all of them
443  /// and refuses none.
444  pub attributed: bool,
445  /// The path to the `ingraph` crate itself — `::ingraph` unless `#[ingraph(crate = "…")]` named
446  /// another.
447  ///
448  /// Every framework name an expansion writes is rooted here, and every one of them continues
449  /// `::__private::<module>::<item>` with no exception: the projection traits an accessor qualifies
450  /// through (`#krate::__private::project::Repeated`), the interpretation → filter map a wire
451  /// filter names (`#krate::__private::graphql::ToGraphqlFilter`), and the serde derives a MongoDB
452  /// document
453  /// carries (`#krate::__private::serde::Serialize`) together with the `#[serde(crate = "…")]`
454  /// string that points serde's own expansion at the same place. `RecordModel::framework` and
455  /// `RecordModel::vendored` are the only two places that spend it.
456  ///
457  /// `crate = "…"` exists because an expansion lands in the DECLARER's namespace, where `::ingraph`
458  /// may not be the framework: the dependency may be renamed, or reached through a re-export shim
459  /// that vendors it under another path. Retargeting the root moves every emitted path at once, so
460  /// a declaration states it once and no emitted path has to be spelled by hand.
461  pub krate: syn::Path,
462  /// `remote = "path::To::Type"` — the FOREIGN TYPE this declaration is a transparent wrapper over,
463  /// or `None` for the ordinary declaration that IS its fields.
464  ///
465  /// Its presence is the REWRITE MODE, and it changes what the declaration's own fields MEAN rather
466  /// than adding anything beside them: they stop being storage and become a MANIFEST — the shape of
467  /// the wrapped type as this framework needs to read it — while the item the compiler sees is
468  /// `#[repr(transparent)] struct X(Remote);`. Every face downstream is unchanged, because a
469  /// manifest column carries exactly what a declared column carried; what moves is where a value is
470  /// READ FROM (the remote's own accessor, crossed by `Into`) and how one is BUILT (the remote's own
471  /// constructor), which is [`crate::remote`]'s whole content.
472  ///
473  /// A `syn::Path` rather than a `syn::Type`: a wrapper's inner type is a named type and nothing
474  /// else — a reference, a slice or a generic instantiation has no accessor family to read a
475  /// manifest through — and the path is EMITTED, so one naming nothing is `E0412` at the string the
476  /// author wrote.
477  pub remote: Option<syn::Path>,
478  /// `builder(…)` — HOW the wrapped type is built, where the declaration described it.
479  ///
480  /// The default value is the default LAW rather than an absence: `Remote::new(<required columns>)`
481  /// followed by one `.with_<name>(…)` per `optional` one, which is what the rewrite mode emitted
482  /// before the vocabulary existed and what it still emits for a declaration that writes no word.
483  /// So this is never an `Option` — see [`Construction`] for the words that move it, and for why
484  /// the DESCRIBING side takes a smaller vocabulary than a generating one.
485  ///
486  /// Meaningful only under [`remote`](Self::remote): an ordinary declaration IS its fields and is
487  /// built by a struct literal, so there is no protocol there for a word to describe. `ingraph-
488  /// derive` refuses one written on such a declaration by name rather than leaving it inert.
489  pub construction: Construction,
490  /// The key type: its name and its columns.
491  pub key: Key,
492  /// The lineage type, or `None` for a root record.
493  ///
494  /// The type and its name are born together and die together, which is why they are one option
495  /// rather than a name beside a possibly-empty list: a root emits no `*Lineage` type, so a root
496  /// has no lineage name to hold.
497  pub lineage: Option<Lineage>,
498  /// EVERY field the record declares, in declared order — the record gets an inherent impl of its
499  /// own, so unmarked data fields reach it too.
500  pub fields: Vec<Field>,
501  /// Where the record is PERSISTED, or `None` for a pure-compute record.
502  ///
503  /// Absence by omission, with no sentinel: a declaration that writes no `persist(…)` block is not
504  /// stored in any persist database, which is the same shape [`RecordModel::lineage`] uses for a root.
505  pub persist: Option<Persist>,
506  /// The ONE order-by type — [`default_order_by_name`] unless `graphql(order_by(rename = "…"))`
507  /// named it.
508  ///
509  /// HERE rather than on [`Graphql`], and the move is the point: an ordering term's content is
510  /// mechanical from the STORED columns and its lowering is pure SQL, so no part of it is a wire
511  /// fact. It sat inside the wire face because that is where the type happened to be declared, and
512  /// the cost was a persist-only record with no term type to name and therefore no page at all.
513  ///
514  /// A name unconditionally, whether or not the record is stored — a model carries what its type
515  /// would be called, and [`RecordModel::ordering`] is the one place that decides whether the type
516  /// is written. The RENAME is still spelled inside the `graphql(…)` block, which is a fact about
517  /// the grammar rather than about this slot: the word has always lived there and moving it would
518  /// break every declaration that writes one.
519  pub order_by: RustSafeName,
520  /// The record's PROGRESS ledger, or `None` when it is stored nowhere a ledger ships.
521  ///
522  /// DERIVED rather than declared, by whichever front end built this model: the ledger is a table in
523  /// the persist engine's own pool, so being stored is the whole of what makes one exist.
524  pub progress: Option<Progress>,
525  /// The record's WIRE face, or `None` when it is not exposed.
526  ///
527  /// Absence by omission again. A [`Graphql`] can only exist beside a [`RecordModel::persist`]: a wire
528  /// field with no stored source cannot be populated by a read, so the parser refuses the one
529  /// without the other.
530  pub graphql: Option<Graphql>,
531  /// The REVERSE positions this record declares — `derived(tracks = "media::VideoTrack", …)` — in
532  /// the order they were written.
533  ///
534  /// Empty rather than `None`, unlike every neighbour above: a reverse position declares no TYPE,
535  /// so there is nothing whose absence a `None` would be standing for. What a `derived` entry
536  /// produces is an AUDIT and a wire position later; the list of them is the whole fact.
537  pub derived: Vec<Derived>,
538  /// The ARTIFACT families this record answers an address for — `locate(cover = "media::Cover", …)`
539  /// — in the order they were written.
540  ///
541  /// [`RecordModel::derived`]'s sibling and its mirror image, which is why it stands beside it
542  /// rather than inside it: a reverse position names a record that points BACK at this one through
543  /// a `ref` column, and an artifact position names a blob node that was DERIVED FROM this one's
544  /// messages. Neither declares a Rust field, both mint one word on this record's wire face, and
545  /// the two share a namespace for exactly that reason — so the front end refuses a `locate` word
546  /// that repeats a `derived` word, and vice versa, before either reaches this model.
547  ///
548  /// Empty rather than `None`, for [`RecordModel::derived`]'s reason: an artifact position declares
549  /// no TYPE of its own, so there is nothing whose absence a `None` would stand for. What the
550  /// OWNING expansion does with each entry is write the field into its own `#[Object]`, which is
551  /// what keeps the blob node's macro out of a coherence argument it cannot win.
552  pub artifacts: Vec<Artifact>,
553  /// `implements(…)` — the INTERFACES this record declares itself a member of, in the order they
554  /// were written.
555  ///
556  /// Empty rather than `None`, for [`RecordModel::derived`]'s reason: a membership declares no TYPE,
557  /// so there is nothing whose absence a `None` would stand for. What each entry produces is one
558  /// impl of `Implements<Interface>`, which is the EVIDENCE an interface's own expansion asserts —
559  /// the two derives cannot see each other, so an interface claiming a membership its member never
560  /// agreed to would be a promise made on somebody else's behalf.
561  ///
562  /// A PATH rather than a resolved type, for the reason [`Derived::source`] is one: every
563  /// consequence of it is type-level, so an alias in the path is transparent and nothing here has to
564  /// know what it resolves to.
565  pub implements: Vec<syn::Path>,
566  /// `error(<db> = "path::To")` — the type every fallible conversion over this record answers with,
567  /// per backend. Empty is the boxed refusal at every one of them.
568  pub errors: Vec<BackendError>,
569  /// `subscribe = "path::To::Upstream"` — the node whose messages drive this one, or `None` for a
570  /// source that is driven by nothing inside the graph.
571  ///
572  /// A PATH rather than a resolved type, for [`RecordModel::implements`]'s reason and one more of
573  /// its own: nothing here can resolve it, since the upstream is another declaration's and the two
574  /// derives cannot see each other. What the emission does with it is emit it, and the COMPILER
575  /// resolves it there — an unresolved path is `E0412` and a path naming something that is not a
576  /// node is `E0277`, both at the declaration that wrote the string.
577  ///
578  /// One upstream and not a list. Several are the FUSION and FAN-IN shapes, which name their
579  /// upstreams with `upstream(…)` entries because each carries a designation this spelling has no room
580  /// for; [`RecordModel::fusion`] is where those land, and a declaration writing both is refused.
581  pub subscribe: Option<syn::Path>,
582  /// The `upstream(…)` entries — the upstreams this node draws from — or `None` for a node driven by
583  /// one upstream or by none.
584  ///
585  /// Beside [`RecordModel::subscribe`] rather than replacing it, because the two are different
586  /// declarations rather than one written twice: `subscribe` names an edge and says nothing about
587  /// where this node's identity comes from, where a `upstream(…)` block says which upstreams there
588  /// are AND how this node's lineage relates to them.
589  pub upstreams: Option<Upstreams>,
590  /// The `subscribe(…)` CONTAINER — every upstream this node's fan-in draws from, in the order they
591  /// were written, or `None` where the declaration wrote none.
592  ///
593  /// A different axis from [`RecordModel::upstreams`], which is why it is a field of its own rather
594  /// than a third arm of [`Upstreams`]: the top-level `upstream(…)` entries say where this node's
595  /// IDENTITY comes from, and the container says how its INTAKE is shaped — which upstreams arrive
596  /// independently, which are joined by key before the body sees them, and which product of a
597  /// multi-product upstream an edge carries.
598  pub subscriptions: Option<Subscription>,
599  /// `emits = "…"` / `emits = ["…", "…"]` — the products this node puts on its edges, in the
600  /// order they were written, or `None` where the declaration named none and the product is the
601  /// declared struct itself.
602  pub products: Option<Products>,
603  /// `options = "path::To::Options"` — the type a deployment's section for this node deserializes
604  /// into, or `None` where the declaration wrote none.
605  ///
606  /// A PATH rather than a resolved type, for [`RecordModel::subscribe`]'s reason: nothing here can
607  /// resolve it, and the compiler resolves it where the expansion lands.
608  ///
609  /// `None` means `()` and not *unknown*. A node with no knobs writes no word, and the emitted
610  /// `Declared::Options` for it is the unit type — which is what its `AsyncConstructor` already spells,
611  /// and what the emitted equation pins the two to.
612  pub options: Option<syn::Path>,
613  /// `poll(<name>, …)` — the node's OWN clocks, in the order they were written, or `None` where it
614  /// declared none, which is most nodes.
615  ///
616  /// Beside [`RecordModel::subscriptions`] rather than inside it, and the ruling is explicit about
617  /// why: a poll source is not an upstream. A tick is a WAKE — it moves no message, it touches no
618  /// `In` enum, and what the node does with it is read through the handles it already holds. So it
619  /// is the node's own word at container level, and what it buys is a vocabulary of its own.
620  pub polls: Option<Polls>,
621  /// `tracing(level = …)` — the level this node's framework spans and its emitted query entries
622  /// open at, or `None` where the declaration wrote no word.
623  ///
624  /// Absence by omission, with no sentinel, which is the shape every optional block here uses: a
625  /// declaration that says nothing is a node at the framework's own default, and the EMISSION says
626  /// nothing either — the const is written only where the word was, so `Declared::TRACING`'s own
627  /// default is what a silent node reads. One default, in one place.
628  ///
629  /// The word parses in every build and this field is filled in every build. What rides `ingraph`'s
630  /// feature is what the emitter DOES with it, which is why nothing about this type is conditional.
631  pub tracing: Option<TracingLevel>,
632  /// `receipt = "path::To::Type"` — the value this node hands BACK to the producer of an acked
633  /// give, or `None` where the declaration wrote none, which is most nodes.
634  ///
635  /// A PATH rather than a resolved type, for [`RecordModel::options`]'s reason exactly: nothing here
636  /// can resolve it, and the compiler resolves it where the expansion lands — at the string the
637  /// author wrote, because [`syn::LitStr::parse`] respans onto the literal.
638  ///
639  /// **`None` means the node states no receipt, and it is NOT `()`.** This is where the word parts
640  /// from `options`, and the difference is the whole of the opt-in seat: `Declared::Options` is a
641  /// member every node fills, so a silent one fills it with the unit type; `Receipts` is a SIBLING
642  /// trait, so a silent node gets no impl at all and every non-receipting operator pays nothing —
643  /// no line, no seat, no bound. See `ingraph`'s own `Receipts` for why the seat is a sibling rather
644  /// than a defaulted member of `Operator` (associated-type defaults are unstable, `E0658`).
645  pub receipt: Option<syn::Path>,
646}
647
648/// The LEVEL a node's spans open at — the closed vocabulary `tracing(level = …)` writes.
649///
650/// A CLOSED unit enum, because the vocabulary is `tracing`'s own five and nothing else can be a
651/// level: a sixth word would name something no subscriber could filter on. That is the same test
652/// [`Label`] and [`DatabaseKind`] are measured by, and the reason this is an enum where an engine or
653/// a backend is a trait.
654///
655/// It mirrors `ingraph`'s own `TracingLevel` word for word, which is what makes the emission
656/// mechanical: the model's variant is the framework's variant, spelled through
657/// [`as_str`](Self::as_str) into the path an expansion writes. The DEFAULT lives at the framework
658/// end alone — `Declared::TRACING`'s own — so this type has none, and a model carrying `None` is a
659/// declaration that wrote no word rather than one that wrote the default.
660#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
661pub enum TracingLevel {
662  /// `tracing(level = trace)`.
663  Trace,
664  /// `tracing(level = debug)`.
665  Debug,
666  /// `tracing(level = info)`.
667  Info,
668  /// `tracing(level = warn)`.
669  Warn,
670  /// `tracing(level = error)`.
671  Error,
672}
673
674impl TracingLevel {
675  /// Every level, in `tracing`'s own order — finest first.
676  pub const ALL: [Self; 5] = [
677    Self::Trace,
678    Self::Debug,
679    Self::Info,
680    Self::Warn,
681    Self::Error,
682  ];
683
684  /// The word a declaration writes — and, capitalised by the emitter, the framework variant it
685  /// names. The two are one string here so a renamed level cannot mean two things.
686  #[must_use]
687  pub const fn as_str(self) -> &'static str {
688    match self {
689      Self::Trace => "trace",
690      Self::Debug => "debug",
691      Self::Info => "info",
692      Self::Warn => "warn",
693      Self::Error => "error",
694    }
695  }
696
697  /// The level this word names, or `None` where the word is not one of them.
698  #[must_use]
699  pub fn named(word: &str) -> Option<Self> {
700    Self::ALL.into_iter().find(|level| level.as_str() == word)
701  }
702
703  /// The framework variant's own spelling — `trace` is `Trace`.
704  ///
705  /// Derived from [`as_str`](Self::as_str) rather than written a second time, so the word a
706  /// declaration writes and the variant an expansion names can never drift apart.
707  #[must_use]
708  pub fn variant(self) -> syn::Ident {
709    let word = self.as_str();
710    let mut capitalised = String::with_capacity(word.len());
711    for (at, letter) in word.chars().enumerate() {
712      if at == 0 {
713        capitalised.extend(letter.to_uppercase());
714      } else {
715        capitalised.push(letter);
716      }
717    }
718    format_ident!("{capitalised}")
719  }
720
721  /// `tracing`'s OWN constant for this level — `trace` is `TRACE`.
722  ///
723  /// A third spelling of one word, derived from the same string for [`variant`](Self::variant)'s
724  /// reason. It is a separate reader because the two name different things: that one names this
725  /// framework's vocabulary, and this one names the LIBRARY's, which an emitted `span!` has to spell
726  /// as a constant because that macro builds its metadata in a `static`.
727  #[must_use]
728  pub fn constant(self) -> syn::Ident {
729    format_ident!("{}", self.as_str().to_uppercase())
730  }
731}
732
733/// The `poll(…)` entries: a node's own clocks, entry by entry.
734///
735/// DECLARATION ORDER IS THE CONTRACT. A poll source is a POSITION in the runtime's schedule, and
736/// the position an entry lands at is the order it was written in — so the emitted `<Node>Due`
737/// translates one into the other and an author never counts.
738#[derive(Debug, Clone)]
739pub struct Polls {
740  /// The entries, in declaration order.
741  pub entries: Vec<PollEntry>,
742}
743
744impl Polls {
745  /// The entries that GRANT, each with its POSITION IN THE WHOLE SCHEDULE, in declaration order.
746  ///
747  /// The position is the schedule's and not the granting subset's, because that is what a tick
748  /// carries: `PollUpstream` is a position among ALL of a node's clocks, so a route keyed on anything
749  /// else would send a granting clock's tick to the wrong entry the day an ungranted clock is
750  /// declared before it.
751  ///
752  /// Written once and read from both the collision table and the emitter, because the two must
753  /// agree entry for entry: a name registered for a clock the emitter skips would refuse a
754  /// declaration for a clash no expansion can make.
755  pub fn granting(&self) -> impl Iterator<Item = (usize, &PollEntry)> {
756    self
757      .entries
758      .iter()
759      .enumerate()
760      .filter(|(_, entry)| entry.grants.is_some())
761  }
762
763  /// The entries that are `<Node>Sweeps` METHODS — the ones that wrote `light` — each with its
764  /// position in the whole schedule, in declaration order.
765  ///
766  /// [`granting`](Self::granting)'s sibling over the other axis, and the PRESENCE SPLIT is read off
767  /// it: an empty answer is a node whose every clock runs a mounted body, which emits no sweep trait
768  /// at all. Written once and read from the collision table and the emitter for `granting`'s reason
769  /// — a name registered for a trait the emitter skips would refuse a declaration for a clash no
770  /// expansion can make.
771  pub fn sweeping(&self) -> impl Iterator<Item = (usize, &PollEntry)> {
772    self
773      .entries
774      .iter()
775      .enumerate()
776      .filter(|(_, entry)| !entry.mounted())
777  }
778}
779
780/// ONE `poll(…)` entry: the name it MINTS, and the clock it runs on.
781#[derive(Debug, Clone)]
782pub struct PollEntry {
783  /// The bare ident the entry minted, as the declaration wrote it.
784  ///
785  /// MINT BARE, by the round's law: this name refers to nothing — no upstream, no type, no other
786  /// declaration — it is a word this entry brings into being so the author can match on it. The
787  /// bare-marker precedent, one axis over.
788  pub name: syn::Ident,
789  /// The word this entry takes in the emitted `<Node>Due` — [`name`](Self::name) in upper camel
790  /// case, which is how a Rust variant is spelled.
791  pub variant: syn::Ident,
792  /// Exactly one of the two schedule words, already read.
793  pub cadence: PollCadence,
794  /// `write = "…"` / `write = ["…", "…"]` — the stores THIS CLOCK's ticks are granted, in the order
795  /// they were written, or `None` where the entry granted itself none.
796  ///
797  /// INSIDE the entry, by the ruling that moved the word here: a permission is spent BY A TICK, so
798  /// it is seated at the clock whose ticks spend it. Two clocks sharing a store write the word
799  /// twice and get two contexts — explicit repetition over one list nobody can read a clock's reach
800  /// off, and it is what makes least privilege structural: deleting an entry deletes its grants.
801  pub grants: Option<Grants>,
802  /// WHO runs this clock's ticks — the settled answer to the entry's mandatory body word.
803  ///
804  /// It is the PRESENCE SPLIT's only input. An entry that mounted leaves `<Node>Sweeps` entirely —
805  /// there is no method for it, because the body is not the operator's — and a node all of whose
806  /// entries mounted emits no sweep trait at all.
807  pub body: PollBody,
808  /// WHERE this clock's tick runs. Mandatory on every entry: a role is DECLARED rather than
809  /// inferred, so there is no default and no second spelling of one.
810  pub mode: PollMode,
811  /// The bare `concurrent` word — free concurrency for a sync-detached entry, where the default is
812  /// at most one tick in flight.
813  ///
814  /// Meaningful only on [`PollMode::Spawn`] and [`PollMode::Rayon`]; every other mode refuses it by
815  /// name, so a `true` here always names one of those two.
816  pub concurrent: bool,
817}
818
819impl PollEntry {
820  /// Whether this entry MOUNTS a citizen — the presence split's own question.
821  #[must_use]
822  pub const fn mounted(&self) -> bool {
823    self.body.mounted()
824  }
825}
826
827/// WHO runs one poll entry's ticks — the two roads a clock's mandatory body word names.
828///
829/// # A closed vocabulary, so an enum
830///
831/// The house rule, and this seat is where it had been paid for with an `Option<syn::Path>` instead.
832/// `None` meant *the entry wrote `light`* rather than *nothing is known*, which the grammar
833/// guarantees with three refusals — an entry naming neither word, an entry naming both, and a
834/// `light` entry in a detached mode — so no unstated state ever reached the model. What the `Option`
835/// cost was that the guarantee lived in a comment: a reader of the field had to be told which of
836/// two meanings the empty case carried, and a caller writing `entry.handler.is_none()` was spelling
837/// *light* in a way nothing checked.
838///
839/// The arms say it instead. `Light` is a WORD and not an absence, and [`Citizen`](Self::Citizen)
840/// carries the one thing the other road has to name.
841#[derive(Debug, Clone)]
842pub enum PollBody {
843  /// The bare `light` — the tick runs a `<Node>Sweeps` method on the node's own operator, which the
844  /// driver lends for the call and takes back.
845  Light,
846  /// `handler = "app::PromScraper"` — a CITIZEN the deployment builds, ticked through its own face.
847  ///
848  /// A PATH for [`Grant::node`]'s reason: nothing here can resolve it, the type being the
849  /// application's, and the compiler resolves it where the expansion lands.
850  Citizen(syn::Path),
851}
852
853impl PollBody {
854  /// The citizen this body mounts, or [`None`] where it is the operator's own.
855  ///
856  /// The accessor every consumer spends, so the match on the arms is written once. Its shape is the
857  /// old field's on purpose — what changed is that the empty case now has a NAME at the seat that
858  /// decides it, rather than a paragraph at the seat that stored it.
859  #[must_use]
860  #[inline]
861  pub const fn citizen(&self) -> Option<&syn::Path> {
862    match self {
863      Self::Light => None,
864      Self::Citizen(path) => Some(path),
865    }
866  }
867
868  /// Whether this body is a mounted citizen — the presence split's own question, asked of the body.
869  #[must_use]
870  #[inline]
871  pub const fn mounted(&self) -> bool {
872    matches!(self, Self::Citizen(_))
873  }
874}
875
876/// WHERE one poll entry's tick runs — the mandatory word, and the whole of the vocabulary.
877///
878/// # A closed unit enum, and the framework-open law is why rather than an exception
879///
880/// The five words are the 2×2 of WORLD (sync / async) by PLACE (here / elsewhere), plus the one
881/// engine that earned a word of its own. What is OPEN is the ENGINE behind each detached word —
882/// `Spawn` and `AsyncSpawn` are seams a third-party pool implements and a deployment
883/// installs — so a new executor costs no word here. That is the same division the store engines
884/// keep: the vocabulary is the grammar's, the implementation is the seam's.
885#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
886pub enum PollMode {
887  /// `block` — sync, ON THE DRIVER'S OWN THREAD. The tick's answer reaches the taps.
888  Block,
889  /// `spawn` — sync, DETACHED to a thread (the shipped `Thread` citizen).
890  Spawn,
891  /// `rayon` — sync, DETACHED to rayon's pool (the shipped `Rayon` citizen, behind the runtime
892  /// crate's `rayon` feature).
893  Rayon,
894  /// `async(inline)` — AWAITED in the driver's loop. Today's behaviour, now said out loud.
895  AsyncInline,
896  /// `async(spawn)` — DETACHED as a task on whichever `AsyncSpawn` the deployment installed.
897  AsyncSpawn,
898}
899
900impl PollMode {
901  /// Every mode, in the order a refusal offers them — the two INLINE roads first, because they are
902  /// the ones an entry with no handler may take.
903  pub const ALL: [Self; 5] = [
904    Self::Block,
905    Self::AsyncInline,
906    Self::Spawn,
907    Self::Rayon,
908    Self::AsyncSpawn,
909  ];
910
911  /// The word a declaration writes, and the word a refusal names.
912  #[must_use]
913  pub const fn as_str(self) -> &'static str {
914    match self {
915      Self::Block => "block",
916      Self::Spawn => "spawn",
917      Self::Rayon => "rayon",
918      Self::AsyncInline => "async(inline)",
919      Self::AsyncSpawn => "async(spawn)",
920    }
921  }
922
923  /// Whether the body is SYNC — which decides whether the mount's bound is `Tick` or
924  /// `AsyncTick`, and which write family a granted store is reached through.
925  #[must_use]
926  pub const fn blocking(self) -> bool {
927    matches!(self, Self::Block | Self::Spawn | Self::Rayon)
928  }
929
930  /// Whether the tick LEAVES the driver — which decides whether the handler and its context are
931  /// cloned per tick, and whether the seat can answer anything at all.
932  #[must_use]
933  pub const fn detached(self) -> bool {
934    matches!(self, Self::Spawn | Self::Rayon | Self::AsyncSpawn)
935  }
936
937  /// Whether the AT-MOST-ONE-IN-FLIGHT default governs it — the sync-detached family, and the only
938  /// place the `concurrent` word has a seat.
939  #[must_use]
940  pub const fn lapses(self) -> bool {
941    matches!(self, Self::Spawn | Self::Rayon)
942  }
943}
944
945/// The clock ONE poll entry runs on — an interval, or a calendar expression.
946///
947/// An enum rather than two options, because the grammar makes them exclusive: an entry writes
948/// `every = "…"` or `cron = "…"` and never both or neither, so a pair of `Option`s would leave two
949/// states nothing means.
950#[derive(Debug, Clone)]
951pub enum PollCadence {
952  /// `every = "…"` — a fixed interval, read by the ONE duration grammar ([`crate::duration`]) and
953  /// already known to be positive.
954  Every(std::time::Duration),
955  /// `cron = "…"` — a calendar expression, with the zone it is read in.
956  Calendar {
957    /// The expression as the declaration wrote it, in the classic five-field dialect.
958    expression: String,
959    /// `tz = "<IANA>"` where the entry named one; `None` is the system zone, resolved where the
960    /// program RUNS rather than where it was compiled.
961    zone: Option<String>,
962  },
963}
964
965/// The `write` word: the stores ONE poll entry granted its ticks, grant by grant.
966///
967/// DECLARATION ORDER IS THE CONTRACT here too, for a different reason than [`Polls`]': a poll entry's
968/// order is the position its ticks arrive under, and a grant's order is the order that clock's
969/// emitted context takes its type parameters and constructor arguments in. Reordering the word
970/// therefore reorders a `new` call, which is why it is the declaration's order and not a sorted one
971/// — the author reads their own list back.
972#[derive(Debug, Clone)]
973pub struct Grants {
974  /// The grants, in declaration order.
975  pub grants: Vec<Grant>,
976}
977
978/// ONE `write` grant: the node it names, and the accessor that names it back.
979#[derive(Debug, Clone)]
980pub struct Grant {
981  /// The granted node, as a PATH — for [`RecordModel::subscribe`]'s reason: nothing here can resolve
982  /// it, the store being another declaration's, and the compiler resolves it where the expansion
983  /// lands.
984  pub node: syn::Path,
985  /// The granted node's MOUNT NAME — the path's last segment, folded to snake case, which is the
986  /// word the emitted accessor is built from (`media` mints `media_write`).
987  ///
988  /// Read off the declaration rather than declared, because the derive that writes the grant cannot
989  /// see the derive that declares the store: the last segment is the only name both ends hold. Two
990  /// grants IN ONE ENTRY whose mounts agree are refused at the front end; two entries granting the
991  /// same store are legal and hold it in two contexts.
992  pub mount: RustSafeName,
993}
994
995/// The `subscribe(…)` container: a node's whole FAN-IN, entry by entry.
996///
997/// One [`Upstream`] per `upstream(…)` inside it, in the order written — which is the order the
998/// emitted `In` enum's variants take, and the order a keyed group's payloads sit in.
999#[derive(Debug, Clone)]
1000pub struct Subscription {
1001  /// The entries, in declaration order.
1002  pub upstreams: Vec<Upstream>,
1003}
1004
1005impl Subscription {
1006  /// The entries that carry the bare word `key` — THE keyed group, in declaration order.
1007  ///
1008  /// One group per container and structurally so: `key` joins THE group rather than opening one, so
1009  /// there is no second group to name and no word that would name it. A `group(…)` word arrives if
1010  /// a declaration ever needs two.
1011  pub fn keyed(&self) -> impl Iterator<Item = &Upstream> {
1012    self.upstreams.iter().filter(|source| source.keyed)
1013  }
1014
1015  /// The entries that carry no `key` — each one an independent flow, one `In` variant apiece.
1016  pub fn straight(&self) -> impl Iterator<Item = &Upstream> {
1017    self.upstreams.iter().filter(|source| !source.keyed)
1018  }
1019
1020  /// Whether this container needs an emitted `In` type at all.
1021  ///
1022  /// A single straight source is TODAY'S WORLD: one upstream, one message type, and the bare type
1023  /// is what an author writes for `In`. An enum there would be a one-variant wrapper around a type
1024  /// that already exists. Anything else — several upstreams, or a keyed group of any size — is a sum,
1025  /// because what arrives is one of several things.
1026  #[must_use]
1027  pub fn is_sum(&self) -> bool {
1028    self.upstreams.len() > 1 || self.keyed().next().is_some()
1029  }
1030}
1031
1032/// ONE entry of a `subscribe(…)` container: an upstream, how it arrives, and which of its products
1033/// this edge carries.
1034#[derive(Debug, Clone)]
1035pub struct Upstream {
1036  /// The upstream node, as the declaration spelled it.
1037  ///
1038  /// A PATH carried verbatim and resolved nowhere, for [`RecordModel::subscribe`]'s reason: the
1039  /// variant's payload is a projection through it, so the compiler resolves it at the declaration
1040  /// that wrote the string.
1041  pub node: syn::Path,
1042  /// Whether the entry carried the bare word `key` — that it joins THE keyed group.
1043  pub keyed: bool,
1044  /// `out = "<Variant>"` — which product of a multi-product upstream this edge carries, or `None`
1045  /// where the upstream emits one and the question does not arise.
1046  pub out: Option<syn::Ident>,
1047  /// The name this entry takes in the emitted `In` enum.
1048  ///
1049  /// The upstream path's last segment, or — where `out = …` selected one product of several — the
1050  /// PRODUCT's own variant word: that is the name the declaration wrote for this edge, and it is
1051  /// what keeps two products of ONE node apart without a word the grammar does not have yet.
1052  pub variant: syn::Ident,
1053  /// `channel = bounded(512)` / `channel = unbounded` — the AUTHOR'S DEFAULT for this edge, or
1054  /// `None` where the declaration said nothing.
1055  ///
1056  /// A default and not a law: a deployment's `[node.channels]` block overrides it, kind included,
1057  /// and what stands where neither speaks is the framework's shipped constant. `None` is therefore a
1058  /// state of its own rather than a stand-in for the constant — it is *this declaration said
1059  /// nothing*, which is what lets the layer under it be reached at all.
1060  pub channel: Option<ChannelOptions>,
1061  /// `changes(<db>)` / `changes(<db>(external))` — the STORE's own change feed as this edge's
1062  /// intake, or [`None`] where the edge takes the ordinary channel.
1063  ///
1064  /// The default is the channel, so this is a state of its own rather than a stand-in: what a
1065  /// declaration says by writing nothing is *messages*, and a store's feed is what it says by naming
1066  /// a database.
1067  pub changes: Option<ChangesFeed>,
1068  /// Whether the entry carried the bare word `notify` — that this edge carries the landed entity's
1069  /// KEY rather than the entity.
1070  ///
1071  /// The RECEIPT, and it is the consumer's to choose per entry: the upstream emits its product once
1072  /// and the wiring projects `(key, T) → key` at the send site, so one store legally feeds a
1073  /// message-receipt consumer and a notify-receipt one at the same time. Both modes are under the
1074  /// same protocol law — only committed items, after the commit, in commit order — which is what
1075  /// makes the key a SEQUENCING receipt rather than a smaller message.
1076  pub notify: bool,
1077}
1078
1079/// A CHANGE FEED as an edge's intake: which database's feed, and whose hand fills it.
1080///
1081/// # The feeder is part of the word, because it is the one fact a feed cannot report
1082///
1083/// A change feed says what arrived; it never says who put it there. So *somebody lands into that
1084/// store* is a claim the declaration makes and the launch walk holds it to — absent `external` it is
1085/// a claim about THIS graph, and a deployment where nothing lands into the watched store earns the
1086/// three-road refusal rather than a listener that waits forever reporting nothing.
1087///
1088/// `external` says the hand is outside this process, and with that the two-process shape is a
1089/// first-class citizen: the dependence reads in the declaration, and the check stands down because
1090/// the answer is somewhere the walk cannot look.
1091///
1092/// # The database is NAMED, and a bare `changes` is refused
1093///
1094/// Which databases an upstream stores in is the UPSTREAM's declaration, and two macro expansions
1095/// cannot see each other — so a bare `changes` would be a word this grammar could not resolve and
1096/// would have to guess at. The refusal says so, which is the same wall every referring word in this
1097/// grammar is on the other side of.
1098#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1099pub struct ChangesFeed {
1100  /// Which database's feed — one block, per the axis law that puts per-database knobs inside the
1101  /// database's own block.
1102  pub database: DatabaseKind,
1103  /// `external` — the hand that fills the watched store is outside this process.
1104  pub external: bool,
1105}
1106
1107/// WHAT an edge is opened as, as the declaration wrote it — the framework's own
1108/// [`ChannelOptions`](https://docs.rs/ingraph) vocabulary, mirrored here because the front end cannot
1109/// depend on the crate it emits for.
1110///
1111/// Two words and no third: the closed vocabulary is the whole of the channel axis, an overflow
1112/// posture belonging to the policy seam and a wait discipline to the engine.
1113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1114pub enum ChannelOptions {
1115  /// `bounded(n)` — a queue of at most `n` deliveries, where a full one is backpressure.
1116  Bounded(usize),
1117  /// `unbounded` — a queue nothing bounds, where a send never waits and memory is the only limit.
1118  Unbounded,
1119}
1120
1121impl Upstream {
1122  /// The FIELD this source takes in the emitted `[node.channels]` shelf, and the key a document
1123  /// writes it under.
1124  ///
1125  /// The P1 naming law, one axis over: the word this edge is already known by — the upstream type's
1126  /// own name, or the product's where `out = "…"` selected one — in snake case. Read off the
1127  /// declaration rather than declared, so a rename moves the document's key with the type it names
1128  /// and there is no second vocabulary to keep in step.
1129  #[must_use]
1130  pub fn shelf(&self) -> RustSafeName {
1131    shelf_name(&self.variant)
1132  }
1133}
1134
1135/// The shelf field ONE variant word takes — its snake case, kept spellable where that is a keyword.
1136///
1137/// A free function beside [`Upstream::shelf`] because the front end needs it BEFORE an `Upstream`
1138/// exists: two entries whose shelf names would collide are refused while the list is still being
1139/// built, and refusing them requires the name the collision is about.
1140#[must_use]
1141pub fn shelf_name(variant: &syn::Ident) -> RustSafeName {
1142  RustSafeName::new(variant.unraw().to_string().to_snake_case(), variant.span())
1143}
1144
1145/// `emits`: the products a node puts on its edges.
1146///
1147/// SELF-DECLARED, and it has to be: two derives cannot see each other, so a node's downstream
1148/// cannot tell it what it produces, and a subscription is a CONNECTION rather than a declaration of
1149/// what flows. What the word buys is the sum a multi-product node's `Out` becomes, the vocabulary
1150/// naming its arms, and the per-product edges its wire set holds.
1151#[derive(Debug, Clone)]
1152pub struct Products {
1153  /// The products, in the order they were written — which is the index every part of the machinery
1154  /// counts on: the `Wanted` bit, the wire set's edge, the `Emits<N>` row a downstream projects
1155  /// through.
1156  pub products: Vec<Product>,
1157}
1158
1159impl Products {
1160  /// Whether this node's `Out` is a SUM — several products — rather than the one type it names.
1161  #[must_use]
1162  pub fn is_sum(&self) -> bool {
1163    self.products.len() > 1
1164  }
1165}
1166
1167/// ONE product: the type that travels, and the word that names it.
1168#[derive(Debug, Clone)]
1169pub struct Product {
1170  /// The message type, as the declaration spelled it. Resolved by the compiler where the expansion
1171  /// lands, which is the declarer's OWN scope — a product is this node's type, not another
1172  /// declaration's, so no wall is crossed here.
1173  pub ty: syn::Path,
1174  /// The product's identity — the type path's last segment, and the variant word both the `Out`
1175  /// enum and its vocabulary take.
1176  pub variant: syn::Ident,
1177}
1178
1179/// How a node with several upstreams RELATES to them — the mode the bare word `key` selects.
1180///
1181/// One word, two topologies, and the difference is what a message coming out means. Written, the
1182/// upstreams JOIN: their messages make one output, whose identity descends from the designated
1183/// parent. Absent, they are INDEPENDENT: each upstream's messages make their own outputs, and which
1184/// upstream a row came from is part of its address.
1185///
1186/// An enum rather than two options, because the two are exclusive by construction — the designation
1187/// is present or it is not — and a pair of `Option`s would leave a fourth state nothing means.
1188#[derive(Debug, Clone)]
1189pub enum Upstreams {
1190  /// `key` on one entry: the upstreams join, and this node's lineage mirrors that parent's key.
1191  Fused(Fusion),
1192  /// No `key`: the upstreams are independent, and this node's lineage is a CHOICE among them.
1193  Fanned(FanIn),
1194}
1195
1196impl Upstreams {
1197  /// Every upstream this node names — the list the subscription audit is emitted over.
1198  ///
1199  /// One walk for both modes, because the claim it discharges is the same one either way: this path
1200  /// names a node.
1201  pub fn upstreams(&self) -> Box<dyn Iterator<Item = &syn::Path> + '_> {
1202    match self {
1203      Self::Fused(fusion) => Box::new(fusion.upstreams()),
1204      Self::Fanned(fanned) => Box::new(fanned.kinds.iter().map(|kind| &kind.node)),
1205    }
1206  }
1207
1208  /// The FUSION, where this node is one.
1209  #[must_use]
1210  pub const fn fused(&self) -> Option<&Fusion> {
1211    match self {
1212      Self::Fused(fusion) => Some(fusion),
1213      Self::Fanned(_) => None,
1214    }
1215  }
1216
1217  /// The FAN-IN, where this node is one.
1218  #[must_use]
1219  pub const fn fanned(&self) -> Option<&FanIn> {
1220    match self {
1221      Self::Fanned(fanned) => Some(fanned),
1222      Self::Fused(_) => None,
1223    }
1224  }
1225}
1226
1227/// Several upstreams producing INDEPENDENT outputs — M×N, N ≤ M.
1228///
1229/// The body stays a struct, because the payload is uniform: what differs between two of this node's
1230/// messages is where it came from, not what it holds. So the variation lives entirely in the
1231/// LINEAGE, which becomes a choice among the upstreams rather than a path through one.
1232#[derive(Debug, Clone)]
1233pub struct FanIn {
1234  /// One entry per upstream, in the order they were written — which is the order the lineage type's
1235  /// variants take, so a declaration read top to bottom is the type read top to bottom.
1236  pub kinds: Vec<Kind>,
1237}
1238
1239/// One upstream of a fan-in: the node, and the word that names it everywhere a discriminant is
1240/// spelled.
1241#[derive(Debug, Clone)]
1242pub struct Kind {
1243  /// The upstream node, as the declaration spelled it.
1244  ///
1245  /// A PATH carried verbatim and resolved nowhere, for [`RecordModel::subscribe`]'s reason: the
1246  /// lineage variant's payload is `<this as Transformer>::Key`, so the compiler resolves it at the
1247  /// declaration that wrote the string.
1248  pub node: syn::Path,
1249  /// The variant's name — the upstream path's LAST segment, which is the type's own name.
1250  ///
1251  /// The path is what a reader has in front of them, so the word is read off it rather than
1252  /// declared: `upstream(node = "asr::Segment")` is the `Segment` variant, and two upstreams whose
1253  /// last segments agree are refused at the declaration rather than colliding inside the emitted
1254  /// enum.
1255  pub variant: syn::Ident,
1256}
1257
1258/// A FUSING node's upstreams: the several messages that jointly make one output, and which of them
1259/// this node's identity descends from.
1260///
1261/// Provenance of the upstreams that are NOT the key parent needs nothing here, and the absence is
1262/// the ruling: it is opt-in, spelled as ordinary `ref = "…"` fields, which is the reference grammar
1263/// every record already has. Deriving a column from a topology fact is the one thing this grammar
1264/// never does.
1265#[derive(Debug, Clone)]
1266pub struct Fusion {
1267  /// The DESIGNATED KEY PARENT — the upstream whose key this node's lineage mirrors, written `key`
1268  /// on exactly one `upstream(…)` entry.
1269  pub parent: syn::Path,
1270  /// The upstreams the fusion joins BESIDE the key parent, in the order they were written. Empty
1271  /// where one entry carries the whole fusion.
1272  pub others: Vec<syn::Path>,
1273  /// One entry per LINEAGE column: the column, and the parent-key field it equals.
1274  ///
1275  /// Complete by construction — a fusion with no `lineage(…)` block is refused, and every column of
1276  /// the block it does write becomes an entry — so the emitted equation names the whole lineage type
1277  /// and a column left out of it would be `E0063` rather than a silently narrower check.
1278  pub mirrors: Vec<Mirror>,
1279}
1280
1281impl Fusion {
1282  /// Every upstream this node names, key parent first — the list the subscription audit is emitted
1283  /// over.
1284  pub fn upstreams(&self) -> impl Iterator<Item = &syn::Path> {
1285    core::iter::once(&self.parent).chain(&self.others)
1286  }
1287}
1288
1289/// One lineage column, and the field of the parent's key it equals.
1290#[derive(Debug, Clone)]
1291pub struct Mirror {
1292  /// The column as the LINEAGE type names it — after `lineage(rename = "…")`, since that is the
1293  /// name the emitted struct literal writes.
1294  pub column: syn::Ident,
1295  /// The parent key's field it is read from.
1296  ///
1297  /// The record field's own name where the two agree, and otherwise the ident parsed out of
1298  /// `<field>(source = "…")` — respanned to the string literal, so every error the equation reports
1299  /// about a mapping lands where the author wrote it.
1300  pub from: syn::Ident,
1301}
1302
1303impl RecordModel {
1304  /// The field a FAN-IN node's ancestry rides in, for the echo to append — or `None` for a node
1305  /// whose ancestry is a path its declaration wrote.
1306  ///
1307  /// The mint lives HERE, beside the model that reads it back, for `IndexModel::carried_key`'s
1308  /// reason: the name, the type and the visibility are one decision, and the party that appends the
1309  /// field is not the party that spends it.
1310  #[must_use]
1311  pub fn fanned_lineage(&self) -> Option<syn::Field> {
1312    use syn::parse::Parser as _;
1313
1314    let lineage = self.lineage.as_ref()?;
1315    matches!(lineage.shape, Shape::Kinds(_)).then(|| {
1316      let (name, ty) = (fanned_lineage(&self.prefix), &lineage.name);
1317      syn::Field::parse_named
1318        .parse2(quote::quote!(pub(crate) #name: #ty))
1319        .expect("a named field")
1320    })
1321  }
1322
1323  /// The error the fallible impls of ONE CELL answer with: the declared type, or the boxed refusal.
1324  ///
1325  /// A cell is a (crossing, database) pair, which is what makes the identity uniform WITHIN an impl
1326  /// and independent BETWEEN them: every fallible leg the row's own `TryFrom` spends names one type,
1327  /// every leg the crossing onto the wire spends names one, and a declaration may make those two
1328  /// different without saying anything twice.
1329  ///
1330  /// The boxed default is what a row's conversions already answered with, and it is the honest one:
1331  /// a row's columns may each fail differently and no type names all of them. `core`'s blanket
1332  /// `From` over it is also what makes an undeclared `?` compile without anybody writing a bound.
1333  #[must_use]
1334  pub fn error(&self, crossing: Crossing, kind: DatabaseKind) -> proc_macro2::TokenStream {
1335    match self
1336      .errors
1337      .iter()
1338      .find(|error| error.crossing == crossing && error.kind == kind)
1339    {
1340      Some(error) => {
1341        let path = &error.path;
1342        quote::quote!(#path)
1343      }
1344      None => boxed_error(),
1345    }
1346  }
1347
1348  /// The OPERAND converter one FIELD's declaration named for `kind` — the declared half of the
1349  /// filter crossing — or `None` where the column takes the stored type's own [`TryFrom`].
1350  ///
1351  /// Keyed on the record FIELD rather than on a column, because that is where the word is written
1352  /// and because a column is one DATABASE's view of the same field: `graphql(input(comparison(…)))`
1353  /// is a wire-side declaration and there is one wire face per record, so the legs live on
1354  /// [`GraphqlField::input_crossing`] and each names the database whose row it crosses into.
1355  ///
1356  /// A column that is stored and NOT exposed has no wire field to carry a word, so it takes the
1357  /// default chain — which is the same answer as an exposed field that declared nothing.
1358  #[must_use]
1359  pub fn operand(&self, source: &syn::Ident, kind: DatabaseKind) -> Option<&Conversion> {
1360    self
1361      .graphql
1362      .as_ref()?
1363      .backends
1364      .first()?
1365      .fields()
1366      .iter()
1367      .find(|field| &field.source == source)?
1368      .input_crossing
1369      .leg(kind)
1370  }
1371
1372  /// The CONDITION a record field is declared under — [`Condition::always`] for one that wrote no
1373  /// `#[cfg]`, and for a name no field of this declaration carries.
1374  ///
1375  /// Looked up on the FIELD by name rather than carried on [`PersistColumn`], because a condition is
1376  /// the declaration's own fact and a column is one database's view of it: four copies of one
1377  /// predicate is four copies that can drift, and the field is the single place it was written.
1378  /// Every emitter that holds a column also holds the model — the per-database walks all take one —
1379  /// so the lookup is reachable everywhere the gate is needed.
1380  #[must_use]
1381  pub fn condition(&self, source: &syn::Ident) -> Option<&Condition> {
1382    self
1383      .fields
1384      .iter()
1385      .find(|field| &field.column.source == source)
1386      .map(|field| &field.condition)
1387  }
1388
1389  /// The `#[cfg(…)]` to prefix onto ONE artifact of a record field — empty where it wrote none, and
1390  /// empty for a name this declaration does not carry.
1391  ///
1392  /// The spelling every emitter uses, so a site gates by interpolating one token stream rather than
1393  /// by asking a question and branching. An unconditional declaration interpolates nothing, which is
1394  /// what keeps its expansion identical to the one before this seat existed.
1395  #[must_use]
1396  pub fn gate(&self, source: &syn::Ident) -> proc_macro2::TokenStream {
1397    self
1398      .condition(source)
1399      .map(Condition::gate)
1400      .unwrap_or_default()
1401  }
1402
1403  /// `1` or `0` for a record field, as a `const` expression — the term an ORDINAL's running sum adds.
1404  #[must_use]
1405  pub fn present(&self, source: &syn::Ident) -> proc_macro2::TokenStream {
1406    self
1407      .condition(source)
1408      .map_or_else(|| quote::quote!(1usize), Condition::present)
1409  }
1410
1411  /// Whether ANY field of this declaration is conditional.
1412  ///
1413  /// The switch between the two shapes an ORDINAL is written in: a declaration with no condition
1414  /// gets the literal positions it has always got — byte for byte the expansion of before this seat
1415  /// — and one with a condition gets the `const` running sum. Two shapes rather than always the
1416  /// second, because the sum is only correct-and-necessary where something can be absent, and an
1417  /// expansion that grew a chain of `const`s for every record in the world would be paying for a
1418  /// case it does not have.
1419  #[must_use]
1420  pub fn conditional(&self) -> bool {
1421    self
1422      .fields
1423      .iter()
1424      .any(|field| !field.condition.always_present())
1425  }
1426}
1427
1428/// The key MongoDB stores a record's id under.
1429///
1430/// The SERVER's name and not this framework's: MongoDB mints an `_id` for every document that
1431/// arrives without one and indexes it uniquely, so a document carrying that beside a declared `id`
1432/// would be one row with two identities and the wrong one indexed.
1433///
1434/// It is a `&str` here and again in `ingraph`'s own `comparison::mongo::ID`, which are two crates
1435/// and therefore two constants — the emitter cannot name a runtime item of the framework in a
1436/// string literal, and the framework cannot depend on the emitter. What keeps them one fact is that
1437/// each has ONE reader: this one is spent by `DatabaseBackend::external`, and that one by
1438/// `field_key`. `ingraph-codegen`'s own `tests::the_mongo_document_reads_the_id_out_of_underscore_id`
1439/// reads the emitted spelling back.
1440pub const MONGO_ID: &str = "_id";
1441
1442/// The refusal a fallible crossing answers with when the declaration named none.
1443///
1444/// The honest default: a row's columns may each fail differently and no type names all of them.
1445/// `core`'s blanket `From` over it is also what makes an undeclared `?` compile without anybody
1446/// writing a bound — and it is the boundary `sqlx`'s own `ColumnDecode` presents, so a decode and
1447/// a crossing report through one shape.
1448///
1449/// One home, because a second family of crossings defaults to the same type — an interface's
1450/// computed field is fallible on its own terms and answers with this where its declaration says
1451/// nothing — and two spellings of one default is how one of them drifts.
1452#[must_use]
1453pub fn boxed_error() -> proc_macro2::TokenStream {
1454  // Assembled in two steps so the formatter has nothing to wrap: laid out across lines inside one
1455  // `quote!`, rustfmt puts a trailing comma after `'static` and the expansion carries it.
1456  let bounds = quote::quote!(::core::error::Error + ::core::marker::Send + ::core::marker::Sync);
1457  quote::quote!(::std::boxed::Box<dyn #bounds + 'static>)
1458}
1459
1460/// The type ONE DATABASE stores a column at: the declared pin, or the domain type.
1461///
1462/// The uniform domain→row mapping, and the ONE place it is decided. A declaration that writes no
1463/// `type = "…"` for a database stores the type the field itself carries — which is what a row's own
1464/// field takes, and what an INTERFACE's row equation reads that field back at. Two readings of one
1465/// default would be two things that can come to disagree about a column nobody renamed.
1466#[must_use]
1467pub const fn stored_type<'a>(
1468  stored: Option<&'a syn::Type>,
1469  domain: &'a syn::Type,
1470) -> &'a syn::Type {
1471  match stored {
1472    Some(stored) => stored,
1473    None => domain,
1474  }
1475}
1476
1477/// One REVERSE position: a record that points at this one, under the name this record calls it by.
1478///
1479/// There is no Rust field for one, ever — no storage, no field, no lie. The declaration names a
1480/// SOURCE and the framework already knows how the two meet, because the source's own declaration
1481/// said so; what this adds is the name the position is reached under and, where the source points
1482/// back through several fields, which of them this position means.
1483#[derive(Debug, Clone)]
1484pub struct Derived {
1485  /// The position's name — the word the declaration wrote, which is also the name a wire face will
1486  /// expose it under.
1487  ///
1488  /// Held to the same namespace as the record's fields: an entry colliding with a real field is
1489  /// refused by the front end, because one face has one namespace.
1490  pub name: syn::Ident,
1491  /// The record whose `ref` points back, exactly as the declaration spelled it.
1492  ///
1493  /// A PATH rather than a resolved type, because a macro has tokens: every consequence of it is
1494  /// type-level — the audit names it in a bound — so an alias in the path is transparent and
1495  /// nothing here has to know what it resolves to.
1496  pub source: syn::Path,
1497  /// `field = "…"` — WHICH of the source's referring fields this position means, or `None` for the
1498  /// shorthand.
1499  ///
1500  /// A string, because a field name is not a type on stable Rust: the audit it produces is a
1501  /// constant evaluation over the source's emitted `COLUMNS` rather than a bound. The literal is
1502  /// kept whole so a refusal about the name lands on the name.
1503  pub field: Option<syn::LitStr>,
1504}
1505
1506/// One ARTIFACT position: a blob family derived from this record's messages, under the name this
1507/// record answers an address for it by.
1508///
1509/// [`Derived`]'s reverse-container sibling, and it exists on the ENTITY for a reason that is about
1510/// COHERENCE rather than taste. The address is a field of THIS record's wire face, so somebody's
1511/// expansion has to write it; a blob node's own macro writing a field into a `#[Object]` it does not
1512/// own is the impl-collision wall, measured. The owning expansion writes it into its own object, and
1513/// the wall never arises — which is only possible if the declaration that names the family is the
1514/// one being expanded, and that is this word.
1515///
1516/// There is no Rust field for one, as there is none for a reverse position: the record carries no
1517/// column holding an artifact, because the artifact is somebody else's storage and its address is
1518/// rendered from the key this record already has.
1519#[derive(Debug, Clone)]
1520pub struct Artifact {
1521  /// The position's name — the word the declaration minted, which is the name the wire face exposes
1522  /// the address under.
1523  ///
1524  /// The author's own DOMAIN word and never a keyword of this grammar: `thumb`, `cover`, `poster`.
1525  /// One record may answer for several families and each one names itself, which is what makes the
1526  /// word a name rather than a vocabulary — nothing here decides what an artifact is CALLED, because
1527  /// nothing here knows what the artifacts are.
1528  ///
1529  /// Held to the same namespace as the record's fields and its reverse positions: an entry that
1530  /// repeats either is refused by the front end, because one face has one namespace.
1531  pub name: syn::Ident,
1532  /// The blob node this position addresses, exactly as the declaration spelled it.
1533  ///
1534  /// The path to the `#[ingraph::blob]` STRUCT and never to a field inside it: a family is named by
1535  /// its type, because the type is what holds the store, the extension and the key the address is
1536  /// rendered from. That is also why there is no second option beside it — where a reverse position
1537  /// may need `field = "…"` to say which of several `ref` columns it means, an artifact family has
1538  /// exactly one upstream and therefore nothing to choose between.
1539  ///
1540  /// A PATH rather than a resolved type, for [`Derived::source`]'s reason: every consequence of it
1541  /// is type-level, so an alias in the path is transparent and nothing here has to know what it
1542  /// resolves to.
1543  pub family: syn::Path,
1544  /// The `data` ASK — `locate(thumb(family = "…", data))` — or [`None`] where the position asks for
1545  /// the address alone.
1546  ///
1547  /// The ASK is here and the PERMIT is on the family, and each word decides what only it can. A
1548  /// GraphQL field's presence is a fact of the expansion writing the `#[Object]` block, which is
1549  /// this record's, so the family's own `data` word could not put a field anywhere however it was
1550  /// read; what it does is bind `ArtifactData`, and what this one does is ask for the field that
1551  /// spends it. A position asking where the family never permitted is `E0277` at the emitted
1552  /// projection, carrying that trait's own sentence — which points both ways, because either half is
1553  /// the fix.
1554  pub data: Option<ArtifactBytes>,
1555  /// `locate(cover(family = "…", required))` — whether the ADDRESS field is `BlobLocation!` rather
1556  /// than `BlobLocation`.
1557  ///
1558  /// # NULLABLE IS THE DEFAULT TRUTH here, and the word is the author's informed promotion
1559  ///
1560  /// [`ArtifactBytes::required`]'s meaning at the position's own grain, and the two spell ONE word
1561  /// because they answer one question about two fields. The address is nullable by ARCHITECTURE:
1562  /// artifacts are written by the indexing pipeline asynchronously after the entity exists, so *not
1563  /// yet generated* is a normal state, and the nullable field is the one telling the truth about it.
1564  ///
1565  /// What the word buys is the deployment where that is not so — a family whose objects are present
1566  /// by read time, served to clients that would rather branch on an error than on a null. That is
1567  /// the AUTHOR's to declare and not this framework's to guess, so the word is one-way: writing it
1568  /// is the signature, and not writing it is the default it reverses.
1569  ///
1570  /// It is a SIGNATURE and not a check — nothing here goes and verifies a deployment's claim — and
1571  /// it is not free of consequence either. A store answers `None` for an object that is not there,
1572  /// and a non-null field has nowhere to put one, so the signed position converts that absence into
1573  /// a named field error QUOTING THIS WORD while the bare position beside it publishes `null`. What
1574  /// the word does not change is the ERROR road: a resolver answering `Err` is dropped from the
1575  /// response whatever the field's type. `ingraph/tests/artifact_absence.rs` executes the absence
1576  /// road at both spellings, and `ingraph/tests/artifact_address_signature.rs` the error road.
1577  ///
1578  /// A bare `bool` beside the ask's [`Option`] rather than a shape pairing the two: the fields are
1579  /// independent — a position may sign for the address, for the bytes, for both or for neither — and
1580  /// one wrapper over both would say they move together.
1581  pub required: bool,
1582}
1583
1584/// The wire field one artifact position's `data` ask mints.
1585///
1586/// # It carries a NAME and nothing else, and the absent name is the DEFAULT
1587///
1588/// `<domain-word>Data` — `thumb` → `thumbData` — in the framework's own camelCase, resolved at the
1589/// wire face where that rule has its one home. The alternative was resolving it in the front end and
1590/// storing a string, which would put a second authority on what a client sees beside
1591/// `emit::wire::wire_member`; the two would then be free to disagree about a word like `key_frame`.
1592///
1593/// So [`None`] is *nothing was written* rather than *nothing is known*, exactly as
1594/// [`Graphql::output`]'s empty rename is.
1595#[derive(Debug, Clone)]
1596pub struct ArtifactBytes {
1597  /// `data = "thumbBytes"` — what a client calls the field, verbatim.
1598  name: Option<String>,
1599  /// `data(required)` — whether the field is `String!` rather than `String`.
1600  ///
1601  /// # NULLABLE IS THE DEFAULT TRUTH, and non-null is the AUTHOR'S SIGNATURE
1602  ///
1603  /// The shipped answer is nullable because it is the true one: an artifact is written by the
1604  /// indexing pipeline asynchronously after the entity exists, so *not there yet* is a normal state
1605  /// of a healthy deployment, and reading one is a round trip against somebody else's store besides.
1606  /// A field that can say so is what a client gets unless somebody says otherwise.
1607  ///
1608  /// Saying otherwise is a real want. A family whose bytes are always there, in a schema whose
1609  /// clients would rather branch on an error than on a null, is a coherent deployment — and it is
1610  /// the AUTHOR's to declare, not this framework's to guess. So the word is one-way: `required`
1611  /// exists and no inverse does, because the inverse is what you get by not writing it.
1612  ///
1613  /// What it buys is the published TYPE — a contract with the client — and not a change of
1614  /// behaviour: see [`Artifact::required`], where the address's identical word carries the
1615  /// measurement.
1616  required: bool,
1617}
1618
1619impl ArtifactBytes {
1620  /// The BARE ask — the `data` form, whose field is named at the face.
1621  ///
1622  /// Written out rather than reached through [`Default`], because *the ask with no name* is a state
1623  /// this type has and not the absence of one: a reader of `ArtifactBytes::default()` would have to
1624  /// go and look up which of the two forms it stands for.
1625  #[must_use]
1626  #[inline]
1627  pub const fn asked() -> Self {
1628    Self {
1629      name: None,
1630      required: false,
1631    }
1632  }
1633
1634  /// The ask WITH a name — the `data = "…"` form.
1635  #[must_use]
1636  #[inline]
1637  pub const fn named(name: String) -> Self {
1638    Self {
1639      name: Some(name),
1640      required: false,
1641    }
1642  }
1643
1644  /// The name a declaration wrote, or [`None`] where the default stands.
1645  ///
1646  /// Verbatim, and never camelCased: a name a declaration CHOSE is that declaration's, and applying
1647  /// the backend's rename rule to it would be this framework overriding the choice. The same fork
1648  /// `emit::wire::wire_field` makes for a column's own rename, one face over.
1649  #[must_use]
1650  #[inline]
1651  pub fn name(&self) -> Option<&str> {
1652    self.name.as_deref()
1653  }
1654
1655  /// The same ask, marked NON-NULL — the `data(required)` form.
1656  ///
1657  /// A consuming builder rather than a fourth constructor, because *required* is orthogonal to the
1658  /// two forms above: it composes with the bare ask and with the named one alike, and a
1659  /// constructor per combination is four names for two facts.
1660  #[must_use]
1661  pub const fn require(mut self) -> Self {
1662    self.required = true;
1663    self
1664  }
1665
1666  /// Whether the emitted field is `String!`.
1667  #[must_use]
1668  pub const fn required(&self) -> bool {
1669    self.required
1670  }
1671}
1672
1673/// Which of a declaration's emitted types one is — the phrase a refusal names it by.
1674///
1675/// A vocabulary rather than a description built at the site, so the sentence a front end writes
1676/// about a type has one author. [`method::Owner`](crate::method::Owner) asks a neighbouring
1677/// question and is deliberately not this: it names the types that host METHODS, so it carries the
1678/// record itself — which no emission declares — and lacks the wire key, which declares none.
1679///
1680/// # It is NOT [`Copy`], and the two variants that took that away are the ones that had to
1681///
1682/// Every role above [`Election`](Self::Election) names a type a declaration has AT MOST ONE of, so
1683/// the variant alone identified it. A derived index mints one marker per ELECTION and one per
1684/// `(field × engine)` SLOT, so *a slot's marker* names as many types as the declaration has slots —
1685/// and a refusal that could not say WHICH would leave an author with two markers of one name and no
1686/// way to tell which pair minted either. The identifying tokens therefore ride the variants, which
1687/// costs the trait's bit-copy and buys the sentence.
1688#[derive(Debug, Clone, PartialEq, Eq)]
1689pub enum Role {
1690  /// The `*Key`.
1691  Key,
1692  /// The `*Lineage`, for a record that has one.
1693  Lineage,
1694  /// One database's row.
1695  Row(DatabaseKind),
1696  /// An INTERFACE's discriminant — which member a row of its projection came from.
1697  ///
1698  /// The four variants below it are an interface's too, and they are here rather than in a
1699  /// vocabulary of the interface's own because the question this enum answers is *which of a
1700  /// declaration's emitted types is this* — and an interface is a declaration. Two vocabularies
1701  /// would make a front end's collision refusal read differently depending on which derive wrote the
1702  /// type. That a record's emission produces none of them is what every variant here already is for
1703  /// some declaration and not for another.
1704  Kind,
1705  /// The refusal a wrong-variant unwrap answers with.
1706  UnwrapError,
1707  /// An INTERFACE's address — the sum over its members' own ids.
1708  Id,
1709  /// An interface's CONTRACT trait.
1710  Fields,
1711  /// An interface's DERIVATIONS trait.
1712  Derivations,
1713  /// One database's comparison.
1714  Comparison(DatabaseKind),
1715  /// One database's cursor value — the record's sum over its orderable columns, in the types that
1716  /// database stores.
1717  Cursor(DatabaseKind),
1718  /// The wire argument object.
1719  Input,
1720  /// The wire output object.
1721  Output,
1722  /// The wire key object.
1723  KeyOutput,
1724  /// The wire key ARGUMENT object — the address a client SENDS, for a record whose key has more
1725  /// than one column.
1726  ///
1727  /// Conditional where every other wire face here is unconditional, and the condition is the key's
1728  /// own arity rather than a word: a ROOT record's key is its id, and an id already crosses inward
1729  /// through [`ToGraphqlInput`](../../ingraph/trait.ToGraphqlInput.html) at every filter and `get`
1730  /// position — so wrapping one in a single-field object would publish a shape the id's own row
1731  /// already answers. A COMPOUND key has no such row, and this is the type that gives it one.
1732  KeyInput,
1733  /// The wire filter.
1734  Filter,
1735  /// The wire order-by.
1736  OrderBy,
1737  /// The wire QUERY UNIT — the trio a root folds, for a record whose declaration reaches one.
1738  Queries,
1739  /// The FAN-IN sum — one variant per upstream of a `subscribe(…)` container.
1740  In,
1741  /// The PRODUCT sum — one variant per product `emits` named, for a node that declares several.
1742  Out,
1743  /// The product VOCABULARY — the identities of an [`Out`](Self::Out)'s arms.
1744  OutKind,
1745  /// The node's own DOWNSTREAM — one out-edge slot per declared product.
1746  Downstream,
1747  /// The POLL vocabulary — one variant per `poll(…)` entry, for a node that declares any.
1748  Due,
1749  /// The CHANNELS shelf — one field per `upstream(…)` entry, for a node that declares a container.
1750  Channels,
1751  /// A CLOCK's GRANTS CONTEXT — one per `poll(…)` entry that wrote a `write` word.
1752  Grants,
1753  /// The LENDING — the value a deployment hands the runtime, holding one clock's context per
1754  /// granting entry, the citizen each mounted entry runs and the executor each detached one runs on.
1755  Lending,
1756  /// The SWEEP TRAIT — one entry per `light` clock, which is where an author writes a sweep.
1757  Sweeps,
1758  /// A DERIVED INDEX's ELECTION MARKER — `<Index>By<Field>`, carrying the field it elected.
1759  Election(syn::Ident),
1760  /// A DERIVED INDEX's SLOT MARKER — `<Index><Field><Engine>`, carrying the pairing that minted it.
1761  ///
1762  /// The pairing and not the name, because the name is what a collision has TWO of: the durable slot
1763  /// NAME keeps its segment boundary (`__`-joined) where the marker's camel-case join cannot, so the
1764  /// only way to tell two colliding markers apart is the field and the engine each came from.
1765  Slot(Slot),
1766  /// One type of a derived index's FUSE FAMILY — an options package, a question package, a fold
1767  /// vocabulary or the column vocabulary. The NAME says which; the role says only whose family.
1768  Fuse,
1769  /// One type of an ELECTION's ANSWER FAMILY — the question a query field takes, and the hit shapes
1770  /// it answers with — carrying the election it is about.
1771  ///
1772  /// Separate from [`Fuse`](Self::Fuse) because the two families sit on opposite sides of a call: a
1773  /// fuse type is what a REQUEST is built from and is minted whether or not the declaration wears a
1774  /// backend word, where these exist only where a query field does. The field is carried for
1775  /// [`Election`](Self::Election)'s reason — it is the token an author moves to clear a collision,
1776  /// where an engine word names a real engine and is not free to be renamed.
1777  Answer(syn::Ident),
1778}
1779
1780impl fmt::Display for Role {
1781  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1782    match self {
1783      Self::Key => f.write_str("the key type"),
1784      Self::Lineage => f.write_str("the lineage type"),
1785      Self::Row(kind) => write!(f, "the `{}` row", kind.as_str()),
1786      Self::Kind => f.write_str("the discriminant"),
1787      Self::UnwrapError => f.write_str("the refusal a wrong-variant unwrap answers with"),
1788      Self::Id => f.write_str("the address"),
1789      Self::Fields => f.write_str("the contract trait"),
1790      Self::Derivations => f.write_str("the derivations trait"),
1791      Self::Comparison(kind) => write!(f, "the `{}` comparison", kind.as_str()),
1792      Self::Cursor(kind) => write!(f, "the `{}` cursor value", kind.as_str()),
1793      Self::Input => f.write_str("the wire arguments"),
1794      Self::Output => f.write_str("the wire output"),
1795      Self::KeyOutput => f.write_str("the wire key"),
1796      Self::KeyInput => f.write_str("the wire key argument"),
1797      Self::Filter => f.write_str("the filter"),
1798      Self::OrderBy => f.write_str("the order-by"),
1799      Self::Queries => f.write_str("the query unit"),
1800      Self::In => f.write_str("the fan-in type"),
1801      Self::Out => f.write_str("the product type"),
1802      Self::OutKind => f.write_str("the product vocabulary"),
1803      Self::Downstream => f.write_str("the downstream set"),
1804      Self::Due => f.write_str("the poll vocabulary"),
1805      Self::Channels => f.write_str("the channels shelf"),
1806      Self::Grants => f.write_str("a clock's grants context"),
1807      Self::Lending => f.write_str("the lending"),
1808      Self::Sweeps => f.write_str("the sweep trait"),
1809      Self::Election(field) => write!(f, "the `{field}` election's marker"),
1810      Self::Slot(slot) => write!(f, "the `{}` × `{}` slot marker", slot.field, slot.engine),
1811      Self::Fuse => f.write_str("the fuse family's type"),
1812      Self::Answer(field) => write!(f, "the `{field}` election's answer family"),
1813    }
1814  }
1815}
1816
1817impl Role {
1818  /// The DECLARED token a refusal about this type points at, or [`None`] for a name no declaration
1819  /// wrote a part of.
1820  ///
1821  /// [`Origin::column`](crate::method::Origin::column) one axis over, and the same argument: a name
1822  /// built through `format_ident!` carries the macro's own call site, which is the span `E0428`
1823  /// already reports at and the reason these rules exist. Every role a record or an interface emits
1824  /// is either renamed by a word the front end holds or defaulted off the declaration's own ident,
1825  /// so those front ends point at what they hold; a derived index's markers are built from a FIELD
1826  /// and an ENGINE WORD, and the field is the token an author moves to fix a collision — an engine
1827  /// word names a real engine and is not free to be renamed.
1828  #[must_use]
1829  pub const fn at(&self) -> Option<&syn::Ident> {
1830    match self {
1831      Self::Election(field) | Self::Answer(field) => Some(field),
1832      Self::Slot(slot) => Some(&slot.field),
1833      Self::Key
1834      | Self::Lineage
1835      | Self::Row(_)
1836      | Self::Kind
1837      | Self::UnwrapError
1838      | Self::Id
1839      | Self::Fields
1840      | Self::Derivations
1841      | Self::Comparison(_)
1842      | Self::Cursor(_)
1843      | Self::Input
1844      | Self::Output
1845      | Self::KeyOutput
1846      | Self::KeyInput
1847      | Self::Filter
1848      | Self::OrderBy
1849      | Self::Queries
1850      | Self::In
1851      | Self::Out
1852      | Self::OutKind
1853      | Self::Downstream
1854      | Self::Due
1855      | Self::Channels
1856      | Self::Grants
1857      | Self::Lending
1858      | Self::Sweeps
1859      | Self::Fuse => None,
1860    }
1861  }
1862}
1863
1864/// Which CROSSING a declared error covers — one IMPL FAMILY each, reached through the words the
1865/// field blocks already speak.
1866///
1867/// No new vocabulary: a declaration that writes `sqlite(try_into = "…")` on a field names
1868/// the crossing whose refusal `sqlite(try_into(error = "…"))` types, and the correspondence
1869/// is the word rather than a table a reader has to hold.
1870///
1871/// # `persist` names TWO of them, and a cell rides its LEG
1872///
1873/// A row's read and its write are different impls with different callers — `TryFrom<Row> for E` and
1874/// `TryFrom<E> for Row` — so one cell over both would say either that they share an error or that
1875/// the question had not been asked. The BLOCK word is the same for the two and the LEG word is what
1876/// tells them apart, which is why [`as_str`](Self::as_str) is not injective and why nothing reads it
1877/// to identify a cell: the identity is this enum's own value.
1878#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1879pub enum Crossing {
1880  /// The ROW's READ leg — `TryFrom<<E><Db>> for E`, the impl every query lane spends, typed by
1881  /// `<db>(try_into(error = "…"))`.
1882  PersistRead,
1883  /// The ROW's WRITE leg — `TryFrom<E> for <E><Db>`, the impl the write lane spends, typed by
1884  /// `<db>(try_from(error = "…"))`.
1885  ///
1886  /// It was a named refuse-until while nothing stored a record. `query::sql::write` is the consumer
1887  /// it was waiting for: a record crosses to its row through `SqlWrite::row` and through nothing
1888  /// else, so the type this cell names is what a caller catches when a column will not cross.
1889  PersistWrite,
1890  /// The crossing from a stored ROW onto the wire OUTPUT object.
1891  Output,
1892  /// The OPERAND crossing: a filter's value into the comparison's, which is the declared-converter
1893  /// half of `TryFromFilter`.
1894  Comparison,
1895}
1896
1897impl Crossing {
1898  /// Every crossing, in the order the grammar lists them — the two `persist` legs first, read before
1899  /// write, which is the order a declaration's own block reads.
1900  pub const ALL: [Self; 4] = [
1901    Self::PersistRead,
1902    Self::PersistWrite,
1903    Self::Output,
1904    Self::Comparison,
1905  ];
1906
1907  /// The word a declaration writes to OPEN this crossing's block.
1908  ///
1909  /// `persist` for both of its legs — see the type's own note. What a cell is identified by is the
1910  /// variant, not this string.
1911  #[must_use]
1912  pub const fn as_str(self) -> &'static str {
1913    match self {
1914      Self::PersistRead | Self::PersistWrite => "persist",
1915      Self::Output => "output",
1916      Self::Comparison => "comparison",
1917    }
1918  }
1919}
1920
1921impl fmt::Display for Crossing {
1922  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1923    f.write_str(self.as_str())
1924  }
1925}
1926
1927/// ONE CELL of the record's declared conversion errors: which crossing, which database, and the type
1928/// its fallible impls answer with.
1929///
1930/// Two axes rather than one, and the second is what the flat shape could not express: a record's row
1931/// decode and its crossing onto the wire are different impls with different callers, so a
1932/// declaration may want them to answer differently — and every cell is independent, an absent one
1933/// taking the boxed refusal on its own.
1934#[derive(Debug, Clone)]
1935pub struct BackendError {
1936  /// Which crossing's impls answer with it.
1937  pub crossing: Crossing,
1938  /// Which database's.
1939  pub kind: DatabaseKind,
1940  /// The type, as the declaration spelled it.
1941  pub path: syn::Path,
1942}
1943
1944/// One TYPE an emission declares, and what it is.
1945#[derive(Debug, Clone)]
1946pub struct Declared {
1947  /// What the type is called.
1948  pub name: syn::Ident,
1949  /// Which of the declaration's types it is.
1950  pub role: Role,
1951}
1952
1953impl RecordModel {
1954  /// Every TYPE this model's emission declares, in EMISSION ORDER.
1955  ///
1956  /// The front end refuses a declaration whose emitted types collide, and it asks HERE which those
1957  /// are rather than keeping a list of its own — one declaration emits every one of these into a
1958  /// single scope, and a list of them written twice is how one copy drifts. That is the argument
1959  /// this module's defaulted names already carry, one step further: the model says not only what
1960  /// each type is CALLED but which ones there are.
1961  ///
1962  /// The order is the emitter's own walk — the key, the lineage, then each database's row and
1963  /// comparison, then the four wire faces — so a front end reporting a collision can name the
1964  /// earlier of the two as the one already there.
1965  ///
1966  /// # The RECORD is not here, because no emission declares it
1967  ///
1968  /// The record's own type is the DECLARER's, already in the scope the emission lands in. It still
1969  /// takes part in the collision rule — a rename onto it clashes like any other — but that is a
1970  /// fact about the scope rather than about the emission, so the front end adds it and this does
1971  /// not. Including it here would put a name in the enumeration that
1972  /// `tests::the_enumeration_names_exactly_the_types_the_emission_declares` could never find.
1973  ///
1974  /// # A wire face with no backend declares nothing
1975  ///
1976  /// [`Graphql::faces`](crate::emit) writes no type at all when no backend renders the record, and
1977  /// this answers alike. The derive cannot reach that state — it refuses a `graphql(…)` naming no
1978  /// backend — but a model is PLAIN and a manifest front end can build one, and an enumeration
1979  /// that named four types the emitter never wrote would refuse a declaration for a clash that
1980  /// could not happen.
1981  pub fn emitted_types(&self) -> Vec<Declared> {
1982    let declared = |name: &syn::Ident, role: Role| Declared {
1983      name: name.clone(),
1984      role,
1985    };
1986    let mut emitted = vec![declared(&self.key.name, Role::Key)];
1987    if let Some(lineage) = &self.lineage {
1988      emitted.push(declared(&lineage.name, Role::Lineage));
1989    }
1990    for database in self.persist.iter().flat_map(|persist| &persist.backends) {
1991      let kind = database.kind();
1992      emitted.push(declared(database.name(), Role::Row(kind)));
1993      emitted.push(declared(database.comparison_name(), Role::Comparison(kind)));
1994    }
1995    // The order-by, beside the comparisons and before the cursor values, because that is the
1996    // emitter's own walk — and beside them rather than among the wire faces because that is where
1997    // it now lives: a term is a fact about the STORED columns, so a record with no wire face has one
1998    // and a record stored nowhere has none.
1999    if self.persist.is_some() {
2000      emitted.push(declared(self.order_by.safe(), Role::OrderBy));
2001    }
2002    // The cursor values, after every row and comparison, because that is the emitter's own walk:
2003    // the query face is emitted once the rows it names are all declared. One per database that can
2004    // carry a query — [`RecordModel::queryable`] is the one place that decides which.
2005    emitted.extend(
2006      self
2007        .queryable()
2008        .into_iter()
2009        .map(|database| declared(&database.cursor_name(), Role::Cursor(database.kind()))),
2010    );
2011    if let Some(graphql) = &self.graphql
2012      && !graphql.backends.is_empty()
2013    {
2014      emitted.extend(
2015        [
2016          (&graphql.input, Role::Input),
2017          (&graphql.output, Role::Output),
2018          (&graphql.key_output, Role::KeyOutput),
2019        ]
2020        .map(|(name, role)| declared(name.safe(), role)),
2021      );
2022      // The KEY ARGUMENT, between the address a client READS and the filter — the emitter's own
2023      // walk, where the two halves of one address sit together. It is the one wire face here whose
2024      // existence is decided by the declaration's SHAPE rather than by a word: a root's address
2025      // crosses inward as its id, so naming a type for one would refuse a declaration for a clash
2026      // that could not happen.
2027      if self.key.compound() {
2028        emitted.push(declared(
2029          &default_key_input_name(&self.record),
2030          Role::KeyInput,
2031        ));
2032      }
2033      emitted.push(declared(graphql.filter.safe(), Role::Filter));
2034      // The QUERY UNIT, after the four faces because that is the emitter's own walk — and only where
2035      // one is written: a record whose store carries no query face binds `()` and declares no type,
2036      // so naming it here would refuse a declaration for a clash that could not happen.
2037      if self.wire_query_row().is_some() {
2038        emitted.push(declared(&default_queries_name(&self.record), Role::Queries));
2039      }
2040    }
2041    // The TOPOLOGY types, last because that is the emitter's own walk: a node's fan-in and its
2042    // products are emitted after everything its declaration is about. Each is conditional on the
2043    // word that declares it, so a node with one upstream and one product adds nothing here — which
2044    // is what keeps the collision rule from reporting a name no expansion writes.
2045    if self
2046      .subscriptions
2047      .as_ref()
2048      .is_some_and(Subscription::is_sum)
2049    {
2050      emitted.push(declared(&default_in_name(&self.record), Role::In));
2051    }
2052    if self.products.as_ref().is_some_and(Products::is_sum) {
2053      let record = &self.record;
2054      emitted.push(declared(&default_out_name(record), Role::Out));
2055      emitted.push(declared(&default_out_kind_name(record), Role::OutKind));
2056      emitted.push(declared(&default_downstream_name(record), Role::Downstream));
2057    }
2058    if self.polls.is_some() {
2059      emitted.push(declared(&default_due_name(&self.record), Role::Due));
2060    }
2061    // The SHELF is emitted at every arity a container has, unlike the fan-in beside it: a node
2062    // drawing from one upstream still has that one edge to tune, and a shelf whose existence
2063    // depended on the count would move the day a second `upstream(…)` arrived.
2064    if self.subscriptions.is_some() {
2065      emitted.push(declared(
2066        &default_channels_name(&self.record),
2067        Role::Channels,
2068      ));
2069    }
2070    // The POLLING names, last: ONE CONTEXT PER GRANTING CLOCK, plus the lending that holds them and
2071    // the sweep trait whose entries they seat. Every one of them is conditional on the word that
2072    // declares it — a node that grants nothing mints no context, and a node whose every clock
2073    // mounts a citizen mints no sweep trait — and every one of them is registered, which is what
2074    // makes the `<Node><Poll>Grants` law collision-proof rather than merely unlikely: `Reap`+`Er`
2075    // and `Reaper`+`` cannot both be spelled, so the only way two of these names can agree is a way
2076    // this table already refuses.
2077    //
2078    // The LENDING is unconditional over polling nodes, which is the threshold the mode words
2079    // widened: every clock now has an execution role to route, so every polling node has an
2080    // apparatus and `Resident::polling` takes one whatever the declaration granted.
2081    if let Some(polls) = self.polls.as_ref() {
2082      let record = &self.record;
2083      for (_, entry) in polls.granting() {
2084        emitted.push(declared(
2085          &poll_grants_name(record, &entry.variant),
2086          Role::Grants,
2087        ));
2088      }
2089      emitted.push(declared(&default_polling_name(record), Role::Lending));
2090      if polls.sweeping().next().is_some() {
2091        emitted.push(declared(&default_sweeps_name(record), Role::Sweeps));
2092      }
2093    }
2094    emitted
2095  }
2096}
2097
2098/// The emitted key type: `lineage ⊕ id`, flat, root-first.
2099#[derive(Debug, Clone)]
2100pub struct Key {
2101  /// The name of the emitted type — [`default_key_name`] unless it was renamed.
2102  pub name: syn::Ident,
2103  /// The lineage steps AS THIS TYPE NAMES THEM, root-first. Empty for a root record.
2104  pub path: Vec<Column>,
2105  /// The id column — this type's last one. Named separately rather than as the tail of `path`,
2106  /// because "the last one is the id" is an invariant a reader would have to be told.
2107  pub id: Column,
2108}
2109
2110/// A record's ancestry, and the name of the type that carries it.
2111#[derive(Debug, Clone)]
2112pub struct Lineage {
2113  /// The name of the emitted lineage type — [`default_lineage_name`] unless it was renamed.
2114  pub name: syn::Ident,
2115  /// WHAT that type is: a path through one ancestry, or a choice among several.
2116  pub shape: Shape,
2117}
2118
2119/// The two things a lineage can BE, and therefore the two types that can be emitted for one.
2120///
2121/// The split is the topology's, not a convenience: a node with one ancestry has a PATH, and every
2122/// row of it carries the same columns; a node drawing from several independent upstreams has a
2123/// CHOICE, and which columns a row carries depends on which upstream it came from. A struct with
2124/// nullable columns would express the second, and would make the invalid states representable —
2125/// which is the whole reason the storage layout beneath it splits too.
2126#[derive(Debug, Clone)]
2127pub enum Shape {
2128  /// A PATH: one column per step, root-first, as a struct. Never empty — an empty path is a root,
2129  /// and a root has no [`Lineage`] at all.
2130  Path(Vec<Column>),
2131  /// A CHOICE: one variant per upstream, each carrying that upstream's whole key, as an enum.
2132  Kinds(Vec<Kind>),
2133}
2134
2135impl Lineage {
2136  /// The path columns, where this lineage is one — and nothing where it is a choice.
2137  ///
2138  /// The shape most of the emitter wants: a walk over columns that simply has none for a lineage
2139  /// whose variation is between rows rather than within one.
2140  pub fn path(&self) -> &[Column] {
2141    match &self.shape {
2142      Shape::Path(columns) => columns,
2143      Shape::Kinds(_) => &[],
2144    }
2145  }
2146
2147  /// The path columns to be edited — for a front end assembling a model, and for the tests that
2148  /// build one by hand.
2149  pub fn path_mut(&mut self) -> &mut [Column] {
2150    match &mut self.shape {
2151      Shape::Path(columns) => columns,
2152      Shape::Kinds(_) => &mut [],
2153    }
2154  }
2155}
2156
2157/// One field of the RECORD, and how its own accessors are shaped.
2158#[derive(Debug, Clone)]
2159pub struct Field {
2160  /// The field's name, type and `copy` claim. On the record a column's name IS its source name —
2161  /// a scoped rename names a column in an emitted type, never the Rust field.
2162  pub column: Column,
2163  /// Whether the field bears identity: the `id`, or a step of the lineage path.
2164  ///
2165  /// Identity is set at construction, so an identity-bearing field gets GETTERS ONLY on the
2166  /// record — no `set_*`, no `with_*`. The rule is the product schema's own, stated at
2167  /// `mediaschema` `video/facet.rs:98`: "Set at construction (identity-bearing — no
2168  /// `with_media_id` / `set_media_id`)".
2169  ///
2170  /// The `*Key` and `*Lineage` types are not bound by it. They are addresses being built rather
2171  /// than rows being edited, and `with_*` on them has a consumer: stepping to a neighbouring key.
2172  pub identity: bool,
2173  /// The INTERPRETATION this field's type is read under, or `None` where the type answers for
2174  /// itself.
2175  ///
2176  /// On the FIELD, because a label is a field's own fact and reaches both of its faces: a column
2177  /// stored and not exposed still crosses into a comparison, and the crossing goes through the same
2178  /// projection the wire filter does. Holding it on one face would leave the other guessing.
2179  ///
2180  /// `None` on an identity-bearing field, whose admission vocabulary is the sealed `Id` trait
2181  /// rather than a family word — see [`Field::identity`].
2182  pub marker: Option<Marker>,
2183  /// `sortable` — whether this COLLECTION asked for the ORDER-PRESERVING COMPANION COLUMN.
2184  ///
2185  /// A STORAGE fact and not an interpretation, which is why it is a `bool` on the field rather than
2186  /// a ninth [`Label`] or a flag on the [`Marker`]: a label says what a column is READ AS, and this
2187  /// says what the storage does with one — a database keeping the collection in a table of its own
2188  /// mirrors its order into `__ig_<field>_sort__` beside the row, so a term over it lands in the
2189  /// statement where it was a remainder.
2190  ///
2191  /// # ONE seat, and it is neither the label's nor a database's
2192  ///
2193  /// It rode the [`FrameworkMarker`] while the word was written inside the label, which put a
2194  /// storage fact in the read-interpretation container — the wire face deliberately never read it,
2195  /// and every consumer was storage- or lowering-side. The word moved to `persist(…)` and the fact
2196  /// moved with it, to the FIELD: a fact carried where it was not written is one two readers can
2197  /// disagree about.
2198  ///
2199  /// Not on [`PersistColumn`], which is per database, because the word is ONE intent from which each
2200  /// database derives its own mechanism — see `DatabaseBackend::mirrors`, which joins this to that
2201  /// database's storage form. A per-database seat would carry the same value four times and let two
2202  /// copies drift, and a client's written order has to fingerprint alike whichever form answered it.
2203  ///
2204  /// `false` on every field that did not write the word, which is the whole of what it costs one.
2205  pub sortable: bool,
2206  /// `indexed` — whether this COLLECTION asked for the VALUE-LED ACCESS PATH.
2207  ///
2208  /// [`sortable`](Self::sortable)'s sibling in every structural respect: a STORAGE fact rather than
2209  /// an interpretation, so a `bool` on the field rather than a ninth [`Label`]; ONE intent from
2210  /// which each database derives its own mechanism, so the FIELD's own seat rather than a
2211  /// per-database one; and `false` on every field that wrote no word.
2212  ///
2213  /// What differs is the mechanism and which shapes take it. The word puts a SECOND index on the
2214  /// elements' table, leading on the VALUE where the derived one leads on the key — *which rows'
2215  /// collections hold `dog`*, a seek nothing served before. And a `set` takes it as readily as a
2216  /// `list`: a set's primary key leads on the key too, so its membership is as unreachable from a
2217  /// value as a sequence's is, where `sortable` is a list's word alone.
2218  ///
2219  /// A per-database seat would be worse here than for `sortable`, and by a wider margin: on SQLite
2220  /// the path carries a CASE FOLD, which is visible in a set's own identity, so a word written for
2221  /// one database and withheld from another would be a declaration meaning two different things
2222  /// depending on which store answered.
2223  pub indexed: bool,
2224  /// The record this field REFERS to — `ref = "media::Keyframe"` — or `None` where it refers to
2225  /// nothing.
2226  ///
2227  /// On the field beside its label rather than on a family of its own, because a reference is a
2228  /// fact about the field's VALUE: the column holds the target's id, which is as true of the key
2229  /// side as of the stored side. A key-side field carries one where it carries no label at all —
2230  /// a lineage step names the parent it steps from, and the id names the record whose identity this
2231  /// record shares.
2232  pub reference: Option<Reference>,
2233  /// `#[ingraph(skip)]` — the field mints NO column in ANY database the record persists to, and
2234  /// this is what fills it when a row is raised back into the record.
2235  ///
2236  /// # The DECLARED absence is not the same fact as an unmarked field's
2237  ///
2238  /// A field carrying neither `persist` nor this word reaches no row either, and the row that
2239  /// results is PARTIAL: it cannot rebuild the record, so `DatabaseBackend::raises` is false and the
2240  /// whole SQL query face goes with it. The word is what turns that silence into a declaration —
2241  /// *this field is not stored, and here is what a read fills it with* — so the row carries every
2242  /// field it is answerable for and the query face survives.
2243  ///
2244  /// # ONE STORAGE SHAPE PER RECORD, and a per-database shape is a SECOND RECORD
2245  ///
2246  /// The word has no per-database seat and will not grow one: a record is the same shape in every
2247  /// database it declares. Where two databases really want different columns, the difference is the
2248  /// GRAPH's to state rather than a field word's — declare a second record as a PARALLEL SUBSCRIBER
2249  /// of the same upstream, lean in one store and fat in the other, each uniform across its own. That
2250  /// is the storage-as-co-subscriber doctrine read at the record grain, and it is the answer.
2251  pub skip: Option<Fill>,
2252  /// The field's own DOC COMMENTS, kept for the one mode that would otherwise delete them.
2253  ///
2254  /// An ordinary declaration is re-emitted verbatim, so its fields keep their own documentation and
2255  /// nothing has to carry it. A REWRITE — see [`RecordModel::remote`] — replaces the item with a
2256  /// transparent wrapper, and the fields the author documented are gone from the program: kept
2257  /// nowhere, the sentences an author wrote would be deleted by the macro that read them. They are
2258  /// MIGRATED onto the reader emitted for the field, which is where that field's meaning is
2259  /// answerable in the rewritten item.
2260  ///
2261  /// Empty on every declaration that is not a rewrite, which costs one an allocation it never makes:
2262  /// the parse gathers them only in that mode.
2263  pub docs: Vec<syn::Attribute>,
2264  /// The `#[cfg(…)]` this field is declared under — see [`Condition`].
2265  ///
2266  /// Gathered in BOTH modes, because the question it answers is the same in both: an ordinary
2267  /// field the build removes leaves its column, its filter seat and its reader behind exactly as a
2268  /// manifest field's would.
2269  pub condition: Condition,
2270  /// `builder(…)` on the FIELD — which seat of the construction protocol this column fills.
2271  ///
2272  /// Its default is the DEFAULT LAW read one column at a time: an `optional` column reaches a
2273  /// `with_<name>` link and every other one is a positional argument to the entry, in declaration
2274  /// order. Every word in [`Build`] is an override of that, and a field writing none carries the
2275  /// value that produces the emission the rewrite mode always had.
2276  ///
2277  /// Meaningful only under [`RecordModel::remote`], for [`RecordModel::construction`]'s reason.
2278  pub build: Build,
2279}
2280
2281/// The CONDITION a field is DECLARED UNDER — the `#[cfg(…)]` attributes written on it.
2282///
2283/// # The macro never learns whether the predicate holds, and that IS the mechanism
2284///
2285/// A proc macro has no API for asking whether a `cfg` predicate is satisfied, and in the REWRITE
2286/// mode the field never reaches the compiler at all — so nothing here evaluates anything. What the
2287/// seat does is CARRY the author's own tokens onto every artifact the field mints, and leave the
2288/// answer to the one party that has it. The family is stripped in a single pass, by the compiler,
2289/// or it is kept whole.
2290///
2291/// # Two kinds of artifact, and the seat serves them differently
2292///
2293/// | artifact | how the condition reaches it |
2294/// |---|---|
2295/// | an item, a struct field, a variant, a match arm, an array element | the attribute verbatim — [`gate`](Self::gate) |
2296/// | a POSITION among the present columns — a bind ordinal, a fence index | [`present`](Self::present), summed in a `const` the compiler folds AFTER stripping |
2297///
2298/// The second is the whole reason this type is not just a list of attributes. An expansion that
2299/// wrote a bind ordinal as the literal `2` would be naming a position the build no longer has the
2300/// moment a column before it is configured out, and a literal is exactly what an emitter reaching
2301/// for `enumerate()` produces. So where any column is conditional, every ordinal is written as a
2302/// running sum of these — `0`, `0 + p₀`, `0 + p₀ + p₁` — and the compiler folds it after it has
2303/// answered the predicates.
2304///
2305/// # `cfg` reaches the FAMILY and `cfg_attr` reaches ONE artifact, because they ask different things
2306///
2307/// `#[cfg]` is about EXISTENCE, and existence is what the whole family follows — a column, a filter
2308/// seat and a reader for a field the build removed are the disease this seat cures, so the gate has
2309/// to reach every one of them.
2310///
2311/// `#[cfg_attr(pred, …)]` removes nothing. It conditionally DECORATES, so it has no presence to
2312/// account for and nothing to strip, and repeating it across the family would put an author's
2313/// `serde(rename = "…")` on a method. It rides the one artifact that STANDS IN for the field: the
2314/// echoed field itself in an ordinary declaration, where the host already forwards it verbatim and
2315/// this type never sees it; the READER in a rewrite, beside the doc comments that migrate there for
2316/// the same reason — see [`decorations`](Self::decorations).
2317///
2318/// Where its payload is this grammar's OWN word, it is refused instead: a macro that cannot read
2319/// `pred` cannot know whether `#[ingraph(id)]` was written. See `ingraph_derive::attribute`.
2320#[derive(Debug, Clone, Default)]
2321pub struct Condition {
2322  /// The `#[cfg(…)]` attributes to repeat onto each artifact, in the order they were written.
2323  gates: Vec<syn::Attribute>,
2324  /// Each `cfg`'s own predicate tokens — `all(unix, feature = "x")` out of
2325  /// `#[cfg(all(unix, feature = "x"))]`.
2326  ///
2327  /// Kept apart from [`gates`](Self::gates) because presence arithmetic has to NEGATE the
2328  /// predicate and an attribute cannot be negated — only the tokens inside one can.
2329  predicates: Vec<proc_macro2::TokenStream>,
2330  /// The `#[cfg_attr(…)]` attributes, for the ONE artifact that stands in for the field.
2331  ///
2332  /// Empty outside a rewrite, where the echoed field carries them and nothing has to.
2333  decorations: Vec<syn::Attribute>,
2334}
2335
2336impl Condition {
2337  /// The condition a field with no `#[cfg]` is under: none.
2338  #[must_use]
2339  pub fn always() -> Self {
2340    Self::default()
2341  }
2342
2343  /// The condition the given attributes state — `#[cfg(…)]` for the family, `#[cfg_attr(…)]` for
2344  /// the stand-in — each list in written order.
2345  ///
2346  /// SEVERAL `#[cfg]` are a conjunction, which is Rust's own rule for several on one item, and it
2347  /// is why [`present`](Self::present) writes `all(…)` rather than one predicate.
2348  #[must_use]
2349  pub fn of(gates: Vec<syn::Attribute>, decorations: Vec<syn::Attribute>) -> Self {
2350    let predicates = gates
2351      .iter()
2352      .filter_map(|gate| match &gate.meta {
2353        syn::Meta::List(list) if list.path.is_ident("cfg") => Some(list.tokens.clone()),
2354        _ => None,
2355      })
2356      .collect();
2357    Self {
2358      gates,
2359      predicates,
2360      decorations,
2361    }
2362  }
2363
2364  /// The `#[cfg_attr(…)]` the field's STAND-IN carries — the rewrite's reader, and nothing else.
2365  #[must_use]
2366  pub fn decorations(&self) -> &[syn::Attribute] {
2367    &self.decorations
2368  }
2369
2370  /// Whether the field is present in EVERY build — the common case, and the one that has to expand
2371  /// to exactly what it expanded to before this seat existed.
2372  #[must_use]
2373  pub fn always_present(&self) -> bool {
2374    self.predicates.is_empty()
2375  }
2376
2377  /// The attributes to prefix onto ONE artifact of the field.
2378  ///
2379  /// Empty for an unconditional field, so an emitter interpolates this unconditionally and a
2380  /// declaration that wrote no `cfg` pays not one token for the seat.
2381  #[must_use]
2382  pub fn gate(&self) -> proc_macro2::TokenStream {
2383    let gates = &self.gates;
2384    quote::quote!(#(#gates)*)
2385  }
2386
2387  /// ONE of two expressions, chosen by this field's predicate — for the seats where an attribute
2388  /// cannot go.
2389  ///
2390  /// [`gate`](Self::gate) serves every position Rust lets an attribute sit in: an item, a struct
2391  /// literal's field, an array element, a statement, a match arm. A TERM of an expression is not one
2392  /// of them — `#[cfg]` on an expression is `stmt_expr_attributes` and unstable — and a folded
2393  /// `a && b && c` over a list the predicates CONTRACT is exactly that seat. So the fork moves one
2394  /// grain out, into a block whose two `let`s are STATEMENTS, and the compiler strips the arm its
2395  /// answer removed.
2396  ///
2397  /// An unconditional field gets `present` back untouched, so a declaration that wrote no `#[cfg]`
2398  /// pays not one token for the seat — [`gate`](Self::gate)'s own discipline.
2399  #[must_use]
2400  pub fn either(
2401    &self,
2402    present: &proc_macro2::TokenStream,
2403    absent: &proc_macro2::TokenStream,
2404  ) -> proc_macro2::TokenStream {
2405    if self.predicates.is_empty() {
2406      return present.clone();
2407    }
2408    let predicates = &self.predicates;
2409    quote::quote! {
2410      {
2411        #[cfg(all(#(#predicates),*))]
2412        let __ingraph_chosen = #present;
2413        #[cfg(not(all(#(#predicates),*)))]
2414        let __ingraph_chosen = #absent;
2415        __ingraph_chosen
2416      }
2417    }
2418  }
2419
2420  /// `1` where the field is present and `0` where it is not — a `const` expression the COMPILER
2421  /// evaluates, after it has stripped what the predicate removes.
2422  ///
2423  /// The two arms are ITEMS inside a block rather than an attribute on an expression, which is what
2424  /// makes this stable Rust: `#[cfg]` on an expression needs `stmt_expr_attributes`, and `#[cfg]` on
2425  /// a `const` item inside a block needs nothing.
2426  #[must_use]
2427  pub fn present(&self) -> proc_macro2::TokenStream {
2428    if self.predicates.is_empty() {
2429      return quote::quote!(1usize);
2430    }
2431    let predicates = &self.predicates;
2432    quote::quote! {
2433      {
2434        #[cfg(all(#(#predicates),*))]
2435        const __INGRAPH_PRESENT: ::core::primitive::usize = 1;
2436        #[cfg(not(all(#(#predicates),*)))]
2437        const __INGRAPH_PRESENT: ::core::primitive::usize = 0;
2438        __INGRAPH_PRESENT
2439      }
2440    }
2441  }
2442}
2443
2444/// What fills a SKIPPED field when a row is raised back into the record.
2445///
2446/// # `Default` is the floor, and the author may name the fill instead
2447///
2448/// A skipped column has no stored value to read, so a read supplies one. The default is
2449/// `Default::default()` — `E0277` at the `skip` word where the field's type has no `Default`, and
2450/// PER-DATABASE PRECISE, since only the raise of a database that actually skips the column asks for
2451/// one. `skip(default = "path::to::fn")` names the filler instead, and the spelling is serde's own
2452/// `default = "…"` verbatim: the path is a `fn() -> T`.
2453#[derive(Debug, Clone)]
2454pub struct Fill {
2455  /// The `skip` word's own span — where an unsatisfied `Default` obligation is reported, so the
2456  /// author reads the demand at the word that made it rather than inside an expansion.
2457  pub at: proc_macro2::Span,
2458  /// `default = "path::to::fn"` — the named filler, or [`None`] for `Default::default()`.
2459  pub named: Option<syn::Path>,
2460}
2461
2462impl Fill {
2463  /// The expression a raise fills the field with, spanned AT THE `skip` WORD.
2464  ///
2465  /// The type is NOT named in the defaulted arm, and the omission is the span. A written
2466  /// `<T as Default>::default()` interpolates the field's own type tokens, and those carry the
2467  /// field's spans — `quote_spanned!` sets the span of tokens it CREATES and never of ones handed
2468  /// to it — so the unsatisfied `Default` reports at the type rather than at the word that demanded
2469  /// one. Inferred, every token of the expression is this word's and so is the obligation; what the
2470  /// author reads is the ruled `E0277` at the `skip` they wrote, with rustc's own *consider
2471  /// annotating `T` with `#[derive(Default)]`* still resolved from the type's declaration.
2472  ///
2473  /// The struct literal is what fixes the type, so nothing is left to infer: a field of a named
2474  /// struct has one type and the fill is being written into it.
2475  #[must_use]
2476  pub fn value(&self, ty: &syn::Type) -> proc_macro2::TokenStream {
2477    let at = self.at;
2478    let _ = ty;
2479    match &self.named {
2480      Some(path) => quote::quote_spanned!(at => #path()),
2481      None => quote::quote_spanned!(at => ::core::default::Default::default()),
2482    }
2483  }
2484}
2485
2486/// ONE field a database's row does not carry, and what its raise supplies instead.
2487///
2488/// The per-database half of [`Fill`]. The record-wide half needs no such pairing — a `skip`ped field
2489/// is reached through the record's own field list, where its type and its fill sit together — and
2490/// this one is stated per [`Storage`], so the field it is about has to travel with it.
2491#[derive(Debug, Clone)]
2492pub struct Filled {
2493  /// The RECORD field this raise supplies rather than reads.
2494  pub source: syn::Ident,
2495  /// What supplies it — `<db>(skip(default = "…"))`'s named function, spanned at the word.
2496  ///
2497  /// Never the defaulted arm: a PARTIAL absence names its fill or is refused, so a `Filled` that
2498  /// reached the emitter carries a written one.
2499  pub fill: Fill,
2500}
2501
2502/// A field's `ref(…)`: the record it names, and how the referring value is reached from the field's
2503/// own type.
2504#[derive(Debug, Clone)]
2505pub struct Reference {
2506  /// The target record, exactly as the declaration spelled it.
2507  ///
2508  /// A PATH rather than a resolved type, for the reason [`Derived::source`] is one: the equation it
2509  /// feeds is type-level, so an alias resolves and nothing here token-matches the spelling.
2510  pub target: syn::Path,
2511  /// Which of the field's types the equation is checked against.
2512  pub through: Through,
2513}
2514
2515/// WHERE the referring value sits inside the field's declared type.
2516///
2517/// A DECLARATION decides it, never the type's spelling: a collection is the field's collection
2518/// LABEL and an absent value is its `optional` marker, which is the same rule the whole projection
2519/// layer runs on — a macro sees tokens, and `type MaybeCover = Option<Uuid7>` is exactly the case
2520/// that proves a spelling cannot be trusted.
2521///
2522/// What the emission does with it is NOT a token operation either: [`Held`](Self::Held) is written
2523/// `<T as State<Extracted<Inner>>>::Output`, so an alias is as transparent one level in as it is at
2524/// the field, and a downstream container joins by writing that one impl.
2525#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2526pub enum Through {
2527  /// The field's own type IS the referring value.
2528  Value,
2529  /// What the field's type HOLDS is: a collection's element, or an optional column's value.
2530  Held,
2531}
2532
2533/// One column of one emitted type.
2534///
2535/// A column is SCOPED: the same record field reaches the key type and the lineage type as two
2536/// separate columns, which may carry different names. That is not a quirk — the key's columns
2537/// become the record table's, the lineage's become the degraded table's, and two tables may name
2538/// their columns differently.
2539#[derive(Debug, Clone)]
2540pub struct Column {
2541  /// The column's name IN THIS TYPE: the declaration's field name, or the rename its scope gave
2542  /// it. Also the accessor's name and the suffix of both mutators'.
2543  pub name: syn::Ident,
2544  /// The RECORD field this column projects.
2545  ///
2546  /// Equal to [`Column::name`] unless a scoped rename moved it. The conversions need both: a
2547  /// `From<Record>` reads `record.source` and writes `Self { name }`.
2548  pub source: syn::Ident,
2549  /// The field's declared type, verbatim.
2550  pub ty: syn::Type,
2551  /// How the column is handed out — the declaration's marker, or the default borrow.
2552  pub project: Projection,
2553}
2554
2555/// How a column is handed out by an accessor.
2556///
2557/// One marker, one projection — the variants are mutually exclusive by construction, which is why
2558/// this is an enum rather than a set of flags. Nothing is INFERRED: an unmarked field takes
2559/// [`Projection::Borrowed`], and removing a marker changes an accessor's shape as a visible source
2560/// change rather than silently.
2561#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2562pub enum Projection {
2563  /// Unmarked: `x_ref(&self) -> &T`.
2564  Borrowed,
2565  /// `#[ingraph(copy)]`: `x(&self) -> T` IN ADDITION to the borrow, and `const` mutators.
2566  ///
2567  /// It is a CLAIM, not a fact the emitter can check: a model carries names and types, not trait
2568  /// implementations, so a column marked `copy` whose type is not `Copy` produces an emission that
2569  /// does not compile. The error lands on the generated accessor ("cannot move out of `self.x`"),
2570  /// which names the column, so the claim that was wrong is identifiable.
2571  Copied,
2572  /// `#[ingraph(repeated)]`: `x_slice(&self) -> &[<T as Repeated>::Item]`.
2573  Repeated,
2574  /// `#[ingraph(optional)]`: `x_ref(&self) -> Option<&<T as Optional>::Item>`.
2575  Optional,
2576}
2577
2578impl Projection {
2579  /// Whether this projection hands the column back by value as well as by reference.
2580  pub const fn copies(self) -> bool {
2581    matches!(self, Self::Copied)
2582  }
2583}
2584
2585impl Key {
2586  /// The key's columns in emission order: lineage root-first, then the id.
2587  ///
2588  /// `Clone` because emission walks them more than once — the struct's fields, `new`'s
2589  /// parameters, the method families, and each conversion's body.
2590  pub fn columns(&self) -> impl Iterator<Item = &Column> + Clone {
2591    self.path.iter().chain([&self.id])
2592  }
2593
2594  /// Whether this address is MORE THAN AN ID — the one bit the wire's inward crossing forks on.
2595  ///
2596  /// Read off [`path`](Self::path) rather than by counting [`columns`](Self::columns), because the
2597  /// path IS the fact: a root's is empty and the id is always there, so *compound* and *has a
2598  /// lineage* are one predicate written two ways, and the shorter one cannot disagree with itself.
2599  ///
2600  /// What forks on it: a root key crosses inward as its id's own wire form and mints no type, where
2601  /// a compound one mints [`Role::KeyInput`](Role::KeyInput). See that variant for why the two are
2602  /// not one shape.
2603  pub const fn compound(&self) -> bool {
2604    !self.path.is_empty()
2605  }
2606}
2607
2608/// Where a record is stored, and what each database's row holds.
2609///
2610/// The declared DATABASES are the storage selection: `persist(sqlite, postgres(…))` stores the record
2611/// in those two and nowhere else, and a record with no `persist(…)` block has no [`Persist`] at all.
2612/// Nothing is inferred from a field's type or name — a column exists because a field carried the
2613/// marker.
2614///
2615/// # The NAMES and the SCHEMA are BOTH emitted now, and this is what closed the gap
2616///
2617/// A record's table name reaches the expansion: [`RecordModel::table_name`] resolves a database's
2618/// own `table = "…"` against the record's, and `emit::query`'s binding writes the result into
2619/// `SqlQuery::ADDRESS` and into the scope aliases beside it. So do the COLUMN names and their
2620/// shapes, through `SqlQuery::COLUMNS`, and the whole read and write lane is rendered over them.
2621///
2622/// The BLUEPRINT — `ingraph`'s `Describe<Db>`, whose `Table` carries the type each column is STORED
2623/// AT, whether it holds `NULL`, which fields take an index, which take a UNIQUE one, and which
2624/// collections hang an edge table off the row — **is emitted beside them**, one per declared ∩
2625/// compiled-in SQL dialect. So [`PersistColumn::nullable`], [`PersistColumn::indexed`] and
2626/// [`PersistColumn::unique`] reach a statement, and a record's schema is its declaration's rather
2627/// than a second text kept beside it. `emit::query`'s roster is where the emission and its one
2628/// condition are.
2629///
2630/// # The two obstacles this note recorded, and what each turned out to need
2631///
2632/// **There was no type WORD to emit.** A `Table`'s `Column` carries the dialect's own spelling —
2633/// `INTEGER`, `int8`, `BIGINT` — and nothing derived one from a field's Rust type. sqlx's own
2634/// `Type<Db>::type_info()` was the nearest existing authority and did not serve: its words are
2635/// `INT8`/`INT4`/`FLOAT8` on PostgreSQL where `information_schema.data_type` answers
2636/// `bigint`/`integer`/`double precision`, and `VARCHAR` with no length on MySQL, which that dialect
2637/// will not create — and the drift audit compares with `eq_ignore_ascii_case` and nothing else, so
2638/// an emission through those names would have failed its own audit on two dialects of three. What
2639/// closed it is a FOURTH FACE on the type rather than a table in this crate: `ingraph`'s
2640/// `StoredAs<Db>`, open the way `ColumnKind` is open, whose rows are written in each catalogue's own
2641/// reported spelling and measured against live servers. Every derive that mints a column type mints
2642/// its row with it — a vocabulary enum at its stored form's word, a flags set at the width its
2643/// dialect holds the bits at, a newtype at its inner type's, and a `fields(record)` fragment at the
2644/// CONCATENATION of its parts'.
2645///
2646/// **A composite column's name could not be spelled here.** A descriptor's columns were FLAT and a
2647/// row's are by FIELD, so a `tb: Timebase` would have had to arrive as `tb_num` and `tb_den` — a
2648/// string that exists nowhere, the segments being joined at RENDER time and never in a `const`. What
2649/// closed it is `Table::shaped`, which takes the row's own `ColumnShape` list and leaves every name
2650/// to the renderer, so the join stays exactly where the law already put it and this macro never has
2651/// to see that a field spans two columns.
2652///
2653/// # What the emission still cannot spell, and where each lands
2654///
2655/// Neither is a gap in this model, and both are stated at the point a reader meets them:
2656///
2657/// * a collection this database keeps in a COLUMN — a PostgreSQL array — has no word, the two
2658///   readers of one wanting two different strings. That database gets NO blueprint; it is a
2659///   documented SKIP on `emit::query`'s roster, not an error, so such a record keeps every lane it
2660///   had. `postgres(edge)` lands the schema.
2661/// * a field whose TYPE has no `StoredAs<Db>` row — `TimeRanged<T>`, whose arity depends on a type
2662///   parameter — is `E0277` at that field, spanned there. A macro reading tokens cannot skip on a
2663///   fact about a type, and the trait's own `#[diagnostic::on_unimplemented]` names the
2664///   `<db>(type = "…")` road out.
2665#[derive(Debug, Clone)]
2666pub struct Persist {
2667  /// The declared backends, in the order they were WRITTEN — see [`DatabaseBackend`] for why the
2668  /// order is kept and what keeping it costs. Never empty: a `persist(…)` naming no database is
2669  /// refused, so a [`Persist`] that exists carries at least one row to emit.
2670  pub backends: Vec<DatabaseBackend>,
2671  /// `table = "…"` — the name every declared database uses unless it named its own.
2672  ///
2673  /// Left where the declaration put it rather than resolved onto each [`DatabaseBackend`], because
2674  /// the two are answers to different questions and a DDL lane wants both: the common name is the
2675  /// record's one table name, and a per-database one is an override a reader should be able to see
2676  /// as an override.
2677  ///
2678  /// Both are EMITTED, through one resolution: [`Persist::table_of`] picks the database's own name
2679  /// over the record's and [`RecordModel::table_name`] falls back to the record's in snake case,
2680  /// and what `emit::query` writes into `SqlQuery::ADDRESS` is that answer. So the table a query
2681  /// selects from and the table a migration creates come from the same function — literally the
2682  /// same `const`, since the blueprint PROJECTS `SqlQuery::ADDRESS` rather than restating it. Which
2683  /// is what makes the one name safe to leave unresolved here.
2684  pub table: Option<RustSafeName>,
2685}
2686
2687impl Persist {
2688  /// The table (or collection) one database stores the record in: its own name, or the common one.
2689  pub fn table_of<'a>(&'a self, database: &'a DatabaseBackend) -> Option<&'a RustSafeName> {
2690    database.table().or(self.table.as_ref())
2691  }
2692}
2693
2694impl RecordModel {
2695  /// The table one database stores the record in, RESOLVED — the declared name, or the record's own
2696  /// in snake case.
2697  ///
2698  /// The default is a convention rather than a declaration, and this is the ONE place it is
2699  /// decided: DDL emission reads the same function, so a table a query selects from and a table a
2700  /// migration creates cannot come from two conventions. `Media` is `media`, `VideoTrack` is
2701  /// `video_track` — heck's own word splitting, which is what [`RustSafeName`] already spends for
2702  /// the other direction.
2703  pub fn table_name(&self, database: &DatabaseBackend) -> String {
2704    use heck::ToSnakeCase as _;
2705
2706    self
2707      .persist
2708      .as_ref()
2709      .and_then(|persist| persist.table_of(database))
2710      .map_or_else(
2711        || self.record.to_string().to_snake_case(),
2712        ToString::to_string,
2713      )
2714  }
2715}
2716
2717/// One database a record is stored in — as the backend it actually is.
2718///
2719/// A VARIANT per backend rather than one struct with a `kind` discriminant, so a backend's own
2720/// vocabulary is structural: `MongoDatabase` has a `collection` and no `schema`, and there is no
2721/// way to build a mongo backend carrying one. A shape that carried both and refused the wrong
2722/// combination at parse time could still represent it, and something downstream would eventually
2723/// have to ask.
2724///
2725/// A `Vec` of these on [`Persist`] rather than an `Option` per backend, because DECLARATION ORDER is
2726/// load-bearing: the rows emit in the order the author wrote them, so an expansion is stable and
2727/// diffable. Four `Option` fields would impose an arbitrary fixed order instead. The cost is that
2728/// a `Vec` can hold `Sqlite` twice where four `Option`s could not — so "one block per database"
2729/// moves from structural to CHECKED, and the parser's `set_once` on the block is now the only thing
2730/// between the model and a state it can represent. `refuses_a_repeated_persist_block_or_option` pins
2731/// that refusal, and a mutation proves the pin.
2732///
2733/// **Three of these four payloads are near-identical today**, and that is measured rather than
2734/// assumed: `table`/`collection` is one slot with two spellings, `schema` is the only SQL-only
2735/// option, and the FIELD-level option set (`rename`, `type`, `indexed`, `unique`, `copy`, the
2736/// conversions) diverges not at all. So `SqliteDatabase`, `PostgresDatabase` and `MySqlDatabase`
2737/// start as the same three fields.
2738///
2739/// They are separate anyway, and deliberately: the divergence that is coming is per BACKEND rather
2740/// than per family — MySQL's engine and charset, Postgres's index methods and tablespace, SQLite's
2741/// journal mode, Mongo's write concern. Splitting a shared `SqlDatabase` later would touch every
2742/// emission site that named it, where four small structs localise each arrival to one variant. The
2743/// duplication is four fields, which is cheap; the later split would not be. If that divergence
2744/// never arrives, this is the decision to reverse, and the measurement above is what to reverse it
2745/// against.
2746///
2747/// CLOSED, and not an oversight in a framework that otherwise refuses closed sets: codegen has to
2748/// KNOW a backend to emit its code — its derives, its rename attribute, its dialect — so a
2749/// third-party backend is a change to this crate whichever shape this takes. Openness for backends
2750/// lives where the spec puts it: traits, visitors, and a codegen plugin. `#[non_exhaustive]` so
2751/// adding the next variant is not a breaking change for anyone matching from outside.
2752#[derive(Debug, Clone)]
2753#[non_exhaustive]
2754pub enum DatabaseBackend {
2755  /// SQLite.
2756  Sqlite(SqliteDatabase),
2757  /// PostgreSQL.
2758  Postgres(PostgresDatabase),
2759  /// MySQL.
2760  MySql(MySqlDatabase),
2761  /// MongoDB.
2762  Mongo(MongoDatabase),
2763}
2764
2765/// What every backend carries, whatever its own vocabulary adds.
2766///
2767/// One struct embedded in each backend rather than six fields repeated four times — the emission
2768/// reads these and nothing else for most of its work, and a field that meant something different
2769/// per backend would not be here.
2770#[derive(Debug, Clone)]
2771pub struct Storage {
2772  /// The name of the emitted ROW type — [`default_row_name`] unless `row(rename = "…")` named it.
2773  pub name: syn::Ident,
2774  /// The name of the emitted COMPARISON type — [`default_comparison_name`] unless
2775  /// `comparison(rename = "…")` named it.
2776  ///
2777  /// Its OWN block, because a database emits two types and a bare `rename` could not say which.
2778  pub comparison: syn::Ident,
2779  /// A conversion for the WHOLE row: `from` BUILDS this projection, so domain → row. A write.
2780  pub from: Conversion,
2781  /// A conversion for the WHOLE row: `into` LEAVES this projection, so row → domain. A read.
2782  ///
2783  /// When it is not [`Conversion::Default`] it replaces the field-wise body, which is what lets a
2784  /// PARTIAL row reach the record at all — the field-wise read can only be emitted when the row
2785  /// carries every field.
2786  pub into: Conversion,
2787  /// THIS DATABASE's columns, in the record's declaration order.
2788  ///
2789  /// # The participation MASK, and what it is a mask over
2790  ///
2791  /// The universal list is every data field the record declares less the ones wearing `skip` — the
2792  /// inversion's own answer, and the whole list for a declaration that narrows nothing. This one is
2793  /// that list masked by what each field said to THIS database: a bare `<db>` list keeps the
2794  /// databases it names, and `<db>(skip(default = "…"))` drops the one it names.
2795  ///
2796  /// So the databases may now DISAGREE about which columns exist, and every seat that reads a
2797  /// per-database fact reads this one: the row struct, the `INSERT` list, the `SELECT`, this
2798  /// database's comparison and its own duplicate-name fence. The seats that must not vary with a
2799  /// deployment's storage choice read the INTERSECTION instead — see
2800  /// [`RecordModel::stored_columns`], where the shared query vocabulary is stated.
2801  ///
2802  /// What a field withheld from this database still owes is the READ, and [`fills`](Self::fills) is
2803  /// where that is answered.
2804  pub columns: Vec<PersistColumn>,
2805  /// What THIS DATABASE's raise supplies for the fields its row does not carry.
2806  ///
2807  /// # A per-database seat, where `skip` at the field is the record's own
2808  ///
2809  /// A field wearing the bare `skip` is a column of no database, so every raise supplies it from the
2810  /// one fill that word named and the answer does not vary — that stays read off the record's own
2811  /// fields. This is the OTHER absence: a field that IS a column of the record's other databases and
2812  /// not of this one, whose fill is therefore this database's own.
2813  ///
2814  /// EMPTY is the ordinary case, and is every declaration that narrows nothing. A partial absence
2815  /// with no fill never reaches here — it is a named refusal at the word that narrowed, because a
2816  /// value that round-trips out of one store and is invented out of the next is a difference only
2817  /// the declaration can record.
2818  pub fills: Vec<Filled>,
2819  /// `alias(…)` — the namespace and the depth this database's row-source names are minted at.
2820  ///
2821  /// Here rather than on the four backend structs because it is the same option in all four: an
2822  /// alias is a name a NESTED scope calls a row source by, which every backend that nests one has.
2823  /// Which is also why it is per BACKEND rather than per record — see [`AliasOptions`].
2824  pub aliases: AliasOptions,
2825}
2826
2827/// `<db>(alias(prefix = "__mine", depth = 16))` — one database's answer about the names its
2828/// nested scopes mint, in the two states each half has.
2829///
2830/// # Per DATABASE, because the emitted table already is
2831///
2832/// `ALIASES` rides one `SqlQuery<Db>` impl, so a record stored in two databases already carries two
2833/// of them; letting the two differ cost nothing that was not already there. And the user story is
2834/// per database too: one deployment's schema holds legacy tables inside the default namespace and
2835/// the others do not, so the override belongs on that database and nowhere else.
2836///
2837/// # DECLARED-or-not is kept, and the FENCE is what needs it
2838///
2839/// [`prefix_in`](Self::prefix_in) resolves to the MODEL's own
2840/// [`EmissionPrefix`](crate::prefix::EmissionPrefix) where nothing was written, which is what the
2841/// emission spends. What the fence needs is the other question — whether anything was written at
2842/// all — because it refuses the union of every DECLARED prefix plus the default wherever a database
2843/// still defaults. A record that overrode every one of its databases has handed `__ig*` back to its
2844/// author, and a model that had already collapsed the absent case into the default could not tell.
2845///
2846/// # The fallback is the MODEL's namespace and not this crate's constant
2847///
2848/// Two seats, one answer: `<db>(alias(prefix = …))` is what a DECLARATION moves, and
2849/// [`RecordModel::prefix`] is what a FRAMEWORK building the model moves. The declaration's word
2850/// wins where it is written, and where it is not the answer is the framework's own mark — so a
2851/// model `mediagraph-codegen` built defaults to `__mg` here, rather than to `ingraph`'s `__ig`
2852/// through a constant that has never heard of it.
2853#[derive(Debug, Clone, Default)]
2854pub struct AliasOptions {
2855  /// `prefix = "…"`, or [`None`] where this database took the default.
2856  pub prefix: Option<String>,
2857  /// `depth = N`, or [`None`] where this database took the default.
2858  pub depth: Option<usize>,
2859}
2860
2861impl AliasOptions {
2862  /// The namespace this database's names are minted in — its own, or the framework's.
2863  ///
2864  /// `prefix` is the model's, so an absent `prefix = "…"` resolves to whichever framework built
2865  /// this declaration rather than to a constant. Every name minted FOR one database goes through
2866  /// here: the row aliases, and the companion column beside them.
2867  #[must_use]
2868  pub fn prefix_in<'a>(&'a self, prefix: &'a EmissionPrefix) -> &'a str {
2869    self.prefix.as_deref().unwrap_or_else(|| prefix.mark())
2870  }
2871
2872  /// How many depths this database's aliases are minted for — its own, or the framework's.
2873  #[must_use]
2874  pub fn depth(&self) -> usize {
2875    self.depth.unwrap_or(crate::alias::DEPTH_CEILING)
2876  }
2877}
2878
2879/// SQLite's own options.
2880#[derive(Debug, Clone)]
2881pub struct SqliteDatabase {
2882  /// `table = "…"`, overriding [`Persist::table`].
2883  pub table: Option<RustSafeName>,
2884  /// `unique(…)` — the composite constraints this database holds, in written order.
2885  pub uniques: Vec<CompositeUnique>,
2886  /// `schema = "…"` — SQLite's attached-database name. Parsed and read by NOTHING: no emitted name
2887  /// is qualified by it, so the table this database is addressed by is the bare one. Unlike the
2888  /// [`table`](Self::table) beside it, which does emit — see [`Persist`].
2889  pub schema: Option<String>,
2890  /// Everything every backend carries.
2891  pub storage: Storage,
2892}
2893
2894/// PostgreSQL's own options.
2895#[derive(Debug, Clone)]
2896pub struct PostgresDatabase {
2897  /// `table = "…"`, overriding [`Persist::table`].
2898  pub table: Option<RustSafeName>,
2899  /// `unique(…)` — the composite constraints this database holds, in written order.
2900  pub uniques: Vec<CompositeUnique>,
2901  /// `schema = "…"`. Read by nothing, per [`SqliteDatabase::schema`].
2902  pub schema: Option<String>,
2903  /// Everything every backend carries.
2904  pub storage: Storage,
2905}
2906
2907/// MySQL's own options.
2908#[derive(Debug, Clone)]
2909pub struct MySqlDatabase {
2910  /// `table = "…"`, overriding [`Persist::table`].
2911  pub table: Option<RustSafeName>,
2912  /// `unique(…)` — the composite constraints this database holds, in written order.
2913  pub uniques: Vec<CompositeUnique>,
2914  /// `schema = "…"` — MySQL's word for a database. Read by nothing, per
2915  /// [`SqliteDatabase::schema`].
2916  pub schema: Option<String>,
2917  /// Everything every backend carries.
2918  pub storage: Storage,
2919}
2920
2921/// MongoDB's own options.
2922///
2923/// A `collection` and no `schema`, which is the whole point of splitting the type: mongo's
2924/// vocabulary is not SQL's, and now it cannot be given SQL's.
2925#[derive(Debug, Clone)]
2926pub struct MongoDatabase {
2927  /// `collection = "…"`, overriding [`Persist::table`]. Mongo's word for the same thing.
2928  pub collection: Option<RustSafeName>,
2929  /// Everything every backend carries.
2930  pub storage: Storage,
2931}
2932
2933/// ONE `<db>(unique(a, b, …))` — a COMPOSITE unique constraint, resolved to this database's own
2934/// column names.
2935///
2936/// # It is SQL's and it is per DATABASE, which is why it is not on [`Storage`]
2937///
2938/// `Storage` is what every backend carries. A composite unique is not: this crate's mongo emission
2939/// renders a collection and builds no index, so the word is refused there BY NAME rather than
2940/// carried and dropped — see `composite_unique` in `ingraph-derive`. Holding the list on the three
2941/// SQL structs is the same split [`MongoDatabase`] already makes for `schema`: mongo's vocabulary is
2942/// not SQL's, and now it cannot be given SQL's.
2943///
2944/// # The entries are COLUMN names, and the audit is already spent
2945///
2946/// What the declaration wrote are FIELD idents. By the time one is here it has been held against
2947/// this database's own column list — every entry names a field this record declares, this database
2948/// carries, and stores in a column of the row — so the emission reads this list and asks nothing.
2949/// A `rename` is already applied, because it is the emitted name that reaches a `CREATE UNIQUE
2950/// INDEX` and a check on the Rust name would walk straight past one.
2951#[derive(Debug, Clone)]
2952pub struct CompositeUnique {
2953  /// The columns the constraint is over, in the order the declaration wrote them — which is the
2954  /// order the index carries them, a composite index being answerable by a leading prefix.
2955  pub entries: Vec<RustSafeName>,
2956}
2957
2958impl DatabaseBackend {
2959  /// Which database this is — for a message, a suffix, or a family.
2960  pub const fn kind(&self) -> DatabaseKind {
2961    match self {
2962      Self::Sqlite(_) => DatabaseKind::Sqlite,
2963      Self::Postgres(_) => DatabaseKind::Postgres,
2964      Self::MySql(_) => DatabaseKind::Mysql,
2965      Self::Mongo(_) => DatabaseKind::Mongo,
2966    }
2967  }
2968
2969  /// What every backend carries.
2970  pub const fn storage(&self) -> &Storage {
2971    match self {
2972      Self::Sqlite(db) => &db.storage,
2973      Self::Postgres(db) => &db.storage,
2974      Self::MySql(db) => &db.storage,
2975      Self::Mongo(db) => &db.storage,
2976    }
2977  }
2978
2979  /// The table this backend stores the record in — or the collection, which is the same option
2980  /// under mongo's own word for it.
2981  pub const fn table(&self) -> Option<&RustSafeName> {
2982    match self {
2983      Self::Sqlite(db) => db.table.as_ref(),
2984      Self::Postgres(db) => db.table.as_ref(),
2985      Self::MySql(db) => db.table.as_ref(),
2986      Self::Mongo(db) => db.collection.as_ref(),
2987    }
2988  }
2989
2990  /// `schema = "…"`, for the backends that have one. `None` for mongo, which has none to have.
2991  pub fn schema(&self) -> Option<&str> {
2992    match self {
2993      Self::Sqlite(db) => db.schema.as_deref(),
2994      Self::Postgres(db) => db.schema.as_deref(),
2995      Self::MySql(db) => db.schema.as_deref(),
2996      Self::Mongo(_) => None,
2997    }
2998  }
2999
3000  /// `unique(…)` — the COMPOSITE constraints this backend holds, in written order.
3001  ///
3002  /// EMPTY for mongo, and structurally so: the word is refused there by name, and there is no field
3003  /// on [`MongoDatabase`] for one to have been stored in. [`schema`](Self::schema)'s own shape, for
3004  /// [`CompositeUnique`]'s reason.
3005  pub fn composite_uniques(&self) -> &[CompositeUnique] {
3006    match self {
3007      Self::Sqlite(db) => &db.uniques,
3008      Self::Postgres(db) => &db.uniques,
3009      Self::MySql(db) => &db.uniques,
3010      Self::Mongo(_) => &[],
3011    }
3012  }
3013
3014  /// The name of the emitted ROW type.
3015  pub const fn name(&self) -> &syn::Ident {
3016    &self.storage().name
3017  }
3018
3019  /// The name of the emitted COMPARISON type. `_name`, because `comparison` is the method that
3020  /// EMITS it — the pair `name`/`row` reads the same way.
3021  pub const fn comparison_name(&self) -> &syn::Ident {
3022    &self.storage().comparison
3023  }
3024
3025  /// This backend's columns, in the record's declaration order.
3026  pub const fn columns(&self) -> &[PersistColumn] {
3027    self.storage().columns.as_slice()
3028  }
3029
3030  /// The whole-row conversion that BUILDS this projection.
3031  pub const fn from(&self) -> &Conversion {
3032    &self.storage().from
3033  }
3034
3035  /// The whole-row conversion that LEAVES it.
3036  pub const fn into(&self) -> &Conversion {
3037    &self.storage().into
3038  }
3039}
3040
3041/// One column of ONE database's row.
3042///
3043/// Per database rather than shared, because nearly everything about a column can differ between
3044/// backends: the same field may be a `BeU64` on one and a `Vec<u8>` on another, be called
3045/// `bit_rate` in one table and `bit_rate_v2` in the next, and be indexed in one alone.
3046#[derive(Debug, Clone)]
3047pub struct PersistColumn {
3048  /// The RECORD field this column projects — what a conversion reads and writes.
3049  pub source: syn::Ident,
3050  /// The column's name in THIS database: the field's own, the common `rename`, or this database's.
3051  pub name: RustSafeName,
3052  /// The record field's declared type, verbatim.
3053  pub domain: syn::Type,
3054  /// `type = "…"` — the type this database STORES, when it is not the domain one.
3055  pub stored: Option<syn::Type>,
3056  /// `edge` in this database's block: this COLLECTION is kept in a second table here rather than in
3057  /// a column of the row.
3058  ///
3059  /// # It is Postgres's word and nobody else's, and the asymmetry is the whole design
3060  ///
3061  /// Postgres is the one dialect with two usable strategies — a native `ARRAY` column for the
3062  /// elements an array can hold, and the same edge table the other two dialects have no choice but
3063  /// to use — and which one an element takes is a fact about the ELEMENT rather than about the
3064  /// dialect. That fact lives in a trait row (`ingraph`'s `PgCollectionStorage`), and a macro
3065  /// holding tokens cannot read one, so the DECLARATION is where it is stated.
3066  ///
3067  /// # OPTIONAL, and the ground is which way each default is WRONG
3068  ///
3069  /// Absent, the column rides the row as an array, which is the default because its failure is
3070  /// LOUD: an element no array can hold has no `Carrier<Postgres>` row for the collection type, and
3071  /// the storability audit is `E0277` at the `#[ingraph::record(…)]` — naming the type, at the
3072  /// declaration, with this word as the answer. Defaulting the other way has no such signal: every
3073  /// array-eligible collection would quietly take a second table, a whole extra statement per page,
3074  /// and nothing would ever say so.
3075  ///
3076  /// So a word is asked for exactly where the compiler has already stopped, and never where it
3077  /// would not have. Neither direction is a claim this crate trusts: the word's emission binds the
3078  /// edge kinds and the wordless path binds the array's carrier, so both are checked at a concrete
3079  /// dialect.
3080  ///
3081  /// SQLite and MySQL carry `false` always — `ingraph-derive` refuses the word there, those dialects
3082  /// having no strategy to choose — so a reader of this field never has to ask which database it is
3083  /// about before knowing what `false` means. See [`DatabaseKind::edge_collections`], which is the
3084  /// dialect's own half of the same question.
3085  pub edge: bool,
3086  /// `copy` in this database's block: the STORED type is `Copy`.
3087  ///
3088  /// Declared per database rather than taken from the domain field's own marker, because the two
3089  /// are different claims about different types and a macro has no type information to bridge
3090  /// them. It shapes the row's accessors exactly as [`Projection::Copied`] shapes the record's.
3091  pub copy: bool,
3092  /// Whether the column is NULLABLE.
3093  ///
3094  /// It follows the `optional` MARKER, never the field's spelled type — the macro cannot inspect
3095  /// types, which is why the whole projection is marker-driven — and it is not overridable. A
3096  /// domain/column disagreement fails loudly in BOTH directions (a null decoded into a required
3097  /// field is a decode error; a `None` written to a `NOT NULL` column is a constraint violation),
3098  /// so an override would buy better wording at the price of a knob that hides the schema bug it
3099  /// reconciles.
3100  ///
3101  /// It reaches the `CREATE TABLE` this record's expansion emits — one flag per FIELD in the
3102  /// blueprint's own list — and it says the WHOLE field may be absent, which is the only thing a
3103  /// marker on a field can say. There is no spelling here for *this segment holds `NULL` and that
3104  /// one does not*, and there does not need to be: a leaf that holds `NULL` whatever its field says
3105  /// declares so on its own segment, as `ingraph`'s `ColumnShape::Nullable`, and reaches the
3106  /// renderer through the TYPE rather than through this flag. The renderer composes the two, so a
3107  /// required `MediaTimestamp` still declares its derived column nullable and this marker is not
3108  /// asked about it.
3109  ///
3110  /// It also reaches the row, as it always did: a nullable column's field is an `Option`, its bind
3111  /// writes one `NULL` per column the value would occupy, and its cursor slot unwraps one.
3112  pub nullable: bool,
3113  /// `indexed` in this database's block.
3114  ///
3115  /// SPENT: `ingraph`'s `Table::with_indexes` takes the list, `Table::create` renders one
3116  /// `CREATE INDEX` per field, and the emitted blueprint is what hands the list over.
3117  ///
3118  /// A COLLECTION this database keeps in a SECOND TABLE is refused the word at the front end — there
3119  /// is no column of this row to index, and the elements' own table already carries the containment
3120  /// index a `list(…)` wants. On a dialect that keeps the collection in a COLUMN the word stays
3121  /// legal and is inert, that database having no blueprint at all; see [`Persist`].
3122  pub indexed: bool,
3123  /// `unique` in this database's block: the column's values are each held by at most one row, this
3124  /// database's own constraint to enforce.
3125  ///
3126  /// SPENT with [`indexed`](Self::indexed) and through the same list, and refused on a COLLECTION
3127  /// wherever it is written — a row here holds MANY values and there is no single one for the
3128  /// comparison to be about.
3129  ///
3130  /// Legal beside `indexed` on the same field — the two words state independent intents, a seek and
3131  /// a constraint, and it is the SCHEMA lane that later collapses them to one statement rather than
3132  /// this model refusing the pair.
3133  pub unique: bool,
3134  /// `flatten` in THIS database's block: the field's own name is dropped, so its type's columns join
3135  /// the holder's namespace — `num`/`den` where the same field unmarked gives `tb_num`/`tb_den`.
3136  ///
3137  /// # It is a NAMING knob, and flattening is the default beneath it
3138  ///
3139  /// A field whose type spans several columns is flattened wherever it is stored; what this decides
3140  /// is only whether the field's name PREFIXES those columns. So the word adds no layout and removes
3141  /// one segment, and a collision with a column the holder already has falls to the same-name
3142  /// refusal by name rather than being prefixed away silently.
3143  ///
3144  /// # PER DATABASE, because it is one database's schema decision
3145  ///
3146  /// It was common while it was read as a layout claim. It is not one: a legacy table whose columns
3147  /// are already `num`/`den` is a fact about that database, and the axis law puts a per-database
3148  /// decision in the database's block. Mongo's block has no `flatten` at all — its default IS the
3149  /// nested subdocument, so there is no prefix there to drop — which makes the invalid state
3150  /// unspellable rather than refused, and `mongo(flatten)` still refuses by name.
3151  ///
3152  /// The macro cannot check the type — `tb: Timebase` and `title: String` are the same tokens — so
3153  /// what refuses `flatten` on a single-column field is the SEGMENT COUNT, at
3154  /// `ingraph`'s `flattened`: an `E0080` where the row's `COLUMNS` is evaluated.
3155  pub flatten: bool,
3156  /// `from` BUILDS the row, so domain → stored: what a WRITE applies to this column.
3157  pub from: Conversion,
3158  /// `into` LEAVES the row, so stored → domain: what a READ applies to this column.
3159  pub into: Conversion,
3160}
3161
3162impl PersistColumn {
3163  /// The type the emitted row's field carries: the `type` override, or the domain type.
3164  pub const fn ty(&self) -> &syn::Type {
3165    stored_type(self.stored.as_ref(), &self.domain)
3166  }
3167
3168  /// What the DECLARATION calls this column — the record's own field name, unraw'd.
3169  ///
3170  /// The CONSTANT axis of the declared→stored pairing: [`name`](Self::name) is per database and
3171  /// this is the same string in every one of them, which is what makes it the key a reverse
3172  /// relation's `field = "…"` is looked up by. It is the field's name and not its `rename`, because
3173  /// a rename — common or per database — is a STORAGE word, and the vocabulary a neighbouring
3174  /// declaration writes is the record's own.
3175  ///
3176  /// Unraw'd, so a field spelled `r#type` is declared `type`: a `field = "…"` literal is a name
3177  /// somebody writes rather than Rust tokens, and the raw prefix is a fact about the token.
3178  pub fn declared(&self) -> String {
3179    self.source.unraw().to_string()
3180  }
3181}
3182
3183/// How one side of a conversion is performed.
3184///
3185/// THREE states rather than a path beside a `fallible` flag, so `from`-xor-`try_from` cannot be
3186/// represented at all: a declaration that wrote both has no model to land in, and the refusal is a
3187/// parse-time report rather than a rule some later pass has to remember to check.
3188///
3189/// # The verb rule
3190///
3191/// **`from` BUILDS this projection; `into` LEAVES it.** Relative to the projection the block is
3192/// about, never to the domain — one rule across every family, rather than one convention per
3193/// family:
3194///
3195/// | declaration | direction | when |
3196/// |---|---|---|
3197/// | `<db>(from \| try_from)` | domain → row | a write |
3198/// | `<db>(into \| try_into)` | row → domain | a read |
3199/// | `graphql(input(into \| try_into))` | input → domain | |
3200/// | `graphql(output(from \| try_from))` | domain → output | |
3201///
3202/// It matches the emitted impls literally: `impl From<VideoTrack> for VideoTrackPostgres` IS "the
3203/// row from the domain", so the declaration that fills it is the row's `from`.
3204#[derive(Debug, Clone, Default, PartialEq, Eq)]
3205pub enum Conversion {
3206  /// Nothing was declared: move the value, or `Into::into` it when the stored type differs.
3207  #[default]
3208  Default,
3209  /// `from = "…"` / `into = "…"` — a function that cannot fail.
3210  Infallible(syn::Path),
3211  /// `try_from = "…"` / `try_into = "…"` — a function returning a `Result`.
3212  Fallible(FallibleConversion),
3213}
3214
3215/// A crossing that can FAIL, and how its error reaches the record's own.
3216///
3217/// # The escape, and why the default is not one
3218///
3219/// A fallible leg is emitted as `f(value)?`, and the `?` is what asks the record's error to absorb
3220/// whatever `f` reports — `From`, which `core`'s own blanket already supplies for the boxed default.
3221/// Where that `From` cannot exist the `?` is `E0277` naming the offending function's error, which is
3222/// a better sentence than any wrapper this emitter could write, and it is the compiler's.
3223///
3224/// [`escape`](Self::escape) is the way out for the cases where the bound genuinely cannot hold: two
3225/// FOREIGN types either side of the impl (the orphan rule, which the comparison layer's own crossing
3226/// already documents), an error a caller wants to WRAP with context rather than absorb, and a
3227/// function whose error is not an `Error` at all. It is `fn(FnErr) -> RecordErr`, applied at the
3228/// crossing, so a signature that does not line up is `E0308` at the call.
3229#[derive(Debug, Clone, PartialEq, Eq)]
3230pub struct FallibleConversion {
3231  /// The declared function.
3232  pub path: syn::Path,
3233  /// `try_from_with = "…"` / `try_into_with = "…"` — the map from this function's error into the
3234  /// record's, where `From` is unavailable. `None` is the plain `?`.
3235  pub escape: Option<syn::Path>,
3236}
3237
3238impl Conversion {
3239  /// Whether this conversion can fail — the one bit that decides `From` or `TryFrom`.
3240  pub const fn fallible(&self) -> bool {
3241    matches!(self, Self::Fallible(_))
3242  }
3243
3244  /// Whether the declaration named a function for this side.
3245  pub const fn declared(&self) -> bool {
3246    !matches!(self, Self::Default)
3247  }
3248}
3249
3250/// A database a record may be stored in.
3251///
3252/// A CLOSED vocabulary, and deliberately so: this is the framework's own list of backends, and
3253/// each one's row carries a different derive, a different rename attribute and a different
3254/// dialect. An open seam belongs where a user extends the framework; a database the framework does
3255/// not ship an emitter for has nothing to be opened.
3256#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
3257pub enum DatabaseKind {
3258  /// SQLite.
3259  Sqlite,
3260  /// PostgreSQL.
3261  Postgres,
3262  /// MySQL.
3263  Mysql,
3264  /// MongoDB.
3265  Mongo,
3266}
3267
3268impl DatabaseKind {
3269  /// Every database, in the order a refusal lists them.
3270  pub const ALL: [Self; 4] = [Self::Sqlite, Self::Postgres, Self::Mysql, Self::Mongo];
3271
3272  /// The name a declaration writes: `sqlite`, `postgres`, `mysql`, `mongo`.
3273  pub const fn as_str(self) -> &'static str {
3274    match self {
3275      Self::Sqlite => "sqlite",
3276      Self::Postgres => "postgres",
3277      Self::Mysql => "mysql",
3278      Self::Mongo => "mongo",
3279    }
3280  }
3281
3282  /// The arm of `ingraph::drive::RetiredEngine` this database is — what the `retired(<engine>)`
3283  /// word emits.
3284  ///
3285  /// A SECOND mapping beside [`suffix`](Self::suffix) rather than a reuse of it, because the two
3286  /// name different things: `suffix` is sqlx's own spelling of a DRIVER (`MySql`), and this is an
3287  /// arm of a framework enum whose spelling is the framework's (`Mysql`). One drifting into the
3288  /// other would emit a path that does not exist.
3289  pub const fn retired_arm(self) -> &'static str {
3290    match self {
3291      Self::Sqlite => "Sqlite",
3292      Self::Postgres => "Postgres",
3293      Self::Mysql => "Mysql",
3294      Self::Mongo => "Mongo",
3295    }
3296  }
3297
3298  /// The arm of `ingraph::drive::GenerationsEngine` this database is — what the
3299  /// `generations(<engine>)` word emits — or [`None`] where this database has no arm there.
3300  ///
3301  /// [`retired_arm`](Self::retired_arm)'s sibling, and a THIRD mapping for its reason: two framework
3302  /// enums are two vocabularies, and one spelling serving both is how they come to disagree.
3303  ///
3304  /// It differs from that one in being PARTIAL. [`Mongo`](Self::Mongo) answers [`None`], and the
3305  /// absence is the generations seat's own scope rather than an oversight: its retention duty is an
3306  /// anchored `DELETE` whose bound is a correlated subquery over a table's distinct runs, which is a
3307  /// SQL shape. A document store sweeps the same closure by MEMBERSHIP, which is a second
3308  /// implementation of `ingraph::GenerationsStore` and not a fourth arm here — so the retirement
3309  /// ledger takes four words and this takes three.
3310  pub const fn generations_arm(self) -> Option<&'static str> {
3311    match self {
3312      Self::Sqlite => Some("Sqlite"),
3313      Self::Postgres => Some("Postgres"),
3314      Self::Mysql => Some("Mysql"),
3315      Self::Mongo => None,
3316    }
3317  }
3318
3319  /// The suffix the emitted row type takes when nothing renamed it — sqlx's own spellings.
3320  pub const fn suffix(self) -> &'static str {
3321    match self {
3322      Self::Sqlite => "Sqlite",
3323      Self::Postgres => "Postgres",
3324      Self::Mysql => "Mysql",
3325      Self::Mongo => "Mongo",
3326    }
3327  }
3328
3329  /// The SHELF path a CONCRETE backend type is reached through — the module segments and the item.
3330  ///
3331  /// The ONE authority on which type each database IS, because two emissions now name one: a
3332  /// record's storability audit binds `Record<Db>` at it, and an interface's row equation projects
3333  /// through the same trait at the same backend. Two spellings of one mapping is how a declaration
3334  /// comes to be audited at one backend and read at another.
3335  ///
3336  /// MongoDB's is not under the vendored `sqlx` segment: its backend is this crate's own name, for
3337  /// the reason `comparison::mongo::Mongo` gives — there is no driver unit struct to borrow, because
3338  /// a MongoDB comparison has no dialect to remember.
3339  pub const fn backend(self) -> (&'static [&'static str], &'static str) {
3340    match self {
3341      Self::Sqlite => (&["sqlx"], "Sqlite"),
3342      Self::Postgres => (&["sqlx"], "Postgres"),
3343      Self::Mysql => (&["sqlx"], "MySql"),
3344      Self::Mongo => (&["comparison", "mongo"], "Mongo"),
3345    }
3346  }
3347
3348  /// The CURSOR seam's marker for this database — the module segments and the item.
3349  ///
3350  /// A second mapping beside [`backend`](Self::backend) rather than a reuse of it, because the two
3351  /// answer different questions. A backend is the DRIVER, and every emission that names one rides
3352  /// that dialect's feature gate. A cursor's bytes name no driver — `ingraph::cursor` is compiled
3353  /// under no backend's feature, *a position in a written order naming no database* — so the seam
3354  /// that says WHICH STORE's bytes these are is keyed on a marker the framework always ships, and
3355  /// every mention of it is ungated.
3356  pub const fn dialect(self) -> (&'static [&'static str], &'static str) {
3357    match self {
3358      Self::Sqlite => (&["cursor", "dialect"], "Sqlite"),
3359      Self::Postgres => (&["cursor", "dialect"], "Postgres"),
3360      Self::Mysql => (&["cursor", "dialect"], "Mysql"),
3361      Self::Mongo => (&["cursor", "dialect"], "Mongo"),
3362    }
3363  }
3364
3365  /// Whether this database speaks SQL — which decides the row's derives, its rename attribute, and
3366  /// whether it has a `schema` and a `table` rather than a `collection`.
3367  pub const fn is_sql(self) -> bool {
3368    matches!(self, Self::Sqlite | Self::Postgres | Self::Mysql)
3369  }
3370
3371  /// Whether a COLLECTION column is kept in a second table here, so its elements are rows and not a
3372  /// value of the record's own row.
3373  ///
3374  /// This is `ingraph`'s `CollectionStorage` read one layer up, and only the two dialects whose row
3375  /// is unconditional can be read: SQLite and MySQL have no array type, so every collection they
3376  /// store goes to an edge table whatever its element is. Both answer `true` here for exactly the
3377  /// reason their impls carry no choice.
3378  ///
3379  /// **Postgres answers `false`, and that is its DEFAULT rather than its only answer.** Its strategy
3380  /// is a fact about the ELEMENT — `PgCollectionStorage`'s row says whether an array can hold one,
3381  /// and lets a row decline the array anyway — and a row is a trait implementation, which a macro
3382  /// reading tokens cannot see. So the dialect answers with the default here and the DECLARATION
3383  /// says otherwise where it must: [`PersistColumn::edge`], the optional word, which is the other
3384  /// half of the same question and the one place the element-level fact can be stated.
3385  ///
3386  /// Mongo answers `false` because it has no edge table to answer with: a document holds its own
3387  /// array, and none of the SQL plan reaches it.
3388  pub const fn edge_collections(self) -> bool {
3389    match self {
3390      Self::Sqlite | Self::Mysql => true,
3391      Self::Postgres | Self::Mongo => false,
3392    }
3393  }
3394}
3395
3396/// The record's PROGRESS ledger: which databases host it.
3397///
3398/// A ledger is a pair of control tables in the unit's OWN `persist` pool — `SqliteProgress::new` takes
3399/// that pool — so its hosts are the declared `persist` databases, and a record with no `persist(…)`
3400/// has no pool to live in. Nothing else has to be declared for one to exist: what it certifies is the
3401/// unit's close, which every stored record has. Derived from the storage alone, therefore, and never
3402/// asked for.
3403///
3404/// Its hosts are the `persist` databases that SHIP a ledger, which may be fewer than [`Persist::backends`]
3405/// and, for a record stored only in MySQL or MongoDB, none — leaving no [`Progress`] at all. A
3406/// SHORTER list rather than a refusal, because nothing here was asked for: a ledger is bookkeeping the
3407/// framework adds wherever a pool can hold it, so a database with no backend for one leaves out
3408/// nothing anybody declared.
3409///
3410/// It carries no root declaration. The ledger is keyed by the WORK's root, the `root` column's DDL
3411/// type is `<Root as Typed>::COLUMN`, and the root is the key's FIRST column — its leading lineage
3412/// step, or the id itself for a root record. Derived, therefore, and a declared one could only
3413/// disagree with the key it is minted for.
3414#[derive(Debug, Clone)]
3415pub struct Progress {
3416  /// The [`Persist::backends`] that ship a ledger, in that order. Never empty: a record none of whose
3417  /// databases hosts one has no [`Progress`] rather than an empty list.
3418  pub hosts: Vec<ProgressHost>,
3419}
3420
3421/// One database hosting a record's progress ledger.
3422///
3423/// TWO variants where [`DatabaseBackend`] has four, and that is a measurement rather than an
3424/// oversight: `store/progress/` contains `sqlite/` and `postgres/`, and there is no MySQL or MongoDB
3425/// ledger. What the missing two make unrepresentable is a ledger in a database that ships none. When a
3426/// third backend arrives, a variant lands here and [`of`](Self::of) gains an arm; nothing else moves.
3427#[derive(Debug, Clone)]
3428#[non_exhaustive]
3429pub enum ProgressHost {
3430  /// SQLite.
3431  Sqlite(SqliteProgress),
3432  /// PostgreSQL.
3433  Postgres(PostgresProgress),
3434}
3435
3436/// SQLite's own ledger options — none yet. The control tables' names come from the store's
3437/// `ControlTables` at construction, and the `root` column's type from the root itself.
3438#[derive(Debug, Clone)]
3439pub struct SqliteProgress {}
3440
3441/// PostgreSQL's own ledger options — none yet, for [`SqliteProgress`]'s reason.
3442#[derive(Debug, Clone)]
3443pub struct PostgresProgress {}
3444
3445impl ProgressHost {
3446  /// Which database this is.
3447  pub const fn kind(&self) -> DatabaseKind {
3448    match self {
3449      Self::Sqlite(_) => DatabaseKind::Sqlite,
3450      Self::Postgres(_) => DatabaseKind::Postgres,
3451    }
3452  }
3453
3454  /// `kind`'s ledger, or `None` when the framework ships none for it.
3455  ///
3456  /// The ONE authority on which of [`DatabaseKind`]'s four can host a ledger. A front end asks this
3457  /// rather than testing a list, so a database is admitted only when there is a variant for it to
3458  /// land in — the predicate and the constructor cannot drift, because there is no predicate.
3459  pub const fn of(kind: DatabaseKind) -> Option<Self> {
3460    match kind {
3461      DatabaseKind::Sqlite => Some(Self::Sqlite(SqliteProgress {})),
3462      DatabaseKind::Postgres => Some(Self::Postgres(PostgresProgress {})),
3463      DatabaseKind::Mysql | DatabaseKind::Mongo => None,
3464    }
3465  }
3466
3467  /// Whether `kind` can host a ledger — [`of`](Self::of)'s question without its answer, for a caller
3468  /// that needs the fact rather than the value.
3469  pub const fn hosts(kind: DatabaseKind) -> bool {
3470    Self::of(kind).is_some()
3471  }
3472}
3473
3474/// The record's WIRE face: which GraphQL backends render it, and what each one calls it.
3475///
3476/// Only the OUTPUT's members need a per-field declaration. The tree fixes the rest — the key object
3477/// is a mechanical projection of the key's columns, the filter of the stored ones, and the ARGUMENT
3478/// object mirrors the engine's own find surface — so this carries the four names and the exposed
3479/// fields, and nothing else.
3480#[derive(Debug, Clone)]
3481pub struct Graphql {
3482  /// The declared backends, in the order they were written. Never empty, as [`Persist::backends`] is.
3483  pub backends: Vec<GraphqlBackend>,
3484  /// The ONE argument object — [`default_input_name`], with no rename knob — filling
3485  /// `Graphql::Input`.
3486  ///
3487  /// What a client SENDS: the filter, the order, and the page the engine's own typestate admits.
3488  /// Its members mirror `query::sql`'s find surface rather than being invented here, which is what
3489  /// keeps a query a client can write from being one the engine has no lane for.
3490  pub input: RustSafeName,
3491  /// The ONE wire output — [`default_output_name`] unless `output(rename = "…")` named it, filling
3492  /// `Graphql::Output`. What a client
3493  /// receives when it queries this record's fields, and the only per-field-authored GraphQL
3494  /// mapping there is.
3495  ///
3496  /// A separate type rather than the record itself, and deliberately. The record is the type the
3497  /// PIPELINE moves, so a wire attribute on it publishes every declaration's compute struct; and the
3498  /// exposure would run the wrong way round — a record's fields are IN unless something says
3499  /// otherwise, where the marker rule opts NONE in and the declaration names what a client sees. The
3500  /// wire form is the second half: a field whose schema type is not its domain type (`u64` →
3501  /// `String`) has nowhere on the record to be that, and this object's accessors are exactly where it
3502  /// is.
3503  ///
3504  /// See [`GraphqlKind::output_object`] for what the object is rendered BY — an `#[Object]` impl over
3505  /// the accessors, which is the layer `output(field = "…")` moves.
3506  pub output: RustSafeName,
3507  /// The ONE key output — [`default_key_output_name`] unless `key(rename = "…")` named it, filling
3508  /// `GraphqlOutput::Key`. MECHANICAL
3509  /// from the key's columns, with no per-field declaration: a search or knn hit IS a `Scored` over
3510  /// `K`, and the search envelopes derive their wire shape from this, so without it a hit has
3511  /// nothing to render into.
3512  pub key_output: RustSafeName,
3513  /// `key(output(rename = "…"))` — what the SCHEMA calls the address OBJECT, where a declaration
3514  /// named it outright. [`None`] is the base above resolved, which is what `emit::wire`'s
3515  /// `published_key` spells.
3516  ///
3517  /// # A SECOND seat over one Rust type, and the two move different things
3518  ///
3519  /// [`Self::key_output`] is the RUST name and moves with `key(rename = "…")`; that same word also
3520  /// re-bases the schema; this one replaces the schema half alone. The 2026-08-16 rename ruling
3521  /// separated them because an address publishes TWO schema names out of one Rust type — GraphQL
3522  /// keeps input and output in one namespace — so a single seat could re-base the pair but could
3523  /// never name either of them.
3524  ///
3525  /// A `String` and not a [`RustSafeName`] for [`Self::connection`]'s reason, a few fields down:
3526  /// what this names lives in GraphQL's flat namespace and has no Rust identifier behind it, so
3527  /// nothing is mangled and a Rust keyword is an ordinary word.
3528  pub key_object: Option<String>,
3529  /// `key(input(rename = "…"))` — what the SCHEMA calls the address ARGUMENT object, the shape a
3530  /// client sends a COMPOUND address in.
3531  ///
3532  /// Its neighbour's kind and its neighbour's fence. [`None`] is the base with `Input` on the end —
3533  /// the one blessed composition in this grammar, and why it is blessed is written at
3534  /// [`default_key_input_name`]. A ROOT's address crosses inward as its id and mints no argument
3535  /// object at all, so on that shape the word is simply unspent.
3536  pub key_argument: Option<String>,
3537  /// The ONE filter type — [`default_filter_name`] unless `filter(rename = "…")` named it.
3538  ///
3539  /// One per record, not one per database, because a filter is a WIRE type: a client must never
3540  /// see a schema that varies with a deployment's storage choice. Its RESOLUTION is per database —
3541  /// it crosses into each one's `*Comparison` through the declared conversions — and that crossing
3542  /// is where storage enters, exactly once.
3543  pub filter: RustSafeName,
3544  /// `graphql(plural = "…")` — THIS ENTITY'S PLURAL, in the declaration's own word, or `None` where
3545  /// it wrote none and the pluraliser's word stands.
3546  ///
3547  /// # A WORD, and deliberately not a field name
3548  ///
3549  /// The declaration corrects the LANGUAGE — *the plural of `Corpus` is `corpora`* — rather than
3550  /// naming one field, and that is why the fact is stored here instead of being consumed at the one
3551  /// place that read it first. THREE readers now, which is the whole point of storing it: the list
3552  /// FIELD, the page's type name and one edge's, so a declaration corrects the English once and gets
3553  /// `corpora(…): CorporaConnection` with `CorporaEdge` beside it. The user's word for that property
3554  /// is *一起跟* — they follow together — and [`Self::connection`] carries the tower it is the base
3555  /// of. An aggregate would be the fourth reader and asks for nothing new.
3556  ///
3557  /// The SPELLING it reaches a schema in is not this value: the word is a word, and each reader
3558  /// spells it for its own position — a field lowers the initial, a type name raises it.
3559  /// `plural = "Corpora"` and `plural = "corpora"` therefore reach one field and one pair of type
3560  /// names, whichever way a declaration wrote it.
3561  ///
3562  /// # What is checked WHERE
3563  ///
3564  /// The word is held to GraphQL's Name grammar at the declaration, where the literal's own span is,
3565  /// so an empty string or a `9lives` refuses at the token that wrote it. What CANNOT be checked
3566  /// there is the derived word, whose input is the published output name — see
3567  /// [`RecordModel::degenerate_plural`], which is the silence this option exists to answer.
3568  pub plural: Option<String>,
3569  /// `connection(rename = "…")` — what the SDL calls this record's PAGE object, where a declaration
3570  /// took the knob.
3571  ///
3572  /// The TOP of a three-tier naming tower, and `None` means the tiers below it decide: the base is
3573  /// [`Self::plural`] resolved — the same word the list field is named from — so a record that wrote
3574  /// nothing publishes `<Plural>Connection` and one that wrote `plural = "corpora"` publishes
3575  /// `CorporaConnection`, with no second correction to make. The user's ruling of 2026-08-13 is where
3576  /// that came from and `emit::queries` is where it is spelled.
3577  ///
3578  /// The base is NOT the Relay Cursor Connections specification's `<Node>Connection`, and the trade
3579  /// is real: Relay, Apollo and every schema codegen recognise a page by the
3580  /// `<Node>Connection` / `<Node>Edge` / `edges { node cursor }` triple, and a plural-stemmed name
3581  /// exits the first two thirds of that. The ruling made the trade once for every record; a `rename`
3582  /// on top of it is a second, per-record exit, and the emitted doc prices each.
3583  ///
3584  /// A SCHEMA WORD and not a Rust name, which is why it is a `String` where its four neighbours are
3585  /// [`RustSafeName`]s. Those name TYPES a declaring scope holds and can collide over; this names a
3586  /// type in one flat GraphQL namespace, and the Rust marker carrying it is emitted inside the wire
3587  /// face's own anonymous const, where no declaration can see it. Nothing is mangled, so the word a
3588  /// declaration wrote is the word a client reads — and a Rust KEYWORD is an ordinary word here,
3589  /// which is the whole of why the grammar carries a literal rather than an ident.
3590  pub connection: Option<String>,
3591  /// `edge(rename = "…")` — what the SDL calls ONE element of that page. `None` is the same tower's
3592  /// base with `Edge` on it.
3593  ///
3594  /// Separate from [`Self::connection`] rather than derived from it, because the two are separate
3595  /// hooks in the library and a schema may want one moved and not the other: async-graphql resolves
3596  /// each through its own trait. They ride ONE tower and are covered independently — the user's *对
3597  /// 一起跟* was about the tower, and their independence is about the top of it.
3598  pub edge: Option<String>,
3599  /// `#[ingraph(graphql(skip))]` — the fields withheld from EVERY wire vocabulary this record
3600  /// publishes, in declaration order.
3601  ///
3602  /// # The word sweeps, and what it sweeps is every vocabulary a client can name the column in
3603  ///
3604  /// The output object drops the accessor, the filter drops the member, and the order-by drops the
3605  /// variant — one word, and the column is unnameable from the wire in all three positions. A
3606  /// half-swept field is the failure worth designing against: a client that cannot READ a column but
3607  /// can ORDER by it reads the column's order back out, one page at a time.
3608  ///
3609  /// The COMPARISON is not among them and that is not an omission: it is the storage form of a
3610  /// predicate, emitted for a record with no wire face at all, so it belongs to the row rather than
3611  /// to the schema. What removes a column from a comparison is the storage word — `skip`, or one
3612  /// database's own — which is the axis that owns the row.
3613  ///
3614  /// A withheld field never becomes a [`GraphqlField`], so the output object is swept by ABSENCE.
3615  /// This list is what the filter and the order-by read, both being one per record and built from
3616  /// the STORED columns rather than from the exposed ones.
3617  pub skipped: Vec<syn::Ident>,
3618}
3619
3620impl Graphql {
3621  /// Whether this record publishes `source` on the wire at all — false where
3622  /// `graphql(skip)` withheld it.
3623  ///
3624  /// The RECORD-wide question, which is the one the FILTER and the ORDER-BY ask: there is one of
3625  /// each per record — *a client must never see a schema that varies with a deployment's storage
3626  /// choice* — so a per-backend answer would have no type to differ in.
3627  ///
3628  /// # A withholding EVERY backend wrote is a record-wide one
3629  ///
3630  /// The common word is the first way to reach that state and not the only one: a field no declared
3631  /// backend renders leaves no backend that still needs a seat for it, so the shared vocabularies
3632  /// have nothing to keep it for. The two spellings therefore reach one answer here, which is what
3633  /// makes the sweep TOTAL wherever it is total — with one backend shipped,
3634  /// `graphql(async_graphql(skip))` and `graphql(skip)` say the same thing, and the ruling's *absent
3635  /// from that backend only* is a distinction with one backend to draw it between.
3636  ///
3637  /// What a PARTIAL withholding does — one backend of several — is that backend's OUTPUT OBJECT and
3638  /// nothing else, the field never becoming one of its wire fields. The shared filter and order-by
3639  /// keep the member, because the backend that still renders it still needs one. That asymmetry is
3640  /// forced by the one-type-per-record law rather than chosen, and it is unreachable today: one
3641  /// backend ships.
3642  #[must_use]
3643  pub fn publishes(&self, source: &syn::Ident) -> bool {
3644    let common = self.skipped.iter().any(|skipped| skipped == source);
3645    let every = !self.backends.is_empty()
3646      && self
3647        .backends
3648        .iter()
3649        .all(|backend| backend.skipped().iter().any(|skipped| skipped == source));
3650    !common && !every
3651  }
3652}
3653
3654/// One GraphQL backend's rendering of a record.
3655///
3656/// One variant today, and that is the extension point rather than a premature abstraction: the
3657/// shape is what keeps a second backend from being a redesign. CLOSED and `#[non_exhaustive]` for
3658/// the reasons [`DatabaseBackend`] gives — codegen must know a backend to emit its derives, so a
3659/// third-party one is a change to this crate whichever shape this takes.
3660#[derive(Debug, Clone)]
3661#[non_exhaustive]
3662pub enum GraphqlBackend {
3663  /// `async-graphql`.
3664  AsyncGraphql(AsyncGraphql),
3665}
3666
3667/// The `async-graphql` backend's rendering.
3668#[derive(Debug, Clone)]
3669pub struct AsyncGraphql {
3670  /// `attrs(…)` — passed onto the emitted type verbatim.
3671  ///
3672  /// The escape hatch that stops the grammar from chasing a backend's feature set: `deprecation`,
3673  /// `visible`, `guard`, `complexity` and every custom scalar reach the emission through here
3674  /// rather than through an option apiece.
3675  pub attrs: proc_macro2::TokenStream,
3676  /// The fields this backend EXPOSES, in the record's declaration order.
3677  pub fields: Vec<GraphqlField>,
3678  /// `graphql(async_graphql(skip))` — the fields withheld from THIS backend alone, in the record's
3679  /// declaration order.
3680  ///
3681  /// Separate from [`Graphql::skipped`], which is every backend at once: a field withheld here is
3682  /// absent from this backend's own face and present in the next one's, which is the axis the
3683  /// per-backend block exists for. It is empty for a record that wrote only the common word, and a
3684  /// field named in both is refused at the declaration — one absence, said once.
3685  pub skipped: Vec<syn::Ident>,
3686}
3687
3688impl GraphqlBackend {
3689  /// Which backend this is.
3690  pub const fn kind(&self) -> GraphqlKind {
3691    match self {
3692      Self::AsyncGraphql(_) => GraphqlKind::AsyncGraphql,
3693    }
3694  }
3695
3696  /// `attrs(…)`, verbatim.
3697  pub const fn attrs(&self) -> &proc_macro2::TokenStream {
3698    match self {
3699      Self::AsyncGraphql(backend) => &backend.attrs,
3700    }
3701  }
3702
3703  /// The fields this backend exposes.
3704  pub const fn fields(&self) -> &[GraphqlField] {
3705    match self {
3706      Self::AsyncGraphql(backend) => backend.fields.as_slice(),
3707    }
3708  }
3709
3710  /// The fields `graphql(<backend>(skip))` withheld from THIS backend alone.
3711  pub const fn skipped(&self) -> &[syn::Ident] {
3712    match self {
3713      Self::AsyncGraphql(backend) => backend.skipped.as_slice(),
3714    }
3715  }
3716}
3717
3718/// One field of the wire face, in both of its schema positions.
3719#[derive(Debug, Clone)]
3720pub struct GraphqlField {
3721  /// The RECORD field this projects.
3722  pub source: syn::Ident,
3723  /// The record field's declared type, verbatim.
3724  pub domain: syn::Type,
3725  /// `graphql(type = "…")` — the WIRE FORM, when it is not the domain type.
3726  ///
3727  /// ONE per field and DATABASE-INDEPENDENT, which is the whole of why it sits here rather than on
3728  /// a [`Face`]: a schema that varied with a deployment's storage backend would be a schema no
3729  /// client could hold against two deployments. It serves both positions for the same reason —
3730  /// the operand a client filters with and the value it receives back are one type, and a client
3731  /// that had to know two would be reading a schema this framework should not be able to write.
3732  pub wire: Option<syn::Type>,
3733  /// `graphql(output(…))` — the crossings from each database's ROW FIELD into the wire form, and
3734  /// the error a fallible one answers with.
3735  pub output_crossing: WirePosition,
3736  /// `graphql(input(comparison(…)))` — the crossings from the wire form into each database's ROW
3737  /// FIELD, spent where a filter's operand becomes a comparison's.
3738  pub input_crossing: WirePosition,
3739  /// The INPUT position's SCHEMA facts: `graphql(<backend>(input(…)))`.
3740  pub input: Face,
3741  /// The OUTPUT position's SCHEMA facts: `graphql(<backend>(output(…)))`.
3742  ///
3743  /// Separate from [`GraphqlField::input`] because a GraphQL input field and an output field are
3744  /// different schema positions and may legitimately differ — in name and in the attributes they
3745  /// carry. They no longer differ in TYPE: see [`wire`](Self::wire).
3746  ///
3747  /// Its NAME is the client-visible one ALONE. What the emitted output struct READS the field
3748  /// through in Rust is [`GraphqlField::accessor`], which is a separate axis — see that method.
3749  pub output: Face,
3750  /// `graphql(<backend>(output(field = "…")))` — the ACCESSOR the output object reads this field
3751  /// through, where the declaration moved it. `None` is the field's own name.
3752  ///
3753  /// HERE rather than on the output [`Face`], and the reason is that a [`Face`] is a SCHEMA
3754  /// POSITION: both of its members are facts about what a client sees, and a Rust ident is not one.
3755  /// Sitting on the face would also put the slot in the INPUT position, where nothing could read it
3756  /// — the input face's Rust spelling belongs to the FILTER, and it is the mangling of that face's
3757  /// own name. An entry nobody reads is a rule its author believes they declared.
3758  ///
3759  /// One slot rather than one per backend for the fact it states: there is ONE `<E>GraphqlOutput`
3760  /// per record, carrying whatever derives its declared backends need, so what its Rust face is
3761  /// called cannot be a backend's business. The name a CLIENT sees can be, and that one is on the
3762  /// face.
3763  pub output_field: Option<syn::Ident>,
3764}
3765
3766impl GraphqlField {
3767  /// The WIRE FORM this field takes: the declared one, or the domain type.
3768  pub const fn wire_ty(&self) -> &syn::Type {
3769    match &self.wire {
3770      Some(ty) => ty,
3771      None => &self.domain,
3772    }
3773  }
3774
3775  /// What the emitted OUTPUT OBJECT's ACCESSOR for this field is named after: the declared word,
3776  /// else the DOMAIN name.
3777  ///
3778  /// # Three layers, and this is layer TWO
3779  ///
3780  /// | written | moves |
3781  /// |---|---|
3782  /// | `graphql(<backend>(output(rename = "…")))` | LAYER 3 — the client-visible name, and nothing in Rust |
3783  /// | `graphql(<backend>(output(field = "…")))` | LAYER 2 — this ACCESSOR, and neither the member nor anything a client sees |
3784  /// | nothing | the client sees the backend's own default rename (camelCase); Rust reads the domain name through the domain name |
3785  ///
3786  /// **LAYER 1 — the emitted member — is [`source`](Self::source), and no word reaches it.** That is
3787  /// the whole of what makes it a substrate: an emitted-to-emitted read spends the FIELD, so a
3788  /// crossing, an equation or an audit written against a member is written against a name no
3789  /// declaration can move, and divergence between what one expansion writes and what its neighbour
3790  /// reads is unspellable rather than guarded against.
3791  ///
3792  /// What moves instead is the Rust FACE, which is where a rename belongs: a caller writing
3793  /// `mass_ref()` over a `weight` column is naming a METHOD, and a method is the layer a library
3794  /// gets to choose the spelling of. The word's REACH changed; its grammar did not.
3795  ///
3796  /// The Rust ident used to be taken from the output FACE's name, which coupled two axes: a schema
3797  /// rename MOVED the struct's field. That coupling is what the interface's stored output face died
3798  /// on — an interface knows a member's field by its DOMAIN name and by nothing else, so a member
3799  /// that renamed its schema field became unreadable to a contract it satisfies. Pinning the member
3800  /// to the domain name is the same fix carried to the one word that could still reach it.
3801  ///
3802  /// The ONE place the default is resolved, and it has two readers rather than four now — this
3803  /// accessor and the emitted-method audit that enumerates it. The member and the row crossing that
3804  /// fills it read [`source`](Self::source), which is the fence made structural rather than agreed.
3805  pub const fn accessor(&self) -> &syn::Ident {
3806    match &self.output_field {
3807      Some(named) => named,
3808      None => &self.source,
3809    }
3810  }
3811}
3812
3813/// ONE POSITION of a field's wire crossing: a leg per database, and the error a fallible one
3814/// answers with.
3815///
3816/// # The legs are PER DATABASE, where the wire form is not
3817///
3818/// A crossing has a row on one side of it, and a row is one database's. `output(sqlite(try_from =
3819/// "…"))` is handed what SQLite stores and answers with the wire form; the Postgres leg beside it is
3820/// handed what Postgres stores. What both answer WITH is the one type
3821/// [`GraphqlField::wire`](GraphqlField::wire) names, which is what keeps the schema from varying
3822/// with a deployment.
3823///
3824/// A database with NO leg takes the DEFAULT CHAIN — the column's own `persist` crossing composed
3825/// with the domain's wire face — so a declaration writes a leg exactly where the default is not what
3826/// it means.
3827#[derive(Debug, Clone, Default)]
3828pub struct WirePosition {
3829  /// The declared legs, in the order the declaration wrote them. Never two for one database.
3830  ///
3831  /// The ERROR a fallible one answers with is not here: it is the RECORD's, at the cell this
3832  /// crossing's own block names — `graphql(output(sqlite(error = "…")))` — so every impl of one
3833  /// crossing at one backend answers alike whatever the fields declared.
3834  pub legs: Vec<WireLeg>,
3835}
3836
3837impl WirePosition {
3838  /// This position's leg for `kind`, or `None` where the database takes the default chain.
3839  pub fn leg(&self, kind: DatabaseKind) -> Option<&Conversion> {
3840    self
3841      .legs
3842      .iter()
3843      .find(|leg| leg.kind == kind)
3844      .map(|leg| &leg.conversion)
3845  }
3846
3847  /// Whether ANY declared leg of this position can fail — the half of the fallibility verdict a
3848  /// declaration owns.
3849  pub fn fallible(&self) -> bool {
3850    self.legs.iter().any(|leg| leg.conversion.fallible())
3851  }
3852}
3853
3854/// ONE database's leg of a wire crossing.
3855#[derive(Debug, Clone)]
3856pub struct WireLeg {
3857  /// Which database's row this leg crosses.
3858  pub kind: DatabaseKind,
3859  /// The function, and whether it can fail.
3860  pub conversion: Conversion,
3861}
3862
3863/// Which INTERPRETATION a field's type is read under, when a declaration names one.
3864///
3865/// The inference it overrides answers per (type, position), never per field: two `Vec<String>`
3866/// columns in one crate read alike, because the row that decides a `Vec`'s reading is keyed on the
3867/// ELEMENT type. A column whose reading must differ from its neighbour's names it here instead.
3868///
3869/// What a marker reaches is the FILTER and nothing below it. It says what may be ASKED of a column
3870/// — whether `[1, 2]` and `[2, 1]` are one operand or two — and decides nothing about what a table
3871/// holds; the crossing from a filter into one database's comparison is a separate map, and it is
3872/// where storage enters.
3873#[derive(Debug, Clone)]
3874pub enum Marker {
3875  /// One of the framework's own — see [`FrameworkMarker`].
3876  Framework(FrameworkMarker),
3877  /// `label = "their::RollMarker"` — a marker the DECLARING crate owns, reached by path.
3878  ///
3879  /// The emitter applies the FIELD's type to it, so such a marker is generic over that type:
3880  /// `M<FieldTy>`. Every one of the framework's own is that shape, and spelling the field type
3881  /// into the declaration as well would write it twice.
3882  Path(syn::Path),
3883}
3884
3885/// The payload of [`Marker::Framework`]: one of the framework's own markers, written as the bare
3886/// word it is short for, and — where the word names a COLLECTION — the element's own word inside
3887/// it.
3888///
3889/// `FrameworkMarker` rather than the variant's own name, which would read as a framework rather
3890/// than as a marker. Fields are `pub` and constructed by literal, which is what every model type in
3891/// this crate carries — and `ingraph-derive` builds one of these from a parsed label, so a
3892/// crate-private constructor would not reach.
3893#[derive(Debug, Clone)]
3894pub struct FrameworkMarker {
3895  /// The word at the FIELD's own level, which decides the field's marker.
3896  pub label: Label,
3897  /// The ELEMENT's word, when the label named a collection: `list(string)`'s `string`.
3898  ///
3899  /// One level and no more, and the grammar is what makes that total: a collection whose element
3900  /// is itself a collection is refused at the declaration, and an element-level custom marker is
3901  /// reserved — so an element is a framework WORD or the label named no element at all.
3902  pub element: Option<Label>,
3903}
3904
3905/// An interpretation the FRAMEWORK names — the words a declaration may write bare.
3906///
3907/// The vocabulary law in one type: what a declaration WRITES is a label, what it RESOLVES to is a
3908/// marker. So the words are here and the type-level artifacts they reach — `ScalarMarker`, the
3909/// `*FilterMarker` family traits, `DefaultMarker` — keep the other name, because nobody writes
3910/// them.
3911///
3912/// A CLOSED vocabulary, for the reason [`DatabaseKind`]'s is closed: these are the markers this
3913/// framework ships a word for, and one it does not is reached by [`Marker::Path`] rather than by a
3914/// word this list would have to grow. Nothing about the surface is closed by closing this.
3915///
3916/// # A word earns its place by DISAGREEING with the inference
3917///
3918/// The list carried the two COLLECTION words alone, and the argument for stopping there was that a
3919/// value reading is at most one per type: if a `String` could only ever be text, `string` on one
3920/// would be a second spelling of the default and no declaration could need it.
3921///
3922/// The marker layer is where that premise broke. A value reading is one trait per FAMILY —
3923/// `ScalarFilterMarker`, `StringFilterMarker`, `BytesFilterMarker` and their siblings — so a type
3924/// may answer several and mean all of them. `Vec<u8>` is a byte string and a list of small integers;
3925/// a downstream identifier can answer the string family and the enumeration one both. The INFERENCE
3926/// picks one, because a `DefaultMarker` row names one; a word is how a column picks another, which
3927/// is a declaration no other short form reaches.
3928///
3929/// So the rule stands and its answer changed: six value families and three collection positions.
3930///
3931/// The third collection word is the one that earns its place against a COLLECTION default rather
3932/// than against a value one. A `Vec<Tag>` infers `list`, and `quantified` is how a column says its
3933/// element has no literal form worth publishing — a different question from *is this ordered*, and
3934/// one no other short form reaches.
3935///
3936/// # What still has no word
3937///
3938/// `value` has none, and that absence IS the rule still holding — it would name whatever the type's
3939/// own row says, which is what omitting the option already means.
3940///
3941/// `nullable` has none for the same reason one level out: an `Option<T>` column infers whatever
3942/// `T`'s own reading says an `Option` of it is — the null test for a value family, the collection
3943/// itself for a collection one — from one blanket that reaches every `T`, so the word could only ever
3944/// restate the default. A column that wants the INNER reading changed says so with the inner word,
3945/// and the outer reading follows it.
3946///
3947/// That blanket is where a COLLECTION-classified column would land too, if the word did not route
3948/// around it first — see [`Label::collection`]. The two agree on the answer and differ in what
3949/// they can SEE: a word is tokens, and the blanket is types.
3950///
3951/// `map` has none because the framework ships no map filter for one to name.
3952#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
3953pub enum Label {
3954  /// A NUMBER: one totally ordered value, which is what makes `gt` and its neighbours mean
3955  /// something.
3956  Scalar,
3957  /// TEXT: one string of characters, which is what makes the substring and affix questions mean
3958  /// something.
3959  String,
3960  /// A BYTE STRING: one opaque run of bytes, searched as bytes and never as characters.
3961  Bytes,
3962  /// An ENUMERATION: a closed vocabulary, so membership is the whole question.
3963  Enum,
3964  /// A FLAGS SET: a closed vocabulary of BITS, so a value is a SUBSET and the questions are
3965  /// set-theoretic.
3966  ///
3967  /// The enumeration's sister and never a case of it: the two share equality and nothing else, and
3968  /// the mask words a flags column answers are questions an enum has no way to ask.
3969  Flags,
3970  /// A BOOLEAN: two values, so an ordering operator would name every row or none.
3971  Bool,
3972  /// A DURATION: an elapsed span, which carries a lexical form no number has.
3973  Duration,
3974  /// An ORDERED collection: order and duplicates carry meaning.
3975  List,
3976  /// An UNORDERED collection: neither does.
3977  Set,
3978  /// A collection asked ONLY through quantifiers — *some element satisfies this*, and *this many*.
3979  ///
3980  /// The third collection word, and it disagrees with the other two about the ELEMENT rather than
3981  /// about the column's order: the wide readings hold the element in seven of their filter's slots
3982  /// and so put its literal form on the wire, where this one holds it in none. A collection of pairs
3983  /// carrying a float is what it was cut for — see `ingraph`'s `QuantifiedFilter`, where each
3984  /// departing operator is named with the reason it could not be answered honestly.
3985  Quantified,
3986}
3987
3988impl Label {
3989  /// Every interpretation with a word, in the order a refusal lists them: the six VALUE families
3990  /// first and the two collection positions last, which is the order `ingraph`'s marker module
3991  /// declares the markers themselves in.
3992  pub const ALL: [Self; 10] = [
3993    Self::Scalar,
3994    Self::String,
3995    Self::Bytes,
3996    Self::Enum,
3997    Self::Flags,
3998    Self::Bool,
3999    Self::Duration,
4000    Self::List,
4001    Self::Set,
4002    Self::Quantified,
4003  ];
4004
4005  /// The word a declaration writes.
4006  ///
4007  /// `enum` is a Rust KEYWORD and is the word anyway: this vocabulary names READINGS, and what rustc
4008  /// reserves for its own grammar has nothing to say about them. The cost is a line in the grammar
4009  /// that reads it — `ingraph-derive`'s `marker` takes the token as any identifier — and nothing
4010  /// here.
4011  pub const fn as_str(self) -> &'static str {
4012    match self {
4013      Self::Scalar => "scalar",
4014      Self::String => "string",
4015      Self::Bytes => "bytes",
4016      Self::Enum => "enum",
4017      Self::Flags => "flags",
4018      Self::Bool => "bool",
4019      Self::Duration => "duration",
4020      Self::List => "list",
4021      Self::Set => "set",
4022      Self::Quantified => "quantified",
4023    }
4024  }
4025
4026  /// The framework type the word is short for.
4027  pub const fn item(self) -> &'static str {
4028    match self {
4029      Self::Scalar => "ScalarMarker",
4030      Self::String => "StringMarker",
4031      Self::Bytes => "BytesMarker",
4032      Self::Enum => "EnumMarker",
4033      Self::Flags => "FlagsMarker",
4034      Self::Bool => "BoolMarker",
4035      Self::Duration => "DurationMarker",
4036      Self::List => "ListMarker",
4037      Self::Set => "SetMarker",
4038      Self::Quantified => "QuantifiedMarker",
4039    }
4040  }
4041
4042  /// Whether the word names a COLLECTION POSITION rather than a VALUE family — the split this
4043  /// vocabulary's own note already counts, asked rather than re-derived from the list.
4044  ///
4045  /// # A collection has no null state
4046  ///
4047  /// It is the one place the two halves are not interchangeable. An edge table has ONE observable
4048  /// for a column that holds nothing — no rows — where the Rust type spells two, `None` beside
4049  /// `Some(<empty>)`; a distinction no storage can keep must not be declarable as though it could.
4050  /// So a field the declaration classified here resolves as if it had been declared BARE: empty and
4051  /// absent are one state, in both directions, and *is it empty* is `count: { eq: 0 }`, which every
4052  /// backend answers alike. polarsync settles the same question the same way — its schema translates
4053  /// an `Option<Vec<T>>` field to `Vec<T>`.
4054  ///
4055  /// [`crate::emit`]'s `filter_of` is where the routing happens, and this is what it asks.
4056  ///
4057  /// An exhaustive match rather than a `matches!`, because the answer is part of what adding a word
4058  /// to this vocabulary MEANS: a word that compiled without deciding would take the value answer by
4059  /// silence. `flags` was the ninth and answered here; `quantified` is the tenth and answers here
4060  /// too — a collection whose filter publishes two operators is still a collection, and what makes
4061  /// the `Option` transparent is the storage rather than the vocabulary.
4062  pub const fn collection(self) -> bool {
4063    match self {
4064      Self::List | Self::Set | Self::Quantified => true,
4065      Self::Scalar
4066      | Self::String
4067      | Self::Bytes
4068      | Self::Enum
4069      | Self::Flags
4070      | Self::Bool
4071      | Self::Duration => false,
4072    }
4073  }
4074}
4075
4076/// One SCHEMA POSITION of one field: what it is CALLED there, and what rides on it verbatim.
4077///
4078/// The TYPE is not here and no longer can be. A position's type used to be its own, and it made two
4079/// things spellable that must not be: an input form differing from the output form, which is a
4080/// schema a client has to read twice, and — through the per-position conversions that went with it —
4081/// a wire form reached from the DOMAIN rather than from the row a deployment actually stores. Both
4082/// live on [`GraphqlField`] now, the form once and the crossings per database.
4083#[derive(Debug, Clone)]
4084pub struct Face {
4085  /// The field's name here: the SDL one is the external face, the Rust one the safe face.
4086  pub name: RustSafeName,
4087  /// `attrs(…)` — passed onto the emitted field verbatim. Descriptions live here and NOWHERE else:
4088  /// a source `///` comment never becomes a schema description, because publishing is deliberate.
4089  pub attrs: proc_macro2::TokenStream,
4090}
4091
4092/// A GraphQL backend a record may be rendered by.
4093///
4094/// One variant today, and the vocabulary exists anyway: a closed framework-owned list, the same
4095/// shape [`DatabaseKind`] takes, so a second backend is an arm rather than a redesign.
4096#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
4097pub enum GraphqlKind {
4098  /// `async-graphql`.
4099  AsyncGraphql,
4100}
4101
4102impl GraphqlKind {
4103  /// Every backend, in the order a refusal lists them.
4104  pub const ALL: [Self; 1] = [Self::AsyncGraphql];
4105
4106  /// The name a declaration writes.
4107  pub const fn as_str(self) -> &'static str {
4108    match self {
4109      Self::AsyncGraphql => "async_graphql",
4110    }
4111  }
4112
4113  /// The ATTRIBUTE this backend's OUTPUT types carry — an impl-position macro over the object's
4114  /// ACCESSORS, and not a derive over its members.
4115  ///
4116  /// # `#[Object]` and not `SimpleObject`, which is a repair rather than a preference
4117  ///
4118  /// This slot answered `::async_graphql::SimpleObject` until the accessor law landed, and the two
4119  /// rulings it now sits between leave no room for that answer:
4120  ///
4121  /// - the wire design rules OUTPUTS AS `#[Object]`-STYLE IMPLS over marked fields — the marker rule
4122  ///   holding on the wire the way it holds everywhere else;
4123  /// - the three-layer accessor law makes the emitted MEMBERS domain-named and `pub(crate)`, puts
4124  ///   the public face on the ACCESSORS beside them, and gives `output(field = "…")` the job of
4125  ///   moving that accessor.
4126  ///
4127  /// A derive that renders FIELDS can honour neither: it would publish layer 1 — the substrate no
4128  /// word may move — so `output(field = "…")` would rename a Rust item the schema never reads, and a
4129  /// `pub(crate)` member would be published by a `pub` type. The attribute renders layer 2 instead,
4130  /// which is the layer the rename word was given and the layer that is API.
4131  ///
4132  /// The shape it takes is one impl block of borrows, so nothing about the object's own declaration
4133  /// changes: the members stay where they are, the inherent accessors stay where they are, and what
4134  /// is added is a second impl naming the same accessors.
4135  pub const fn output_object(self) -> &'static str {
4136    match self {
4137      Self::AsyncGraphql => "::async_graphql::Object",
4138    }
4139  }
4140
4141  /// The derive path this backend's input types carry.
4142  pub const fn input_derive(self) -> &'static str {
4143    match self {
4144      Self::AsyncGraphql => "::async_graphql::InputObject",
4145    }
4146  }
4147
4148  /// The derive path this backend's order-by carries.
4149  ///
4150  /// Not the plain enum derive, though the emitted type IS a Rust enum: the order-by renders as a
4151  /// `@oneOf` INPUT OBJECT — one nullable field per column, exactly one of them supplied — and the
4152  /// derive that produces that from an enum of single-value tuple variants is this one. The plain
4153  /// `Enum` derive would render the type as a GraphQL enum of bare column names, which is the shape
4154  /// this face stopped being: it cannot carry a direction, and a list of it cannot pair one.
4155  pub const fn order_by_derive(self) -> &'static str {
4156    match self {
4157      Self::AsyncGraphql => "::async_graphql::OneofObject",
4158    }
4159  }
4160
4161  /// The attribute this backend's names and passthrough ride on.
4162  pub const fn attribute(self) -> &'static str {
4163    match self {
4164      Self::AsyncGraphql => "graphql",
4165    }
4166  }
4167}
4168
4169/// What a record's wire output is called. ONE per record — the SDL is identical whichever Rust
4170/// library serves it, so the type carries cfg-gated derives per declared backend rather than
4171/// splitting into one type per backend.
4172///
4173/// `<Record>GraphqlOutput` rather than `<Record>Output`, because this type is now BOTH of what the
4174/// two names used to stand for: the object a client receives AND the half of the wire face
4175/// `Graphql::Output` binds. The carrier that held the second job was a `struct …(())` with the
4176/// members named on it and nothing in it; it has the members now, so a second name for one type
4177/// would be the only thing left to keep.
4178pub fn default_output_name(base: &syn::Ident) -> syn::Ident {
4179  format_ident!("{base}GraphqlOutput")
4180}
4181
4182/// What a record's wire INPUT is called: `<Record>GraphqlInput`, the object a query's arguments
4183/// arrive in.
4184///
4185/// No rename knob, where the output has one — the grammar's `graphql(output(rename = "…"))` has no
4186/// twin here and is not being given one on demand. What a collision gets instead is the emitted-type
4187/// rule's refusal, naming this type and the one already in the scope.
4188pub fn default_input_name(base: &syn::Ident) -> syn::Ident {
4189  format_ident!("{base}GraphqlInput")
4190}
4191
4192/// What a SUBSCRIBING derived index's node is called: `<Decl>Indexer`, the launchable unit that
4193/// receives the upstream's messages and fills this declaration's corpora.
4194///
4195/// # It is a SECOND TYPE, and the alternative was refused rather than overlooked
4196///
4197/// Every other node macro makes the declaration ITSELF the unit — `impl Declared for Scene` beside
4198/// `impl Operator for Scene` — and a derived index cannot follow it. A node's resource demands are
4199/// `Shared<R>` FIELDS on the value its constructor builds, and this declaration's value is a
4200/// DOCUMENT: one per upstream message, built by `new`, handed to an engine and put on an edge.
4201/// Giving it store handles would put a mount inside every document that crosses a wire.
4202///
4203/// So the document stays what it is and the node is minted beside it. That also keeps the two roads
4204/// separable in the DEPLOYMENT: a root that mounts `MediaIndexer` runs the subscriber, and a root
4205/// that mounts `#[ingraph(fuse)] media: Media` alone gets the hand road, byte for byte as before.
4206pub fn default_indexer_name(base: &syn::Ident) -> syn::Ident {
4207  format_ident!("{base}Indexer")
4208}
4209
4210/// What a record's key output is called. ONE per record — see [`default_output_name`].
4211pub fn default_key_output_name(base: &syn::Ident) -> syn::Ident {
4212  format_ident!("{base}KeyOutput")
4213}
4214
4215/// What a COMPOUND record's key argument object is called IN RUST: `<Record>KeyInput`, the address a
4216/// client sends when the whole address is more than an id.
4217///
4218/// No rename knob, [`default_input_name`]'s reason unchanged: a rename word moves a FACE and this is
4219/// the Rust name, which no word moves.
4220///
4221/// The PUBLISHED name is not this one and is not derived here. GraphQL puts input and output types
4222/// in ONE namespace, and the output half publishes `<Record>Key` — the shorter word, because reading
4223/// an address is the commoner act — so the sending half has to differ by something, and it differs
4224/// by the `Input` suffix composed off the SAME base the output published. `emit::wire`'s
4225/// `published_key` is where that composition lives, and where the ruling that it is the one blessed
4226/// derivation is written down: `key(rename = "Address")` gives `Address` and `AddressInput`, and an
4227/// unrenamed record's two names are exactly what they always were.
4228pub fn default_key_input_name(base: &syn::Ident) -> syn::Ident {
4229  format_ident!("{base}KeyInput")
4230}
4231
4232/// What a record's filter is called. ONE per record — see [`Graphql::filter`].
4233///
4234/// At the FRAGMENT tier this is the FULL face's name — every field the declaration holds — and
4235/// [`default_column_filter_name`] is its twin.
4236pub fn default_filter_name(base: &syn::Ident) -> syn::Ident {
4237  format_ident!("{base}Filter")
4238}
4239
4240/// What the STORED face of a fragment's predicate is called: `<base>ColumnFilter`.
4241///
4242/// # A second name because there are two truths, not because there are two spellings
4243///
4244/// *Each face tells its own truth* — the 2026-08-22 ruling. A fragment held by a record can be
4245/// compared only by the columns it is stored in, a `record(skip)`ped field's query-time value being
4246/// a raise's fill rather than anything a row carries; held by an entity it is compared by every
4247/// field it declares. A declaration activated for ONE kind emits one type and this composition is
4248/// the name it wears where that kind is the record; activated for both, it emits two and the names
4249/// part here.
4250///
4251/// `Column` is the marker word, ruled 2026-08-22 out of the family's own register — `stored_columns`,
4252/// the *存了才能发* law. It composes onto the same base [`default_filter_name`] does, so a base a
4253/// word moves carries both faces with it and neither can come to wear a stem the other has left.
4254pub fn default_column_filter_name(base: &syn::Ident) -> syn::Ident {
4255  format_ident!("{base}ColumnFilter")
4256}
4257
4258/// What a record's order-by is called. ONE per record — see [`Graphql::filter`].
4259pub fn default_order_by_name(base: &syn::Ident) -> syn::Ident {
4260  format_ident!("{base}OrderBy")
4261}
4262
4263/// What a record's QUERY UNIT is called: `<Record>Queries`, the type a root folds to serve this
4264/// record's root fields.
4265///
4266/// PLURAL, because the type is the trio rather than one query — and unprefixed, like every other
4267/// emitted wire type, because it is visible vocabulary an application mounts. No rename word, for
4268/// [`default_input_name`]'s reason: what a collision gets is the emitted-type rule's refusal naming
4269/// both.
4270pub fn default_queries_name(record: &syn::Ident) -> syn::Ident {
4271  format_ident!("{record}Queries")
4272}
4273
4274/// What one database's comparison type is called: the row's name, suffixed.
4275///
4276/// Named after the ROW because that is what it compares against, and per database because its
4277/// values are STORAGE-typed — the whole point of the layer.
4278pub fn default_comparison_name(row: &syn::Ident) -> syn::Ident {
4279  format_ident!("{row}Comparison")
4280}
4281
4282/// What a record's row type is called in one database when nothing renamed it:
4283/// `<Record><Suffix>`.
4284pub fn default_row_name(base: &syn::Ident, kind: DatabaseKind) -> syn::Ident {
4285  format_ident!("{base}{}", kind.suffix())
4286}
4287
4288/// What a record's key type is called when nothing renamed it: `<Record>Key`.
4289pub fn default_key_name(record: &syn::Ident) -> syn::Ident {
4290  format_ident!("{record}Key")
4291}
4292
4293/// What a record's lineage type is called when nothing renamed it: `<Record>Lineage`.
4294pub fn default_lineage_name(record: &syn::Ident) -> syn::Ident {
4295  format_ident!("{record}Lineage")
4296}
4297
4298/// What a node's FAN-IN sum is called: `<Node>In`.
4299///
4300/// No rename word, and its absence is the same ruling every emitted name here started from: a word
4301/// arrives when a declaration needs it. What a reader spells is the node's own name plus the
4302/// contract member it fills, which is what makes `type In = <Node>In` read as the tautology it is.
4303pub fn default_in_name(record: &syn::Ident) -> syn::Ident {
4304  format_ident!("{record}In")
4305}
4306
4307/// What a node's CHANNELS SHELF is called: `<Node>Channels`.
4308///
4309/// The fourth of the emitted per-node names beside `<Node>In`, `<Node>Out` and `<Node>Due`, and the
4310/// one a DEPLOYMENT names rather than a body: it is the type a `[node.channels]` block parses into,
4311/// mounted on the node's section beside its options.
4312pub fn default_channels_name(record: &syn::Ident) -> syn::Ident {
4313  format_ident!("{record}Channels")
4314}
4315
4316/// What a node's PRODUCT sum is called: `<Node>Out`.
4317pub fn default_out_name(record: &syn::Ident) -> syn::Ident {
4318  format_ident!("{record}Out")
4319}
4320
4321/// What a node's product VOCABULARY is called: `<Node>OutKind`.
4322///
4323/// The one emitted name a DOWNSTREAM declaration spells: `out = "Boxes"` becomes
4324/// `<upstream::Detector as Emits<{ upstream::DetectorOutKind::Boxes as usize }>>::Out`, built by
4325/// swapping the upstream path's last segment for this. That makes the convention load-bearing
4326/// across the two-derive wall, which is why it lives here — one function, and both sides of the
4327/// wall read it.
4328pub fn default_out_kind_name(record: &syn::Ident) -> syn::Ident {
4329  format_ident!("{record}OutKind")
4330}
4331
4332/// What a node's own DOWNSTREAM is called: `<Node>Downstream`.
4333///
4334/// The set of out-edges a node publishes into, one slot per declared product.
4335pub fn default_downstream_name(record: &syn::Ident) -> syn::Ident {
4336  format_ident!("{record}Downstream")
4337}
4338
4339/// What a node's POLL vocabulary is called: `<Node>Due`.
4340///
4341/// The third of the rename-proof identity types, beside `<Node>In` and `<Node>Out`: a tick arrives
4342/// carrying a POSITION, and this is the word that position means. An author matches on the name
4343/// they minted, so reordering the entries moves the positions and changes no body.
4344pub fn default_due_name(record: &syn::Ident) -> syn::Ident {
4345  format_ident!("{record}Due")
4346}
4347
4348/// What ONE CLOCK's grants context is called: `<Node><Poll>Grants`.
4349///
4350/// What a tick FROM THAT CLOCK is lent — one write socket per grant that entry wrote, and nothing
4351/// else, which is the whole of 路 A: a tick reaching for a store a SIBLING clock was granted is an
4352/// unsatisfied bound rather than a permission refused at run time.
4353///
4354/// The poll's own word is in the middle, and that is not decoration — it is what makes the refusal
4355/// self-explaining. `rustc` names the type in the `E0277` sentence and lists the impls that DO
4356/// exist beside the one that does not, so a sweep reaching past its clock reads
4357/// *`ReaperHourlyGrants<…>: AsyncLands<Transcript>` is not satisfied* with `ReaperNightlyGrants<…>`
4358/// named among the types that satisfy it. The clock holding the grant is in the sentence because it
4359/// is in the name.
4360///
4361/// The poll word arrives already in UPPER CAMEL — it is [`PollEntry::variant`], the same spelling
4362/// the `<Node>Due` arm takes — so a clock is spelled one way wherever it is spelled.
4363pub fn poll_grants_name(record: &syn::Ident, variant: &syn::Ident) -> syn::Ident {
4364  format_ident!("{record}{variant}Grants")
4365}
4366
4367/// What a node's LENDING is called: `<Node>Polling`.
4368///
4369/// The value a DEPLOYMENT builds and hands to `Resident::polling` — one field per granting clock,
4370/// each holding that clock's own context, beside the citizen each mounted clock ticks and the
4371/// executor each detached one runs on. Only the runtime ever looks inside it.
4372///
4373/// It is named for the SEAM rather than for the permission, and that is the whole of the rename: the
4374/// value is what a node's POLLING needs, of which grants are one part — `Resident::polling(op,
4375/// ExporterPolling::new(…))` reads as its own sentence, where `ExporterGrants` claimed a word that
4376/// belongs to the per-clock contexts. Those keep it ([`poll_grants_name`]), because they hold
4377/// exactly grants and nothing else.
4378///
4379/// It is the fifth emitted per-node name beside `<Node>In`, `<Node>Out`, `<Node>Due` and
4380/// `<Node>Channels`, and it is named for the WORD rather than for the borrow: `Context` is spoken
4381/// for twice over in the framework (the resource map, and the emission buffer that gave the name
4382/// back).
4383pub fn default_polling_name(record: &syn::Ident) -> syn::Ident {
4384  format_ident!("{record}Polling")
4385}
4386
4387/// What a node's SWEEP TRAIT is called: `<Node>Sweeps`.
4388///
4389/// Where an author writes a sweep, one ENTRY per `light` CLOCK, named by the word that clock
4390/// minted — a clock that wrote `handler = "…"` has no entry, because its body is a citizen the
4391/// deployment built. A node whose every clock mounted one emits no trait at all.
4392///
4393/// It carries ONE `Info` and ONE `Error` for the whole node, which is not a convenience — the
4394/// resident has one observation stream and one `Effect` table, so two clocks answering in two types
4395/// is a thing that cannot be true, and here it is a thing that cannot be WRITTEN (`E0201`, duplicate
4396/// definition). An INLINE mounted citizen is bound to the same pair on the route, so the law reaches
4397/// across the split.
4398///
4399/// The framework word one scope down, as `<Node>Due` and `<Node>Channels` are.
4400pub fn default_sweeps_name(record: &syn::Ident) -> syn::Ident {
4401  format_ident!("{record}Sweeps")
4402}
4403
4404/// The item a storage node mints so that a second storage on the same type cannot be spelled.
4405///
4406/// Two macro expansions cannot see one another, so `#[ingraph::fulltext(…)]` beside
4407/// `#[ingraph::vector(…)]` is not detectable by either of them. What IS detectable is the
4408/// collision the two expansions make: each mints this name in the declaring scope, and two of them
4409/// are `E0428` — *the name `__ig_<Record>_holds_one_storage` is defined multiple times* — reported
4410/// at the offending type, with rustc's own note naming the second macro. The invariant is enforced
4411/// by construction rather than documented beside the code.
4412///
4413/// It carries the RECORD's name because the scope is the declarer's: two storage nodes in one
4414/// module are an ordinary program, and a marker that named only the framework would refuse it.
4415///
4416/// A `const` and not a unit struct, which would occupy the type namespace as well for no gain, and
4417/// PRIVATE, so a marker never joins the declaring crate's public API. Both of those and the
4418/// namespace mark are why the emission spends three `allow`s on it: it is dead by construction,
4419/// its name is neither upper case nor camel case, and nothing may make a declaration fail its own
4420/// `-D warnings` build over an item its author did not write.
4421///
4422/// It is PREFIXED rather than framed: the frame is the column law, and this is an item. It also
4423/// takes the model's own [`EmissionPrefix`], which is what makes two FRAMEWORKS' storage nodes on
4424/// one type an ordinary program — `__ig_Clip_holds_one_storage` and `__mg_Clip_holds_one_storage` are
4425/// two names, so the refusal stays what it is for, a SECOND storage under ONE framework.
4426pub fn one_storage_marker(prefix: &EmissionPrefix, record: &syn::Ident) -> syn::Ident {
4427  prefix.prefixed_ident(&format!("{record}_holds_one_storage"))
4428}
4429
4430/// What ONE ELECTION's marker type is called: `<Record>By<Field>`.
4431///
4432/// The name is the TYPE spelling of the method name beside it — `retrieve_by_image_embedding` and
4433/// `SegmentPairByImageEmbedding` are one election read two ways, so a reader who has found either has
4434/// found the other, and a declaration's elections and its per-election methods cannot drift apart in
4435/// spelling.
4436///
4437/// It carries the RECORD's name for [`one_storage_marker`]'s reason, which is the naming law every
4438/// item this family mints in the declarer's scope is under: the scope belongs to the author, two
4439/// declarations electing a field of the same name are an ordinary program, and a marker named after
4440/// the field alone would make the second one `E0428`.
4441///
4442/// A UNIT STRUCT and not a `const`, which is the one place it parts from the storage marker: this
4443/// name is spelled by the wiring — `SlotLane<E, T, SegmentPairByImageEmbedding>` — so the type namespace is
4444/// exactly where it is needed, and it takes the declaration's own visibility for the same reason the
4445/// retrieve methods do.
4446pub fn elected_marker(record: &syn::Ident, field: &syn::Ident) -> syn::Ident {
4447  format_ident!(
4448    "{record}By{field}",
4449    field = crate::emit::upper_camel(&field.to_string()),
4450  )
4451}
4452
4453/// The FIELD a derived index carries its upstream's key in — the one field a macro in this family
4454/// adds to a declaration its author wrote.
4455///
4456/// *The key is not its to mint.* A derived index has no `id`, so `Identifiable::id_ref` and
4457/// `Transformer::key` have nothing in the declaration to answer from; this field is what they answer
4458/// from, and its TYPE is a projection — `<Upstream as Transformer>::Key` — so the upstream's own
4459/// declaration decides it and re-keying the upstream re-keys every index over it.
4460///
4461/// It is why the family is attribute macros. A derive is handed a copy and may only append, so a
4462/// field that is not in the source cannot exist; an attribute macro emits the item in the source's
4463/// place, and this is the field it puts there.
4464///
4465/// # THE FRAME LAW
4466///
4467/// Every name the framework mints into a declaration's own namespace wears `__ig` at the front, and
4468/// a FIELD wears `__` at both ends as well — which is what makes the injection safe rather than
4469/// merely conventional. `ingraph-derive`'s fence refuses a declared column inside either namespace,
4470/// so a user field called `__ig_key__` is refused at the declaration and can never be the field this
4471/// one collides with.
4472///
4473/// The tail of such a word must not look like `_<digits>__`. Where a mint is INDEXED the digits fuse
4474/// into the word — `__ig_ord0__`, never `__ig_ord_0__` — so that the index cannot be read as a
4475/// separate segment and two schemes cannot produce one name. Nothing minted today is indexed;
4476/// `upstream(…)`'s second entry is what will be, one source per key variant, and the law is stated
4477/// here because here is where a reader of the first mint will look for it.
4478///
4479/// The frame is [`EmissionPrefix::framed_ident`]'s, so the mark is the MODEL's rather than this
4480/// crate's: a declaration a domain framework expanded carries that framework's injected key, fenced
4481/// by that framework's own derive, and the law above holds unchanged one namespace over.
4482pub fn borrowed_key(prefix: &EmissionPrefix) -> syn::Ident {
4483  prefix.framed_ident("key")
4484}
4485
4486/// The field a FAN-IN node carries its lineage in — [`borrowed_key`]'s sibling, obeying the same
4487/// frame law and injected the same way.
4488///
4489/// A node drawing from several independent upstreams cannot DECLARE its ancestry as columns: which
4490/// columns a row has depends on which upstream it came from, and a struct with nullable columns
4491/// would make the invalid combinations representable. So the whole ancestry is one value of the
4492/// emitted choice, and the expansion puts the field there — the same reason `__ig_key__` exists one
4493/// tier over, arriving at a node that DOES mint an id.
4494///
4495/// It does not contradict *indexes inject, records declare*. That boundary is about a lineage a
4496/// declaration COULD spell: a fusing node's mirror columns are query surface and its declaration
4497/// names them. Here there is nothing to name — a variant is not a column — so the injection is the
4498/// only spelling there is.
4499///
4500/// It takes the model's [`EmissionPrefix`] for [`borrowed_key`]'s reason, and the two are the
4501/// whole of what a framework injects into a declaration's own struct.
4502pub fn fanned_lineage(prefix: &EmissionPrefix) -> syn::Ident {
4503  prefix.framed_ident("lineage")
4504}
4505
4506/// The column that field becomes IN THE KEY.
4507///
4508/// A plain word rather than the framework's fenced one, because a key's columns are read by name
4509/// wherever an address is spelled and `__ig_lineage___ref` is not a name anyone should have to
4510/// type. A record declaring its own `lineage` field collides with it in the key type, which the
4511/// same-name rule already refuses, by name.
4512pub fn fanned_lineage_column() -> syn::Ident {
4513  format_ident!("lineage")
4514}
4515
4516#[cfg(test)]
4517mod node_kind_tests;
4518#[cfg(test)]
4519mod poll_body_tests;