pigeonhole-db 1.2.2 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. checksums.yaml +4 -4
  2. data/Cargo.lock +16 -16
  3. data/Cargo.toml +5 -5
  4. data/lib/pigeonhole/version.rb +1 -1
  5. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/io-event-1.22.3/IO_Event.so +0 -0
  6. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/io-event-1.22.3/gem_make.out +6 -6
  7. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/io-event-1.22.3/mkmf.log +26 -26
  8. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/json-3.1.0/gem_make.out +6 -6
  9. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/json-3.1.0/json/ext/generator.so +0 -0
  10. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/json-3.1.0/json/ext/parser.so +0 -0
  11. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/json-3.1.0/mkmf.log +19 -19
  12. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/prism-1.9.0/gem_make.out +9 -9
  13. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/prism-1.9.0/mkmf.log +6 -6
  14. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/prism-1.9.0/prism/prism.so +0 -0
  15. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/rbs-4.2.0/gem_make.out +6 -6
  16. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/rbs-4.2.0/mkmf.log +7 -7
  17. data/vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/rbs-4.2.0/rbs_extension.so +0 -0
  18. data/vendor/bundle/ruby/3.4.0/gems/io-event-1.22.3/ext/Makefile +3 -3
  19. data/vendor/bundle/ruby/3.4.0/gems/io-event-1.22.3/lib/IO_Event.so +0 -0
  20. data/vendor/bundle/ruby/3.4.0/gems/json-3.1.0/ext/json/ext/generator/Makefile +3 -3
  21. data/vendor/bundle/ruby/3.4.0/gems/json-3.1.0/ext/json/ext/parser/Makefile +3 -3
  22. data/vendor/bundle/ruby/3.4.0/gems/json-3.1.0/lib/json/ext/generator.so +0 -0
  23. data/vendor/bundle/ruby/3.4.0/gems/json-3.1.0/lib/json/ext/parser.so +0 -0
  24. data/vendor/bundle/ruby/3.4.0/gems/prism-1.9.0/ext/prism/Makefile +3 -3
  25. data/vendor/bundle/ruby/3.4.0/gems/prism-1.9.0/lib/prism/prism.so +0 -0
  26. data/vendor/bundle/ruby/3.4.0/gems/rbs-4.2.0/ext/rbs_extension/Makefile +3 -3
  27. data/vendor/bundle/ruby/3.4.0/gems/rbs-4.2.0/lib/rbs_extension.so +0 -0
  28. data/vendor/cache/Cargo.toml +2 -2
  29. data/vendor/cache/src/lib.rs +37 -0
  30. data/vendor/cache/src/loom_tests.rs +32 -0
  31. data/vendor/cache/src/s3fifo.rs +239 -11
  32. data/vendor/cache/src/sync.rs +4 -4
  33. data/vendor/compaction/Cargo.toml +6 -6
  34. data/vendor/compaction/src/cursor.rs +86 -4
  35. data/vendor/compaction/src/job.rs +24 -2
  36. data/vendor/engine/Cargo.toml +11 -11
  37. data/vendor/engine/src/admission.rs +3 -1
  38. data/vendor/engine/src/catalog.rs +39 -4
  39. data/vendor/engine/src/check.rs +59 -20
  40. data/vendor/engine/src/compact.rs +2 -2
  41. data/vendor/engine/src/engine/hooks.rs +144 -2
  42. data/vendor/engine/src/engine/info.rs +6 -0
  43. data/vendor/engine/src/engine.rs +1492 -50
  44. data/vendor/engine/src/external_registry.rs +447 -0
  45. data/vendor/engine/src/feed.rs +313 -84
  46. data/vendor/engine/src/feed_reader/catalog.rs +490 -0
  47. data/vendor/engine/src/feed_reader/history.rs +236 -0
  48. data/vendor/engine/src/feed_reader/read_ahead.rs +241 -0
  49. data/vendor/engine/src/feed_reader/token.rs +232 -0
  50. data/vendor/engine/src/feed_reader.rs +970 -852
  51. data/vendor/engine/src/feed_stop_loom.rs +73 -0
  52. data/vendor/engine/src/flush.rs +29 -4
  53. data/vendor/engine/src/io_count.rs +190 -0
  54. data/vendor/engine/src/large.rs +4 -1
  55. data/vendor/engine/src/lib.rs +16 -2
  56. data/vendor/engine/src/maintenance.rs +2 -2
  57. data/vendor/engine/src/manifest.rs +38 -6
  58. data/vendor/engine/src/nonblocking.rs +3 -3
  59. data/vendor/engine/src/options.rs +26 -0
  60. data/vendor/engine/src/punch.rs +282 -0
  61. data/vendor/engine/src/range_copy.rs +365 -0
  62. data/vendor/engine/src/read/keys.rs +37 -5
  63. data/vendor/engine/src/read/reduce.rs +1 -0
  64. data/vendor/engine/src/read.rs +7 -0
  65. data/vendor/engine/src/row_cache.rs +24 -0
  66. data/vendor/engine/src/shard/tablets.rs +127 -31
  67. data/vendor/engine/src/shard.rs +1006 -33
  68. data/vendor/engine/src/source.rs +105 -12
  69. data/vendor/engine/src/write.rs +310 -4
  70. data/vendor/format/Cargo.toml +1 -1
  71. data/vendor/format/src/shm.rs +10 -0
  72. data/vendor/format/src/superblock.rs +9 -2
  73. data/vendor/format/src/wal.rs +818 -16
  74. data/vendor/io/Cargo.toml +3 -3
  75. data/vendor/io/src/count.rs +76 -0
  76. data/vendor/io/src/file.rs +70 -0
  77. data/vendor/io/src/lib.rs +2 -0
  78. data/vendor/io/src/os/unix.rs +124 -0
  79. data/vendor/io/src/os/windows.rs +51 -0
  80. data/vendor/io/src/pread.rs +26 -0
  81. data/vendor/io/src/sim.rs +81 -9
  82. data/vendor/io/src/sys.rs +53 -0
  83. data/vendor/io/src/uring.rs +28 -0
  84. data/vendor/io/src/vfs.rs +4 -0
  85. data/vendor/memory/Cargo.toml +4 -4
  86. data/vendor/memory/src/hooks.rs +6 -0
  87. data/vendor/memory/src/ivf.rs +67 -1
  88. data/vendor/memory/src/lib.rs +4 -1
  89. data/vendor/memory/src/recall/pool.rs +872 -0
  90. data/vendor/memory/src/recall.rs +351 -273
  91. data/vendor/memory/src/store.rs +15 -0
  92. data/vendor/memtable/Cargo.toml +3 -3
  93. data/vendor/pager/Cargo.toml +3 -3
  94. data/vendor/pager/src/alloc.rs +430 -0
  95. data/vendor/pager/src/lib.rs +114 -0
  96. data/vendor/pigeonhole/Cargo.toml +6 -5
  97. data/vendor/pigeonhole/src/db.rs +91 -2
  98. data/vendor/pigeonhole/src/error.rs +2 -1
  99. data/vendor/pigeonhole/src/feed.rs +210 -6
  100. data/vendor/pigeonhole/src/lib.rs +3 -0
  101. data/vendor/pigeonhole/src/metrics.rs +37 -0
  102. data/vendor/pigeonhole/src/nonblocking.rs +94 -111
  103. data/vendor/pigeonhole/src/options.rs +69 -0
  104. data/vendor/pigeonhole/src/replication.rs +601 -11
  105. data/vendor/pigeonhole/src/write.rs +81 -0
  106. data/vendor/runtime/Cargo.toml +2 -2
  107. data/vendor/shm/Cargo.toml +3 -3
  108. data/vendor/shm/src/region.rs +20 -2
  109. data/vendor/sst/Cargo.toml +4 -4
  110. data/vendor/sst/src/blob.rs +85 -7
  111. data/vendor/sst/src/iter.rs +98 -2
  112. data/vendor/sst/src/lib.rs +11 -2
  113. data/vendor/sst/src/writer.rs +12 -2
  114. data/vendor/text/Cargo.toml +2 -2
  115. data/vendor/text/src/block.rs +638 -0
  116. data/vendor/text/src/error.rs +8 -3
  117. data/vendor/text/src/fuzzy.rs +1 -1
  118. data/vendor/text/src/index.rs +1055 -80
  119. data/vendor/text/src/layout.rs +63 -2
  120. data/vendor/text/src/lib.rs +5 -1
  121. data/vendor/text/src/maxscore.rs +481 -94
  122. data/vendor/text/src/merged.rs +470 -0
  123. data/vendor/text/src/search.rs +1278 -341
  124. data/vendor/text/src/stats.rs +431 -0
  125. data/vendor/vector/Cargo.toml +2 -2
  126. data/vendor/vector/src/hooks.rs +33 -4
  127. data/vendor/vector/src/index.rs +498 -69
  128. data/vendor/wal/Cargo.toml +3 -3
  129. data/vendor/wal/src/feed.rs +313 -19
  130. data/vendor/wal/src/recovery.rs +31 -1
  131. data/vendor/wal/src/stream.rs +28 -0
  132. metadata +15 -1
