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
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
//! The READ lane: what a query node's answering half actually calls, and the seam a third party
//! wraps it at.
//!
//! [`Serves`] is [`AsyncLands`](super::AsyncLands)' twin one arm over — *take this question, give me its
//! answer* — and the two are deliberately the same KIND of thing: a CAPABILITY, statically
//! monomorphised, implemented rather than assembled. Nothing about an engine, a slot, a connection
//! or a query grammar crosses it. What a question IS and what an answer IS are the two type
//! parameters, so the seam names a shape and never a backend, which is the same division
//! [`AsyncLands`](super::AsyncLands) states from the write side.
//!
//! # The widening r1 pre-authorised
//!
//! [`retrieve`](crate::retrieve)'s ruling on the emitted face wrote this trait's warrant before
//! there was a caller for it:
//!
//! > A trait minted OVER those methods, if the fused cross-index query ever needs one, is a pure
//! > widening.
//!
//! This is that trait, minted for the arm's answering half rather than for the fused query, and the
//! widening is pure in exactly the sense r1 named: `retrieve_keys` and `retrieve` are untouched,
//! the per-node face they present is unchanged, and nothing that reached an engine without a trait
//! now has to go through one. What is added is a VALUE somebody can wrap.
//!
//! # Why the framework ships a read lane where it ships no write lane
//!
//! [`AsyncLands`](super::AsyncLands)' note records that a generic `FulltextLane<E: FulltextEngine>` cannot be
//! written: `land` takes N items through ONE write scope, so it must reborrow
//! `E::WriteContext<'_>` per item, and a GAT projection over an unknown backend has no reborrow.
//!
//! A read has no such loop. [`SlotLane`] serves ONE question per call and hands the scope it was
//! given straight to the branded verb, so the reborrow that blocks the write side never arises and
//! the lane is writable exactly once, here, for every engine. That asymmetry is measured rather
//! than asserted — it is the same GAT in both seams, and the difference is the count.
//!
//! # Holder-and-door
//!
//! [`SlotLane`] HOLDS its [`SlotHandle<E, T>`](crate::SlotHandle) and [`AsyncServes::serve`]'s signature
//! names no backend, which is the write side's ratified seating mirrored: the declaration a lane
//! serves for is a fact about the LANE's type, and handing one another declaration's slot is
//! `E0308` naming both. `tests/slot_brand` pins that through a real compile.
//!
//! The vector half carries a SECOND such fact, for the same dividend: which of the declaration's
//! elections the lane answers from is `C`, so wiring the image lane into a door typed for the text
//! one is `E0308` naming both elections. `tests/election_brand` pins that one.

use core::{future::Future, marker::PhantomData, num::NonZeroUsize};

use super::invoke::{Answers, AsyncAnswers, Door, QueryError};
use crate::store::{
  AsyncFulltextRead, AsyncVectorRead, Connected, Elected, FulltextEngine, FulltextSubset, Hits,
  SlotHandle, VectorEngine,
};

/// What a server IS, under either face — and the one seat its KNOBS sit in.
///
/// [`Serves`] and [`AsyncServes`] are the two faces a server may wear; this is the base beneath
/// both, and it holds exactly one thing. A type wears it ONCE however many questions it answers and
/// whichever faces it wears, so its [`Options`](Self::Options) is a fact about the SERVER rather
/// than about a call.
///
/// # Why the knobs are HERE and the error is not
///
/// The library's binding criterion decides both, and decides them oppositely: a seat spent by a
/// VERB belongs to the face that spends the verb, and a seat whose spender calls nothing belongs to
/// the base.
///
/// `Options` has both kinds of spender. `serve` reads it, on each face — but the tower emission
/// PROJECTS it, one field per step into the emitted tower options and one row per configured step
/// into the schema, and that spender calls no verb at all. A projection cannot name a face without
/// deciding the step's MODE on the wire's behalf, which is the one thing a kind-agnostic tower must
/// not do. So the seat comes down here, where both faces read one.
///
/// [`Serves::Error`] has only the verb, and could not come down here even if something wanted it:
/// this base is per-TYPE, and an error is per QUESTION. [`Responding<Q>`] answers every input its
/// responder does and reports a different error type for each, so one type genuinely has as many
/// errors as it has questions and a single seat could not hold them.
///
/// # A TWO-FACED type has ONE seat, and that is the whole dividend
///
/// [`Door`] answers on both faces; a delegating wrapper implements both by passing through. Written
/// per face, such a type would carry two `Options` seats that nothing forces to agree, and an
/// emitted options row would have to pick one of them BY MODE. Here there is nothing to pick.
pub trait Serve {
  /// The knobs a caller may hand this server for ONE call.
  ///
  /// `()` where a server takes none, which is most of them today and is an ANSWER rather than a
  /// placeholder: *this server is configured with nothing*. A tower's emitted options still carries
  /// a ROW for such a step — whether a seat is `()` is the compiler's knowledge and never a macro's
  /// — and the row is zero-sized and read by nobody, so what a caller can usefully name stays
  /// exactly what some server reads. What a `()` seat publishes nothing of is the WIRE row, a seat
  /// crossing only if it can. [`Flow`] is the shipped shape for a step whose knobs are the usual
  /// two, offered and never required.
  ///
  /// Bound-free, per [`Serves::Error`]'s discipline: what a step's knobs must ALSO be — parsed off
  /// a request, rendered into a schema — is demanded where that is spent, and a step configured in
  /// process pays for none of it.
  type Options;
}

