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
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
use core::{
  num::NonZeroUsize,
  pin::pin,
  task::{Context, Poll, Waker},
};

use tantivy::{Term, collector::Count, query::TermQuery, schema::IndexRecordOption};

use super::{
  AsyncFulltextRead, AsyncFulltextWrite, ColumnReader, ColumnWriter, Connected, Field,
  FulltextEngine, FulltextStore, FulltextSubset, Hits, KeyDecodeError, Scored, TantivyDoc,
  TantivyFulltext, TantivyFulltextError, TantivyStore,
};
use crate::{FulltextRecord, FulltextTable, Identifiable, SlotName, Transformer, retrieve::keyed};

/// Drive a future to its value without a runtime.
///
/// Hand-rolled for the reason `store::vector`'s twin is: every future this backend returns is
/// already-ready — it does its work inline and wraps the outcome — so what this needs is one poll
/// and a `Waker` that is never woken. An async runtime as a dev-dependency to spin a `Ready` would
/// be the dependency the backend itself declines to take.
fn block_on<F: Future>(future: F) -> F::Output {
  let mut future = pin!(future);
  let mut cx = Context::from_waker(Waker::noop());
  loop {
    if let Poll::Ready(value) = future.as_mut().poll(&mut cx) {
      return value;
    }
  }
}

/// The arena every writer here is minted with — the engine's floor, which is all a test batch needs.
const HEAP: usize = TantivyStore::MIN_WRITER_HEAP_BYTES;

mod ceiling;

// A record's id, as a DECLARATION may write one: a newtype rather than a bare `i64`.
//
// It is a CHOICE, and A′ is what made it one. The engine's key trait was a LOCAL trait over foreign
// types, so `impl TantivyKey for i64` in a declaring crate was `E0117` — and so was one for
// `TypedId<i64, Caption>` — which made a newtype the only reachable shape for anyone downstream.
// The COLUMN LANGUAGE went one further and took the engine off the row entirely, so `impl Field for
// MyId` in a declaring crate crosses into every engine there is; the newtype stays here because the
// fixture is about a declaration's own types, and a key struct beside an id newtype is what one
// writes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Frame(i64);

impl Field for Frame {
  fn write(&self, w: &mut impl ColumnWriter) {
    w.i64(self.0);
  }

  fn read<R: ColumnReader>(r: &mut R) -> Result<Self, R::Error> {
    r.i64().map(Self)
  }
}

// A keyed caption: the compound lineage key `(media, frame)`, the frame as the id, and the text as a
// field. The shape every full-text declaration has.
struct Caption {
  media: String,
  frame: Frame,
  text: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct CaptionKey {
  media: String,
  frame: Frame,
}

// The key's own STRUCTURE row: one column per call, in the order the read takes them back. This is
// what a full-text derive emits per key — the neutral half, carrying walk order and nothing else,
// with each column's VALUE crossing through its own row.
impl Field for CaptionKey {
  fn write(&self, w: &mut impl ColumnWriter) {
    self.media.write(w);
    self.frame.write(w);
  }

  fn read<R: ColumnReader>(r: &mut R) -> Result<Self, R::Error> {
    Ok(Self {
      media: String::read(r)?,
      frame: Frame::read(r)?,
    })
  }
}

impl Identifiable for Caption {
  type Id = Frame;

  fn id_ref(&self) -> &Frame {
    &self.frame
  }
}

impl Transformer for Caption {
  type Key = CaptionKey;
  type Lineage = ();
  type Record = Self;
  type Graphql = ();

  fn key(&self) -> CaptionKey {
    CaptionKey {
      media: self.media.clone(),
      frame: self.frame,
    }
  }
}

impl FulltextRecord for Caption {
  type Document = String;

  fn document(&self) -> &String {
    &self.text
  }
}

impl FulltextTable for Caption {
  const SLOT: &'static SlotName = SlotName::new("captions");
}

// A SECOND SOURCE over the same id space and the same key shape, differing from `Caption` in exactly
// one thing: the word it enters an index under. It is what the fan-in pin needs — two records whose
// ids collide and whose sources do not.
struct Alias {
  media: String,
  frame: Frame,
  text: String,
}

impl Identifiable for Alias {
  type Id = Frame;

  fn id_ref(&self) -> &Frame {
    &self.frame
  }
}

impl Transformer for Alias {
  type Key = CaptionKey;
  type Lineage = ();
  type Record = Self;
  type Graphql = ();

  fn key(&self) -> CaptionKey {
    CaptionKey {
      media: self.media.clone(),
      frame: self.frame,
    }
  }
}

impl FulltextRecord for Alias {
  type Document = String;

