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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
//! THE EIGHT VERB FACES — each engine family's verbs split by DIRECTION and by MODE, so a bound asks
//! for the half it spends.
//!
//! An engine trait carrying every verb its family has is a bound that asks for all of them: a
//! retrieve that only searches demands a write it never calls, and an engine that only READS — a
//! snapshot, a replica, a served index — cannot be spelled at all. These eight traits are those
//! seams split along the two axes their own members already differ on.
//!
//! **WHICH DIRECTION.** The read verbs take a [`ReadContext`](VectorRead::ReadContext) and the write
//! verb takes a [`WriteContext`](VectorWrite::WriteContext); the lease was already two members, and
//! the faces are that division carried up to where a bound can see it. So a walk that emits a query
//! binds `Read`, a drainer binds `Write`, and write-exclusivity has a face of its own to hang from
//! when it arrives.
//!
//! **WHICH MODE.** `Async<face>` returns the future today's seam returns; the bare name is the SAME
//! signature with the wrapper off. Implementing a blocking face is therefore a STRUCTURAL claim that
//! the body is synchronous — the signature is the witness, and there is nothing left for an author to
//! be wrong about. That is the dual-mode law's own reason for refusing a defaulted `const` in this
//! seat, and [`BlobEngine`](crate::BlobEngine) / [`AsyncBlobEngine`](crate::AsyncBlobEngine) is the
//! same pair one family over.
//!
//! # A face declares THE SEATS ITS OWN VERBS SPEND, and nothing else
//!
//! Every face names its family's engine trait as a SUPERTRAIT, so `Self::Connection`,
//! `Self::Address`, `Self::Score`, `Self::Element`, `Self::SearchOptions` and `Self::Error` all
//! project through it and none is restated here. Two copies of one seat would be two types that must
//! agree and are free to stop agreeing.
//!
//! THE LEASE IS THE EXCEPTION, and it is an exception because it has exactly one spender. Only the
//! read verbs take a read scope and only the write verb takes a write one, so each lives on the face
//! that takes it — which buys a second thing the shared seat could not have: the two MODES may lease
//! differently, an async transaction ticket being a different type from a blocking searcher's.
//! `Doc` goes the same way and for the same test: only `upsert` spends it, and a reader is not shown
//! a payload.
//!
//! **BOTH HALVES HAVE LANDED.** [`VectorEngine`] and [`FulltextEngine`] are pure bases —
//! vocabulary and the address lifecycle, no verb and no GAT — so all eight faces below declare
//! their own leases and an engine wearing one inherits no verb it does not answer.
//!
//! # THE ONE COST OF SPLITTING BY MODE: `E0034` at a TWO-FACED type
//!
//! A face and its async twin declare the SAME method name, so a type wearing both — the absent
//! engine `()` wears all eight, and any engine offering a blocking read beside an async one wears
//! two — has two applicable `knn` in scope the moment both traits are imported. Method-call syntax
//! is ambiguous there, and the compiler says so.
//!
//! MEASURED rather than predicted: `().knn(…)` in a scope importing both [`VectorRead`] and
//! [`AsyncVectorRead`] is
//!
//! ```text
//! error[E0034]: multiple applicable items in scope
//! note: candidate #1 is defined in an impl of the trait `AsyncVectorRead` for the type `()`
//! note: candidate #2 is defined in an impl of the trait `VectorRead` for the type `()`
//! ```
//!
//! It is a NUISANCE rather than a defect, and the whole of the fix is spelling which face is meant:
//! `VectorRead::knn(&engine, …)`, or `<E as AsyncVectorRead>::knn(…)` where the receiver's type
//! needs saying too. `faces/tests.rs` writes every call that way already — that file drives both
//! modes of all four verbs on one type, so it is where the ambiguity is densest, and the qualified
//! form reads better there anyway: the trait NAMED at the call is the thing those tests are about.
//!
//! It also cannot be designed away at this layer. One name per mode (`knn` beside `knn_async`) is
//! the alternative, and it would put the mode into every emitted call site and every bound's
//! vocabulary to spare an import collision only a two-faced type ever meets — which is the dual-mode
//! law's own trade, made once, one family over.
//!
//! # The lifecycle that is NOT here
//!
//! [`VectorEngine::buffer`], [`finalize`](VectorEngine::finalize) and
//! [`open`](VectorEngine::open) stay on the base — and [`FulltextEngine`]'s three do too — and that
//! is not an oversight. An address vocabulary is a fact about the ENGINE rather than about a
//! direction: the write phase seals one and the read phase spends it, so a face-shaped home for
//! either half would put one end of a correspondence behind a bound the other end does not carry.
//! Every walk over it is generic in the ENGINE alone, which is what that placement is for.

use core::{
  future::{Future, ready},
  num::NonZeroUsize,
};

use super::{Connected, FulltextEngine, FulltextSubset, Hits, VectorColumn, VectorEngine};

