ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
//! The full-text family's two seams: [`FulltextEngine`] (the per-slot handle) and
//! [`AsyncFulltextStore`] / [`FulltextStore`] (the construction layer that mints the handle) — and
//! the read's GRAIN, [`FulltextColumn`] with the [`FulltextSubset`] every search is scoped by.
//!
//! There is no third. The per-(value type × engine) ROW this family shipped is gone: a key reports
//! itself in COLUMNS now ([`Field`](crate::Field)), so one impl per TYPE crosses into every engine
//! there is and this module names none.

use core::future::Future;

use smol_bytes::Utf8Bytes;

use super::{ColumnReader, ColumnWriter, NoColumns};

/// WHICH searchable field of a slot a call is about — the full-text ELECTION SELECTOR.
///
/// [`VectorColumn`](super::VectorColumn)'s twin, minted for its reason and spelled the same way: a
/// declaration may elect N fields, each searchable, and the subject of a search has to be sayable
/// when the caller means one of them rather than all of them.
///
/// # A NEWTYPE over `&'static str`, and both halves of that are the point
///
/// A STRING because a column is a name at the storage boundary: what an engine does with one is
/// scope a query to a field, pick that field's analyzer, or open a per-column index, and every one
/// of those wants the name. A NEWTYPE because a bare `&str` in this position is a magic string —
/// beside a query `&str` in the same call it type-checks against the wrong argument — where a named
/// type makes the parameter's subject readable at the call and unmistakable in a signature.
///
/// `&'static str` because of where the value COMES FROM: a `#[ingraph(searchable)]` marker on a
/// FIELD, so the column's name is that field's own ident — a token of the declaration — and every
/// column an emission addresses is minted `const` from it and outlives everything. A backend that
/// needs an owned form takes one off [`as_str`](Self::as_str); nothing here allocates.
///
/// # The value world's half of a TYPED vocabulary
///
/// A declaration's emission mints a `<Tier>Column` ENUM whose variants are its elected fields, and
/// translates a variant into one of these at a single point. So a CALLER spells the enum — where an
/// unelected column has no variant to write with — and this type is what crosses the seam, where an
/// engine that never saw the declaration reads a name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FulltextColumn(&'static str);

impl FulltextColumn {
  /// Name a column.
  ///
  /// `const`, because the caller with the strongest claim to one is an expansion writing the name of
  /// the field a `searchable` marker elected.
  #[inline]
  #[must_use]
  pub const fn new(name: &'static str) -> Self {
    Self(name)
  }

  /// The name, as the backend spells it.
  #[inline]
  #[must_use]
  pub const fn as_str(self) -> &'static str {
    self.0
  }
}

/// WHICH of a slot's searchable columns one [`search`](crate::FulltextRead::search) runs over — the read
/// GRAIN, always passed.
///
/// # One verb, and the whole subject is a VARIANT rather than an absence
///
/// The alternative was a second verb — `search` beside a scoped one — and a family of two verbs is a
/// family every engine implements twice and every caller picks between. Here the whole-subject
/// question is [`All`](Self::All): spelled, passed, and no more special than any other subset. An
/// engine writes one body and matches; a caller that never scopes anything writes one word.
///
/// # What each arm MEANS, and what this seam does not check
///
/// [`All`](Self::All) is *whatever this slot holds*, which is the question this seam always asked
/// and the one no declaration has to enumerate — an engine whose slot holds columns the declaration
/// never mentioned still answers over them, because what a slot holds is the ENGINE's fact.
///
/// [`These`](Self::These) names columns. A name this slot does not hold is the ENGINE's refusal, in
/// the engine's own vocabulary, because only the engine has a schema to check it against; the same
/// goes for an EMPTY slice, which asks over nothing. Neither is checked here: a seam that refused
/// either would be a seam holding a schema, and it holds none. What the framework does instead is
/// put a TYPED vocabulary in front of the caller — the emitted `<Tier>Column` enum — so a column
/// this declaration never elected is unspellable long before it reaches an engine.
///
/// # `Copy`, and a borrow rather than a collection
///
/// The columns are a SLICE and not a `Vec`, so the whole value is [`Copy`] and a caller holding a
/// `const` list — which is what an emitted per-field door holds — allocates nothing to ask. An
/// engine wanting an owned form makes one; the seam does not make one on its behalf.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum FulltextSubset<'a> {
  /// Every searchable column this slot holds — the whole subject.
  #[default]
  All,
  /// Exactly these columns, and no other.
  These(&'a [FulltextColumn]),
}