/// **WHAT THIS SERVER IS CANONICALLY ASKED, AND WHAT IT CANONICALLY ANSWERS** — the one-time line
/// that makes a tower's own words omissible.
///
/// A server usually has ONE question it is for. `#[ingraph::tower]`'s `question(type = "…")` and
/// `answer = "…"` are the words that say so per declaration; this is the same fact said once, by
/// the server itself, so that every tower holding it as a step can leave those words out:
///
/// ```ignore
/// impl DefaultServe for Tokenize {
///   type Question = String;
///   type Answer = Vec<String>;
/// }
///
/// #[ingraph::tower]                 // no question, no answer: this line is read for both
/// pub struct Words { tokenize: Tokenize }
/// ```
///
/// # IT IS A LINE AND NOT A CAPABILITY, which is why it names no face
///
/// Nothing here is callable — two type seats, no verb. So a tower that reads this line still has to
/// DEMAND the hop, and the demand it writes is the face the step's own word chose: an omitted
/// `answer` puts `<Self as DefaultServe>::Answer` on both ends of that predicate, and a server whose
/// canonical line names a `Q → A` it does not serve is `E0277` at the step's own field. The line
/// says what a server is FOR; the chain proves it.
///
/// # THE SUPERTRAIT IS THE BASE, and that is load-bearing
///
/// [`Serve`] and never [`Serves`] or [`AsyncServes`]. The framework's binding criterion decides it —
/// *a binding that spends verbs binds a face; a binding that spends only vocabulary binds the base*
/// — and the dividend is the one that matters here: an AWAITED-ONLY server declares its canonical
/// line exactly as a blocking one does, so the omissible word is not a capability that arrives with
/// a mode. Pinning it to a face instead would have withheld the word from precisely the steps a
/// search tower is made of.
///
/// The floor is kept rather than dropped, though: a type with a canonical `Q → A` and no knobs seat
/// is not a step. [`Serve`] is what makes this line a fact about a SERVER.
///
/// # Selection never comes from inference
///
/// This trait takes no parameter, so `<Tokenize as DefaultServe>::Answer` is ONE type. A server
/// answering several kinds of question — the shipped [`SlotLane`] answers two — is no more ambiguous
/// for having a canonical line: the line picks nothing, it STATES something, and a tower that wants
/// one of the other questions writes the word.
#[diagnostic::on_unimplemented(
  message = "`{Self}` declares no canonical question and answer",
  label = "no `DefaultServe`",
  note = "TWO ROADS lead out of this. Write the WORD where the type is wanted — \
          `#[ingraph::tower(question(type = \"…\"))]` for what a tower is asked, `#[ingraph(answer \
          = \"…\")]` for what a step answers — and the declaration names it once, there. Or give \
          `{Self}` ITS OWN LINE — `impl DefaultServe for {Self} {{ type Question = …; type Answer \
          = …; }}` — the one-time *what this server is for*, which every tower holding it then \
          omits."
)]
pub trait DefaultServe: Serve {
  /// What this server is CANONICALLY asked.
  ///
  /// A tower that omits `question(type = "…")` is asked what its FIRST STEP is canonically asked,
  /// which is this.
  type Question;

  /// What this server CANONICALLY answers.
  ///
  /// A step that omits `answer = "…"` answers this — and the next step's question is it, exactly as
  /// a written word's would be.
  type Answer;
}

/// Answer a question — the read path's capability seam.
///
/// `Q` is what is asked and `A` is what comes back, and both are PARAMETERS rather than associated
/// types: one lane legitimately answers several kinds of question (the shipped one below answers a
/// full-text ask and a vector ask through the same held slot), and an associated type would make
/// that a second lane.
///
/// # The KNOBS are the base's, and the questions are this face's
///
/// [`Serve`] is the supertrait and it carries [`Options`](Serve::Options) — one seat per server,
/// read by both faces — while `Q`, `A` and [`Error`](Self::Error) stay here, where a call spends
/// them. That division is what lets a server wearing both faces be configured once.
///
/// # A capability, not a hook
///
/// Statically monomorphised, no `dyn`, no boxed error. The hook law's boundary is *hooks are
/// assembled, capabilities are implemented*: a policy is chosen at launch from options and so
/// must be dyn-compatible; a capability is a thing a type IS, known at the call, and paying erasure
/// for it would buy nothing. That puts this seam in [`AsyncGather`](crate::retrieve::AsyncGather),
/// [`AsyncLands`](super::AsyncLands) and [`AsyncChanges`](super::AsyncChanges)' family and not in the policy family.
///
/// # What wraps here
///
/// A lane that DELEGATES is itself a lane — `struct Cache<S>(S, …)`, `struct Counting<S>(S, …)`,
/// a shadow read that asks two and returns one — so a third party changes what answering costs
/// without touching the arm that calls it or the engine that answers. The arm holds one server and
/// cannot tell how deep the stack under it goes, which is the whole sentence the seam is here to
/// say.
///
/// # `&mut self`
///
/// [`Answers::on_invoke`]'s reason, and it is the same resource: a server that matters holds a
/// reader — a searcher, a snapshot, a pooled handle, a scratch buffer — and the exclusive borrow
/// makes that ownership the compiler's rather than a comment. It costs nothing, an arm owning
/// exactly one server.
///
/// # TWO MODES, one per face, and this trait is the BLOCKING one
///
/// [`AsyncServes`] is the other, and the axis is the framework's: `Async*` is the asynchronous face,
/// the BARE name is the blocking one. A lane implements the face its body actually has, and the
/// BOUND is what selects — [`QueryArm::run`](super::QueryArm::run) asks for this one,
/// [`QueryArm::run_async`](super::QueryArm::run_async) for the other.
///
/// The pair is what deleted a `block_on` from the thread arm. While this seam was async-only, a
/// server answering out of a held reader still minted a future, and the thread engine had to drive
/// it with no runtime to drive it with. Now the thread cell CALLS.
///
/// # There is NO blanket bridge between the faces, and that is load-bearing
///
/// A blanket `impl<S: Serves<Q, A>> AsyncServes<Q, A> for S` would compile and would be the end of
/// the mechanism: every blocking lane would acquire an async face it never wrote, the async bound
/// would stop selecting anything, and an arm could no longer tell from a type whether a call mints a
/// future. What crosses between the faces instead is written PER DECLARATION, at the two places the
/// framework names them — [`Responding`] seats each responder face under its own server face, and
/// [`Door`] implements both because a transient edge genuinely has two doors.
pub trait Serves<Q, A>: Serve {
  /// What a refused answer reports.
  ///
  /// Bound-free here, per [`Answers::Error`]'s discipline: the arm bounds it at its own call site,
  /// where the erasure a tap needs is paid for.
  type Error;