@@ -31,6 +31,7 @@
31
31
 
32
32
  use std::cmp::Ordering;
33
33
  use std::collections::{BTreeMap, BinaryHeap};
34
+ use std::marker::PhantomData;
34
35
  use std::task::Poll;
35
36
 
36
37
  use pigeonhole::{CellEntry, RowCells, Snapshot};
@@ -39,6 +40,7 @@ use crate::index::Rows;
39
40
 
40
41
  use crate::error::{Result, corrupt};
41
42
  use crate::layout::*;
43
+ use crate::merged::{Merged, Side, Tier};
42
44
 
43
45
  /// A point read's cost in posting steps (perf287's ski-rental rule, #1368): measured at
44
46
  /// 100,000 documents on a laptop, on one hub term's posting row (67,972 postings), a
@@ -49,7 +51,7 @@ use crate::layout::*;
49
51
  /// real index switches to advancing a little late, never early. A modestly wrong value
50
52
  /// costs a constant factor (ski-rental's bound assumes the price is right; one off by a
51
53
  /// factor `f` costs up to about `f` times more, perf287 on #1377).
52
- const LOOKUP_IN_STEPS: u64 = 14;
54
+ pub(crate) const LOOKUP_IN_STEPS: u64 = 14;
53
55
 
54
56
  /// [`LOOKUP_IN_STEPS`] as a step budget's charge for a point read (#1560).
55
57
  #[cfg(feature = "async")]
@@ -120,6 +122,7 @@ pub(crate) trait Reads {
120
122
  fn seek<'c>(
121
123
  cells: &'c mut RowCells<'_>,
122
124
  cx: &mut Self::Cx<'_, '_>,
125
+ family: &str,
123
126
  doc: &[u8],
124
127
  ) -> Poll<pigeonhole::Result<Option<CellEntry<'c>>>>;
125
128
 
@@ -138,10 +141,11 @@ pub(crate) trait Reads {
138
141
  /// #1560: `cells.next()?` with nothing between it and the posting's use. Through
139
142
  /// [`Reads::next`] the entry came back wrapped in `Poll` and was copied on every posting
140
143
  /// (`memcpy`, #1560's profile).
141
- fn skip_while<'t>(
142
- w: &mut Walk<'t, Self>,
144
+ fn skip_while<'t, L: Layout>(
145
+ w: &mut Walk<'t, Self, L>,
143
146
  bm: &Bm25,
144
147
  cx: &mut Self::Cx<'_, '_>,
148
+ floor: f64,
145
149
  skip: impl Fn(&[u8]) -> bool,
146
150
  ) -> Poll<Result<()>>
147
151
  where
@@ -155,7 +159,16 @@ pub(crate) trait Reads {
155
159
  w.stepped += 1;
156
160
  match e {
157
161
  Some(e) if skip(e.qualifier) => continue,
158
- e => return Poll::Ready(Walk::<Self>::hold(&mut w.cur, w.weight, bm, e)),
162
+ e => {
163
+ if let Err(e) = Walk::<Self, L>::hold(&mut w.cur, w.weight, bm, e) {
164
+ return Poll::Ready(Err(e));
165
+ }
166
+ // A posting under the walk's floor can't matter ([`Walk::floor`]).
167
+ if w.cur.get().is_some_and(|(_, c)| under(c, floor)) {
168
+ continue;
169
+ }
170
+ return Poll::Ready(Ok(()));
171
+ }
159
172
  }
160
173
  }
161
174
  }
@@ -191,6 +204,7 @@ impl Reads for Blocking {
191
204
  fn seek<'c>(
192
205
  _: &'c mut RowCells<'_>,
193
206
  (): &mut (),
207
+ _: &str,
194
208
  _: &[u8],
195
209
  ) -> Poll<pigeonhole::Result<Option<CellEntry<'c>>>> {
196
210
  unreachable!("a sync walk skips by stepping")
@@ -209,10 +223,11 @@ impl Reads for Blocking {
209
223
  }
210
224
 
211
225
  #[inline(always)]
212
- fn skip_while<'t>(
213
- w: &mut Walk<'t, Self>,
226
+ fn skip_while<'t, L: Layout>(
227
+ w: &mut Walk<'t, Self, L>,
214
228
  bm: &Bm25,
215
229
  (): &mut (),
230
+ floor: f64,
216
231
  skip: impl Fn(&[u8]) -> bool,
217
232
  ) -> Poll<Result<()>> {
218
233
  Poll::Ready(loop {
@@ -221,7 +236,7 @@ impl Reads for Blocking {
221
236
  Ok(e) => e,
222
237
  Err(e) => break Err(e.into()),
223
238
  }) else {
224
- w.cur = None;
239
+ w.cur.clear();
225
240
  break Ok(());
226
241
  };
227
242
  if skip(e.qualifier) {
@@ -232,10 +247,13 @@ impl Reads for Blocking {
232
247
  None => break Err(corrupt("a posting isn't a u64")),
233
248
  };
234
249
  let (tf, len) = unposting(posting);
235
- w.cur = Some((
236
- e.qualifier.to_vec(),
237
- w.weight * bm.tf_factor(f64::from(tf), f64::from(len)),
238
- ));
250
+ let here = w.weight * bm.tf_factor(f64::from(tf), f64::from(len));
251
+ // A posting under the walk's floor can't matter ([`Walk::floor`]): passed
252
+ // without a copy of its document.
253
+ if under(here, floor) {
254
+ continue;
255
+ }
256
+ w.cur.set(e.qualifier, here);
239
257
  break Ok(());
240
258
  })
241
259
  }
@@ -331,9 +349,10 @@ impl Reads for Nonblocking {
331
349
  fn seek<'c>(
332
350
  cells: &'c mut RowCells<'_>,
333
351
  cx: &mut Polling<'_, '_>,
352
+ family: &str,
334
353
  doc: &[u8],
335
354
  ) -> Poll<pigeonhole::Result<Option<CellEntry<'c>>>> {