/// A full-text index (Tantivy, an FTS5 virtual table, a Postgres `tsvector` column) — **R-FREE**.
///
/// It names no record, no key and no document type of the declaration's. What crosses it is the
/// engine's OWN vocabulary: an [`Address`](Self::Address) it addresses entries by, a
/// [`Score`](Self::Score) it ranks them in, and the [`Doc`](crate::FulltextWrite::Doc) its write
/// face builds them in. The TYPING is the emission's — the declaration flattens its record into the
/// `Doc`, reports its id and its key as COLUMNS, and reads a hit's `Address` back into its own key
/// type. This trait says what an engine SPEAKS, and it says it with no opinion about what an entry
/// means.
///
/// # It is the BASE, and a base has no verbs
///
/// What lives here is that vocabulary together with the ADDRESS LIFECYCLE that turns a key into one
/// of this engine's addresses and back. The verbs are on the four faces
/// ([`FulltextRead`](crate::FulltextRead) / [`AsyncFulltextRead`](crate::AsyncFulltextRead),
/// [`FulltextWrite`](crate::FulltextWrite) / [`AsyncFulltextWrite`](crate::AsyncFulltextWrite)),
/// each naming this trait as a supertrait and each holding the LEASE its own direction spends.
///
/// So a bound asks for exactly the half it uses. A query type that only spells an
/// [`Address`](Self::Address) and a [`Score`](Self::Score) binds THIS and inherits no search; a
/// retrieve binds a read face; a drainer binds a write one; and an engine that only reads — a
/// snapshot, a replica, a served index — is spellable, which it was not while one trait carried
/// every verb.
///
/// **THERE IS NO GAT LEFT HERE.** Both leases moved onto the faces that spend them, so nothing a
/// query type or a walk binds carries borrowing machinery, and the read/write scopes are free to be
/// two different types on the two modes — an async transaction ticket is not a blocking searcher's.
///
/// # Why the record parameter went, and what it was costing
///
/// `FulltextDb<R>` carried the record so its signatures could project `R::Key`, `R::Document` and
/// `R::Id`. Three prices came with it, all of them paid by callers rather than by backends:
///
/// - **The ORPHAN WALL.** A record-generic engine trait needs a per-engine bound on what it
///   addresses entries by (`R::Id: TantivyKey`), and that bound is a trait over FOREIGN types, so
///   every member of the id vocabulary had to be implemented FROM this crate — `impl TantivyKey for
///   i64` in a declaring crate is `E0117`. The COLUMN LANGUAGE takes the axis away entirely: a
///   key's row ([`Field`](crate::Field)) names no engine at all, so there is nothing left for an
///   orphan rule to be about.
/// - **An unrequirable bound in an expansion.** A method-level `where R: …` that an expansion cannot
///   satisfy is `E0277` — *add `#![feature(trivial_bounds)]`* — at a span the declaration's author
///   cannot edit. An R-free seam has no such `where` to satisfy.
/// - **Inference.** Every call had to name the record (`FulltextDb::<Caption>::search(…)`) because a
///   query string names no record — `E0284` otherwise. There is nothing left to name.
///
/// # THE ADDRESS LIFECYCLE — three functions, and the phase each one ends
///
/// An address is a KEY'S IDENTITY in this engine's own vocabulary, and it is built and read in
/// phases that cannot be confused for one another:
///
/// ```text
/// buffer() ─► WriteBuffer ─(the key reports its columns)─► finalize(buf) ─► Address
/// Address ─► open(address) ─► ReadBuffer ─(the key takes its columns)─► ColumnReader::finish
/// ```
///
/// [`WriteBuffer`](Self::WriteBuffer) is a [`ColumnWriter`] and [`ReadBuffer`](Self::ReadBuffer) is
/// a [`ColumnReader`], so what crosses between a key and an engine is TYPED COLUMNS — never an
/// intermediate encoding both sides then decode. That is what makes a key's row engine-blind and
/// costs a new engine no row at all.
///
/// All three are ASSOCIATED FUNCTIONS rather than methods: minting a buffer, sealing it and opening
/// an address ask nothing of a handle, so `E::open(…)` is spellable wherever `E` is — which is what
/// [`keyed`](crate::retrieve::keyed), the framework's full-text read walk, needs of it. The WRITE
/// half has no framework walk of its own yet, for the reason `retrieve::address`' module doc states:
/// this family's by-key read has no grammar, so the only caller that builds an address is a
/// backend's own entry builder, spelling the three phases where the engine is concrete.
///
/// # THE SAME-BYTES LAW
///
/// The column sequence a key reports into a [`WriteBuffer`](Self::WriteBuffer) is the sequence it
/// takes back off the [`ReadBuffer`](Self::ReadBuffer) [`open`](Self::open) mints from the finished
/// address. An address built by the write walk and an address a hit arrives under are THE SAME BYTES
/// for the same key, which is the whole correspondence a keyed replace stands on.
///
/// # `SearchOptions` and the LEASE are two different seats, and only one of them is here
///
/// [`SearchOptions`](Self::SearchOptions) is the BACKEND's own per-query knobs and stays on the base
/// because a wire face carries it: an emitted engine variant's `options` row is typed on it, so the
/// type must be nameable from a bound that spends no verb. The LEASE is the half a request cannot
/// carry — a committed snapshot, a reader's ticket — and it went with the verbs, onto
/// [`FulltextRead::ReadContext`](crate::FulltextRead::ReadContext) and its three siblings.
///
/// # What is NOT here, and where each of them went
///
/// `put`/`get` stay the ARTIFACT family's own. A blob store derives nothing and holds no index: it
/// is handed a key and gives bytes back, so its verbs name a store rather than a replace.
///
/// The write is also NOT the socket a storing node writes through — see
/// [`AsyncLands`](crate::AsyncLands). That is one layer up, it answers per ITEM rather than per
/// entry, and the layering is the whole reason there are two names: a lane IMPLEMENTS the socket and
/// CALLS the face's verb. Two parallel write verbs at one layer would be the duplication that
/// arrangement exists to refuse.
pub trait FulltextEngine {
  /// **PER-SLOT CREATION INPUT** — the knobs an author states for ONE home this engine makes.
  ///
  /// # It has a spender now, and the spender is LAYER TWO
  ///
  /// The seat was reserved and honest about being reserved: *a reserved extension point, `()` where
  /// a backend needs none*. What it was waiting for is the initialization walk. A slot maker CREATES
  /// the home a blueprint describes, and the half of that description a DECLARATION cannot state is
  /// the deployment's — a tokenizer, an analyzer chain, an `ef`, a replication factor. Those arrive
  /// at BOOT and belong to nobody but the engine, so the walk's own per-slot table is typed on this
  /// member and the value crosses at the store's own `create_slot` door, one per corpus — see the
  /// shipped tantivy backend, where the first one is written.
  ///
  /// # Why it is not on the blueprint
  ///
  /// A [`Describe`](crate::Describe) blueprint is a `const`, so a descriptor built per boot is a
  /// schema that could differ between two of them. A knob a document decides is exactly such a
  /// value, which is why it lives on the VISITOR — see [`Habitat`](crate::Habitat), where the split
  /// is written down.
  ///
  /// # `()` where a backend needs none
  ///
  /// Still the shipped answer, and the reservation still buys what it bought: adding the member
  /// LATER would break every engine impl there is, and adding a value to it now is purely additive.
  type Options;
  /// PER-QUERY tuning — the knobs one [`search`](crate::FulltextRead::search) runs under, in this
  /// engine's own
  /// vocabulary. `()` where a backend has none.
  ///
  /// [`VectorEngine::SearchOptions`](crate::VectorEngine::SearchOptions) carries the whole
  /// argument — the same three divisions (against [`Options`](Self::Options), which is spent once
  /// at construction; against [`FulltextRead::ReadContext`](crate::FulltextRead::ReadContext), which is
  /// a scope a request cannot
  /// carry; and the third party's wire duty at the emitted `options` row) — and this face states it
  /// in the vocabulary a full-text engine tunes in: an analyzer choice, a per-field boost, a
  /// fuzziness, a conjunction default.
  ///
  /// The SHIPPED engine answers `()` — see
  /// [`TantivyFulltext`](crate::store::tantivy::TantivyFulltext) for the measurement, which found
  /// exactly one per-query knob and found it to be a UNIVERSAL one.
  type SearchOptions;
  /// This backend's failure — ONE error for the engine, whatever raised it.
  ///
  /// It is the read phase's error too: [`ReadBuffer`](Self::ReadBuffer) is tied to it
  /// (`ColumnReader<Error = Self::Error>`), so a column a key could not take and a search that could
  /// not run refuse in one type. That tie is what puts [`ColumnError`](crate::ColumnError) on this
  /// member in practice — a ROW has refusals of its own and no way to name this type, so the floor
  /// is what lets it word them.
  type Error;
  /// The currency [`search`](crate::FulltextRead::search) scores in — `f32` for a BM25 engine,
  /// `f64` for a face
  /// whose driver hands back double precision, a fused or composite shape for a layer that ranks
  /// rather than measures.
  ///
  /// # [`PartialOrd`] and nothing else, and the FLOOR is the site that bought it
  ///
  /// The member was bound by NOTHING while nothing above the seam compared a score. That site now
  /// exists: every retrieve carries a MANDATORY minimum score, and the framework's portable
  /// backstop compares each hit against it — see
  /// [`FulltextQuery`](crate::retrieve::FulltextQuery). A comparison needs an ordering, so the
  /// contract grows the ordering and stops there.
  ///
  /// `PartialOrd` rather than [`Ord`]: `f32` is the currency the shipped engine scores in, and a
  /// total order would refuse it. What partiality costs is one decision, made once at the walk — a
  /// score that will not compare against the floor reads as below it, which is the conservative
  /// answer and the honest one.
  type Score: PartialOrd;
  /// The engine's OWN address vocabulary — what a key's columns seal into on the way in, and what a
  /// hit's stored address arrives as on the way out.
  ///
  /// ONE type for both directions, because it is one correspondence: an address written by a key has
  /// to be readable by that same key's type, and two members would let a backend supply one half and
  /// not the other — which is exactly how a stored address becomes unreadable by the code that wrote
  /// it.
  ///
  /// OWNED, not a borrow of the engine's buffers: a search hands these back inside the hits, so a
  /// borrowing form would tie every result to the searcher that produced it.
  type Address;
  /// The shared connection-manager (the [`AsyncFulltextStore`] that opened it), reached via
  /// `ctx.connection()` — the slot's index and its reader, held ONCE, not reopened per call. PLAIN,
  /// not a GAT.
  type Connection;
  /// THE WRITE PHASE — the buffer a key reports its columns into, before there is an address at all.
  ///
  /// A [`ColumnWriter`], so what it is handed is one TYPED column at a time and it lands each in
  /// whatever this storage natively has: a tantivy term, an FTS5 bound parameter, a `tsvector`
  /// literal. Nothing is encoded to a shared form on the way, which is the whole economy of the
  /// language.
  type WriteBuffer: ColumnWriter;
  /// THE READ PHASE — the cursor an address is opened into, which a key takes its columns back off.
  ///
  /// OWNED, with no lifetime of its own: it is minted by [`open`](Self::open) from an address it
  /// CONSUMES, so it borrows nothing and a walk holding one is not tied to whatever the address came
  /// out of. That is what keeps the base free of GATs.
  ///
  /// Its error IS this engine's error, tied here rather than left to agree by convention: a column
  /// a key could not take and a search that could not run are one backend's refusals, and a caller
  /// unwrapping the walk should not have two types to name.
  type ReadBuffer: ColumnReader<Error = Self::Error>;