  fn document(&self) -> &String {
    &self.text
  }
}

impl FulltextTable for Alias {
  const SLOT: &'static SlotName = SlotName::new("aliases");
}

fn caption(media: &str, frame: i64, text: &str) -> Caption {
  Caption {
    media: media.to_owned(),
    frame: Frame(frame),
    text: text.to_owned(),
  }
}

fn alias(media: &str, frame: i64, text: &str) -> Alias {
  Alias {
    media: media.to_owned(),
    frame: Frame(frame),
    text: text.to_owned(),
  }
}

fn caption_key(media: &str, frame: i64) -> CaptionKey {
  CaptionKey {
    media: media.to_owned(),
    frame: Frame(frame),
  }
}

// A fresh store under a temporary root. The `TempDir` must OUTLIVE the store — its drop removes the
// on-disk indices.
fn open_store() -> (tempfile::TempDir, TantivyStore) {
  let dir = tempfile::tempdir().expect("a temporary directory");
  let store = TantivyStore::open(dir.path()).expect("the store opens");
  (dir, store)
}

// THE EMISSION, by hand: a record flattened into the engine's own entry.
//
// It is the whole of what A′ moved out of the backend, and it is four lines: the source word off the
// record's own const, the id into the identity, the key into the stored address, the document into
// the body. The `where` clause is what a derive would emit as bounds — the record's own faces, plus
// one row demand per value that crosses.
fn entry<R>(record: &R) -> TantivyDoc
where
  R: FulltextTable + FulltextRecord<Document: AsRef<str>>,
  R::Id: Field,
  R::Key: Field,
{
  TantivyDoc::new(R::SLOT.as_ref())
    .with_identity(record.id_ref())
    .with_address(&record.key())
    .with_body(record.document().as_ref())
}

// Queue `records` on a fresh writer for the face's slot, commit, release the lock, then reload that
// slot — a batch's whole shape, collapsed. The writer is dropped BEFORE the reload so the slot's
// lockfile is free for the next call.
fn commit<R>(store: &TantivyStore, face: &TantivyFulltext, records: &[R])
where
  R: FulltextTable + FulltextRecord<Document: AsRef<str>>,
  R::Id: Field,
  R::Key: Field,
{
  {
    let mut writer = store
      .writer(face.slot(), HEAP)
      .expect("the slot's writer opens");
    for record in records {
      block_on(face.upsert(Connected::new(store, &mut writer), entry(record)))
        .expect("the document queues");
    }
    writer.commit().expect("the batch commits");
  }
  store
    .reload(face.slot())
    .expect("the slot's reader reloads");
}

// The READ, as the emission spells it: the engine answers with its own addresses, and the typed read
// back into the key is the caller's — `retrieve::keyed`, the framework's shared walk, with the key
// named here because here is where it is known.
fn search(
  store: &TantivyStore,
  face: &TantivyFulltext,
  query: &str,
) -> Result<Hits<CaptionKey, f32>, TantivyFulltextError> {
  let hits = block_on(face.search(
    Connected::new(store, ()),
    FulltextSubset::All,
    query,
    ROOMY,
    None,
  ))?;
  keyed::<TantivyFulltext, CaptionKey>(hits)
}

/// A `k` wider than anything these fixtures index — what a test asking *everything that matched*
/// hands the verb now that the seam takes the number rather than reading one off a scope.
const ROOMY: NonZeroUsize = NonZeroUsize::new(10).expect("10 is not zero");

/// How many documents the slot's committed snapshot holds — reached through the private cache
/// because a document COUNT is not the seam's business, and an assertion about a keyed replace has
/// nothing else to look at.
fn live_documents(store: &TantivyStore, slot: &str) -> u64 {
  store
    .slot_index(slot, false)
    .expect("the slot opens")
    .reader
    .searcher()
    .num_docs()
}

/// The round trip: a record indexed through the face comes back out of a search as its own key, with
/// the engine's BM25 score on it.
#[test]
fn a_document_indexed_comes_back_as_its_key() {
  let (_dir, store) = open_store();
  let captions = store.fulltext(Caption::SLOT.as_ref());

  commit(
    &store,
    &captions,
    &[
      caption("m1", 1, "the quick brown fox"),
      caption("m2", 2, "a heron over still water"),
    ],
  );

  let hits = search(&store, &captions, "fox").expect("the search runs");

  assert_eq!(hits.len(), 1);
  assert_eq!(hits[0].data_ref(), &caption_key("m1", 1));
  // BM25 is natively higher-is-better, so a match scores ABOVE zero with no negation anywhere on
  // the path — which is the whole of what this face's score contract says.
  assert!(hits[0].score() > 0.0, "{hits:?}");

  // The whole key comes back, ancestry included: the frame is the id the entry was named by, and
  // the media step rode the stored address beside it.
  let hits = search(&store, &captions, "heron").expect("the search runs");
  assert_eq!(hits.len(), 1);
  assert_eq!(hits[0].data_ref().media, "m2");
  assert_eq!(hits[0].data_ref().frame, Frame(2));
}

/// A query matching nothing is an empty result and not an error — the limit is a ceiling on hits,
/// never a floor.
#[test]
fn a_query_matching_nothing_is_an_empty_result() {
  let (_dir, store) = open_store();
  let captions = store.fulltext(Caption::SLOT.as_ref());

  commit(
    &store,
    &captions,
    &[caption("m1", 1, "the quick brown fox")],
  );

  assert_eq!(
    search(&store, &captions, "heron").expect("the search runs"),
    []
  );
}

/// THE KEYED REPLACE, which is the backend's core obligation: a second write under the same identity
/// REPLACES the first rather than adding beside it.
///
/// Three assertions, because two of them can pass while the obligation is broken. The old text
/// finding nothing and the new text finding one hit would both hold if the second document had been
/// APPENDED and the first merely re-ranked below it — so the document COUNT is what has teeth here.
/// It is also what the schema's own hazard needs: `delete_term` swallows a term whose field is not
/// indexed and returns a bare opstamp, so an identity field that lost `set_indexed()` would turn
/// every replace into an append with no error anywhere on the path.
#[test]
fn a_keyed_replace_leaves_exactly_one_document() {
  let (_dir, store) = open_store();
  let captions = store.fulltext(Caption::SLOT.as_ref());

  commit(&store, &captions, &[caption("m1", 1, "alpha")]);
  assert_eq!(live_documents(&store, captions.slot()), 1);

  commit(&store, &captions, &[caption("m1", 1, "beta")]);

  assert_eq!(
    live_documents(&store, captions.slot()),
    1,
    "a replace must not leave the old document beside the new one"
  );
  assert_eq!(
    search(&store, &captions, "alpha").expect("the search runs"),
    []
  );
  let hits = search(&store, &captions, "beta").expect("the search runs");
  assert_eq!(hits.len(), 1);
  assert_eq!(hits[0].data_ref(), &caption_key("m1", 1));
}

/// Two records that differ in their ID are two entries, not one replacing the other — the identity's
/// other direction, and what keeps the replace above from being a store that holds one document.
#[test]
fn distinct_ids_are_distinct_entries() {
  let (_dir, store) = open_store();
  let captions = store.fulltext(Caption::SLOT.as_ref());

  commit(
    &store,
    &captions,
    &[caption("m1", 1, "alpha"), caption("m1", 2, "alpha")],
  );

  assert_eq!(live_documents(&store, captions.slot()), 2);
  let mut hits = search(&store, &captions, "alpha").expect("the search runs");
  hits.sort_by_key(|hit| hit.data_ref().frame.0);
  assert_eq!(
    hits
      .iter()
      .map(|hit| hit.data_ref().frame.0)
      .collect::<Vec<_>>(),
    [1, 2]
  );
}

/// A batch that queues two documents through ONE writer, in turn — the shape the exclusive write
/// scope admits, and the one the doctest on `SlotWriter` states from the other side.
#[test]
fn one_writer_carries_a_whole_batch() {
  let (_dir, store) = open_store();
  let captions = store.fulltext(Caption::SLOT.as_ref());

  let mut writer = store
    .writer(captions.slot(), HEAP)
    .expect("the slot's writer opens");
  for record in [caption("m1", 1, "alpha"), caption("m2", 2, "beta")] {
    block_on(captions.upsert(Connected::new(&store, &mut writer), entry(&record)))
      .expect("the document queues");
  }
  writer.commit().expect("the batch commits");
  drop(writer);
  store
    .reload(captions.slot())
    .expect("the slot's reader reloads");

  assert_eq!(live_documents(&store, captions.slot()), 2);
}

/// Visibility is EXPLICIT: an uncommitted batch is invisible to a search, and a committed one is
/// invisible until the slot's reader is reloaded. `ReloadPolicy::Manual` is what makes that a
/// contract rather than a race — the two steps are the caller's, in that order.
#[test]
fn a_search_sees_committed_and_reloaded_writes_only() {
  let (_dir, store) = open_store();
  let captions = store.fulltext(Caption::SLOT.as_ref());

  let mut writer = store
    .writer(captions.slot(), HEAP)
    .expect("the slot's writer opens");
  block_on(captions.upsert(
    Connected::new(&store, &mut writer),
    entry(&caption("m1", 1, "alpha")),
  ))
  .expect("the document queues");

  assert_eq!(
    search(&store, &captions, "alpha").expect("the search runs"),
    [],
    "a queued document is not a visible one"
  );

  writer.commit().expect("the batch commits");
  assert_eq!(
    search(&store, &captions, "alpha").expect("the search runs"),
    [],
    "a committed document is not visible until the reader is reloaded"
  );

  drop(writer);
  store
    .reload(captions.slot())
    .expect("the slot's reader reloads");
  assert_eq!(
    search(&store, &captions, "alpha")
      .expect("the search runs")
      .len(),
    1
  );
}

/// The writer is TRANSIENT and its lock is per-directory: dropping it frees the slot for the next
/// one, and a batch that never released it would deadlock the very next call.
#[test]
fn dropping_a_writer_frees_the_slot() {
  let (_dir, store) = open_store();
  let captions = store.fulltext(Caption::SLOT.as_ref());

  drop(
    store
      .writer(captions.slot(), HEAP)
      .expect("the slot's writer opens"),
  );
  drop(
    store
      .writer(captions.slot(), HEAP)
      .expect("the slot's writer opens a second time"),
  );
}

/// A rollback discards the queued batch and leaves the writer usable — a reset rather than a poison,
/// which is what makes it the caller's answer to a failed `upsert` mid-batch.
#[test]
fn a_rollback_discards_the_batch_and_keeps_the_writer() {
  let (_dir, store) = open_store();
  let captions = store.fulltext(Caption::SLOT.as_ref());

  let mut writer = store
    .writer(captions.slot(), HEAP)
    .expect("the slot's writer opens");
  block_on(captions.upsert(
    Connected::new(&store, &mut writer),
    entry(&caption("m1", 1, "alpha")),
  ))
  .expect("the document queues");
  writer.rollback().expect("the batch rolls back");

  block_on(captions.upsert(
    Connected::new(&store, &mut writer),
    entry(&caption("m2", 2, "beta")),
  ))
  .expect("the writer is still usable");
  writer.commit().expect("the batch commits");
  drop(writer);
  store
    .reload(captions.slot())
    .expect("the slot's reader reloads");

  assert_eq!(live_documents(&store, captions.slot()), 1);
  assert_eq!(
    search(&store, &captions, "alpha").expect("the search runs"),
    []
  );
  assert_eq!(
    search(&store, &captions, "beta")
      .expect("the search runs")
      .len(),
    1
  );
}

/// A store REOPENED over the same root reads what the previous one committed. The index is the
/// durable thing; the manager in front of it is not.
#[test]
fn a_reopened_store_reads_the_previous_one_s_writes() {
  let dir = tempfile::tempdir().expect("a temporary directory");
  {
    let store = TantivyStore::open(dir.path()).expect("the store opens");
    let captions = store.fulltext(Caption::SLOT.as_ref());
    commit(&store, &captions, &[caption("m1", 1, "alpha")]);
  }

  let store = TantivyStore::open(dir.path()).expect("the store reopens");
  let captions = store.fulltext(Caption::SLOT.as_ref());
  // No reload: the reader built when this store first reaches the slot snapshots whatever is
  // committed at that moment, which is everything the previous store left.
  assert_eq!(
    search(&store, &captions, "alpha")
      .expect("the search runs")
      .len(),
    1
  );
}

// How many documents in `slot` carry `source` as their discriminant — a native `TermQuery` over the
// untokenized field, which is the property rule one is about. Reached through the private cache
// because no seam exposes a term, and the whole point of the assertion is that the ENGINE can build
// one.
fn documents_with_source(store: &TantivyStore, slot: &str, source: &str) -> usize {
  let opened = store.slot_index(slot, false).expect("the slot opens");
  let query = TermQuery::new(
    Term::from_field_text(opened.fields.source, source),
    IndexRecordOption::Basic,
  );
  opened
    .reader
    .searcher()
    .search(&query, &Count)
    .expect("the term query runs")
}

// A body of `count` copies of each token, space-separated. The token COUNT is what BM25's length
// normalization divides by, so a length-sensitive body is BUILT to a known length rather than
// spelled out and counted by eye.
fn tokens(spec: &[(&str, usize)]) -> String {
  spec
    .iter()
    .flat_map(|&(token, count)| core::iter::repeat_n(token, count))
    .collect::<Vec<_>>()
    .join(" ")
}

// The hits' media halves in rank order — what a BM25 assertion is actually about.
fn ranking(hits: &[Scored<CaptionKey, f32>]) -> Vec<&str> {
  hits
    .iter()
    .map(|hit| hit.data_ref().media.as_str())
    .collect()
}

/// LAW ONE, as the regression guard for the defect one index per slot exists to prevent.
///
/// BM25 computes from corpus statistics that are INDEX-wide — `docfreq` over `numdocs`, hence IDF,
/// and the average document length the length normalization divides by — so pooling every slot into
/// one index would let a SIBLING slot's documents into this slot's ranking. `avgdl` is the leak that
/// survives even a single-term query, where IDF is one factor common to every hit and so cannot
/// reorder anything: it sits inside each document's OWN length normalization, scaled by that
/// document's OWN length, and never factors out.
///
/// The two caption documents are built to expose exactly that. `short` carries the term once in 4
/// tokens; `long` three times in 40. With only the two of them in the corpus the length penalty on
/// `long` outweighs its higher term frequency, so `short` ranks first — and the pair sits either
/// side of the tipping point: pool in the 200-token sibling and the average triples, the penalty on
/// `long` shrinks, and it OVERTAKES.
#[test]
fn a_sibling_slot_cannot_move_this_slot_s_bm25_ranking() {
  let (_dir, store) = open_store();
  let captions = store.fulltext(Caption::SLOT.as_ref());
  commit(
    &store,
    &captions,
    &[
      caption("short", 1, "fox alpha beta gamma"),
      caption("long", 2, &tokens(&[("fox", 3), ("delta", 37)])),
    ],
  );

  let before = search(&store, &captions, "fox").expect("the search runs");
  assert_eq!(
    ranking(&before),
    ["short", "long"],
    "the short document outranks the long one: {before:?}"
  );

  // The sibling document carries NONE of the query term, so this slot's `docfreq` for it is
  // provably untouched — only the POOLED statistics could move a shared corpus, which is precisely
  // the leak under test.
  let transcripts = store.fulltext("transcripts");
  commit(
    &store,
    &transcripts,
    &[caption("big", 3, &tokens(&[("chatter", 200)]))],
  );
  // Refresh THIS slot's reader before re-searching. Not ceremony: a stale reader would report the
  // old statistics whatever index it is reading, so without this the assertion below could pass on
  // a shared index simply by not having looked.
  store
    .reload(captions.slot())
    .expect("the slot's reader reloads");

  let after = search(&store, &captions, "fox").expect("the search runs");
  assert_eq!(
    ranking(&after),
    ["short", "long"],
    "a sibling slot must not reorder this slot: {after:?}"
  );
  // Not only the order: the scores are the same computation over the same untouched corpus, so they
  // are identical. The tolerance is tight on purpose — a shared corpus moves these in the FIRST
  // decimal, so a loose epsilon would hide the very drift this guards.
  for (before, after) in before.iter().zip(&after) {
    assert!(
      (before.score() - after.score()).abs() < 1e-6,
      "a sibling slot must not move this slot's scores: {before:?} vs {after:?}"
    );
  }
}

/// RULE ONE: the discriminant is a NATIVE FIELD, so *which source* is a `Term` the engine builds —
/// untokenized, matched exactly, and never a scan over a packed value.
///
/// The source word is the RECORD's own const and not the handle's slot, which is what this asserts
/// by indexing captions into a slot of another name: an entry says which source it came from
/// independently of which index it landed in.
#[test]
fn the_source_word_is_a_native_term() {
  let (_dir, store) = open_store();
  let elsewhere = store.fulltext("elsewhere");

  commit(&store, &elsewhere, &[caption("m1", 1, "alpha")]);

  assert_eq!(documents_with_source(&store, "elsewhere", "captions"), 1);
  assert_eq!(documents_with_source(&store, "elsewhere", "elsewhere"), 0);
  assert_eq!(documents_with_source(&store, "elsewhere", "aliases"), 0);
}

/// RULE TWO, and the reason the identity is `source ⊕ id` rather than the id alone: two SOURCES
/// sharing one slot with the same id do not delete each other.
///
/// A mutation-grade pin. `Caption` and `Alias` differ in exactly one thing — the word they enter an
/// index under — and both are written here at the same id, into the same slot. Drop the source
/// append from the identity and the second write's `delete_term` tombstones the first: one document
/// where there should be two, silently, with the repair being a reindex rather than a code change.
#[test]
fn two_sources_sharing_a_slot_do_not_delete_each_other() {
  let (_dir, store) = open_store();
  let shared = store.fulltext("shared");

  commit(&store, &shared, &[caption("m1", 1, "alpha")]);
  commit(&store, &shared, &[alias("m1", 1, "beta")]);

  assert_eq!(
    live_documents(&store, "shared"),
    2,
    "an identity framed over (source, id) must not collide across sources"
  );
  assert_eq!(documents_with_source(&store, "shared", "captions"), 1);
  assert_eq!(documents_with_source(&store, "shared", "aliases"), 1);
  // And each source still replaces its OWN entry, which is the half a source-blind identity would
  // have kept while losing the half above.
  commit(&store, &shared, &[caption("m1", 1, "gamma")]);
  assert_eq!(live_documents(&store, "shared"), 2);
  assert_eq!(
    search(&store, &shared, "alpha").expect("the search runs"),
    []
  );
  assert_eq!(
    search(&store, &shared, "beta")
      .expect("the search runs")
      .len(),
    1
  );
}

/// A WRITE PHASE with `columns` landed in it, sealed — the framework's own write walk, spelled at
/// this engine so the codec tests reach it the way a key does.
fn sealed(columns: impl FnOnce(&mut <TantivyFulltext as FulltextEngine>::WriteBuffer)) -> Vec<u8> {
  let mut buf = TantivyFulltext::buffer();
  columns(&mut buf);
  TantivyFulltext::finalize(buf).into_bytes()
}

/// A READ PHASE over stored bytes.
fn opened(bytes: Vec<u8>) -> <TantivyFulltext as FulltextEngine>::ReadBuffer {
  TantivyFulltext::open(bytes.into())
}

/// THE INJECTIVITY PIN at the codec level: the pair whose naive concatenation collides — `"ab"+"c"`
/// and `"a"+"bc"` are both `"abc"` — renders DISTINCT terms. The length prefixes are the only thing
/// keeping them apart, so this fails the moment they are removed.
#[test]
fn the_address_is_injective_for_the_concatenation_colliding_pair() {
  let ab_c = sealed(|w| {
    w.text("ab");
    w.text("c");
  });
  let a_bc = sealed(|w| {
    w.text("a");
    w.text("bc");
  });

  assert_ne!(ab_c, a_bc);

  // And each parses back into the sequence it was written from, which is the other half of an
  // injective correspondence.
  let mut read = opened(ab_c);
  assert_eq!(read.text().expect("the first column"), "ab");
  assert_eq!(read.text().expect("the second column"), "c");
  read.finish().expect("the key took every column");
}

/// Every typed column is a byte-copy its own read reverses exactly — including the widths, which is
/// what makes a malformed stored address a typed refusal rather than a plausible wrong value.
#[test]
fn every_typed_column_round_trips() {
  let uuid = uuid::Uuid::from_bytes([7; 16]);
  let mut read = opened(sealed(|w| {
    w.bytes(&[1, 2, 3]);
    w.text("a red car");
    w.i64(-42);
    w.uuid(uuid);
  }));

  assert_eq!(read.bytes().expect("the raw column"), [1, 2, 3]);
  assert_eq!(read.text().expect("the text column"), "a red car");
  assert_eq!(read.i64().expect("the integer column"), -42);
  assert_eq!(read.uuid().expect("the uuid column"), uuid);
  read.finish().expect("the key took every column");
}

/// The read NAMES what is wrong with an address rather than half-reading it.
///
/// MUTATION-CHECKED on the last assertion: a `finish` that always answers `Ok(())` — the
/// completeness check bypassed, which is what a re-inlined decode inside the engine would do — turns
/// this red. That check is the one thing the engine still owes the read after A′ moved the typed
/// half out and the column language moved it onto the phase.
#[test]
fn the_read_names_a_malformed_address() {
  // A prefix with no body behind it.
  assert!(matches!(
    opened(vec![0, 0, 0, 8, 1, 2]).bytes(),
    Err(TantivyFulltextError::Key(KeyDecodeError::Truncated))
  ));
  // An address that ends inside the prefix itself.
  assert!(matches!(
    opened(vec![0, 0]).bytes(),
    Err(TantivyFulltextError::Key(KeyDecodeError::Truncated))
  ));

  let invalid = sealed(|w| w.bytes(&[0xff, 0xfe]));
  assert!(matches!(
    opened(invalid.clone()).text(),
    Err(TantivyFulltextError::Key(KeyDecodeError::NotText))
  ));
  assert!(matches!(
    opened(invalid.clone()).i64(),
    Err(TantivyFulltextError::Key(KeyDecodeError::NotI64))
  ));
  assert!(matches!(
    opened(invalid).uuid(),
    Err(TantivyFulltextError::Key(KeyDecodeError::NotUuid))
  ));

  // An address with MORE columns than the key reads — what `finish` turns into `Trailing`.
  let mut read = opened(sealed(|w| {
    w.i64(1);
    w.i64(2);
  }));
  assert_eq!(read.i64().expect("the first column"), 1);
  assert!(matches!(
    read.finish(),
    Err(TantivyFulltextError::Key(KeyDecodeError::Trailing))
  ));
}

/// The query string may name `body` and nothing else — the guard that keeps the stored address from
/// being an existence probe for any row.
///
/// Every shape a field name can hide in is here: a bare literal, a nested boolean clause, a boost, a
/// range, a set, and an `exists`. A check that looked only at the top level would pass the second of
/// them, which is the shape an attacker writes.
#[test]
fn a_query_naming_an_unsearchable_field_is_refused() {
  let (_dir, store) = open_store();
  let captions = store.fulltext(Caption::SLOT.as_ref());
  commit(
    &store,
    &captions,
    &[caption("m1", 1, "the quick brown fox")],
  );

  for (query, field) in [
    ("key:AAAA", "key"),
    ("body:fox AND key:AAAA", "key"),
    ("(body:fox OR identity:AAAA)", "identity"),
    ("key:AAAA^2", "key"),
    ("key:[a TO b]", "key"),
    ("key:IN [a b]", "key"),
    ("key:*", "key"),
    ("source:captions", "source"),
  ] {
    match search(&store, &captions, query) {
      Err(TantivyFulltextError::UnsearchableField { field: named }) => {
        assert_eq!(named, field, "{query}")
      }
      other => panic!("{query} must be refused, got {other:?}"),
    }
  }

  // The two admitted shapes: the bare form, which resolves against the default field, and the
  // explicit name of the one field that IS searchable.
  assert_eq!(search(&store, &captions, "fox").expect("bare").len(), 1);
  assert_eq!(
    search(&store, &captions, "body:fox").expect("named").len(),
    1
  );
}

/// A handle refuses ANOTHER slot's write capability, and refuses it before either in-memory side
/// effect — so the writer it was handed carries nothing away.
///
/// Every slot's schema is structurally identical, which is what makes this silent without the
/// check: the document would land in the writer's index, and the handle's own slot would stay empty.
#[test]
fn a_handle_refuses_another_slot_s_writer() {
  let (_dir, store) = open_store();
  let captions = store.fulltext(Caption::SLOT.as_ref());
  let transcripts = store.fulltext("transcripts");

  let mut writer = store
    .writer(transcripts.slot(), HEAP)
    .expect("the slot's writer opens");
  let refused = block_on(captions.upsert(
    Connected::new(&store, &mut writer),
    entry(&caption("m1", 1, "alpha")),
  ))
  .expect_err("a mispaired writer is refused");

  match &refused {
    TantivyFulltextError::SlotMismatch(mismatch) => {
      assert_eq!(mismatch.handle(), "captions");
      assert_eq!(mismatch.writer(), "transcripts");
    }
    other => panic!("expected a slot mismatch, got {other:?}"),
  }

  writer.commit().expect("the empty batch commits");
  drop(writer);
  store
    .reload(transcripts.slot())
    .expect("the slot's reader reloads");
  assert_eq!(
    live_documents(&store, transcripts.slot()),
    0,
    "a refused pairing must queue nothing"
  );
}

/// A slot NAMES a directory under the store root, so an unchecked one is a path-traversal surface —
/// and it is also every other backend's resource name, so a rule of this backend's own would fork
/// the vocabulary. Both are answered by the crate's ONE identifier rule, refused with a typed error
/// by every verb that resolves a slot, BEFORE the name reaches the filesystem.
#[test]
fn a_slot_that_is_not_an_identifier_creates_nothing() {
  let dir = tempfile::tempdir().expect("a temporary directory");
  // The root is NESTED inside the tempdir, so a slot that escaped it would land somewhere this test
  // can still look at.
  let root = dir.path().join("root");
  let store = TantivyStore::open(&root).expect("the store opens");

  for slot in ["../escape", "with space", "", "a/b", "9leading"] {
    assert!(
      matches!(
        store.writer(slot, HEAP),
        Err(TantivyFulltextError::InvalidSlot(_))
      ),
      "{slot:?} must not mint a writer"
    );
    assert!(
      matches!(
        store.reload(slot),
        Err(TantivyFulltextError::InvalidSlot(_))
      ),
      "{slot:?} must not reload"
    );
    assert!(
      matches!(
        search(&store, &store.fulltext(slot), "fox"),
        Err(TantivyFulltextError::InvalidSlot(_))
      ),
      "{slot:?} must not search"
    );
  }

  assert!(!dir.path().join("escape").exists());
  assert_eq!(
    std::fs::read_dir(&root)
      .expect("the root is readable")
      .count(),
    0,
    "a refused slot must create no directory"
  );
}

/// The read scope's one knob is a CEILING on hits: a limit below the match count truncates by rank
/// rather than failing, and the type is what keeps a zero from reaching the engine's own assertion.
#[test]
fn the_limit_is_a_ceiling_on_hits() {
  let (_dir, store) = open_store();
  let captions = store.fulltext(Caption::SLOT.as_ref());
  commit(
    &store,
    &captions,
    &[
      caption("m1", 1, "fox fox fox fox"),
      caption("m2", 2, "fox alpha beta gamma"),
    ],
  );

  let one = keyed::<TantivyFulltext, CaptionKey>(
    block_on(captions.search(
      Connected::new(&store, ()),
      FulltextSubset::All,
      "fox",
      NonZeroUsize::new(1).expect("1 is not zero"),
      None,
    ))
    .expect("the search runs"),
  )
  .expect("the addresses read back");

  assert_eq!(one.len(), 1);
  // The one kept is the highest-ranked, not an arbitrary member: the collector orders by score.
  assert_eq!(ranking(&one), ["m1"]);
  assert_eq!(
    search(&store, &captions, "fox")
      .expect("the default limit")
      .len(),
    2
  );
}

/// THE SHIPPED VOCABULARY, CROSSING THIS ENGINE — every [`Field`] row `store::field` ships, run
/// through the shipped engine's own three phases, and the two properties the codec exists for read
/// back.
///
/// A compiler-instantiated bound can say a member HAS a row; it cannot say the row is right. These
/// are that other half, and the two are different questions — a member whose read took the wrong
/// width would satisfy any bound and fail here.
///
/// It is also the pairing this file inherited when `store::tantivy`'s own row block died. That block
/// had a SHIPPED-PARITY AUDIT closing it, whose obligation was *this crate's engine pairs this
/// crate's vocabulary*; a row that names no engine cannot fail that, so what is left to check is the
/// only thing that was ever checkable by a test: the ROUND TRIP, at the engine that stores it.
mod vocabulary {
  extern crate alloc;