  /// Answer `q`, on THIS thread, under whatever `options` the caller named.
  ///
  /// The BARE name that [`AsyncServes::serve`] also carries, for
  /// [`Lands::land`](crate::Lands::land)'s measured reason: a body importing one face calls `serve`
  /// with no ceremony, and a type wearing both is `E0034` naming the two candidates.
  ///
  /// # `options` is BORROWED and OMISSIBLE, and both halves are load-bearing
  ///
  /// [`None`] means this call named nothing — the server runs at its own floor, which is the only
  /// reading under which a step's author stays the party that decides what its defaults are.
  ///
  /// A borrow rather than a value because ONE options value serves a whole walk: a tower holds its
  /// options and hands each step that step's field, so a by-value seat would clone per hop, and a
  /// step wanting its own copy takes one. It is the spelling the engine seam beside it already
  /// carries for its per-call knobs.
  fn serve(&mut self, q: Q, options: Option<&Self::Options>) -> Result<A, Self::Error>;
}

/// [`Serves`]' ASYNCHRONOUS face — the same read-path capability, for a lane whose answer has to be
/// awaited.
///
/// Everything [`Serves`] states holds here verbatim: the same two parameters and why neither is an
/// associated type, the same `&mut self`, the same capability-not-a-hook posture, the same wrapping
/// story. THE ONLY DIFFERENCE IS THAT THE ANSWER IS A FUTURE.
///
/// # The future is `Send`
///
/// Spelled `impl Future + Send` rather than `async fn` so the bound is part of the CONTRACT instead
/// of something each caller has to hope for. An arm may be a task on somebody's runtime, and
/// [`QueryArm::run_async`](super::QueryArm::run_async) awaits this future inside its own — so a
/// server whose future were not `Send` would take the arm's `Send`ness with it. It is the spelling
/// [`AsyncAnswers`](super::AsyncAnswers) and [`AsyncLands`](super::AsyncLands) already carry, for
/// that same reason.
///
/// It is the face the SHIPPED [`SlotLane`] wears, and honestly so: its body is the engine's own
/// `search` / `knn`, which are async seams.
///
/// # A BLOCKING LANE DOES NOT SATISFY THIS BOUND, and that is the whole mechanism
///
/// The refusal below is what a blanket bridge would have deleted. With one, every blocking lane
/// would wear this face too, [`QueryArm::run_async`](super::QueryArm::run_async)'s bound would name
/// a set nothing is outside of, and no caller could tell from a type whether a call mints a future.
///
/// ```compile_fail,E0277
/// use ingraph::{AsyncServes, Serve, Serves};
///
/// struct Local;
///
/// impl Serve for Local {
///   type Options = ();
/// }
///
/// impl Serves<String, usize> for Local {
///   type Error = core::convert::Infallible;
///
///   fn serve(
///     &mut self,
///     q: String,
///     _options: Option<&Self::Options>,
///   ) -> Result<usize, Self::Error> {
///     Ok(q.len())
///   }
/// }
///
/// fn awaited<S: AsyncServes<String, usize>>() {}
///
/// awaited::<Local>(); // a blocking lane has no awaited face
/// ```
pub trait AsyncServes<Q, A>: Serve {
  /// What a refused answer reports. Bound-free, per [`Serves::Error`]'s discipline.
  type Error;

  /// [`Serves::serve`], answering a future the arm awaits — the SAME seat, the same parameter, the
  /// same position.
  ///
  /// The options borrow is captured by the returned future, so a caller holds its options across
  /// the await. That is what the walk already does and what a transient edge cannot (see the
  /// [`Door`] seating, whose seat is empty for exactly that reason).
  fn serve(
    &mut self,
    q: Q,
    options: Option<&Self::Options>,
  ) -> impl Future<Output = Result<A, Self::Error>> + Send;
}