  /// Open a WRITE PHASE — an empty buffer, positioned before the first column.
  ///
  /// # NOT `Self::WriteBuffer: Default`, and the difference is a real one
  ///
  /// A bound would have cost no function and would have been WRONG for a whole class of engine: an
  /// address that is a row id or a uuid has a `Default` that is a perfectly valid ADDRESS — row
  /// zero, the nil uuid — and a key reporting its columns *into* one would be appending to a
  /// location rather than starting at an empty one. The shipped engine's own address is exactly that
  /// coincidence: `TantivyAddress::default()` is the empty byte string, which is what would have
  /// made the bound look right. A named function states the contract the bound could only imply.
  ///
  /// The phase split makes that confusion unrepresentable rather than merely refused: what this
  /// mints is not an address and has no address's type, so there is no empty address for an empty
  /// start to be mistaken for. What the argument still buys is the FUNCTION — an engine whose buffer
  /// is a handle, a pooled arena or a builder carrying schema is minting rather than defaulting.
  fn buffer() -> Self::WriteBuffer;

  /// SEAL a write phase into the address its columns spell.
  ///
  /// It CONSUMES the buffer, which is the typestate half of the same argument: a key that has
  /// reported itself is done reporting, so there is no buffer left beside the address for a second
  /// column to be appended to. What comes back is the engine's own [`Address`](Self::Address) — the
  /// same bytes a hit for that key arrives under.
  fn finalize(buf: Self::WriteBuffer) -> Self::Address;