336
- cells.poll_seek(cx.cx, POST, doc)
355
+ cells.poll_seek(cx.cx, family, doc)
337
356
  }
338
357
 
339
358
  fn get(
@@ -371,7 +390,127 @@ impl Reads for Nonblocking {
371
390
 
372
391
  /// A term's posting row, walked in document order. A posting contributes
373
392
  /// `weight · tf_factor`: the weight is the term's idf, times its boost in a fuzzy clause.
374
- pub(crate) struct Walk<'t, R: Reads> {
393
+ /// Whether a contribution is under `floor`, with the bounds' slack: the test
394
+ /// [`Scored::drop_below`] applies to an expansion's bound, applied to one posting.
395
+ #[inline(always)]
396
+ pub(crate) fn under(here: f64, floor: f64) -> bool {
397
+ here * (1.0 + SLACK) < floor
398
+ }
399
+
400
+ /// The posting a walk, or a fuzzy clause, stands on: its document and contribution there.
401
+ ///
402
+ /// The document's buffer is reused from one posting to the next (#1585): a `Vec` per posting
403
+ /// was 7% of a hub-term search's instructions in the allocator alone (the callgrind split of
404
+ /// `text-term-hub`, run 43979031087).
405
+ #[derive(Default)]
406
+ pub(crate) struct Cur {
407
+ doc: Vec<u8>,
408
+ here: f64,
409
+ /// Whether it stands on a posting: `doc` and `here` are stale otherwise.
410
+ on: bool,
411
+ }
412
+
413
+ impl Cur {
414
+ #[inline(always)]
415
+ fn set(&mut self, doc: &[u8], here: f64) {
416
+ self.doc.clear();
417
+ self.doc.extend_from_slice(doc);
418
+ self.here = here;
419
+ self.on = true;
420
+ }
421
+
422
+ #[inline(always)]
423
+ fn clear(&mut self) {
424
+ self.on = false;
425
+ }
426
+
427
+ #[inline(always)]
428
+ fn doc(&self) -> Option<&[u8]> {
429
+ if self.on {
430
+ Some(self.doc.as_slice())
431
+ } else {
432
+ None
433
+ }
434
+ }
435
+
436
+ #[inline(always)]
437
+ fn get(&self) -> Option<(&[u8], f64)> {
438
+ if self.on {
439
+ Some((self.doc.as_slice(), self.here))
440
+ } else {
441
+ None
442
+ }
443
+ }
444
+
445
+ /// The contribution where it stands, 0 off the end.
446
+ #[inline(always)]
447
+ fn here(&self) -> f64 {
448
+ if self.on { self.here } else { 0.0 }
449
+ }
450
+ }
451
+
452
+ /// Which index layout a search's walks read (#1585), as a type: the walk, the clauses and
453
+ /// the document loop are compiled once for each, so a version 1 index's search is the code
454
+ /// it was before version 2 existed, with no test of the layout anywhere in it (a test per
455
+ /// lookup cost the fuzzy shape 0.7% in callgrind).
456
+ pub(crate) trait Layout {
457
+ /// Whether the walk merges blocks under its cells.
458
+ const MERGED: bool;
459
+ /// The walk's block tier: nothing in a version 1 index.
460
+ type Blocks<'t>: Send;
461
+
462
+ /// Opens `row`'s block tier, for ids starting with `prefix`.
463
+ fn open<'t>(
464
+ t: &'t Rows,
465
+ s: &Snapshot,
466
+ row: &[u8],
467
+ prefix: Option<&[u8]>,
468
+ ) -> Result<Self::Blocks<'t>>;
469
+
470
+ /// The merged stream. Only called where [`MERGED`](Self::MERGED) is true.
471
+ fn merged<'a, 't: 'a>(blocks: &'a mut Self::Blocks<'t>) -> &'a mut Merged<'t>;
472
+ }
473
+
474
+ /// Layout version 1: a posting is a cell.
475
+ pub(crate) struct Cells;
476
+
477
+ impl Layout for Cells {
478
+ const MERGED: bool = false;
479
+ type Blocks<'t> = ();
480
+
481
+ #[inline(always)]
482
+ fn open(_: &Rows, _: &Snapshot, _: &[u8], _: Option<&[u8]>) -> Result<()> {
483
+ Ok(())
484
+ }
485
+
486
+ fn merged<'a, 't: 'a>((): &'a mut ()) -> &'a mut Merged<'t> {
487
+ unreachable!("a version 1 walk has no blocks")
488
+ }
489
+ }
490
+
491
+ /// Layout version 2: cells over packed blocks ([`Merged`]).
492
+ pub(crate) struct Packed;
493
+
494
+ impl Layout for Packed {
495
+ const MERGED: bool = true;
496
+ type Blocks<'t> = Box<Merged<'t>>;
497
+
498
+ fn open<'t>(
499
+ t: &'t Rows,
500
+ s: &Snapshot,
501
+ row: &[u8],
502
+ prefix: Option<&[u8]>,
503
+ ) -> Result<Box<Merged<'t>>> {
504
+ Ok(Box::new(Merged::new(t, s, row, POST, prefix)?))
505
+ }
506
+
507
+ #[inline(always)]
508
+ fn merged<'a, 't: 'a>(blocks: &'a mut Box<Merged<'t>>) -> &'a mut Merged<'t> {
509
+ blocks
510
+ }
511
+ }
512
+
513
+ pub(crate) struct Walk<'t, R: Reads, L: Layout> {
375
514
  row: Vec<u8>,
376
515
  weight: f64,
377
516
  /// `weight · tf_factor(maxtf, minlen)`: the most it adds to a document.
@@ -379,7 +518,22 @@ pub(crate) struct Walk<'t, R: Reads> {
379
518
  /// Boxed: a walk is far larger than a phrase clause.
380
519
  cells: Box<RowCells<'t>>,
381
520
  /// The posting the walk stands on: its document and contribution.
382
- cur: Option<(Vec<u8>, f64)>,
521
+ cur: Cur,
522
+ /// What a posting must add for its document to be able to reach the top `k`, once `k`
523
+ /// are held: the threshold less every other clause's bound ([`Scored::drop_below`]).
524
+ /// [`step`](Self::step) passes a posting that adds less, without standing on it (#1585).
525
+ ///
526
+ /// **Exact.** Such a document scores at most this posting's contribution plus the other
527
+ /// clauses' bounds, which is under the threshold, so it can't enter the top `k`, and the
528
+ /// threshold only rises. If another clause brings it up as a candidate, it is scored
529
+ /// without this contribution, lower still. A document that does enter never had a
530
+ /// posting passed, so its score is the same.
531
+ ///
532
+ /// **An async walk** stands on each posting it reads, so a `Pending` in the middle of a
533
+ /// pass can leave it on one under the floor. That posting is then scored as any
534
+ /// candidate is, and can't reach the top `k` by the same bound: the result doesn't
535
+ /// change, and the next poll passes on from it (ai1249's S1 on #2003).
536
+ floor: f64,
383
537
  /// The postings the row holds (its `df`), and how many the walk has stepped past. With
384
538
  /// `id_prefix` the walk reads only part of the row, so `df` over-estimates what's left:
385
539
  /// it switches to advancing a little later than it could, which costs a little and never
@@ -391,6 +545,9 @@ pub(crate) struct Walk<'t, R: Reads> {
391
545
  advancing: bool,
392
546
  /// A point lookup in flight (async only).
393
547
  get: R::Get,