/// The vector family's READ half, answered SYNCHRONOUSLY — [`knn`](Self::knn) and
/// [`get`](Self::get), and the lease both of them spend.
///
/// What implementing it CLAIMS is that both bodies run to their answer on the calling thread: no
/// await, no runtime, no pool. An engine that cannot say that implements [`AsyncVectorRead`]
/// instead, and a caller's bound is what picks between them — where a `block_on` inside a body would
/// be the fiction the dual-mode law exists to refuse.
///
/// THIS FACE HOLDS THE READ CONTRACT for the family, and [`AsyncVectorRead`] states it by pointing
/// here: the two differ in synchronicity and in nothing else, so the words about what a column is,
/// what `k` promises and what the knobs are exist once.
///
/// # THE PARAMETER LAW — where a fact about one call lives, and why there are exactly three seats
///
/// **Positional is UNIVERSAL.** A parameter earns a seat in the signature when every engine of every
/// family takes one: the column a knn runs over, the coordinates it measures, and `k` — how many
/// neighbours. There is no vector engine that does not take all three, so none of them is a knob and
/// none of them belongs in a type a backend picked.
///
/// **[`SearchOptions`](VectorEngine::SearchOptions) is the BACKEND's own.** A probe count, an `ef`, a
/// metric override — the axes one engine has and the next does not. `()` where a backend has none,
/// which is what makes the seat honest. It sits on the BASE rather than here, because a wire face
/// names it without spending a verb.
///
/// **[`ReadContext`](Self::ReadContext) is the LEASE.** A snapshot, a transaction handle, a
/// searcher's ticket — the thing whoever holds the connection assembles, and the thing a request
/// arriving over a wire cannot carry.
///
/// `k` sat in the lease until the seam grew it a seat, and what that cost was measured: the door's
/// own limit could shrink the answer but never widen it, because the fetch cap lived in a
/// backend-chosen scope the door could not see — a caller asking for 50 against a scope assembled by
/// [`Default`] silently got that scope's number. One universal fact, two seats, two owners. It is one
/// seat now, and the silent narrowing is unrepresentable rather than merely fixed.
///
/// # A DEFAULT `k` is the door's business and never the seam's
///
/// [`knn`](Self::knn) takes a [`NonZeroUsize`] and has no opinion about what a caller who named no
/// number meant. *How many hits when the request did not say* is a wire-layer policy — it belongs
/// where the request is parsed, beside every other absent-field default — and an engine inventing one
/// is an engine answering a question it was never asked. The type is `NonZeroUsize` rather than
/// `usize` for the other half of the same posture: zero is not a search with an empty answer, it is a
/// question the seam declines to represent, and a caller holding a `usize` short-circuits it above
/// the seam ([`NonZeroUsize::new`] returning [`None`] is that fork, spelled once). Backends assert on
/// it — tantivy's `TopDocs::with_limit` does — and an assertion inside an engine is a panic no caller
/// can catch.
#[diagnostic::on_unimplemented(
  message = "`{Self}` has no BLOCKING vector read face",
  label = "this engine answers through a future, and a sync body cannot spend one",
  note = "two roads: implement `VectorRead` for an engine whose knn and get are natively blocking \
          (an embedded index, a memory-mapped table), or move the caller onto the async face \
          `AsyncVectorRead` — wrapping an async read in a block-on here would be the fiction the \
          dual-mode law exists to refuse"
)]
pub trait VectorRead: VectorEngine {
  /// The read-path LEASE (may borrow) — a snapshot, a transaction handle, a reader's ticket. Reads
  /// resolve against committed state; it must not enable writes.
  ///
  /// `k` is NOT here and no longer may be: it is universal, so it sits in the signature — see the
  /// parameter law on the trait. What is left is the half a request cannot carry, which is what a
  /// GAT is for.
  ///
  /// ON THE FACE rather than on the base, so [`AsyncVectorRead`] may lease differently: an engine
  /// wearing both modes hands its blocking searcher one ticket and its async transaction another,
  /// and one shared seat would have made those two the same type by construction.
  type ReadContext<'a>;