  /// Open a READ PHASE over `address` — the cursor a key takes its columns back off.
  ///
  /// **BY VALUE.** The address is consumed rather than borrowed, and that is the phase saying what
  /// it means: an address handed to this is being SPENT as one key's identity, so there is no
  /// half-read address left behind for a second reader to start over on. It also frees the reader
  /// from the address's storage — a buffer that wants to take the bytes rather than walk them may.
  ///
  /// # The SURPLUS is asked at the other end, and it is the engine's own fact
  ///
  /// Whether the key took ALL of the columns is [`ColumnReader::finish`]'s question, asked once by
  /// the walk that owns the reader. A surplus is a fact about THIS ENGINE's own vocabulary, which is
  /// why the engine answers it — tolerating one would let `(7, 42)` pose as the address of
  /// `(7, 42, 3)`, a hit carrying the wrong entity, silently.
  fn open(address: Self::Address) -> Self::ReadBuffer;
}

/// Construction for a full-text store — per-slot indices opened and cached behind ONE
/// connection-manager.
///
/// A `*Store` IS the [`Connection`](FulltextEngine::Connection) its handles borrow: opened once by
/// [`open`](Self::open), its per-slot factory mints a STATELESS handle that reaches back through
/// `ctx.connection()`, so nothing reconnects per call. `open`'s future is `Send` (a multi-threaded
/// runtime); [`fulltext`](Self::fulltext) is SYNC and INFALLIBLE — a stateless handle needs no I/O
/// to mint, so any per-slot index open happens lazily behind the shared manager on first use.
/// `: Sized` because `open` returns `Self` by value.
///
/// [`FulltextStore`] is the BLOCKING twin, and the pair is [`AsyncBlobStore`](crate::AsyncBlobStore)
/// / [`BlobStore`](crate::BlobStore)'s verbatim one family over: [`fulltext`](Self::fulltext) is
/// already synchronous on both faces, so [`open`](Self::open) is the whole of what a mode can change
/// here.
pub trait AsyncFulltextStore: Sized {
  /// How to open the connection-manager — an index root, pool options. Open for the reason
  /// [`AsyncBlobStore::Options`](crate::AsyncBlobStore::Options) is: hardening it to a path is refused in
  /// advance.
  type Options;
  /// An open failure.
  type Error;
  /// The stateless per-slot handle produced — its `Connection` is `Self`.
  type Handle;