/// A STEP'S FLOW — how many to take and how far to go: the shipped convention shape for
/// [`Serve::Options`], OFFERED and never coerced.
///
/// These are the two numbers a step with any knobs at all usually has. An expansion that mints
/// candidates bounds how many (`limit`); a walk that follows something bounds how far (`depth`). A
/// step whose knobs are those two names this type instead of writing its own pair, so two steps'
/// options read as one vocabulary — and a step whose knobs are anything else writes its own, this
/// type narrowing nothing about what a `type Options` may be.
///
/// # BOTH ABSENT is the shipped state, and absence is the STEP'S FLOOR rather than zero
///
/// [`None`] means THIS CALL NAMED NOTHING, so the step runs at whatever floor its own author wrote.
/// That is the currency wall the retrieve layer already states one seam over: a floor is the step's
/// and a number on a call is a PREFERENCE, so a preference that silently became a floor would let a
/// request rewrite a step's own contract. A step reading these spends its own `unwrap_or` and stays
/// the party that decides.
///
/// [`NonZeroUsize`] for both, because zero of either is a question with no answer to give — a limit
/// of none asks for nothing, a depth of none goes nowhere — and a type that can hold them makes
/// every reader check for what the constructor could have refused.
///
/// `Eq` and `Hash` beside the obvious derives, for the wrapper this seam is built around: a `Cache`
/// over a server keys on what it was asked AND what it was asked under, so a knobs value that
/// could not be a key would push every cache back to hashing its own copy.
///
/// # The OTHER `Flow`
///
/// The source-drive vocabulary — `Flow::{Open, Closed}`, a run's *is there more* — is a different
/// thing under one word: it lives in the legacy arrangement layer today, and this crate's
/// [`Emitter`](crate::Emitter) prose promises it here. Nothing collides while that one is unbuilt,
/// and the day it lands one of the two names moves.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Flow {
  limit: Option<NonZeroUsize>,
  depth: Option<NonZeroUsize>,
}

impl Flow {
  /// A flow that names NEITHER number — every step it is handed to at its own floor.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self {
      limit: None,
      depth: None,
    }
  }

  /// The same flow, asking for at most `limit`.
  #[inline]
  #[must_use]
  pub const fn with_limit(mut self, limit: NonZeroUsize) -> Self {
    self.limit = Some(limit);
    self
  }

  /// The same flow, going at most `depth` far.
  #[inline]
  #[must_use]
  pub const fn with_depth(mut self, depth: NonZeroUsize) -> Self {
    self.depth = Some(depth);
    self
  }

  /// This flow's limit, named IN PLACE — including named back to nothing.
  ///
  /// The in-place form exists for [`Route::set_depth`](crate::Route::set_depth)'s reason: a package
  /// parsed off a wire is owned whole, and reaching one field inside it has no other spelling than
  /// `&mut`. It takes an [`Option`] where the consuming form takes the number, so *this call names
  /// nothing* stays sayable after construction — which is what a holder narrowing somebody else's
  /// package needs and a builder never does.
  #[inline]
  pub const fn set_limit(&mut self, limit: Option<NonZeroUsize>) -> &mut Self {
    self.limit = limit;
    self
  }

  /// This flow's depth, named in place — [`set_limit`](Self::set_limit)'s twin.
  #[inline]
  pub const fn set_depth(&mut self, depth: Option<NonZeroUsize>) -> &mut Self {
    self.depth = depth;
    self
  }

  /// How many this call asks for, where it asks for a number at all.
  #[inline]
  #[must_use]
  pub const fn limit(&self) -> Option<NonZeroUsize> {
    self.limit
  }

  /// How far this call goes, where it says.
  #[inline]
  #[must_use]
  pub const fn depth(&self) -> Option<NonZeroUsize> {
    self.depth
  }
}

/// The unconfigured flow — [`Flow::new`], and one source of truth for it.
impl Default for Flow {
  #[inline]
  fn default() -> Self {
    Self::new()
  }
}

/// A RESPONDER, seated under the seam — what puts [`Serves`] BELOW [`Answers`] rather than beside
/// it.
///
/// [`Answers`] is the ROLE a query node's author writes: one input, one output, an arm's worth of
/// contract. [`Serves`] is the smaller thing underneath, and this is the bridge that keeps the two
/// from being a fork — a node written against the role is seated by
/// [`QueryArm::new`](super::QueryArm::new), which wraps it in this, so the author names the role and
/// the arm calls the seam. A lane that is no node at all (the shipped one below holds a slot and has
/// nothing behind it) reaches the same arm through [`QueryArm::serving`](super::QueryArm::serving).
///
/// # Why a wrapper and not a blanket impl
///
/// `impl<T: Answers<Q>> Serves<Q, T::Output> for T` is what this would rather be, and it is
/// `E0119` — MEASURED, not feared. A blanket over every `T` conflicts with every generic lane that
/// implements the seam by delegating (`Counting<S>`, a cache, a shadow read), because coherence
/// cannot rule out a downstream `impl Answers<TheirType> for Counting<TheirType>`: a foreign type
/// constructor with a local type inside it is orphan-legal. The conflict is with the WRAPPING that
/// is the seam's entire purpose, so the blanket is the thing that has to go.
///
/// A named wrapper costs one call at construction and buys the composition back: `Responding<Q>` is
/// one type constructor among many, so it overlaps nothing.
///
/// The direction is forced too. [`Answers`] carries its answer as an ASSOCIATED type and [`Serves`]
/// carries it as a PARAMETER, so a bridge the other way would leave that parameter unconstrained;
/// this way the projection supplies it.
pub struct Responding<Q> {
  responder: Q,
}

impl<Q> Responding<Q> {
  /// Seat `responder` under the seam.
  #[inline]
  #[must_use]
  pub const fn new(responder: Q) -> Self {
    Self { responder }
  }

  /// The responder it seats.
  #[inline]
  #[must_use]
  pub const fn responder(&self) -> &Q {
    &self.responder
  }

  /// Take the responder back out.
  #[inline]
  #[must_use]
  pub fn into_responder(self) -> Q {
    self.responder
  }
}

impl<Q: core::fmt::Debug> core::fmt::Debug for Responding<Q> {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_tuple("Responding").field(&self.responder).finish()
  }
}