548
+ /// In a version 2 index (#1585): the row's packed blocks, merged under `cells`. Nothing
549
+ /// in a version 1 index, whose walk is the code it was.
550
+ packed: L::Blocks<'t>,
394
551
  }
395
552
 
396
553
  /// MaxScore's bound factor for a term (M1): the largest frequency at the shortest length any
@@ -404,7 +561,31 @@ pub(crate) fn bound_factor(bm: &Bm25, maxtf: Option<i64>, minlen: Option<i64>) -
404
561
  }
405
562
  }
406
563
 
407
- impl<'t> Walk<'t, Blocking> {
564
+ /// `row`'s posting cells, for ids starting with `prefix`.
565
+ ///
566
+ /// One expression a case, never `read = read.qualifier_prefix(p)`: the read builder is a
567
+ /// large struct passed and returned by value, and the reassignment copied it three times a
568
+ /// walk once the compiler stopped inlining the call (#1585: about 53 instructions a walk on
569
+ /// the id-prefix shapes).
570
+ #[inline(always)]
571
+ fn posting_cells<'t>(
572
+ t: &'t Rows,
573
+ s: &Snapshot,
574
+ row: &[u8],
575
+ prefix: Option<&[u8]>,
576
+ ) -> Result<RowCells<'t>> {
577
+ Ok(match prefix {
578
+ Some(p) => t
579
+ .row(row)
580
+ .family(POST)
581
+ .snapshot(s)
582
+ .qualifier_prefix(p)
583
+ .cells()?,
584
+ None => t.row(row).family(POST).snapshot(s).cells()?,
585
+ })
586
+ }
587
+
588
+ impl<'t, L: Layout> Walk<'t, Blocking, L> {
408
589
  /// The walk over `term`'s postings (restricted to doc ids starting with `prefix`), and
409
590
  /// its bound: `weight · tf_factor(maxtf, minlen)`. `postings` is the term's `df`.
410
591
  fn new(
@@ -421,11 +602,9 @@ impl<'t> Walk<'t, Blocking> {
421
602
  Ok(t.get_at(s, &row, family, BOUND)?.and_then(|c| c.as_i64()))
422
603
  };
423
604
  let factor = bound_factor(bm, agg(MAXTF)?, agg(MINLEN)?);
424
- let mut read = t.row(&row).family(POST).snapshot(s);
425
- if let Some(p) = prefix {
426
- read = read.qualifier_prefix(p);
427
- }
428
- let mut w = Walk::opened(row, weight, factor, read.cells()?, postings);
605
+ let cells = posting_cells(t, s, &row, prefix)?;
606
+ let blocks = L::open(t, s, &row, prefix)?;
607
+ let mut w = Walk::opened(row, weight, factor, cells, postings, blocks);
429
608
  match w.step(bm, &mut ()) {
430
609
  Poll::Ready(r) => r?,
431
610
  Poll::Pending => unreachable!("sync reads are always ready"),
@@ -438,7 +617,7 @@ impl<'t> Walk<'t, Blocking> {
438
617
  /// [`Walk::new`] as a future (#1560): the bound's aggregates read with point-read futures,
439
618
  /// and the walk stepped onto its first posting without blocking.
440
619
  #[cfg(feature = "async")]
441
- pub(crate) async fn walk_async<'t>(
620
+ pub(crate) async fn walk_async<'t, L: Layout>(
442
621
  t: &'t Rows,
443
622
  s: &Snapshot,
444
623
  bm: &Bm25,
@@ -446,7 +625,7 @@ pub(crate) async fn walk_async<'t>(
446
625
  weight: f64,
447
626
  postings: u64,
448
627
  prefix: Option<&[u8]>,
449
- ) -> Result<Walk<'t, Nonblocking>> {
628
+ ) -> Result<Walk<'t, Nonblocking, L>> {
450
629
  let row = post_row(term);
451
630
  let maxtf = t.get_at_async(s, &row, MAXTF, BOUND).await?;
452
631
  let minlen = t.get_at_async(s, &row, MINLEN, BOUND).await?;
@@ -455,16 +634,14 @@ pub(crate) async fn walk_async<'t>(
455
634
  maxtf.and_then(|c| c.as_i64()),
456
635
  minlen.and_then(|c| c.as_i64()),
457
636
  );
458
- let mut read = t.row(&row).family(POST).snapshot(s);
459
- if let Some(p) = prefix {
460
- read = read.qualifier_prefix(p);
461
- }
462
- let mut w = Walk::opened(row, weight, factor, read.cells()?, postings);
637
+ let cells = posting_cells(t, s, &row, prefix)?;
638
+ let blocks = L::open(t, s, &row, prefix)?;
639
+ let mut w = Walk::opened(row, weight, factor, cells, postings, blocks);
463
640
  std::future::poll_fn(|cx| w.step(bm, &mut Polling::new(cx))).await?;
464
641
  Ok(w)
465
642
  }
466
643
 