  /// Open the connection-manager (a pool / client) ONCE.
  fn open(options: Self::Options) -> impl Future<Output = Result<Self, Self::Error>> + Send;

  /// The stateless handle for full-text slot `slot`.
  ///
  /// # Why there is no width here, where [`AsyncVectorStore::vector`](crate::AsyncVectorStore::vector) takes
  /// one
  ///
  /// A vector slot's `dim` is a fact the slot's storage cannot be shaped without — a column of
  /// 768-wide embeddings is a different column from a 384-wide one. A document schema has no such
  /// number: what a slot holds is text, and how it is analyzed is the engine's own configuration
  /// rather than a shape the caller has to state to open the thing. One parameter is the whole
  /// difference between the two factories, and it is this.
  fn fulltext(&self, slot: impl Into<Utf8Bytes>) -> Self::Handle;
}

/// Construction for a full-text store whose OPENING is a blocking act — [`AsyncFulltextStore`]'s
/// twin, and the narrowest shape a store pair takes: it differs in exactly one verb.
///
/// [`fulltext`](Self::fulltext) is already synchronous on the async face — a stateless handle needs
/// no I/O to mint — so [`open`](Self::open) is the whole of what a mode can change. Opening an index
/// directory is a syscall that returns; the shipped
/// [`TantivyStore`](crate::store::tantivy::TantivyStore) was always spelled that way behind its own
/// inherent `open`, and this seam is where it stops wrapping that fact in an `async fn`.
///
/// # The two faces are SIBLINGS
///
/// Neither is a supertrait of the other, per [`BlobEngine`](crate::BlobEngine)'s ratified argument: a
/// supertrait either way taxes one kind of store with a face nobody asked it for. What a store CAN
/// answer is what it implements, and a caller's bound is what says which face it needs. A store
/// answering both writes both — which is what the shipped tantivy store does, the blocking face
/// holding the body and the async one delegating to it.
#[diagnostic::on_unimplemented(
  message = "`{Self}` has no BLOCKING full-text-store face",
  label = "this store opens through a future, and a sync body cannot spend one",
  note = "two roads: implement `FulltextStore` for a store whose open is natively blocking (an \
          index directory, a memory-mapped volume), or move the caller onto the async face \
          `AsyncFulltextStore` — wrapping an async open in a block-on here would be the fiction the \
          dual-mode law exists to refuse"
)]
pub trait FulltextStore: Sized {
  /// How to open the connection-manager — an index root, pool options.
  type Options;
  /// An open failure.
  type Error;
  /// The stateless per-slot handle produced — its `Connection` is `Self`.
  type Handle;

  /// Open the connection-manager ONCE, on this thread.
  ///
  /// # Errors
  ///
  /// [`Error`](Self::Error) where the store cannot be opened.
  fn open(options: Self::Options) -> Result<Self, Self::Error>;