  use super::{
    ColumnReader, Field, FulltextEngine, KeyDecodeError, TantivyFulltext, TantivyFulltextError,
  };

  /// Row in, row out, and assert the value survived — the only property an address has to have.
  ///
  /// The walk is the framework's, spelled out: `buffer` → the row's own `write` → `finalize`, then
  /// `open` → the row's own `read` → `finish`. So what this exercises is the path a real retrieve
  /// takes and not a shortcut through the codec.
  fn round_trip<K>(value: K) -> Vec<u8>
  where
    K: Field + PartialEq + core::fmt::Debug,
  {
    let mut buf = TantivyFulltext::buffer();
    value.write(&mut buf);
    let bytes = TantivyFulltext::finalize(buf).into_bytes();

    let mut read = TantivyFulltext::open(bytes.clone().into());
    assert_eq!(K::read(&mut read).expect("the address reads back"), value);
    read
      .finish()
      .expect("and one member reads exactly one column");
    bytes
  }

  #[test]
  fn every_integer_width_round_trips_at_its_own_width() {
    for value in [i8::MIN, -1, 0, 1, i8::MAX] {
      round_trip(value);
    }
    round_trip(i128::MIN);
    round_trip(u128::MAX);
    round_trip(0_u8);
    round_trip(u64::MAX);
    // Four bytes of body behind the four-byte prefix — the width is the TYPE's, not widened to the
    // codec's `i64` column, which is what makes every decode total.
    assert_eq!(round_trip(7_u32).len(), 4 + 4);
    assert_eq!(round_trip(7_u64).len(), 4 + 8);
  }