  /// Nearest neighbours of `query`, as scored hits — then read each address back and hydrate it from
  /// the system of record.
  ///
  /// HOW MANY is `k`, and it is THIS CALL's. HOW is split: the probe count, the metric and a
  /// prefilter over [`VectorRecord::Filter`] are the backend's own, reached through
  /// [`SearchOptions`](VectorEngine::SearchOptions) when a request named them and through the
  /// [`ReadContext`](Self::ReadContext) when only the connection's holder can, the way an
  /// async-graphql resolver reads its context — which is what lets a search verb exist here without
  /// a query language the neutral seam would first have to define.
  ///
  /// `query` is a bare slice of this handle's own element: the carrier SPELLED, not projected
  /// through a record. Its width is unchecked at this seam and checked where an embedding is BUILT —
  /// a caller holding an `Embedding<f32, 768>` passes [`coordinates()`](crate::Embedding), and a
  /// value of that type has 768 of them or was never constructed.
  ///
  /// `column` is the ELECTION — WHICH of this slot's embeddings answers. A declaration may elect
  /// several and they live as several vector columns of one slot, so the subject that used to be
  /// implied is now said; see [`VectorColumn`]. A slot holding exactly one column takes the
  /// parameter too, which is what keeps the seam's shape a fact about the FACE rather than about
  /// whichever declaration reached it first.
  ///
  /// `k` is HOW MANY, positional between the query and the knobs — the CEILING on the hits this
  /// call fetches, spent by the engine's own collector. It is universal (see the parameter law on
  /// the trait), so it is neither a knob nor a scope member, and the engine spends the number it is
  /// HANDED rather than one it read off a type somebody else assembled. A shorter answer is legal
  /// and ordinary — a corpus with fewer matches, a floor the layer above applies — but a LONGER one
  /// is not: `k` is what the caller asked for and the ceiling is the promise.
  ///
  /// **`k` IS A CEILING, NOT AN ALLOCATION HINT — an engine must never preallocate by `k`.** That is
  /// this seam's law and not a suggestion, because the number is honestly unbounded: the emitted
  /// tier-B door asks with [`NonZeroUsize::MAX`], meaning *as many as exist*, and its own fill loop's
  /// filter is what decides how many of them fill a page. What a huge `k` MEANS is each engine's own
  /// business in its own storage, and the shipped tantivy full-text engine is the reference
  /// discipline: it clamps to `min(k, num_docs)`, which is answer-preserving by construction — a
  /// search cannot return more hits than there are live documents, so the clamp can only remove
  /// capacity the collector could never have filled. An engine that sizes a buffer by `k` instead
  /// aborts on the ask rather than answering it.
  ///
  /// `options` is the PER-QUERY half of *how* — [`SearchOptions`](VectorEngine::SearchOptions), the
  /// knobs a REQUEST named. [`None`] means this call names none and the engine's own defaults stand.
  ///
  /// BORROWED, and behind an [`Option`] rather than owned: the knobs live in an emitted package's
  /// `options` row, which is itself an [`Option`], so a door hands down what it has without cloning
  /// a request's own value into every leg of a fan.
  ///
  /// # Errors
  ///
  /// This backend's own refusal — an unreadable scope, a column it does not hold, a failed search.
  ///
  /// [`VectorRecord::Filter`]: crate::VectorRecord::Filter
  fn knn(
    &self,
    ctx: Connected<'_, Self::Connection, Self::ReadContext<'_>>,
    column: VectorColumn,
    query: &[Self::Element],
    k: NonZeroUsize,
    options: Option<&Self::SearchOptions>,
  ) -> Result<Hits<Self::Address, Self::Score>, Self::Error>;

  /// THE BY-KEY READ: this entity's OWN vectors in `column`, at `address`.
  ///
  /// The read the similar-by-example door is built on — *fetch own set → query with it → exclude
  /// self* — and the reason the seam grew rather than the emission gathering an upstream row: a
  /// vector an engine holds is the engine's to hand back, and re-projecting the record through
  /// [`VectorRecord::vectors`](crate::VectorRecord::vectors) would put a store hop at a tier that
  /// takes none.
  ///
  /// `address` is a key's own address, sealed by [`VectorEngine::finalize`] out of the buffer the
  /// key reported its columns into — the same bytes [`knn`](Self::knn) hands a hit BACK under,
  /// spelled in the other direction. So the two halves of the door speak one vocabulary, and an
  /// engine that can answer a hit can answer this.
  ///
  /// `column` is the ELECTION, exactly as [`knn`](Self::knn)'s is: a slot may hold several vector
  /// columns of one field, and *which of this entity's embeddings* is as real a question on the read
  /// as it is on the search.
  ///
  /// # `Vec<Vec<Element>>` — a SET, at a grain no declaration can yet state here
  ///
  /// One entity may hold SEVERAL vectors in one column (a video's frames, a document's passages),
  /// and the set is the shape that serves both that case and the ordinary one. What the DECLARATION
  /// can elect decides how many the emission then admits: an election of a single
  /// [`Embedding`](crate::Embedding) is answered by exactly one, and an engine handing back more is
  /// a drift the emitted door names — the same restraint [`ColumnReader::finish`]
  /// takes about an address holding more columns than the key reads.
  ///
  /// EMPTY is a legal answer and means *this address holds nothing in this column* — the entity was
  /// never indexed here, or its entry has gone. It is not an error at the SEAM, an engine having
  /// nothing to say about a key it does not hold; what to do about it belongs to the caller, and
  /// the emitted door names it rather than answering with a page that cannot be told apart from
  /// *nothing was near enough*.
  ///
  /// # Errors
  ///
  /// This backend's own refusal — an unreadable address, a column it does not hold, a failed read.
  ///
  /// [`ColumnReader::finish`]: crate::ColumnReader::finish
  fn get(
    &self,
    ctx: Connected<'_, Self::Connection, Self::ReadContext<'_>>,
    column: VectorColumn,
    address: &Self::Address,
  ) -> Result<Vec<Vec<Self::Element>>, Self::Error>;
}