  /// The stateless handle for full-text slot `slot`.
  ///
  /// No width, for [`AsyncFulltextStore::fulltext`]'s stated reason: a document schema has no number
  /// a slot's storage cannot be shaped without.
  fn fulltext(&self, slot: impl Into<Utf8Bytes>) -> Self::Handle;
}

/// The unused full-text face.
///
/// FULLY UNBOUNDED, which it was not before: the record-generic seam needed `R: Transformer` and
/// `R::Key: Send` on the impl block, because the key rode `search`'s output and an RPITIT `+ Send`
/// return demanded it. An R-free seam projects nothing off anything, so the whole `where` clause is
/// gone — the poverty dividend, visible as a deletion.
///
/// Every member is `()`: an address vocabulary with no values and a face with no scoring vocabulary,
/// which is the honest answer for a store that never ranks anything.
///
/// The whole address lifecycle is the UNIT, in all three phases: the column language's own unused
/// pair ([`ColumnWriter for ()`](ColumnWriter), [`ColumnReader for ()`](ColumnReader)) accepts every
/// column and drops it, and refuses every read for the honest reason that nothing was ever landed.
/// So `Error = NoColumns` rather than [`Infallible`](core::convert::Infallible): the read phase is
/// tied to this member, and a key asking a face that holds nothing for a column has to be answered.
/// The face still cannot fail at a VERB — see the four face impls, every one of which answers.
impl FulltextEngine for () {
  type Options = ();
  /// `()`, the seam's own word for *no per-query knobs* — a face that searches nothing is tuned by
  /// nothing, and it is named by no declaration's typed word, so no wire duty is owed.
  type SearchOptions = ();
  type Error = NoColumns;
  type Score = ();
  type Address = ();
  type Connection = ();
  type WriteBuffer = ();
  type ReadBuffer = ();

  #[inline(always)]
  fn buffer() -> Self::WriteBuffer {}

  /// `Address = ()`, so a sealed buffer IS the unit — a face that stores nothing addresses nothing,
  /// and `()` is the one value it can hand back.
  #[inline(always)]
  fn finalize(_buf: Self::WriteBuffer) -> Self::Address {}

  #[inline(always)]
  fn open(_address: Self::Address) -> Self::ReadBuffer {}
}

/// ONE FULL-TEXT SLOT's document contract: the ROAD its elected field takes into the sink, and
/// whether the engine KEEPS the original value beside what it indexed.
///
/// A derived index's expansion implements this on the `(elected field × engine)` marker it already
/// mints for [`Slot`], one impl per full-text slot. Nothing implements it by hand.
///
/// # Why it hangs off the SLOT rather than off the field
///
/// One field may be held by two engines under two roads — `tantivy(multi)` beside
/// `fts5(join = ", ")` — and the reason is not taste: the SEGMENTATION means different things to
/// them. A positional engine puts a gap between segments; a single-text-column face has to flatten
/// them, and then a phrase spans a boundary that was written to stop it. The same
/// `fn(&mut BoxWriter, &T)` therefore indexes correctly in one and subtly wrongly in the other,
/// with nobody notified — both "work" and only the results differ. So a field-level,
/// engine-agnostic road is not expressible, and the slot is the finest grain at which one is.
///
/// # ONE trait with an [`Error`](Self::Error), where the record side has two shapes
///
/// A record's crossing is `From` when nothing can fail and `TryFrom` when something can, never
/// both, because those are `core`'s traits and its blanket decides. This is the framework's own
/// trait, so the same fact — *fallibility is per declared set, never per direction* — is carried by
/// the member instead: an infallible road names [`Infallible`](core::convert::Infallible) and the
/// `Result` costs nothing, a `try_from` road names the boxed refusal its `?` already absorbs into.
/// One trait, one shape, and the bit is still in the type.
pub trait FulltextRoad: super::Slot {
  /// Whether the engine KEEPS the original value, retrievable, beside what it indexed.
  ///
  /// `false` unless the declaration wrote `stored` inside this engine's block, and the cheap
  /// default is the honest one: what a full-text index promises is that the text is SEARCHABLE, and
  /// handing the text back is a second promise a corpus pays for in bytes on every entry. A caller
  /// that wants the value has the system of record, addressed by the key every hit already carries.
  const STORED: bool;

  /// How this slot's road can FAIL — [`Infallible`](core::convert::Infallible) for the identity
  /// road, both shorthands, and a plain `from`.
  type Error;