  /// A `NonZero*` is TRANSPARENT: the same bytes the integer inside it writes, so the two address
  /// one document. The law `store::fs`'s rendering states for the same pair in its own alphabet.
  #[test]
  fn a_nonzero_writes_the_address_its_integer_writes() {
    let bare = round_trip(7_u64);
    let wrapped = round_trip(core::num::NonZeroU64::new(7).expect("7 is not zero"));
    assert_eq!(bare, wrapped);
  }

  /// And the narrowing happens on the way OUT, which is the one address that is well-formed and
  /// inadmissible.
  ///
  /// The refusal is the ROW's — an engine-blind row has only [`ColumnError::domain`] to raise — and
  /// the ARM is this engine's, because [`TantivyFulltextError`] overrides that method onto the arm
  /// its retired per-engine row raised. A defaulted `domain` would land in `Column` instead, which
  /// is exactly what this assertion refuses.
  ///
  /// [`ColumnError::domain`]: crate::ColumnError::domain
  #[test]
  fn a_zero_is_not_a_nonzero_and_the_address_says_so() {
    let mut buf = TantivyFulltext::buffer();
    0_u64.write(&mut buf);
    let mut read = TantivyFulltext::open(TantivyFulltext::finalize(buf));
    assert!(matches!(
      <core::num::NonZeroU64 as Field>::read(&mut read),
      Err(TantivyFulltextError::Key(KeyDecodeError::Domain)),
    ));
  }