/// A SEATED RESPONDER TAKES NO KNOBS, and that is the role's own shape rather than a gap.
///
/// [`Answers`] and [`AsyncAnswers`] are the ROLE a query node's author writes — one input, one
/// output — and neither carries an options seat. An author who wants one implements the seam
/// directly, where the seat is; giving the ROLE a seat of its own is the one repair this
/// arrangement refuses, a seat landed twice being the thing the base exists to prevent.
///
/// ONE row for however many questions the responder answers, which is the base's arity: the two
/// seatings below are per-question, this is per-type.
impl<Q> Serve for Responding<Q> {
  type Options = ();
}

/// The BLOCKING seating: a responder wearing [`Answers`] reaches [`Serves`] and nothing else.
impl<Q, In> Serves<In, <Q as Answers<In>>::Output> for Responding<Q>
where
  Q: Answers<In>,
{
  type Error = <Q as Answers<In>>::Error;

  #[inline]
  fn serve(
    &mut self,
    q: In,
    _options: Option<&Self::Options>,
  ) -> Result<<Q as Answers<In>>::Output, Self::Error> {
    self.responder.on_invoke(q)
  }
}

/// The AWAITED seating — the same wrapper, the other face, written out rather than bridged.
///
/// TWO seatings and not one plus a blanket, which is the dual-mode law spelled at the one place a
/// responder face crosses into a server face. Each row demands the responder face it is the seat
/// FOR, so a blocking responder never acquires an async server face and the arm's bound keeps
/// selecting. The two do not overlap: `Serves` and `AsyncServes` are two traits, so two impls for
/// one `Responding<Q>` are two trait refs and coherence has nothing to object to — the same
/// mechanism [`Driven<F>`](crate::Driven)'s two blanket rows are built on, one seam over.
impl<Q, In> AsyncServes<In, <Q as AsyncAnswers<In>>::Output> for Responding<Q>
where
  Q: AsyncAnswers<In>,
{
  type Error = <Q as AsyncAnswers<In>>::Error;

  #[inline]
  fn serve(
    &mut self,
    q: In,
    _options: Option<&Self::Options>,
  ) -> impl Future<Output = Result<<Q as AsyncAnswers<In>>::Output, Self::Error>> + Send {
    self.responder.on_invoke(q)
  }
}

/// A DOOR IS A WAY OF ASKING: send the question through the transient edge, await the reply.
///
/// The composition of two seams that were already ruled rather than a third one — [`Door`] is the
/// query edge's SENDING half and [`Serves`] is what a read lane implements, so this impl is the
/// sentence that lets an `ask` chain take a hop running as its own resident exactly where it takes
/// one that answers in process. Without it the emitted road would have to CHOOSE a transport, which
/// is the thing the seam exists to avoid: the declaration names hops, and how each hop is reached is
/// the wiring's business.
///
/// It overlaps nothing. [`Responding<Q>`] and [`SlotLane`] are other type constructors, and
/// coherence asks nothing beyond that — the blanket that would have collided is the one
/// [`Responding`] exists instead of.
///
/// # A DOOR ANSWERS ON BOTH FACES, and it is the one type in this file that honestly can
///
/// A transient edge already carries two doors of its own — [`Door::invoke`] beside
/// [`Door::invoke_async`], [`Awaiting::take`](super::Awaiting::take) beside
/// [`take_async`](super::Awaiting::take_async) — because the transport was built for both engines
/// before the mode pair reached this seam. So the two rows below are not a bridge and not a fiction:
/// each spends the transport's own verb for its own mode, and neither wraps the other.
///
/// That is what keeps an `ask` hop reachable from either arm. A chain whose middle hop runs as its
/// own resident is asked through this type, and which cell of the matrix the asking arm is in
/// decides which row it lands on — by the bound, as everywhere else.
///
/// It overlaps nothing. [`Responding<Q>`] and [`SlotLane`] are other type constructors, and
/// coherence asks nothing beyond that — the blanket that would have collided is the one
/// [`Responding`] exists instead of.
/// A DOOR'S SEAT IS EMPTY, and the BORROW is why.
///
/// [`Serves::serve`] takes `Option<&Self::Options>` — a borrow the callee reads during the call —
/// and a transient edge carries no borrow: what crosses is an OWNED message, and the answer comes
/// back on a reply channel that outlives the send. So a hop reached through a door carries its
/// knobs INSIDE the question it is sent — which is what the wire's `{ question, options }` payload
/// pair already is — and this seat is honestly empty rather than dropped on the floor.
impl<T, R> Serve for Door<T, R> {
  type Options = ();
}

impl<T, R> Serves<T, R> for Door<T, R> {
  type Error = QueryError;

  /// SEND, then WAIT — both blocking, both the transport's own. No runtime is present and none is
  /// wanted.
  #[inline]
  fn serve(&mut self, q: T, _options: Option<&Self::Options>) -> Result<R, Self::Error> {
    self.invoke(q)?.take()
  }
}

/// The awaited row: the same two hops, each awaiting instead.
///
/// `T: Send` and `R: Send` because [`AsyncServes::serve`]'s future is `Send` by contract and this
/// one holds the question across the send and the answer across the wait. The blocking row above
/// needs neither, and the absence is a fact rather than an omission — a bound that exists to let a
/// future cross threads has nothing to say about a call that returns before it could.
impl<T, R> AsyncServes<T, R> for Door<T, R>
where
  T: Send,
  R: Send,
{
  type Error = QueryError;

  #[inline]
  async fn serve(&mut self, q: T, _options: Option<&Self::Options>) -> Result<R, Self::Error> {
    self.invoke_async(q).await?.take_async().await
  }
}