  /// Run this slot's road over `entry`, pushing its segments into `into`.
  ///
  /// # Errors
  ///
  /// Whatever a declared `try_from` converter reported, absorbed into [`Error`](Self::Error).
  fn write(entry: &Self::Of, into: &mut crate::BoxWriter) -> Result<(), Self::Error>;
}

/// **ONE ENGINE'S WRITE LANE** — how a party holding nothing but this engine opens a batch, builds
/// the entries for it, publishes it, and throws it away.
///
/// [`AsyncFulltextWrite`] carries the QUEUE VERB and stops there: `upsert` takes a finished
/// [`Doc`](AsyncFulltextWrite::Doc) inside a [`WriteContext`](AsyncFulltextWrite::WriteContext), and
/// names no way to obtain either. That is the honest shape for a HAND-WRITTEN caller, which holds
/// the concrete engine and builds both by name — and it is exactly what a SUBSCRIBING declaration
/// cannot do: an emission holds `<R as FulltextMount>::Handle` and no idea which engine that is.
/// This trait is the half that was missing, and the reason it is a trait rather than three lines in
/// an expansion is the standing law: **an engine is a seam, never a name an emitter hard-codes.**
///
/// # FIVE members, and each one is a step an emitted body cannot write for itself
///
/// | member | what only the engine knows |
/// |---|---|
/// | [`open`](Self::open) | what a batch even IS — a writer, a transaction, a queue |
/// | [`scope`](Self::scope) | how a held batch becomes the per-call lease the verb takes |
/// | [`entry`](Self::entry) | what a document looks like in this engine's own vocabulary |
/// | [`publish`](Self::publish) | when a write becomes VISIBLE, which is not the same as committed |
/// | [`discard`](Self::discard) | how a half-applied batch is unwound |
///
/// # `publish` is VISIBILITY and not merely a commit
///
/// The two come apart, and a lane that conflated them would ship a subscriber whose writes are
/// durable and unfindable. The shipped backend is the case in point: tantivy reads through a
/// `ReloadPolicy::Manual` reader, so a committed batch stays invisible until that slot's reader is
/// reloaded — see [`TantivyStore::reload`](crate::TantivyStore::reload). *Read your own committed
/// writes* is what a caller means, so it is what this member promises, and each engine pays whatever
/// that costs it.
///
/// # It takes the CONNECTION at every step rather than holding one
///
/// [`FulltextEngine::Connection`] is threaded by the caller in this family — a handle is stateless
/// and holds only its slot — so a lane that captured a connection would be a second, contradictory
/// answer to *who owns the store*. Every member takes it back exactly as
/// [`upsert`](AsyncFulltextWrite::upsert) does.
#[diagnostic::on_unimplemented(
  message = "`{Self}` has no full-text WRITE LANE, so a subscribing declaration cannot land through \
             it",
  label = "this engine states how to queue a document, but not how to open, publish or discard a \
           batch of them",
  note = "a `subscribe`d `#[ingraph::fulltext]` declaration is a launchable node: it opens one \
          batch per delivery, queues its documents through the branded `SlotHandle`, and publishes \
          before it answers — three acts only the engine can perform",
  note = "implement `FulltextLane` for the engine this declaration's `resource = \"…\"` points at, \
          or drop the `subscribe` word and write the lane by hand"
)]
pub trait FulltextLane: super::AsyncFulltextWrite {
  /// The LEASE one batch of entries is written under — a writer, a transaction, an open queue.
  ///
  /// OWNED and not a GAT, because a subscriber HOLDS it across the whole of one delivery and hands
  /// out a borrow per entry; [`scope`](Self::scope) is where the borrow is minted, and it is the one
  /// member that names the write face's own lifetime-carrying seat.
  type Batch;

  /// Open a batch on the slot `S` names, at the POSTURE `S` declares.
  ///
  /// # The slot arrives as a TYPE, and that is what keeps the two halves in step
  ///
  /// Opening a corpus takes two facts a declaration owns — its NAME and whether it keeps the
  /// original value beside what it indexed ([`FulltextRoad::STORED`]) — and passing both by hand is
  /// two chances to pass the wrong one. It matters beyond tidiness here: a batch is the first thing
  /// that touches a corpus in a deployment whose initialization walk has not run, so a batch opened
  /// at the wrong posture CREATES the index at that posture, and the walk then refuses the boot after
  /// it. Naming the slot type makes both facts one fact.
  ///
  /// # Errors
  ///
  /// This engine's own — a lock another writer holds, a slot that will not open, a posture that
  /// disagrees with one this corpus was already created under, a lease refused.
  fn open<S: FulltextRoad>(
    &self,
    connection: &Self::Connection,
  ) -> Result<Self::Batch, Self::Error>;