  /// A value of the wrong width is refused rather than read as something else — the arm the whole
  /// fixed-width half of the vocabulary shares.
  #[test]
  fn an_address_of_another_width_is_not_this_value() {
    let mut read = TantivyFulltext::open(round_trip(7_u64).into());
    assert!(
      matches!(
        <u32 as Field>::read(&mut read),
        Err(TantivyFulltextError::Key(KeyDecodeError::Width)),
      ),
      "eight bytes are not a `u32`",
    );
  }

  /// A row that reads its arms apart BY WIDTH raises [`ColumnError::width`], which this engine also
  /// overrides — so an untagged network enum handed a width outside its set refuses in the same arm
  /// it always did rather than in the open floor.
  ///
  /// [`ColumnError::width`]: crate::ColumnError::width
  #[test]
  fn a_width_outside_an_untagged_enums_set_is_the_engines_own_arm() {
    let mut read = TantivyFulltext::open(round_trip(7_u64).into());
    assert!(matches!(
      <core::net::IpAddr as Field>::read(&mut read),
      Err(TantivyFulltextError::Key(KeyDecodeError::Width)),
    ));
  }

  /// INJECTIVITY over the case a separator scheme cannot make injective: two column sequences that
  /// concatenate alike still render two addresses, because each column carries its own length.
  #[test]
  fn two_value_sequences_never_render_one_address() {
    let split = |a: &str, b: &str| {
      let mut buf = TantivyFulltext::buffer();
      a.to_owned().write(&mut buf);
      b.to_owned().write(&mut buf);
      TantivyFulltext::finalize(buf).into_bytes()
    };
    assert_ne!(split("ab", "c"), split("a", "bc"));
  }