/// The vector family's READ half, answered through a FUTURE — [`VectorRead`]'s twin, at the same
/// signatures with the wrapper on.
///
/// The two are SIBLINGS and neither is a supertrait of the other, per
/// [`BlobEngine`](crate::BlobEngine)'s ratified argument: a supertrait either way taxes one kind of
/// engine with a face nobody asked it for. An engine that can answer both writes both, and the
/// reference discipline is the shipped tantivy face — the blocking half holds the body and the async
/// half resolves it immediately.
///
/// The future is `+ Send` because a multi-threaded runtime is what spends it.
///
/// Every word about what the parameters mean is [`VectorRead`]'s, and the parameter law and the
/// posture on a default `k` are stated there.
pub trait AsyncVectorRead: VectorEngine {
  /// The read-path LEASE — [`VectorRead::ReadContext`]'s twin, and its OWN type.
  ///
  /// Declared here rather than inherited, so the two modes may lease differently: the ticket an
  /// async transaction hands out is not the blocking searcher's, and an engine wearing both faces
  /// says so by writing two members.
  type ReadContext<'a>;

  /// Nearest neighbours of `query` in `column`, as scored hits — [`VectorRead::knn`]'s contract
  /// verbatim.
  fn knn(
    &self,
    ctx: Connected<'_, Self::Connection, Self::ReadContext<'_>>,
    column: VectorColumn,
    query: &[Self::Element],
    k: NonZeroUsize,
    options: Option<&Self::SearchOptions>,
  ) -> impl Future<Output = Result<Hits<Self::Address, Self::Score>, Self::Error>> + Send;

  /// This entity's OWN vectors in `column`, at `address` — [`VectorRead::get`]'s contract verbatim.
  fn get(
    &self,
    ctx: Connected<'_, Self::Connection, Self::ReadContext<'_>>,
    column: VectorColumn,
    address: &Self::Address,
  ) -> impl Future<Output = Result<Vec<Vec<Self::Element>>, Self::Error>> + Send;
}

/// The vector family's WRITE half, answered SYNCHRONOUSLY — the keyed replace, and the two seats
/// only a write spends.
///
/// ONE VERB, and that is the honest count rather than a stub: a derived index is written by a keyed
/// replace on the source's own identity, last-write-wins, and there is no second write act at this
/// layer. What the face buys is the direction — a drainer binds this and never inherits a search,
/// and an engine that only writes is spellable.
///
/// THIS FACE HOLDS THE WRITE CONTRACT for the family, and [`AsyncVectorWrite`] states it by pointing
/// here.
#[diagnostic::on_unimplemented(
  message = "`{Self}` has no BLOCKING vector write face",
  label = "this engine queues through a future, and a sync body cannot spend one",
  note = "two roads: implement `VectorWrite` for an engine whose upsert is natively blocking (an \
          in-memory queue, an embedded index), or move the caller onto the async face \
          `AsyncVectorWrite` — wrapping an async write in a block-on here would be the fiction the \
          dual-mode law exists to refuse"
)]
pub trait VectorWrite: VectorEngine {
  /// The write-path scope (may borrow) — a transaction or batch lease whose commit belongs to the
  /// caller.
  ///
  /// ON THE FACE for [`VectorRead::ReadContext`]'s reason, and with the same dividend across the two
  /// modes.
  type WriteContext<'a>;
  /// The engine's OWN entry builder — [`FulltextWrite::Doc`](crate::FulltextWrite::Doc)'s twin,
  /// and the same division: the emission flattens the record into it, and the seam carries the
  /// finished entry.
  ///
  /// ON THE WRITE FACE because [`upsert`](Self::upsert) is its only spender — a reader is never
  /// shown a payload, and a read face that inherited this would be asking an engine to name a type
  /// no read of it ever mentions.
  type Doc;

  /// Index one entry — a keyed replace at the identity the [`Doc`](Self::Doc) carries.
  ///
  /// # Errors
  ///
  /// This backend's own refusal — a failed write, a scope that cannot commit, an entry this storage
  /// will not take.
  fn upsert(
    &self,
    ctx: Connected<'_, Self::Connection, Self::WriteContext<'_>>,
    doc: Self::Doc,
  ) -> Result<(), Self::Error>;
}

/// The vector family's WRITE half, answered through a FUTURE — [`VectorWrite`]'s twin, at the same
/// signature with the wrapper on.
///
/// Siblings rather than one bridging the other, for [`AsyncVectorRead`]'s stated reason.
pub trait AsyncVectorWrite: VectorEngine {
  /// The write-path scope — [`VectorWrite::WriteContext`]'s twin, and its OWN type.
  type WriteContext<'a>;
  /// The engine's OWN entry builder — [`VectorWrite::Doc`]'s twin, and its OWN type: an async write
  /// may take a different entry from a blocking one (a queued row against an owned batch), and one
  /// shared seat would have ruled that out.
  type Doc;