/// The framework's own serving lane: one branded slot, answered through the engine's own verb.
///
/// It is TODAY'S DIRECT PATH wearing the seam and nothing more — `serve` is the branded
/// [`search`](SlotHandle::search) / [`knn`](SlotHandle::knn) the emitted retrieve already calls, so
/// a build that routes through this lane does byte for byte what one calling the handle by hand
/// did. What the lane adds is that the path is now a VALUE: it can be held, passed, and wrapped.
///
/// # What it does NOT do, and why the line is where it is
///
/// It stops at the engine's verb and does not run tier A's address read, floor, dedup or rank. Those
/// need the DECLARATION's key type and its declared dedup mechanism, which is r1's own finding —
/// a unifying face over them "would have to be generic over everything that differs and would name
/// nothing that is shared". So they stay in the emitted method, where the declaration is concrete,
/// and this lane is the shared half beneath them.
///
/// # ONE struct, two engine kinds
///
/// [`SlotHandle`]'s own arrangement, for its reason: the brand is engine-kind agnostic, so a lane
/// over a full-text engine and a lane over a vector one are one type with two [`Serves`] impls
/// distinguished by what they are ASKED — [`FulltextAsk`] against [`VectorAsk`]. An engine
/// implementing both faces is legal and gets both impls, which is why the question types are what
/// separate them rather than the answer types.
///
/// # `C` — WHICH ELECTION, and why it is a parameter rather than a field
///
/// A vector declaration may elect several embeddings into ONE slot, so `T` no longer says what a
/// `knn` is about: the column does, and the column is [`Elected`]'s. `C` carries it, defaulting to
/// `()` — the no-election shape, which is every full-text lane and which no vector ask can be served
/// through, nothing implementing [`Elected`] for `()`.
///
/// A CONSTRUCTION-TIME [`VectorColumn`](crate::VectorColumn) field would have carried the same fact
/// and refused nothing: two lanes over one slot differing in that field are ONE TYPE, so wiring the
/// image lane into the door that answers text questions type-checks and answers from the wrong
/// embedding — a wrong result at the one layer where a wrong result cannot be told from a right one.
/// As a parameter the two lanes are two types, and that wiring is `E0308` NAMING BOTH ELECTIONS, at
/// the line where they were joined. It is the medicine [`SlotHandle`] already is, one grain finer:
/// the slot was made a type fact, and the column now is too.
///
/// `PhantomData<fn() -> C>` for [`SlotHandle`]'s reason, argued at its own field: a marker must not
/// lend the thing that carries it its auto-traits.
pub struct SlotLane<E, T: ?Sized, C = ()> {
  slot: SlotHandle<E, T>,
  election: PhantomData<fn() -> C>,
}

impl<E, T: ?Sized, C> SlotLane<E, T, C> {
  /// Serve `T`'s slot through `slot`.
  ///
  /// The ELECTION is not an argument and cannot be: it is `C`, so it is written wherever the lane's
  /// type is written — at the binding, at the field of whatever holds it, or in the signature of the
  /// door it is handed to. A lane whose type names no election serves no [`VectorAsk`] at all.
  #[inline]
  #[must_use]
  pub const fn new(slot: SlotHandle<E, T>) -> Self {
    Self {
      slot,
      election: PhantomData,
    }
  }

  /// The slot it serves from.
  #[inline]
  #[must_use]
  pub const fn slot(&self) -> &SlotHandle<E, T> {
    &self.slot
  }

  /// Take the slot back — for a caller that has left the seam and is asking the handle directly.
  #[inline]
  #[must_use]
  pub fn into_slot(self) -> SlotHandle<E, T> {
    self.slot
  }
}

/// Hand-written for [`SlotHandle`]'s reason: the declaration is a TYPE with no value to print, and
/// the election is a second such type, so the bound is on the engine alone.
impl<E: core::fmt::Debug, T: ?Sized, C> core::fmt::Debug for SlotLane<E, T, C> {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("SlotLane")
      .field("slot", &self.slot)
      .finish()
  }
}

/// The per-call scope a full-text ask carries: the connection borrow — off the BASE — bundled with
/// whatever the READ FACE's [`ReadContext`](AsyncFulltextRead::ReadContext) GAT resolved to.
///
/// TWO TRAITS in one alias, because the two members live in two places now: a qualified path must
/// name the trait that DECLARES what it asks for, and the lease went with the verb that spends it.
///
/// A NAME for the bundle rather than a new type — an alias is transparent, so a caller building one
/// writes [`Connected::new`] exactly as it would at the branded verb.
pub type FulltextScope<'c, 's, E> =
  Connected<'c, <E as FulltextEngine>::Connection, <E as AsyncFulltextRead>::ReadContext<'s>>;

/// [`FulltextScope`]'s twin on the vector face — the connection off the BASE and the lease off the
/// READ FACE, exactly as above.
pub type VectorScope<'c, 's, E> =
  Connected<'c, <E as VectorEngine>::Connection, <E as AsyncVectorRead>::ReadContext<'s>>;