467
- impl<'t, R: Reads> Walk<'t, R> {
644
+ impl<'t, R: Reads, L: Layout> Walk<'t, R, L> {
468
645
  /// A walk over `row`'s postings in `cells`, not yet on its first (call `step`).
469
646
  pub(crate) fn opened(
470
647
  row: Vec<u8>,
@@ -472,44 +649,214 @@ impl<'t, R: Reads> Walk<'t, R> {
472
649
  factor: f64,
473
650
  cells: RowCells<'t>,
474
651
  postings: u64,
652
+ blocks: L::Blocks<'t>,
475
653
  ) -> Self {
476
654
  Walk {
477
655
  row,
478
656
  weight,
479
657
  bound: weight * factor,
480
658
  cells: Box::new(cells),
481
- cur: None,
659
+ cur: Cur::default(),
660
+ floor: f64::NEG_INFINITY,
482
661
  postings,
483
662
  stepped: 0,
484
663
  lookups: 0,
485
664
  advancing: false,
486
665
  get: R::Get::default(),
666
+ packed: blocks,
487
667
  }
488
668
  }
489
669
 
490
670
  fn doc(&self) -> Option<&[u8]> {
491
- self.cur.as_ref().map(|(d, _)| d.as_slice())
671
+ self.cur.doc()
492
672
  }
493
673
 
494
674
  /// Out of line, as the sync walk's step was before #1560 (the compiler's choice then):
495
675
  /// inlined into `TopK::run`, it doubled the loop's own cost on the text shapes.
496
676
  #[inline(never)]
497
677
  pub(crate) fn step(&mut self, bm: &Bm25, cx: &mut R::Cx<'_, '_>) -> Poll<Result<()>> {
498
- self.skip_while(bm, cx, |_| false)
678
+ if L::MERGED {
679
+ return self.step_merged(bm, cx);
680
+ }
681
+ R::skip_while(self, bm, cx, self.floor, |_| false)
682
+ }
683
+
684
+ /// [`step`](Self::step) in a version 2 index: to the merged stream's next posting that
685
+ /// reaches the floor.
686
+ ///
687
+ /// An async walk stands on each posting it reads, as the unpacked one does, so a
688
+ /// `Pending` mid-pass can leave it on a posting under the floor. That is the posting it
689
+ /// would have passed: a candidate there is scored with it and can't reach the top `k`
690
+ /// ([`Walk::floor`]), and the next poll goes on from it.
691
+ fn step_merged(&mut self, bm: &Bm25, cx: &mut R::Cx<'_, '_>) -> Poll<Result<()>> {
692
+ let Walk {
693
+ packed,
694
+ cells,
695
+ cur,
696
+ weight,
697
+ floor,
698
+ stepped,
699
+ ..
700
+ } = self;
701
+ let m = L::merged(packed);
702
+ if let Some(doc) = cur.doc() {
703
+ m.pass(doc);
704
+ }
705
+ loop {
706
+ if R::spend(cx, 1) {
707
+ return Poll::Pending;
708
+ }
709
+ // A block that can't hold a posting at the floor is passed whole.
710
+ ready!(m.settle::<R>(cells, cx, Some((bm, *weight, *floor))));
711
+ *stepped = m.stepped;
712
+ let Some(tier) = m.head() else {
713
+ cur.clear();
714
+ return Poll::Ready(Ok(()));
715
+ };
716
+ let (tf, len) = unposting(match m.post(tier) {
717
+ Ok(v) => v,
718
+ Err(e) => return Poll::Ready(Err(e)),
719
+ });
720
+ let here = *weight * bm.tf_factor(f64::from(tf), f64::from(len));
721
+ if under(here, *floor) {
722
+ if R::ASYNC {
723
+ cur.set(m.id(tier), here);
724
+ }
725
+ m.skip(tier);
726
+ continue;
727
+ }
728
+ cur.set(m.id(tier), here);
729
+ return Poll::Ready(Ok(()));
730
+ }
731
+ }
732
+
733
+ /// [`advance`](Self::advance) in a version 2 index: both tiers to `doc`, then the
734
+ /// stream's posting there or after. Every move is a target, so a re-poll repeats it.
735
+ fn advance_merged(
736
+ &mut self,
737
+ bm: &Bm25,
738
+ cx: &mut R::Cx<'_, '_>,
739
+ doc: &[u8],
740
+ past: bool,
741
+ ) -> Poll<Result<()>> {
742
+ let Walk {
743
+ packed,
744
+ cells,
745
+ cur,
746
+ weight,
747
+ stepped,
748
+ ..
749
+ } = self;
750
+ let m = L::merged(packed);
751
+ if R::spend(cx, 1) {
752
+ return Poll::Pending;
753
+ }
754
+ ready!(m.cells_to::<R>(cells, cx, doc));
755
+ ready!(m.blocks_to::<R>(cx, doc));
756
+ if past {
757
+ m.pass(doc);
758
+ }
759
+ ready!(m.settle::<R>(cells, cx, None));
760
+ *stepped = m.stepped;
761
+ let Some(tier) = m.head() else {
762
+ cur.clear();
763
+ return Poll::Ready(Ok(()));
764
+ };
765
+ let (tf, len) = unposting(match m.post(tier) {
766
+ Ok(v) => v,
767
+ Err(e) => return Poll::Ready(Err(e)),
768
+ });
769
+ cur.set(
770
+ m.id(tier),
771
+ *weight * bm.tf_factor(f64::from(tf), f64::from(len)),
772
+ );
773
+ Poll::Ready(Ok(()))
774
+ }
775
+
776
+ /// [`lookup`](Self::lookup) in a version 2 index.
777
+ ///
778
+ /// The block tier always advances to `doc`: a block passed costs a key compare and is
779
+ /// never decoded, so there is nothing for a point read to save. The cell tier answers
780
+ /// from where it stands when it can (its head is past `doc`, or on it, or it has no
781
+ /// cells: a fully packed row costs no read at all), and otherwise by the unpacked walk's
782
+ /// rule: point reads until they'd cost more than stepping through what's left
783
+ /// ([`LOOKUP_IN_STEPS`]), then advancing for good. `cur` isn't moved by the point-read
784
+ /// path, as in the unpacked walk; [`pass`](Self::pass) brings it up when the walk is
785
+ /// walked again.
786
+ fn lookup_merged(
787
+ &mut self,
788
+ t: &Rows,
789
+ s: &Snapshot,
790
+ bm: &Bm25,
791
+ cx: &mut R::Cx<'_, '_>,
792
+ doc: &[u8],
793
+ ) -> Poll<Result<f64>> {
794
+ let score = |weight: f64, v: u64| {
795
+ let (tf, len) = unposting(v);
796
+ weight * bm.tf_factor(f64::from(tf), f64::from(len))
797
+ };
798
+ if !R::get_pending(&self.get) {
799
+ if !self.advancing {
800
+ let m = L::merged(&mut self.packed);
801
+ ready!(m.blocks_to::<R>(cx, doc));
802
+ match m.cell_side(doc) {
803
+ Side::Absent => {
804
+ return Poll::Ready(match m.block_has(doc) {
805
+ true => m.post(Tier::Block).map(|v| score(self.weight, v)),
806
+ false => Ok(0.0),
807
+ });
808
+ }
809
+ Side::Here => {
810
+ return Poll::Ready(
811
+ m.cell_post()
812
+ .map(|v| v.map_or(0.0, |v| score(self.weight, v))),
813
+ );
814
+ }
815
+ Side::Behind => {}
816
+ }
817
+ if R::spend(cx, LOOKUP_IN_STEPS as u32) {
818
+ return Poll::Pending;
819
+ }
820
+ self.lookups += 1;
821
+ let left = self.postings.saturating_sub(m.stepped);
822
+ self.advancing = self.lookups.saturating_mul(LOOKUP_IN_STEPS) > left;
823
+ }
824
+ if self.advancing {
825
+ if self.doc().is_some_and(|d| d < doc) {
826
+ ready!(self.advance_merged(bm, cx, doc, false));
827
+ }
828
+ return Poll::Ready(Ok(match self.cur.get() {
829
+ Some((d, c)) if d == doc => c,
830
+ _ => 0.0,
831
+ }));
832
+ }
833
+ }
834
+ // The cell by a point read; without one, the block's posting.
835
+ match ready!(R::get(t, s, &self.row, doc, &mut self.get, cx)) {
836
+ Some(v) => {
837
+ let v = v.ok_or_else(|| corrupt("a posting isn't a u64"))?;
838
+ Poll::Ready(Ok(match v {
839
+ TOMBSTONE => 0.0,
840
+ v => score(self.weight, v),
841
+ }))
842
+ }
843
+ None => {
844
+ let m = L::merged(&mut self.packed);
845
+ Poll::Ready(match m.block_has(doc) {
846
+ true => m.post(Tier::Block).map(|v| score(self.weight, v)),
847
+ false => Ok(0.0),
848
+ })
849
+ }
850
+ }
499
851
  }
500
852
 
501
853
  /// Stands `cur` on `e`, the posting stepped to (`None`: the row is done). On the walk's
502
854
  /// fields, not `self`: `e` borrows its cells. Always inline: out of line, `e` was copied
503
855
  /// in on every posting (`memcpy`, about 12 instructions a posting on #1560's profile).
504
856
  #[inline(always)]
505
- fn hold(
506
- cur: &mut Option<(Vec<u8>, f64)>,
507
- weight: f64,
508
- bm: &Bm25,
509
- e: Option<CellEntry<'_>>,
510
- ) -> Result<()> {
857
+ fn hold(cur: &mut Cur, weight: f64, bm: &Bm25, e: Option<CellEntry<'_>>) -> Result<()> {
511
858
  let Some(e) = e else {
512
- *cur = None;
859
+ cur.clear();
513
860
  return Ok(());
514
861
  };
515
862
  let (tf, len) = unposting(
@@ -517,10 +864,10 @@ impl<'t, R: Reads> Walk<'t, R> {
517
864
  .as_u64()
518
865
  .ok_or_else(|| corrupt("a posting isn't a u64"))?,
519
866
  );
520
- *cur = Some((
521
- e.qualifier.to_vec(),
867
+ cur.set(
868
+ e.qualifier,
522
869
  weight * bm.tf_factor(f64::from(tf), f64::from(len)),
523
- ));
870
+ );
524
871
  Ok(())
525
872
  }
526
873
 
@@ -535,7 +882,8 @@ impl<'t, R: Reads> Walk<'t, R> {
535
882
  cx: &mut R::Cx<'_, '_>,
536
883
  skip: impl Fn(&[u8]) -> bool,
537
884
  ) -> Poll<Result<()>> {
538
- R::skip_while(self, bm, cx, skip)
885
+ // No floor: a lookup's walk answers for one document, whatever it adds.
886
+ R::skip_while(self, bm, cx, f64::NEG_INFINITY, skip)
539
887
  }
540
888
 
541
889
  /// Stands on the first posting at or after `doc`, or after it with `past`: by stepping
@@ -549,6 +897,9 @@ impl<'t, R: Reads> Walk<'t, R> {
549
897
  doc: &[u8],
550
898
  past: bool,
551
899
  ) -> Poll<Result<()>> {
900
+ if L::MERGED {
901
+ return self.advance_merged(bm, cx, doc, past);
902
+ }
552
903
  if !R::ASYNC {
553
904
  return if past {
554
905
  self.skip_while(bm, cx, |d| d <= doc)
@@ -560,7 +911,7 @@ impl<'t, R: Reads> Walk<'t, R> {
560
911
  if R::spend(cx, 1) {
561
912
  return Poll::Pending;
562
913
  }
563
- let e = ready!(R::seek(&mut self.cells, cx, doc));
914
+ let e = ready!(R::seek(&mut self.cells, cx, POST, doc));
564
915
  self.stepped += 1;
565
916
  match e {
566
917
  Some(e) if past && e.qualifier == doc => continue,
@@ -595,6 +946,9 @@ impl<'t, R: Reads> Walk<'t, R> {
595
946
  cx: &mut R::Cx<'_, '_>,
596
947
  doc: &[u8],
597
948
  ) -> Poll<Result<f64>> {
949
+ if L::MERGED {
950
+ return self.lookup_merged(t, s, bm, cx, doc);
951
+ }
598
952
  if !R::get_pending(&self.get) {
599
953
  if !self.advancing {
600
954
  if R::spend(cx, LOOKUP_IN_STEPS as u32) {
@@ -608,8 +962,8 @@ impl<'t, R: Reads> Walk<'t, R> {
608
962
  if self.doc().is_some_and(|d| d < doc) {
609
963
  ready!(self.advance(bm, cx, doc, false));
610
964
  }
611
- return Poll::Ready(Ok(match &self.cur {
612
- Some((d, c)) if d.as_slice() == doc => *c,
965
+ return Poll::Ready(Ok(match self.cur.get() {
966
+ Some((d, c)) if d == doc => c,
613
967
  _ => 0.0,
614
968
  }));
615
969
  }
@@ -625,21 +979,21 @@ impl<'t, R: Reads> Walk<'t, R> {
625
979
  }
626
980
 
627
981
  /// A clause as MaxScore runs it.
628
- pub(crate) enum Clause<'t, R: Reads> {
982
+ pub(crate) enum Clause<'t, R: Reads, L: Layout> {
629
983
  /// A term's posting row.
630
- Term(Walk<'t, R>),
984
+ Term(Walk<'t, R, L>),
631
985
  /// A fuzzy term's expansions (D309 §4.4): a document's contribution is the largest of
632
986
  /// theirs, not their sum.
633
987
  Fuzzy {
634
988
  /// The expansions still in play, largest bound first. One whose bound falls below
635
989
  /// what a document would need from it is dropped ([`Scored::drop_below`], #1333).
636
- walks: Vec<Walk<'t, R>>,
990
+ walks: Vec<Walk<'t, R, L>>,
637
991
  /// How many of `walks` are walked (#1363): the rest can't bring a document in on
638
992
  /// their own, and are only looked up ([`Scored::set_solo`]).
639
993
  solo: usize,
640
994
  /// The document the clause stands on (the walked ones' smallest) and its
641
995
  /// contribution there.
642
- cur: Option<(Vec<u8>, f64)>,
996
+ cur: Cur,
643
997
  },
644
998
  /// A phrase, scored up front: its documents and their scores, in document order.
645
999
  Phrase {
@@ -649,8 +1003,8 @@ pub(crate) enum Clause<'t, R: Reads> {
649
1003
  }
650
1004
 
651
1005
  /// One clause: what it is, and its bound.
652
- pub(crate) struct Scored<'t, R: Reads> {
653
- pub(crate) clause: Clause<'t, R>,
1006
+ pub(crate) struct Scored<'t, R: Reads, L: Layout> {
1007
+ pub(crate) clause: Clause<'t, R, L>,
654
1008
  pub(crate) bound: f64,
655
1009
  }
656
1010
 
@@ -662,17 +1016,20 @@ struct Progress {
662
1016
  best: f64,
663
1017
  }
664
1018
 
665
- impl<'t> Scored<'t, Blocking> {
666
- /// A term clause over its posting row (restricted to doc ids starting with `prefix`).
1019
+ impl<'t, L: Layout> Scored<'t, Blocking, L> {
1020
+ /// A term clause over its posting row (restricted to doc ids starting with `prefix`):
1021
+ /// `df` the one its idf scores with, `postings` the row's own (ICR 0138: they differ
1022
+ /// for a search given another index's statistics).
667
1023
  pub(crate) fn term(
668
1024
  t: &'t Rows,
669
1025
  s: &Snapshot,
670
1026
  bm: &Bm25,
671
1027
  term: &str,
672
1028
  df: i64,
1029
+ postings: u64,
673
1030
  prefix: Option<&[u8]>,
674
1031
  ) -> Result<Self> {
675
- let (walk, _) = Walk::new(t, s, bm, term, bm.idf(df), df.max(0) as u64, prefix)?;
1032
+ let (walk, _) = Walk::new(t, s, bm, term, bm.idf(df), postings, prefix)?;
676
1033
  Ok(Scored::of_term(walk))
677
1034
  }
678
1035
 
@@ -695,9 +1052,9 @@ impl<'t> Scored<'t, Blocking> {
695
1052
  }
696
1053
  }
697
1054
 
698
- impl<'t, R: Reads> Scored<'t, R> {
1055
+ impl<'t, R: Reads, L: Layout> Scored<'t, R, L> {
699
1056
  /// A term clause over its walk, which stands on its first posting.
700
- pub(crate) fn of_term(walk: Walk<'t, R>) -> Self {
1057
+ pub(crate) fn of_term(walk: Walk<'t, R, L>) -> Self {
701
1058
  let bound = walk.bound;
702
1059
  Scored {
703
1060
  clause: Clause::Term(walk),
@@ -706,7 +1063,7 @@ impl<'t, R: Reads> Scored<'t, R> {
706
1063
  }
707
1064
 
708
1065
  /// A fuzzy clause over its expansions' walks, each on its first posting.
709
- pub(crate) fn of_fuzzy(mut walks: Vec<Walk<'t, R>>) -> Self {
1066
+ pub(crate) fn of_fuzzy(mut walks: Vec<Walk<'t, R, L>>) -> Self {
710
1067
  let bound = walks.iter().map(|w| w.bound).fold(0.0f64, f64::max);
711
1068
  walks.sort_by(|a, b| b.bound.total_cmp(&a.bound));
712
1069
  let solo = walks.len();
@@ -714,7 +1071,7 @@ impl<'t, R: Reads> Scored<'t, R> {
714
1071
  clause: Clause::Fuzzy {
715
1072
  walks,
716
1073
  solo,
717
- cur: None,
1074
+ cur: Cur::default(),
718
1075
  },
719
1076
  bound: bound * (1.0 + SLACK),
720
1077
  };
@@ -727,15 +1084,18 @@ impl<'t, R: Reads> Scored<'t, R> {
727
1084
  fn settle(&mut self) {
728
1085
  if let Clause::Fuzzy { walks, solo, cur } = &mut self.clause {
729
1086
  let walks = &walks[..*solo];
730
- *cur = walks.iter().filter_map(|w| w.doc()).min().map(|doc| {
731
- let best = walks
732
- .iter()
733
- .filter_map(|w| w.cur.as_ref())
734
- .filter(|(d, _)| d.as_slice() == doc)
735
- .map(|(_, c)| *c)
736
- .fold(0.0, f64::max);
737
- (doc.to_vec(), best)
738
- });
1087
+ match walks.iter().filter_map(|w| w.doc()).min() {
1088
+ Some(doc) => {
1089
+ let best = walks
1090
+ .iter()
1091
+ .filter_map(|w| w.cur.get())
1092
+ .filter(|(d, _)| *d == doc)
1093
+ .map(|(_, c)| c)
1094
+ .fold(0.0, f64::max);
1095
+ cur.set(doc, best);
1096
+ }
1097
+ None => cur.clear(),
1098
+ }
739
1099
  }
740
1100
  }
741
1101
 
@@ -755,7 +1115,7 @@ impl<'t, R: Reads> Scored<'t, R> {
755
1115
  fn doc(&self) -> Option<&[u8]> {
756
1116
  match &self.clause {
757
1117
  Clause::Term(w) => w.doc(),
758
- Clause::Fuzzy { cur, .. } => cur.as_ref().map(|(d, _)| d.as_slice()),
1118
+ Clause::Fuzzy { cur, .. } => cur.doc(),
759
1119
  Clause::Phrase { scores, at } => scores.get(*at).map(|(d, _)| d.as_slice()),
760
1120
  }
761
1121
  }
@@ -763,9 +1123,7 @@ impl<'t, R: Reads> Scored<'t, R> {
763
1123
  /// The contribution where it stands.
764
1124
  fn here(&self) -> f64 {
765
1125
  match &self.clause {
766
- Clause::Term(Walk { cur, .. }) | Clause::Fuzzy { cur, .. } => {
767
- cur.as_ref().map_or(0.0, |(_, c)| *c)
768
- }
1126
+ Clause::Term(Walk { cur, .. }) | Clause::Fuzzy { cur, .. } => cur.here(),
769
1127
  Clause::Phrase { scores, at } => scores.get(*at).map_or(0.0, |(_, c)| *c),
770
1128
  }
771
1129
  }
@@ -777,11 +1135,11 @@ impl<'t, R: Reads> Scored<'t, R> {
777
1135
  match &mut self.clause {
778
1136
  Clause::Term(w) => ready!(w.step(bm, cx)),
779
1137
  Clause::Fuzzy { walks, solo, cur } => {
780
- let Some((doc, _)) = cur.as_ref() else {
1138
+ let Some(doc) = cur.doc() else {
781
1139
  return Poll::Ready(Ok(()));
782
1140
  };
783
1141
  for w in walks[..*solo].iter_mut() {
784
- if w.doc() == Some(doc.as_slice()) {
1142
+ if w.doc() == Some(doc) {
785
1143
  ready!(w.step(bm, cx));
786
1144
  }
787
1145
  }
@@ -815,7 +1173,7 @@ impl<'t, R: Reads> Scored<'t, R> {
815
1173
 
816
1174
  /// The largest of `walks`' contributions to `doc`, resuming at `at`.
817
1175
  fn lookup_each(
818
- walks: &mut [Walk<'t, R>],
1176
+ walks: &mut [Walk<'t, R, L>],
819
1177
  t: &Rows,
820
1178
  s: &Snapshot,
821
1179
  bm: &Bm25,
@@ -912,6 +1270,10 @@ impl<'t, R: Reads> Scored<'t, R> {
912
1270
  /// Dropped expansions aren't looked up either: by the same bound, they can't change
913
1271
  /// the score of a document that enters.
914
1272
  fn drop_below(&mut self, cut: f64) {
1273
+ // A term's walk passes the postings that the same bound rules out ([`Walk::floor`]).
1274
+ if let Clause::Term(w) = &mut self.clause {
1275
+ w.floor = cut;
1276
+ }
915
1277
  let Clause::Fuzzy { walks, .. } = &mut self.clause else {
916
1278
  return;
917
1279
  };
@@ -929,23 +1291,33 @@ impl<'t, R: Reads> Scored<'t, R> {
929
1291
 
930
1292
  /// A held result, ordered so the worst is greatest (a lower score, or an equal score with a
931
1293
  /// larger id): the top of a [`BinaryHeap`] is the one a better candidate replaces.
932
- struct Held(f64, Vec<u8>);
1294
+ ///
1295
+ /// It carries the layout as a type so each layout's document loop has its own heap code,
1296
+ /// as the one loop had before #1585: with one `BinaryHeap<Held>` shared by both loops the
1297
+ /// compiler stopped inlining `pop` (about 185 instructions a search on `text-term-rare`).
1298
+ struct Held<L>(f64, Vec<u8>, PhantomData<fn() -> L>);
1299
+
1300
+ impl<L> Held<L> {
1301
+ fn new(score: f64, doc: Vec<u8>) -> Self {
1302
+ Held(score, doc, PhantomData)
1303
+ }
1304
+ }
933
1305
 
934
- impl PartialEq for Held {
1306
+ impl<L> PartialEq for Held<L> {
935
1307
  fn eq(&self, other: &Self) -> bool {
936
1308
  self.cmp(other) == Ordering::Equal
937
1309
  }
938
1310
  }
939
1311
 
940
- impl Eq for Held {}
1312
+ impl<L> Eq for Held<L> {}
941
1313
 
942
- impl PartialOrd for Held {
1314
+ impl<L> PartialOrd for Held<L> {
943
1315
  fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
944
1316
  Some(self.cmp(other))
945
1317
  }
946
1318
  }
947
1319
 
948
- impl Ord for Held {
1320
+ impl<L> Ord for Held<L> {
949
1321
  fn cmp(&self, other: &Self) -> Ordering {
950
1322
  other
951
1323
  .0
@@ -996,14 +1368,14 @@ enum At {
996
1368
  /// expansions ([`Scored`]). Only the loop's control flow is written twice, and
997
1369
  /// `tests/search_async.rs` checks the two give the same hits and stats on random queries.
998
1370
  #[cfg(feature = "async")]
999
- pub(crate) struct TopK<'t, R: Reads> {
1000
- clauses: Vec<Scored<'t, R>>,
1371
+ pub(crate) struct TopK<'t, R: Reads, L: Layout> {
1372
+ clauses: Vec<Scored<'t, R, L>>,
1001
1373
  k: usize,
1002
1374
  /// Clause indexes by ascending bound; `prefix[i]` sums the first `i` bounds in that order.
1003
1375
  by_bound: Vec<usize>,
1004
1376
  prefix: Vec<f64>,
1005
1377
  /// The held documents, the worst on top.
1006
- held: BinaryHeap<Held>,
1378
+ held: BinaryHeap<Held<L>>,
1007
1379
  /// How many of `by_bound`'s first clauses are non-essential.
1008
1380
  skip: usize,
1009
1381
  /// The threshold the non-essential prefix and the fuzzy cuts were last taken at.
@@ -1024,8 +1396,8 @@ pub(crate) struct TopK<'t, R: Reads> {
1024
1396
  }
1025
1397
 
1026
1398
  #[cfg(feature = "async")]
1027
- impl<'t, R: Reads> TopK<'t, R> {
1028
- pub(crate) fn new(clauses: Vec<Scored<'t, R>>, k: usize) -> Self {
1399
+ impl<'t, R: Reads, L: Layout> TopK<'t, R, L> {
1400
+ pub(crate) fn new(clauses: Vec<Scored<'t, R, L>>, k: usize) -> Self {
1029
1401
  debug_assert!(k > 0, "the search returns before MaxScore at k = 0");
1030
1402
  let n = clauses.len();
1031
1403
  let mut by_bound: Vec<usize> = (0..n).collect();
@@ -1057,7 +1429,7 @@ impl<'t, R: Reads> TopK<'t, R> {
1057
1429
  // Best first: score descending, then id ascending (`Held` orders the worst greatest).
1058
1430
  let mut out = self.held.into_vec();
1059
1431
  out.sort();
1060
- out.into_iter().map(|Held(s, d)| (d, s)).collect()
1432
+ out.into_iter().map(|Held(s, d, _)| (d, s)).collect()
1061
1433
  }
1062
1434
 
1063
1435
  /// Runs the document loop until it's done (`Ready(Ok)`), or, async, until a read is
@@ -1158,6 +1530,11 @@ impl<'t, R: Reads> TopK<'t, R> {
1158
1530
  else {
1159
1531
  break;
1160
1532
  };
1533
+ // Candidates ascend, as in [`top_k`] (#2010).
1534
+ debug_assert!(
1535
+ !decided || next > self.last.as_slice(),
1536
+ "a candidate at or before the last document decided"
1537
+ );
1161
1538
  // The candidate, in `last`'s buffer: once it's decided, it's the last
1162
1539
  // document decided, which the next pass's re-walk steps past. No allocation
1163
1540
  // per candidate; a document that enters the top `k` is copied.
@@ -1282,7 +1659,7 @@ impl<'t, R: Reads> TopK<'t, R> {
1282
1659
  let score = self.contrib.iter().flatten().fold(0.0, |sum, v| sum + v);
1283
1660
  let doc: &[u8] = &self.last;
1284
1661
  if self.held.len() < k {
1285
- self.held.push(Held(score, doc.to_vec()));
1662
+ self.held.push(Held::new(score, doc.to_vec()));
1286
1663
  } else {
1287
1664
  // Better than the worst held (`Held`'s order: a higher score, or an equal
1288
1665
  // score and a smaller id): it takes the worst one's place.
@@ -1294,7 +1671,7 @@ impl<'t, R: Reads> TopK<'t, R> {
1294
1671
  };
1295
1672
  if better {
1296
1673
  self.held.pop();
1297
- self.held.push(Held(score, doc.to_vec()));
1674
+ self.held.push(Held::new(score, doc.to_vec()));
1298
1675
  }
1299
1676
  }
1300
1677
  }
@@ -1318,11 +1695,11 @@ impl<'t, R: Reads> TopK<'t, R> {
1318
1695
  /// each posting (text-term-hub +3.6%, two-terms +3.0% in callgrind), which the text shapes'
1319
1696
  /// ceilings don't allow. The rules both loops apply are shared ([`Walk`], [`Scored`],
1320
1697
  /// [`Reads`]); `tests/search_async.rs` checks the two agree.
1321
- pub(crate) fn top_k(
1698
+ pub(crate) fn top_k<L: Layout>(
1322
1699
  t: &Rows,
1323
1700
  s: &Snapshot,
1324
1701
  bm: &Bm25,
1325
- mut clauses: Vec<Scored<'_, Blocking>>,
1702
+ mut clauses: Vec<Scored<'_, Blocking, L>>,
1326
1703
  k: usize,
1327
1704
  ) -> Result<Vec<(Vec<u8>, f64)>> {
1328
1705
  debug_assert!(k > 0, "the search returns before MaxScore at k = 0");
@@ -1335,7 +1712,7 @@ pub(crate) fn top_k(
1335
1712
  prefix[i + 1] = prefix[i] + clauses[c].bound;
1336
1713
  }
1337
1714
  // The held documents, the worst on top.
1338
- let mut held: BinaryHeap<Held> = BinaryHeap::with_capacity(k + 1);
1715
+ let mut held: BinaryHeap<Held<L>> = BinaryHeap::with_capacity(k + 1);
1339
1716
  // How many of `by_bound`'s first clauses are non-essential.
1340
1717
  let mut skip = 0;
1341
1718
  // The threshold the non-essential prefix and the fuzzy cuts were last taken at.
@@ -1384,6 +1761,16 @@ pub(crate) fn top_k(
1384
1761
  let Some(next) = essential.iter().filter_map(|&c| clauses[c].doc()).min() else {
1385
1762
  break;
1386
1763
  };
1764
+ // Candidates ascend: every essential walk stands after the last document decided (a
1765
+ // fuzzy expansion walked again steps past it, [`Walk::pass`]). A walk left on that
1766
+ // document makes it a candidate twice. In a version 2 index that can change no hit
1767
+ // (a clause already past the document adds nothing the second time, so it may
1768
+ // score too little to enter again), so this check, not a result, is what a test
1769
+ // can rely on there (#2010).
1770
+ debug_assert!(
1771
+ !decided || next > last.as_slice(),
1772
+ "a candidate at or before the last document decided"
1773
+ );
1387
1774
  // The candidate, in `last`'s buffer: once it's decided, it's the last document
1388
1775
  // decided, which the next pass's re-walk steps past. No allocation per candidate; a
1389
1776
  // document that enters the top `k` is copied.
@@ -1445,7 +1832,7 @@ pub(crate) fn top_k(
1445
1832
  // The exact score: contributions in the clauses' fixed order.
1446
1833
  let score = contrib.iter().flatten().fold(0.0, |sum, v| sum + v);
1447
1834
  if held.len() < k {
1448
- held.push(Held(score, doc.to_vec()));
1835
+ held.push(Held::new(score, doc.to_vec()));
1449
1836
  } else {
1450
1837
  // Better than the worst held (`Held`'s order: a higher score, or an equal score
1451
1838
  // and a smaller id): it takes the worst one's place.
@@ -1457,19 +1844,19 @@ pub(crate) fn top_k(
1457
1844
  };
1458
1845
  if better {
1459
1846
  held.pop();
1460
- held.push(Held(score, doc.to_vec()));
1847
+ held.push(Held::new(score, doc.to_vec()));
1461
1848
  }
1462
1849
  }
1463
1850
  }
1464
1851
  // Best first: score descending, then id ascending (`Held` orders the worst greatest).
1465
1852
  let mut out = held.into_vec();
1466
1853
  out.sort();
1467
- Ok(out.into_iter().map(|Held(s, d)| (d, s)).collect())
1854
+ Ok(out.into_iter().map(|Held(s, d, _)| (d, s)).collect())
1468
1855
  }
1469
1856
 
1470
1857
  /// A [`Blocking`] read's result: always ready.
1471
1858
  #[inline(always)]
1472
- fn sync<T>(p: Poll<T>) -> T {
1859
+ pub(crate) fn sync<T>(p: Poll<T>) -> T {
1473
1860
  match p {
1474
1861
  Poll::Ready(v) => v,
1475
1862
  Poll::Pending => unreachable!("sync reads are always ready"),