  /// Index one entry — a keyed replace at the identity the [`Doc`](Self::Doc) carries.
  fn upsert(
    &self,
    ctx: Connected<'_, Self::Connection, Self::WriteContext<'_>>,
    doc: Self::Doc,
  ) -> impl Future<Output = Result<(), Self::Error>> + Send;
}

/// The full-text family's READ half, answered SYNCHRONOUSLY — [`search`](Self::search), and the
/// lease it spends.
///
/// [`VectorRead`]'s twin one family over, and one verb where that one has two: a full-text index
/// answering *what did you store for this key* is the `stored` marker's own question, whose grammar
/// has not arrived, so this face carries the search and does not grow half of a by-key read to look
/// symmetrical.
///
/// THIS FACE HOLDS THE READ CONTRACT for the family, and [`AsyncFulltextRead`] states it by pointing
/// here: the two differ in synchronicity and in nothing else, so the words about what a subset is,
/// what `k` promises and what the knobs are exist once.
///
/// # THE PARAMETER LAW — three seats, and what earns each
///
/// [`VectorRead`]'s own law, spelled on this family's parameters: **positional is UNIVERSAL** (the
/// subset a query is scoped to, the query text, and `k` — how many hits),
/// **[`SearchOptions`](FulltextEngine::SearchOptions) is the BACKEND's own** (an analyzer, a boost,
/// a fuzziness, a conjunction default), and **[`ReadContext`](Self::ReadContext) is the LEASE** (a
/// committed snapshot, a reader's ticket).
///
/// `k` sat in the lease until this seam grew it a seat, and the measurement that moved it is one
/// story on both faces: the caller's limit could shrink an answer but never widen it, because the
/// fetch cap lived in a scope the backend chose and the caller could not see. ONE universal fact,
/// ONE seat.
///
/// # A DEFAULT hit count is the door's business and never the seam's
///
/// [`search`](Self::search) takes a [`NonZeroUsize`] and holds no opinion about what a caller who
/// named no number meant — *how many when the request did not say* belongs where a request is
/// parsed, beside every other absent-field default. The nonzero type is the same posture from the
/// other end: zero is a question this seam declines to represent, a caller holding a `usize`
/// resolves it above the seam, and backends assert on it (tantivy's `TopDocs::with_limit` does)
/// where an assertion inside an engine is a panic no caller can catch.
#[diagnostic::on_unimplemented(
  message = "`{Self}` has no BLOCKING full-text read face",
  label = "this engine answers through a future, and a sync body cannot spend one",
  note = "two roads: implement `FulltextRead` for an engine whose search is natively blocking (an \
          embedded index directory, an in-process FTS table), or move the caller onto the async \
          face `AsyncFulltextRead` — wrapping an async search in a block-on here would be the \
          fiction the dual-mode law exists to refuse"
)]
pub trait FulltextRead: FulltextEngine {
  /// The read-path LEASE (may borrow) — a committed snapshot, a reader's ticket. Reads resolve
  /// against committed state; it must not enable writes.
  ///
  /// HOW MANY is NOT here and no longer may be: `k` is universal, so it sits in the signature — see
  /// the parameter law on the trait. An analyzer or a boost is the backend's own and reaches the
  /// call through [`SearchOptions`](FulltextEngine::SearchOptions) when a request named it.
  ///
  /// ON THE FACE rather than on the base, so [`AsyncFulltextRead`] may lease differently: an engine
  /// wearing both modes hands its blocking searcher one ticket and its async transaction another,
  /// and one shared seat would have made those two the same type by construction.
  type ReadContext<'a>;