/// What a full-text [`SlotLane`] is asked: the per-call scope, the COLUMN SUBSET, the query string
/// and HOW MANY.
///
/// All four are the branded verb's own arguments, carried as ONE value because [`Serves::serve`]
/// takes one. Nothing is added and nothing is interpreted — the string goes to whichever grammar
/// the engine has, the subset goes beside it and `k` goes through untouched, which is
/// [`FulltextRead::search`](crate::FulltextRead::search)'s own posture.
///
/// # The subset is CARRIED rather than defaulted, and that is the lane keeping its promise
///
/// A lane that passed [`All`](FulltextSubset::All) on its caller's behalf would be a lane that
/// interprets, and would make *every* scoped question unaskable through the serving face while the
/// same question is spellable at the branded verb one layer down. A caller with nothing to scope
/// writes [`FulltextSubset::All`], which is one word and the type's own [`Default`].
///
/// # Three lifetimes, and each names a different borrow
///
/// `'c` is the connection borrow inside [`Connected`]. `'s` is whatever the engine's
/// [`ReadContext`](AsyncFulltextRead::ReadContext) GAT itself borrows. `'q` is the query text. They
/// are independent — a caller may hold the connection for a run, build knobs from a local, and
/// point at a string owned by the request — so collapsing any two would refuse a legal caller. The
/// GAT is the reason it cannot simply be inferred away: a projection is free to be invariant in its
/// lifetime, and then `'s` must match rather than shorten.
///
/// THE SUBSET RIDES `'q` and needs no fourth. Both it and the query text are covariant shared
/// borrows — an emitted door's `&'static [FulltextColumn]` shortens into any `'q` — so one lifetime
/// over the two refuses nobody, where the GAT's invariance is what made `'s` its own.
///
/// # The KNOBS ride `'q` too, and that is the same measurement one member over
///
/// [`SearchOptions`](FulltextEngine::SearchOptions) is a PLAIN associated type — it is the half a
/// request can carry, so it cannot be a GAT and cannot be invariant in a lifetime of its own. A
/// shared borrow of one shortens into `'q` exactly as the query text does, which is why the ask
/// grew a member and not a lifetime.
pub struct FulltextAsk<'c, 's, 'q, E>
where
  E: AsyncFulltextRead,
{
  scope: FulltextScope<'c, 's, E>,
  subset: FulltextSubset<'q>,
  query: &'q str,
  k: NonZeroUsize,
  options: Option<&'q E::SearchOptions>,
}

impl<'c, 's, 'q, E> FulltextAsk<'c, 's, 'q, E>
where
  E: AsyncFulltextRead,
{
  /// Ask `query` over `subset` within `scope` for at most `k` hits, under the engine's own defaults.
  ///
  /// # The knobs are a `with_` and not a further argument, and the asymmetry is the ruled one
  ///
  /// A subset, a query text and `k` are UNIVERSAL — every full-text engine there is takes all three,
  /// so all three are positional and none is omissible.
  /// [`SearchOptions`](FulltextEngine::SearchOptions) is the engine's OWN, and an engine with none
  /// answers `()`; a further argument would make every caller of every engine spell a `None` for a
  /// member most of them do not have. So it takes the shape the emitted packages take — a
  /// constructor that names nothing, and one `with_` for the caller that names something.
  ///
  /// `k` is on THIS side of the line and not the other, which is what the seam's parameter law
  /// decided: an ask that omitted it would have to default one, and a default hit count is the
  /// door/wire layer's policy rather than a lane's.
  #[inline]
  #[must_use]
  pub const fn new(
    scope: FulltextScope<'c, 's, E>,
    subset: FulltextSubset<'q>,
    query: &'q str,
    k: NonZeroUsize,
  ) -> Self {
    Self {
      scope,
      subset,
      query,
      k,
      options: None,
    }
  }

  /// The same ask, carrying the request's own per-query knobs.
  #[inline]
  #[must_use]
  pub const fn with_options(mut self, options: &'q E::SearchOptions) -> Self {
    self.options = Some(options);
    self
  }

  /// The per-call scope.
  #[inline]
  #[must_use]
  pub const fn scope(&self) -> &FulltextScope<'c, 's, E> {
    &self.scope
  }

  /// The columns asked over.
  #[inline]
  #[must_use]
  pub const fn subset(&self) -> FulltextSubset<'q> {
    self.subset
  }

  /// The query text.
  #[inline]
  #[must_use]
  pub const fn query(&self) -> &'q str {
    self.query
  }

  /// How many hits at most.
  #[inline]
  #[must_use]
  pub const fn k(&self) -> NonZeroUsize {
    self.k
  }

  /// The per-query knobs this ask names, if it names any.
  #[inline]
  #[must_use]
  pub const fn options(&self) -> Option<&'q E::SearchOptions> {
    self.options
  }

  /// Split into the five arguments the branded verb takes — what the lane does, the scope being
  /// owned and the verb wanting it by value.
  #[inline]
  #[must_use]
  pub fn into_parts(
    self,
  ) -> (
    FulltextScope<'c, 's, E>,
    FulltextSubset<'q>,
    &'q str,
    NonZeroUsize,
    Option<&'q E::SearchOptions>,
  ) {
    (self.scope, self.subset, self.query, self.k, self.options)
  }
}

/// What a vector [`SlotLane`] is asked: the per-call scope, and the coordinates.
///
/// [`FulltextAsk`]'s twin, and the one difference is the one the seams already have — coordinates
/// are a neutral shape where a query grammar is not.
pub struct VectorAsk<'c, 's, 'q, E>
where
  E: AsyncVectorRead,
{
  scope: VectorScope<'c, 's, E>,
  coordinates: &'q [E::Element],
  k: NonZeroUsize,
  options: Option<&'q E::SearchOptions>,
}