  /// The per-call lease a held batch lends out — what
  /// [`upsert`](AsyncFulltextWrite::upsert)'s [`Connected`](crate::Connected) carries.
  ///
  /// An ASSOCIATED function rather than a method, because it borrows the batch and nothing else: an
  /// engine that also borrowed `self` here would put its own lifetime into a lease that outlives the
  /// call, for a handle that holds nothing but a slot name.
  fn scope(batch: &mut Self::Batch) -> Self::WriteContext<'_>;

  /// Build ONE entry for this engine's slot: the identity a keyed replace deletes by, the address a
  /// hit is answered with, and the text a declared road segmented.
  ///
  /// The SEGMENTS arrive as the [`BoxWriter`](crate::BoxWriter) a
  /// [`FulltextRoad`] filled, because how many of them there are is the DECLARATION's word — an
  /// identity or a `join` road pushes exactly one, a `multi` road pushes one per value — and what an
  /// engine can hold is the ENGINE's. An engine that stores one value per lane refuses a segmented
  /// entry by name rather than flattening it, because flattening lets a phrase match across a
  /// boundary the declaration wrote to stop it, and nobody is told.
  ///
  /// # Errors
  ///
  /// This engine's own, where the segmentation, the identity or the address is one it will not take.
  fn entry<I, K>(
    &self,
    identity: &I,
    address: &K,
    segments: &crate::BoxWriter,
  ) -> Result<Self::Doc, Self::Error>
  where
    I: crate::Field,
    K: crate::Field;

  /// Make everything queued into `batch` DURABLE AND VISIBLE, consuming the lease.
  ///
  /// # Errors
  ///
  /// This engine's own — a commit that failed, or a visibility step that did.
  fn publish(&self, connection: &Self::Connection, batch: Self::Batch) -> Result<(), Self::Error>;

  /// Throw `batch` away, leaving the slot as it was at the last [`publish`](Self::publish).
  ///
  /// It ANSWERS NOTHING, and that is the contract rather than an omission: a discard runs on the
  /// path where something has already failed, and a caller that has a refusal to report cannot do
  /// anything with a second one. An engine that cannot unwind leaves the batch dropped, which is
  /// what a lease with no rollback already means.
  fn discard(&self, connection: &Self::Connection, batch: Self::Batch);
}

/// **WHAT A SUBSCRIBING DECLARATION'S BODY REFUSES WITH** — one error over the three seams a landing
/// crosses.
///
/// A subscriber's `accept` can be refused by a declared ROAD's own converter, by the ENGINE building
/// an entry it will not take, and by the engine opening or publishing a batch. Those are three
/// unrelated types from three seams, and an expansion cannot name a sum over them: two of the three
/// are associated-type projections whose concrete identity is decided by a `resource = "…"` path in
/// somebody else's crate.
///
/// So the refusals are BOXED, and this type is the box — a type rather than the bare
/// [`BoxedError`](crate::BoxedError) alias, because the launch floor bounds a node's error
/// `Error + Send + Sync + 'static` and `Box<dyn Error + …>` famously implements none of `Error`.
/// One newtype answers the bound, and the boxed refusal stays reachable as its
/// [`source`](core::error::Error::source).
///
/// # No blanket `From`, and the `?`s that would have used one are spelled `map_err`
///
/// `impl<E> From<E> for Self` collides with core's reflexive `From<T> for T`, so the conversion is a
/// named constructor and the emitted body calls it at every fallible step. That is the honest
/// arrangement in any case: the three seams are three different failures, and a reader of the
/// expansion can see which one each `map_err` is absorbing.
#[derive(Debug)]
pub struct IndexRefusal(crate::BoxedError);

impl IndexRefusal {
  /// Box `refusal`.
  ///
  /// It takes `Into<BoxedError>` rather than `Error + Send + Sync + 'static` so that BOTH shapes a
  /// [`FulltextRoad::Error`] takes are admitted: an infallible road's
  /// [`Infallible`](core::convert::Infallible), which is an error, and a declared `try_from` road's
  /// already-boxed refusal, which is not.
  #[must_use]
  pub fn of(refusal: impl Into<crate::BoxedError>) -> Self {
    Self(refusal.into())
  }

  /// The refusal this one is carrying.
  #[must_use]
  pub fn refusal(&self) -> &(dyn core::error::Error + Send + Sync + 'static) {
    &*self.0
  }
}

impl core::fmt::Display for IndexRefusal {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    write!(f, "a derived index refused a delivery: {}", self.0)
  }
}

impl core::error::Error for IndexRefusal {
  fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
    Some(&*self.0)
  }
}

#[cfg(test)]
mod tests;