  /// Matches for a query string within `subset`, as scored hits — then read each address back into
  /// a key and hydrate it from the system of record.
  ///
  /// HOW MANY is `k`, and it is THIS CALL's — the ceiling on the hits this search collects, spent by
  /// the engine's own collector, and a fact of the question rather than of whoever assembled the
  /// lease. HOW is the backend's: an analyzer choice and a boost reach it through
  /// [`SearchOptions`](FulltextEngine::SearchOptions) when a request named them and through the
  /// [`ReadContext`](Self::ReadContext) when only the connection's holder can, the way an
  /// async-graphql resolver reads its context — which is what lets a search verb exist here without
  /// a query language the neutral seam would first have to define. The QUERY is a `&str` for the
  /// same reason from the other side: every full-text engine already has a query grammar, and
  /// naming one here would elect it for the engines that have not arrived.
  ///
  /// # WHICH COLUMNS is a parameter, and it is the one thing a query grammar must not be trusted
  /// with
  ///
  /// A field-scoped query is spellable in most grammars — `title:fox` — and scoping a search by
  /// writing one is exactly the magic string this seam refuses everywhere else: the field name is
  /// unchecked, the escaping is the grammar's, and a caller composing one from a request is
  /// composing an injection. [`FulltextSubset`] carries the scope BESIDE the text, where the engine
  /// applies it to a parsed query rather than parsing it out of one, and where the framework's own
  /// `<Tier>Column` vocabulary can stand in front of it.
  ///
  /// It is [`All`](FulltextSubset::All) that makes this a widening rather than a break in meaning:
  /// the whole-subject call this verb has always answered is that word, passed, and an engine's body
  /// for it is the body it already had.
  ///
  /// The hit's halves are the engine's OWN, both of them:
  /// [`Address`](FulltextEngine::Address) is the vocabulary it stored, and
  /// [`Score`](FulltextEngine::Score) is the currency it ranked in. Neither projects anything off a
  /// record, because a score belongs to the ENGINE and an address is what the engine was handed.
  ///
  /// `k` is HOW MANY, positional between the query and the knobs, exactly as [`VectorRead::knn`]'s
  /// is. A shorter answer is legal and ordinary — a corpus holding fewer matches, a floor applied
  /// above — but a longer one is not.
  ///
  /// **`k` IS A CEILING, NOT AN ALLOCATION HINT — an engine must never preallocate by `k`.** That is
  /// this seam's law and not a suggestion, because the number is honestly unbounded: the emitted
  /// tier-B door asks with [`NonZeroUsize::MAX`], meaning *as many as exist*, and its own fill loop's
  /// filter is what decides how many of them fill a page. What a huge `k` MEANS is each engine's own
  /// business in its own storage, and the shipped tantivy full-text engine is the reference
  /// discipline: it clamps to `min(k, num_docs)`, which is answer-preserving by construction — a
  /// search cannot return more hits than there are live documents, so the clamp can only remove
  /// capacity the collector could never have filled. An engine that sizes a buffer by `k` instead
  /// aborts on the ask rather than answering it: tantivy's own `TopNComputer` allocates
  /// `k.max(1) * 2` up front, which is exactly the abort the clamp exists to prevent.
  ///
  /// `options` is the PER-QUERY half of *how* — [`SearchOptions`](FulltextEngine::SearchOptions),
  /// the knobs a REQUEST named, borrowed behind an [`Option`] for [`VectorRead::knn`]'s reason.
  /// [`None`] means this call names none and the engine's own defaults stand.
  ///
  /// # Errors
  ///
  /// This backend's own refusal — a malformed query, a column the slot does not hold, a subset
  /// naming nothing, a failed read.
  fn search(
    &self,
    ctx: Connected<'_, Self::Connection, Self::ReadContext<'_>>,
    subset: FulltextSubset<'_>,
    query: &str,
    k: NonZeroUsize,
    options: Option<&Self::SearchOptions>,
  ) -> Result<Hits<Self::Address, Self::Score>, Self::Error>;
}

/// The full-text family's READ half, answered through a FUTURE — [`FulltextRead`]'s twin, at the
/// same signature with the wrapper on.
///
/// Siblings rather than one bridging the other, for [`AsyncVectorRead`]'s stated reason.
///
/// Every word about what the parameters mean is [`FulltextRead`]'s, and the parameter law and the
/// posture on a default hit count are stated there.
pub trait AsyncFulltextRead: FulltextEngine {
  /// The read-path LEASE — [`FulltextRead::ReadContext`]'s twin, and its OWN type.
  ///
  /// Declared here rather than inherited, so the two modes may lease differently: the ticket an
  /// async transaction hands out is not the blocking searcher's, and an engine wearing both faces
  /// says so by writing two members.
  type ReadContext<'a>;

  /// Matches for `query` within `subset`, as scored hits — [`FulltextRead::search`]'s contract
  /// verbatim.
  fn search(
    &self,
    ctx: Connected<'_, Self::Connection, Self::ReadContext<'_>>,
    subset: FulltextSubset<'_>,
    query: &str,
    k: NonZeroUsize,
    options: Option<&Self::SearchOptions>,
  ) -> impl Future<Output = Result<Hits<Self::Address, Self::Score>, Self::Error>> + Send;
}