impl<'c, 's, 'q, E> VectorAsk<'c, 's, 'q, E>
where
  E: AsyncVectorRead,
{
  /// Ask for at most `k` neighbours of `coordinates` within `scope`, under the engine's own
  /// defaults.
  ///
  /// The knobs are a [`with_options`](Self::with_options) rather than a further argument, for
  /// [`FulltextAsk::new`]'s stated reason — and `k` is positional there for the same law's other
  /// half.
  #[inline]
  #[must_use]
  pub const fn new(
    scope: VectorScope<'c, 's, E>,
    coordinates: &'q [E::Element],
    k: NonZeroUsize,
  ) -> Self {
    Self {
      scope,
      coordinates,
      k,
      options: None,
    }
  }

  /// The same ask, carrying the request's own per-query knobs.
  #[inline]
  #[must_use]
  pub const fn with_options(mut self, options: &'q E::SearchOptions) -> Self {
    self.options = Some(options);
    self
  }

  /// The per-call scope.
  #[inline]
  #[must_use]
  pub const fn scope(&self) -> &VectorScope<'c, 's, E> {
    &self.scope
  }

  /// The coordinates asked for.
  #[inline]
  #[must_use]
  pub const fn coordinates(&self) -> &'q [E::Element] {
    self.coordinates
  }

  /// How many neighbours at most.
  #[inline]
  #[must_use]
  pub const fn k(&self) -> NonZeroUsize {
    self.k
  }

  /// The per-query knobs this ask names, if it names any.
  #[inline]
  #[must_use]
  pub const fn options(&self) -> Option<&'q E::SearchOptions> {
    self.options
  }

  /// Split into the four arguments the branded verb takes.
  #[expect(
    clippy::type_complexity,
    reason = "the tuple IS the verb's argument list, projected off the engine — an alias would put \
              one more name between a caller and the four things it is about to pass"
  )]
  #[inline]
  #[must_use]
  pub fn into_parts(
    self,
  ) -> (
    VectorScope<'c, 's, E>,
    &'q [E::Element],
    NonZeroUsize,
    Option<&'q E::SearchOptions>,
  ) {
    (self.scope, self.coordinates, self.k, self.options)
  }
}

/// THE SHIPPED LANE'S KNOBS ARE THE ENGINE'S AND RIDE THE ASK, so its own seat is empty.
///
/// [`FulltextAsk::with_options`] and [`VectorAsk::with_options`] carry
/// [`SearchOptions`](FulltextEngine::SearchOptions) — what an ENGINE is asked with, per query —
/// where this seat is what a STEP is configured with. Two seats with two spenders, and the division
/// is the ruled one: a lane that merged them would make an engine's per-query knobs a fact about
/// the lane's TYPE instead of about the call, and a caller could no longer ask the same lane two
/// differently-tuned questions.
///
/// Unbounded, and that is bound minimization rather than an oversight: a seat answered `()` reads
/// nothing off `E`, so demanding an engine face here would refuse a lane that has not been asked
/// anything yet.
impl<E, T: ?Sized, C> Serve for SlotLane<E, T, C> {
  type Options = ();
}

/// The full-text lane: [`SlotHandle::search`], and nothing else.
///
/// Generic over `C` and reading none of it — which is now a statement about the LANE rather than
/// about the seam. The full-text seam does have a column selector ([`FulltextSubset`], one grain
/// finer than the slot), but where the vector lane reads its column off `C` as a `const`, this one
/// takes the subset PER CALL: a search's subject is a question a caller asks, several columns at a
/// time and differently on the next call, so pinning one into the lane's type would fix at
/// construction what the ask is about. [`Elected`](crate::Elected)'s full-text twin is the day a
/// lane wants one column forever, and no caller has asked for it.
impl<'c, 's, 'q, E, T, C> AsyncServes<FulltextAsk<'c, 's, 'q, E>, Hits<E::Address, E::Score>>
  for SlotLane<E, T, C>
where
  E: AsyncFulltextRead,
  T: ?Sized,
{
  type Error = E::Error;

  #[inline]
  fn serve(
    &mut self,
    q: FulltextAsk<'c, 's, 'q, E>,
    _options: Option<&Self::Options>,
  ) -> impl Future<Output = Result<Hits<E::Address, E::Score>, Self::Error>> + Send {
    let (scope, subset, query, k, options) = q.into_parts();
    self.slot.search(scope, subset, query, k, options)
  }
}

/// The vector lane: [`SlotHandle::knn`] in `C`'s column, and nothing else.
///
/// The column is READ OFF THE TYPE — `C::COLUMN`, a `const` — so the column argument the branded
/// verb takes is supplied by the lane rather than asked of the caller. That is what keeps
/// [`VectorAsk`] free of it: a caller states where to look by choosing a LANE, which is a choice the
/// compiler checks, and never by spelling a column, which is a choice nothing could check.
///
/// `k` is the other way round and stays in the ASK, which is the same test answered oppositely: a
/// column is a fact about WHICH storage a lane addresses and is fixed for the lane's life, where how
/// many hits is a fact about ONE question — different on the next call, and a lane defaulting one
/// would be a lane interpreting.
///
/// The bound is `C: Elected<T>` and it is here rather than on the struct, which is what makes the
/// no-election default honest: `SlotLane<E, T>` is a legal, constructible lane that simply has no
/// vector face, so a declaration's elections are the only way one is reached.
impl<'c, 's, 'q, E, T, C> AsyncServes<VectorAsk<'c, 's, 'q, E>, Hits<E::Address, E::Score>>
  for SlotLane<E, T, C>
where
  E: AsyncVectorRead,
  T: ?Sized,
  C: Elected<T>,
{
  type Error = E::Error;

  #[inline]
  fn serve(
    &mut self,
    q: VectorAsk<'c, 's, 'q, E>,
    _options: Option<&Self::Options>,
  ) -> impl Future<Output = Result<Hits<E::Address, E::Score>, Self::Error>> + Send {
    let (scope, coordinates, k, options) = q.into_parts();
    self.slot.knn(scope, C::COLUMN, coordinates, k, options)
  }
}

#[cfg(test)]
mod tests;