  #[test]
  fn the_uuid_member_rides_its_sixteen_bytes() {
    assert_eq!(round_trip(uuid::Uuid::from_u128(7)).len(), 4 + 16);
  }

  /// The network family, each as its own octets — and the two ENUM members untagged, which is only
  /// injective because their arms have different widths.
  #[test]
  fn the_network_family_rides_its_octets() {
    let v4 = core::net::Ipv4Addr::new(10, 0, 0, 1);
    let v6 = core::net::Ipv6Addr::LOCALHOST;
    assert_eq!(round_trip(v4).len(), 4 + 4);
    assert_eq!(round_trip(v6).len(), 4 + 16);
    assert_eq!(round_trip(core::net::IpAddr::V4(v4)).len(), 4 + 4);
    assert_eq!(round_trip(core::net::IpAddr::V6(v6)).len(), 4 + 16);

    let socket_v4 = core::net::SocketAddrV4::new(v4, 8080);
    // The two fields BEYOND the obvious pair are part of a v6 socket's identity, so both ride.
    let socket_v6 = core::net::SocketAddrV6::new(v6, 8080, 3, 5);
    assert_eq!(round_trip(socket_v4).len(), 4 + 6);
    assert_eq!(round_trip(socket_v6).len(), 4 + 26);
    assert_eq!(
      round_trip(core::net::SocketAddr::V4(socket_v4)).len(),
      4 + 6
    );
    assert_eq!(
      round_trip(core::net::SocketAddr::V6(socket_v6)).len(),
      4 + 26
    );
    assert_ne!(
      round_trip(core::net::SocketAddrV6::new(v6, 8080, 3, 5)),
      round_trip(core::net::SocketAddrV6::new(v6, 8080, 3, 6)),
      "the scope id is identity, not decoration",
    );
  }