/// The full-text family's WRITE half, answered SYNCHRONOUSLY — the keyed replace, and the two seats
/// only a write spends.
///
/// The write verb is the one the two families SHARE, and the sharing is the point: a derived index —
/// vector or full-text — is written by a keyed replace on the source's own identity, and that is ONE
/// protocol. So the two write faces differ in the engine they are bound to and in nothing else.
///
/// THIS FACE HOLDS THE WRITE CONTRACT for the family, and [`AsyncFulltextWrite`] states it by
/// pointing here.
#[diagnostic::on_unimplemented(
  message = "`{Self}` has no BLOCKING full-text write face",
  label = "this engine queues through a future, and a sync body cannot spend one",
  note = "two roads: implement `FulltextWrite` for an engine whose upsert is natively blocking (an \
          index writer's in-memory queue), or move the caller onto the async face \
          `AsyncFulltextWrite` — wrapping an async write in a block-on here would be the fiction \
          the dual-mode law exists to refuse"
)]
pub trait FulltextWrite: FulltextEngine {
  /// The write-path scope (may borrow) — a commit or segment lease whose commit belongs to the
  /// caller.
  ///
  /// ON THE FACE for [`FulltextRead::ReadContext`]'s reason, and with the same dividend across the
  /// two modes.
  type WriteContext<'a>;
  /// The engine's OWN entry builder — one entry under construction, and
  /// [`VectorWrite::Doc`]'s twin.
  ///
  /// Bound by nothing, and reached by nothing in this crate: the emission builds it through the
  /// engine's own inherent API, which is where a backend states what an entry of its needs. That is
  /// the whole of *the emission owns the typing* on the write side — the record's fields are
  /// flattened by the code that can see them, and the seam carries the finished entry.
  ///
  /// The multi-field, per-field-option shape (`docs/2026-07-28-derive-design-notes.md`'s `DocSink`)
  /// is what this member becomes the interface OF when it lands. It is not designed here: what a
  /// document is remains the engine's, and naming a field vocabulary at this seam would elect one
  /// for the engines that have not arrived.
  ///
  /// ON THE WRITE FACE because [`upsert`](Self::upsert) is its only spender — a reader is never
  /// shown a payload, and a read face that inherited this would be asking an engine to name a type
  /// no read of it ever mentions.
  type Doc;

  /// Index one entry — a keyed replace at the identity the [`Doc`](Self::Doc) carries.
  ///
  /// The entry arrives BUILT. What identifies it, what it is addressed by and what it holds are all
  /// decided by the emission that filled the builder in; this call is the durable half, and it reads
  /// nothing about the record it came from because there is nothing about a record here to read.
  ///
  /// # Errors
  ///
  /// This backend's own refusal — a failed write, a scope that cannot commit, an entry this storage
  /// will not take.
  fn upsert(
    &self,
    ctx: Connected<'_, Self::Connection, Self::WriteContext<'_>>,
    doc: Self::Doc,
  ) -> Result<(), Self::Error>;
}

/// The full-text family's WRITE half, answered through a FUTURE — [`FulltextWrite`]'s twin, at the
/// same signature with the wrapper on.
///
/// Siblings rather than one bridging the other, for [`AsyncVectorRead`]'s stated reason.
pub trait AsyncFulltextWrite: FulltextEngine {
  /// The write-path scope — [`FulltextWrite::WriteContext`]'s twin, and its OWN type.
  type WriteContext<'a>;
  /// The engine's OWN entry builder — [`FulltextWrite::Doc`]'s twin, and its OWN type: an async
  /// write may take a different entry from a blocking one (a queued row against an owned batch), and
  /// one shared seat would have ruled that out.
  type Doc;

  /// Index one entry — a keyed replace at the identity the [`Doc`](Self::Doc) carries.
  fn upsert(
    &self,
    ctx: Connected<'_, Self::Connection, Self::WriteContext<'_>>,
    doc: Self::Doc,
  ) -> impl Future<Output = Result<(), Self::Error>> + Send;
}

/// The unused vector face's READ half — every answer EMPTY, which is what a store that never indexed
/// anything honestly holds.
///
/// The bodies are [`VectorEngine for ()`](VectorEngine)'s own, with the `ready` wrapper gone: a face
/// that computes nothing is synchronous in the strongest sense a signature can state.
///
/// The context parameter is spelled as the GAT PROJECTION inside the wrapper —
/// `Connected<'_, Self::Connection, Self::ReadContext<'_>>` — and not as the resolved
/// `Connected<'_, (), ()>`, which is the spelling a real borrowing impl writes and the one the
/// async twin below is obliged to write.
impl VectorRead for () {
  type ReadContext<'a> = ();

  #[inline(always)]
  fn knn(
    &self,
    _ctx: Connected<'_, Self::Connection, Self::ReadContext<'_>>,
    _column: VectorColumn,
    _query: &[Self::Element],
    _k: NonZeroUsize,
    _options: Option<&Self::SearchOptions>,
  ) -> Result<Hits<Self::Address, Self::Score>, Self::Error> {
    Ok(Vec::new())
  }

  #[inline(always)]
  fn get(
    &self,
    _ctx: Connected<'_, Self::Connection, Self::ReadContext<'_>>,
    _column: VectorColumn,
    _address: &Self::Address,
  ) -> Result<Vec<Vec<Self::Element>>, Self::Error> {
    Ok(Vec::new())
  }
}