  /// The five GENERIC rows, each transparent to what it holds — and a `TypedId`'s entity marker
  /// reaching no byte, which is the type's own stated law.
  #[test]
  fn the_generic_rows_are_transparent_to_what_they_hold() {
    struct Scene;

    let bare = round_trip(7_u64);
    assert_eq!(round_trip(alloc::sync::Arc::new(7_u64)), bare);
    assert_eq!(round_trip(alloc::boxed::Box::new(7_u64)), bare);
    assert_eq!(round_trip([1_u8, 2, 3, 4]).len(), 4 + 4);
    assert_eq!(
      round_trip(crate::TypedId::<u64, Scene>::new(7)),
      bare,
      "storage sees only `I`",
    );
  }
}

/// THE LAYERING, BUILT: a write LANE that implements the socket by CALLING the engine.
///
/// `AsyncLands::land` and `FulltextWrite::upsert` are one write at two layers, and this is the only
/// shape in which a node's items reach an index — the socket's impl is where the engine verb is
/// called, and there is no second write verb at either layer. What each answers is what makes the
/// pair irreducible: the socket answers *which of these items are durable*, positionally, over a
/// batch; the engine answers *this entry is written*, over one entry the emission built.
///
/// It is written HERE and not in the framework because the write SCOPE is concrete here. A generic
/// lane would have to reborrow `E::WriteContext<'_>` once per item, and a GAT projection over an
/// unknown backend has no reborrow — see [`AsyncLands`]'s own note for the measurement. `&mut *writer`
/// below is that reborrow, spelled at the one layer that can spell it.
mod layering {
  use super::{
    Caption, Connected, HEAP, TantivyFulltext, TantivyFulltextError, TantivyStore, block_on,
    caption, entry, open_store, search,
  };
  use crate::{AsyncLands, Commit, FulltextStore, FulltextTable, Lands, SlotHandle, SlotWriter};

  /// The lane: the BRANDED engine handle, the connection it reaches through, and the write
  /// capability the batch is queued into. All three concrete, which is what lets the reborrow be
  /// written.
  ///
  /// `SlotHandle<TantivyFulltext, Caption>` is the brand doing its work at the site that matters:
  /// this lane implements `AsyncLands<Caption>`, so the handle it holds must be `Caption`'s. Handing the
  /// constructor another declaration's handle is `E0308` naming both, which is what the trybuild
  /// fixture pins from outside the crate.
  struct Captions<'a> {
    connection: &'a TantivyStore,
    slot: SlotHandle<TantivyFulltext, Caption>,
    writer: SlotWriter,
  }