/// The unused vector face's ASYNCHRONOUS read half — the blocking bodies above, resolved
/// immediately.
///
/// It DELEGATES rather than answering twice, which is the reference discipline the shipped stores
/// already keep: there is one empty answer here and both faces name it, so the two cannot drift.
/// Written out rather than bridged by a blanket, per the dual-mode law — a blanket from one face to
/// the other would hand every blocking engine an async face and blind the bound that selects.
impl AsyncVectorRead for () {
  type ReadContext<'a> = ();

  #[inline(always)]
  fn knn(
    &self,
    ctx: Connected<'_, Self::Connection, Self::ReadContext<'_>>,
    column: VectorColumn,
    query: &[Self::Element],
    k: NonZeroUsize,
    options: Option<&Self::SearchOptions>,
  ) -> impl Future<Output = Result<Hits<Self::Address, Self::Score>, Self::Error>> + Send {
    ready(<Self as VectorRead>::knn(
      self, ctx, column, query, k, options,
    ))
  }

  #[inline(always)]
  fn get(
    &self,
    ctx: Connected<'_, Self::Connection, Self::ReadContext<'_>>,
    column: VectorColumn,
    address: &Self::Address,
  ) -> impl Future<Output = Result<Vec<Vec<Self::Element>>, Self::Error>> + Send {
    ready(<Self as VectorRead>::get(self, ctx, column, address))
  }
}

/// The unused vector face's WRITE half — an entry accepted and dropped, the honest act for a store
/// with nothing to index into.
impl VectorWrite for () {
  type WriteContext<'a> = ();
  type Doc = ();

  #[inline(always)]
  fn upsert(
    &self,
    _ctx: Connected<'_, Self::Connection, Self::WriteContext<'_>>,
    _doc: Self::Doc,
  ) -> Result<(), Self::Error> {
    Ok(())
  }
}

/// The unused vector face's ASYNCHRONOUS write half — the blocking body above, resolved immediately.
impl AsyncVectorWrite for () {
  type WriteContext<'a> = ();
  type Doc = ();

  #[inline(always)]
  fn upsert(
    &self,
    ctx: Connected<'_, Self::Connection, Self::WriteContext<'_>>,
    doc: Self::Doc,
  ) -> impl Future<Output = Result<(), Self::Error>> + Send {
    ready(<Self as VectorWrite>::upsert(self, ctx, doc))
  }
}

/// The unused full-text face's READ half — EMPTY for every subset, which is not this impl ignoring
/// the scope: a store holding no columns matches no column, so
/// [`These`](FulltextSubset::These) and [`All`](FulltextSubset::All) have the same answer here, and
/// it could not refuse an unheld column even where refusing were right — its
/// [`Error`](FulltextEngine::Error) is [`NoColumns`](crate::NoColumns), whose one word is about a
/// column that was never landed. The face still cannot fail at this VERB, which is what the `Ok`
/// below says.
impl FulltextRead for () {
  type ReadContext<'a> = ();

  #[inline(always)]
  fn search(
    &self,
    _ctx: Connected<'_, Self::Connection, Self::ReadContext<'_>>,
    _subset: FulltextSubset<'_>,
    _query: &str,
    _k: NonZeroUsize,
    _options: Option<&Self::SearchOptions>,
  ) -> Result<Hits<Self::Address, Self::Score>, Self::Error> {
    Ok(Vec::new())
  }
}

/// The unused full-text face's ASYNCHRONOUS read half — the blocking body above, resolved
/// immediately.
impl AsyncFulltextRead for () {
  type ReadContext<'a> = ();

  #[inline(always)]
  fn search(
    &self,
    ctx: Connected<'_, Self::Connection, Self::ReadContext<'_>>,
    subset: FulltextSubset<'_>,
    query: &str,
    k: NonZeroUsize,
    options: Option<&Self::SearchOptions>,
  ) -> impl Future<Output = Result<Hits<Self::Address, Self::Score>, Self::Error>> + Send {
    ready(<Self as FulltextRead>::search(
      self, ctx, subset, query, k, options,
    ))
  }
}

/// The unused full-text face's WRITE half — an entry accepted and dropped.
impl FulltextWrite for () {
  type WriteContext<'a> = ();
  type Doc = ();

  #[inline(always)]
  fn upsert(
    &self,
    _ctx: Connected<'_, Self::Connection, Self::WriteContext<'_>>,
    _doc: Self::Doc,
  ) -> Result<(), Self::Error> {
    Ok(())
  }
}

/// The unused full-text face's ASYNCHRONOUS write half — the blocking body above, resolved
/// immediately.
impl AsyncFulltextWrite for () {
  type WriteContext<'a> = ();
  type Doc = ();

  #[inline(always)]
  fn upsert(
    &self,
    ctx: Connected<'_, Self::Connection, Self::WriteContext<'_>>,
    doc: Self::Doc,
  ) -> impl Future<Output = Result<(), Self::Error>> + Send {
    ready(<Self as FulltextWrite>::upsert(self, ctx, doc))
  }
}

#[cfg(test)]
mod tests;