  impl Captions<'_> {
    /// THE WHOLE WRITE, and it never awaits.
    ///
    /// Written once and worn by both faces below, which is the honesty this lane exists to show:
    /// tantivy's writer is a blocking machine, so the ASYNC socket is this same body in a coat —
    /// `ready(…)` around an answer that was already complete. A pool-backed lane cannot be written
    /// this way round, and that asymmetry is the whole of why the write axis has two traits and the
    /// grammar refuses neither.
    fn landed(&mut self, items: &[Caption]) -> Commit<TantivyFulltextError> {
      let queued = items.iter().try_for_each(|record| {
        // THE CALL. The socket's body is the engine's verb, per item, through a fresh reborrow of
        // the ONE write scope this lane owns — which is what serializes the keyed replace's
        // non-atomic pair. `&mut self.writer` inside a closure over `&mut self` is the reborrow, and
        // it is expressible only because the scope type is concrete here.
        block_on(self.slot.upsert_document(
          Connected::new(self.connection, &mut self.writer),
          entry(record),
        ))
      });
      // A batch's durability is the COMMIT's, so nothing is reported committed before it lands —
      // the socket's own law (a `Commit` is a POSITIVE set) meeting the engine's (visibility waits
      // on the caller's commit). A mid-batch refusal rolls back, because a keyed replace that
      // failed between its delete and its add would otherwise commit a tombstone with no
      // replacement.
      let landed = queued
        .and_then(|()| self.writer.commit().map(drop))
        .inspect_err(|_| {
          let _ = self.writer.rollback();
        });
      match landed {
        Ok(()) => Commit::all(),
        Err(refusal) => Commit::none(refusal),
      }
    }
  }

  impl AsyncLands<Caption> for Captions<'_> {
    type Error = TantivyFulltextError;

    fn land(&mut self, items: &[Caption]) -> impl Future<Output = Commit<Self::Error>> + Send {
      core::future::ready(self.landed(items))
    }
  }

  /// THE HONESTY SWEEP, at the one shipped engine that can answer it.
  ///
  /// A `block`, `spawn` or `rayon` poll entry reaches its granted store through this family, and
  /// whether a given store HAS the family is the engine's own fact — which is why the grammar
  /// decides nothing about it and the type layer adjudicates at the line that reached. Tantivy's
  /// does: nothing above yields, so a sync tick can write here with no runtime anywhere near it.
  ///
  /// An sqlx-backed lane implements only the async face and MUST, because its engine is async to the
  /// bottom. `ingraph-derive`'s `tests/mount_bounds/` pins what a sync body reaching for one earns.
  impl Lands<Caption> for Captions<'_> {
    type Error = TantivyFulltextError;

    fn land(&mut self, items: &[Caption]) -> Commit<Self::Error> {
      self.landed(items)
    }
  }

  /// One socket call writes the whole batch through the engine, and the index reads it back.
  ///
  /// The call is SPELLED OUT, and that is the double-name measurement showing up in this crate's own
  /// code: this lane implements both faces, both are imported in this module, so `lane.land(…)` is
  /// `E0034` naming the two candidates. It is a good refusal — it fires exactly where a lane really
  /// has two roads and the caller has not said which — and disambiguating is one word.
  #[test]
  fn the_socket_writes_through_the_engine() {
    let (_dir, store) = open_store();
    let engine = FulltextStore::fulltext(&store, Caption::SLOT.as_ref());
    let writer = store
      .writer(engine.slot(), HEAP)
      .expect("the slot's writer opens");
    let batch = [
      caption("m1", 1, "the quick brown fox"),
      caption("m2", 2, "a slow fox"),
    ];

    let commit = {
      let mut lane = Captions {
        connection: &store,
        slot: SlotHandle::mint(engine.clone()),
        writer,
      };
      block_on(AsyncLands::land(&mut lane, &batch))
    };

    assert!(commit.committed(0) && commit.committed(1));
    assert!(commit.refusal().is_none());
    store.reload(engine.slot()).expect("the reader reloads");
    assert_eq!(
      search(&store, &engine, "fox")
        .expect("the search runs")
        .len(),
      2,
      "every item the socket reported went through the engine",
    );
  }

  /// THE BLOCKING FACE writes the same batch, with no runtime anywhere.
  ///
  /// What a `block`, `spawn` or `rayon` poll entry actually does when its grant reaches this store —
  /// no `block_on`, no driver, nothing to await. The async walk above and this one go through the
  /// same body, which is the claim: on this engine the two faces are one write seen from two worlds.
  #[test]
  fn the_blocking_socket_writes_through_the_same_engine() {
    let (_dir, store) = open_store();
    let engine = FulltextStore::fulltext(&store, Caption::SLOT.as_ref());
    let writer = store
      .writer(engine.slot(), HEAP)
      .expect("the slot's writer opens");
    let batch = [caption("m1", 1, "the quick brown fox")];

    let commit = {
      let mut lane = Captions {
        connection: &store,
        slot: SlotHandle::mint(engine.clone()),
        writer,
      };
      Lands::land(&mut lane, &batch)
    };

    assert!(commit.committed(0));
    assert!(commit.refusal().is_none());
    store.reload(engine.slot()).expect("the reader reloads");
    assert_eq!(
      search(&store, &engine, "fox")
        .expect("the search runs")
        .len(),
      1,
      "the sync socket reached the engine too",
    );
  }

  /// A lane that is handed ANOTHER slot's writer reports NOTHING committed, and the refusal is the
  /// engine's own — which is the layering read from the failure side: the socket does not invent a
  /// verdict, it relays the engine's.
  ///
  /// MUTATION-CHECKED: a `land` that answers `Commit::all()` without consulting the engine — a
  /// socket that has become a SECOND write verb rather than a layer over the first — turns this red
  /// on `!commit.committed(0)`.
  #[test]
  fn a_refused_engine_write_is_a_refused_socket_call() {
    let (_dir, store) = open_store();
    let engine = FulltextStore::fulltext(&store, Caption::SLOT.as_ref());
    let writer = store
      .writer("elsewhere", HEAP)
      .expect("the other slot's writer opens");

    let mut lane = Captions {
      connection: &store,
      slot: SlotHandle::mint(engine),
      writer,
    };
    let commit = block_on(AsyncLands::land(
      &mut lane,
      &[caption("m1", 1, "the quick brown fox")],
    ));

    assert!(!commit.committed(0));
    assert!(matches!(
      commit.refusal(),
      Some(TantivyFulltextError::SlotMismatch(_))
    ));
  }
}