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
@@ -5,12 +5,14 @@ use std::collections::{BTreeMap, BTreeSet, HashMap};
5
5
  use pigeonhole::Snapshot;
6
6
 
7
7
  use crate::error::{Error, Result, corrupt};
8
- use crate::fuzzy::{Expansion, edits, expand};
8
+ use crate::fuzzy::{edits, expand};
9
9
  use crate::highlight::{Match, Want, find};
10
10
  use crate::index::{Index, Rows};
11
11
  use crate::layout::*;
12
- use crate::maxscore::{Bm25, Scored};
12
+ use crate::maxscore::{Blocking, Bm25, Cells, Layout, Packed, Scored, sync};
13
+ use crate::merged::{Merged, Side, Tier};
13
14
  use crate::query::{Clause, Fuzziness, Query};
15
+ use crate::stats::{Fuzzy, QueryStats, Stats, other_query};
14
16
 
15
17
  /// One search result.
16
18
  #[derive(Debug, Clone, PartialEq)]
@@ -80,6 +82,109 @@ struct Resolved {
80
82
  wants: Vec<(usize, Want)>,
81
83
  }
82
84
 
85
+ impl Resolved {
86
+ /// Whether no clause can match anything.
87
+ fn is_empty(&self) -> bool {
88
+ self.terms.is_empty() && self.phrases.is_empty() && self.fuzzy.is_empty()
89
+ }
90
+
91
+ /// Its terms, then its phrases' terms (a term may come more than once).
92
+ fn all_terms(&self) -> impl Iterator<Item = &String> {
93
+ self.terms.iter().chain(
94
+ self.phrases
95
+ .iter()
96
+ .flat_map(|p| p.terms.iter().map(|(t, _)| t)),
97
+ )
98
+ }
99
+ }
100
+
101
+ /// The `df`s of a search's terms and phrase terms: the one each scores with, and its
102
+ /// postings in this index, which a walk steps through. They're the same numbers (`here` is
103
+ /// `None`) unless the search was given statistics ([`Search::stats`], ICR 0138).
104
+ #[derive(Clone, Copy)]
105
+ struct Dfs<'a> {
106
+ score: &'a HashMap<String, i64>,
107
+ here: Option<&'a HashMap<String, i64>>,
108
+ }
109
+
110
+ impl Dfs<'_> {
111
+ /// The `df` `term` scores with.
112
+ fn score(&self, term: &str) -> i64 {
113
+ self.score[term]
114
+ }
115
+
116
+ /// `term`'s postings here.
117
+ fn here(&self, term: &str) -> i64 {
118
+ self.here.unwrap_or(self.score)[term]
119
+ }
120
+
121
+ /// Both, with one lookup when they're the same.
122
+ fn both(&self, term: &str) -> (i64, i64) {
123
+ let score = self.score[term];
124
+ (score, self.here.map_or(score, |h| h[term]))
125
+ }
126
+ }
127
+
128
+ /// What a search given statistics reads of its own index (ICR 0138): the postings here of
129
+ /// each term they hold, and of each fuzzy term's given expansions, in their order. A term
130
+ /// can have a `df` in the statistics and no postings here.
131
+ struct Here {
132
+ df: HashMap<String, i64>,
133
+ fuzzy: Vec<Vec<i64>>,
134
+ }
135
+
136
+ impl Here {
137
+ fn read(t: &Rows, s: &Snapshot, given: &Stats) -> Result<Here> {
138
+ let mut df = HashMap::with_capacity(given.df.len());
139
+ for term in given.df.keys() {
140
+ df.insert(term.clone(), term_df(t, s, term)?);
141
+ }
142
+ let mut fuzzy = Vec::with_capacity(given.fuzzy.len());
143
+ for f in &given.fuzzy {
144
+ let mut ns = Vec::with_capacity(f.expansions.len());
145
+ for e in &f.expansions {
146
+ ns.push(term_df(t, s, &e.term)?);
147
+ }
148
+ fuzzy.push(ns);
149
+ }
150
+ Ok(Here { df, fuzzy })
151
+ }
152
+
153
+ #[cfg(feature = "async")]
154
+ async fn read_async(t: &Rows, s: &Snapshot, given: &Stats) -> Result<Here> {
155
+ let mut df = HashMap::with_capacity(given.df.len());
156
+ let terms: Vec<&String> = given.df.keys().collect();
157
+ for term in terms {
158
+ df.insert(term.clone(), term_df_async(t, s, term).await?);
159
+ }
160
+ let mut fuzzy = Vec::with_capacity(given.fuzzy.len());
161
+ for f in &given.fuzzy {
162
+ let mut ns = Vec::with_capacity(f.expansions.len());
163
+ for e in &f.expansions {
164
+ ns.push(term_df_async(t, s, &e.term).await?);
165
+ }
166
+ fuzzy.push(ns);
167
+ }
168
+ Ok(Here { df, fuzzy })
169
+ }
170
+ }
171
+
172
+ /// `term`'s document frequency: its posting row's `df` counter.
173
+ fn term_df(t: &Rows, s: &Snapshot, term: &str) -> Result<i64> {
174
+ Ok(t.get_at(s, &post_row(term), DF, N)?
175
+ .and_then(|c| c.as_i64())
176
+ .unwrap_or(0))
177
+ }
178
+
179
+ /// [`term_df`] as a future.
180
+ #[cfg(feature = "async")]
181
+ async fn term_df_async(t: &Rows, s: &Snapshot, term: &str) -> Result<i64> {
182
+ Ok(t.get_at_async(s, &post_row(term), DF, N)
183
+ .await?
184
+ .and_then(|c| c.as_i64())
185
+ .unwrap_or(0))
186
+ }
187
+
83
188
  /// A search to run ([`Index::search`]).
84
189
  #[derive(Debug)]
85
190
  #[must_use = "a search does nothing until it runs"]
@@ -92,6 +197,8 @@ pub struct Search<'a> {
92
197
  max_expansions: usize,
93
198
  prefix_length: usize,
94
199
  highlight: bool,
200
+ /// The statistics to score with ([`Search::stats`]), or `None` for its own.
201
+ given: Option<QueryStats>,
95
202
  }
96
203
 
97
204
  /// A phrase as the evaluator matches it: each term with its offset from the first, and the
@@ -113,6 +220,7 @@ impl<'a> Search<'a> {
113
220
  max_expansions: DEFAULT_MAX_EXPANSIONS,
114
221
  prefix_length: 0,
115
222
  highlight: false,
223
+ given: None,
116
224
  }
117
225
  }
118
226
 
@@ -170,20 +278,65 @@ impl<'a> Search<'a> {
170
278
  /// The top `k` hits: by score descending, then id ascending.
171
279
  ///
172
280
  /// `InvalidQuery` for a query string that didn't parse; `InvalidArgument` for a phrase
173
- /// on an index without positions. It fails with `Busy` while a [`repair`](Index::repair)
174
- /// runs: retry after it finishes.
281
+ /// on an index without positions, or for [`stats`](Self::stats) of another query. It
282
+ /// fails with `Busy` while a [`repair`](Index::repair) runs: retry after it finishes.
175
283
  pub fn run(self) -> Result<Vec<Hit>> {
176
284
  self.run_with_stats().map(|(hits, _)| hits)
177
285
  }
178
286
 
287
+ /// Scores with `stats` instead of this index's own statistics (#1722, ICR 0138): the
288
+ /// merged statistics of every index a collection is split into, so each part's scores
289
+ /// are the whole collection's ([`QueryStats`] has the steps). Each fuzzy term expands
290
+ /// to the terms `stats` kept, whatever this index's own walk would keep.
291
+ ///
292
+ /// The statistics must be of this search's terms, phrase terms and fuzzy terms, read
293
+ /// with the same [`max_expansions`](Self::max_expansions) and
294
+ /// [`prefix_length`](Self::prefix_length), or the search fails with `InvalidArgument`.
295
+ /// A query that resolves to the same terms passes (a phrase's statistics serve its
296
+ /// words as terms), since the numbers are the same.
297
+ ///
298
+ /// The statistics are as of when they were read. A term whose documents were written
299
+ /// since has postings here and a `df` of 0 in them, so it scores as the rarest term, and
300
+ /// the document count leaves the new documents out: a consistent ranking, though not
301
+ /// one index's at either moment.
302
+ pub fn stats(mut self, stats: QueryStats) -> Self {
303
+ self.given = Some(stats);
304
+ self
305
+ }
306
+
307
+ /// This index's statistics for the query (#1722, ICR 0138): its document count and
308
+ /// length, each term's document frequency and each fuzzy term's expansions, all read at
309
+ /// one snapshot (the search's, or the latest). [`QueryStats`] says what they're for.
310
+ ///
311
+ /// They're the whole index's: `k`, [`id_prefix`](Self::id_prefix),
312
+ /// [`highlight`](Self::highlight) and [`stats`](Self::stats) don't change them. The
313
+ /// fuzzy options do.
314
+ ///
315
+ /// # Errors
316
+ /// As [`run`](Self::run).
317
+ pub fn query_stats(self) -> Result<QueryStats> {
318
+ self.check()?;
319
+ let index = self.index;
320
+ let owned;
321
+ let s = match self.snapshot {
322
+ Some(s) => s,
323
+ None => {
324
+ owned = index.inner.db.snapshot()?;
325
+ &owned
326
+ }
327
+ };
328
+ let packed = match index.inner.table.get_at(s, GLOBAL, META, REPAIR)? {
329
+ None => false,
330
+ Some(c) => crate::index::packed_state(c.value())?,
331
+ };
332
+ let t = index.rows(packed)?;
333
+ let mut r = self.resolve()?;
334
+ Ok(QueryStats(self.gather(t, s, &mut r)?))
335
+ }
336
+
179
337
  /// [`run`](Self::run), with what the search met.
180
338
  pub fn run_with_stats(self) -> Result<(Vec<Hit>, SearchStats)> {
181
- self.query.check()?;
182
- if self.max_expansions == 0 {
183
- return Err(Error::InvalidArgument(
184
- "max_expansions must be at least 1".into(),
185
- ));
186
- }
339
+ self.check()?;
187
340
  let index = self.index;
188
341
  let inn = &*index.inner;
189
342
  let owned;
@@ -194,106 +347,82 @@ impl<'a> Search<'a> {
194
347
  &owned
195
348
  }
196
349
  };
197
- let t = &inn.table;
198
- if t.get_at(s, GLOBAL, META, REPAIR)?.is_some() {
199
- return Err(Error::Busy);
200
- }
350
+ // The index's state, in one read ([`REPAIR`]): a repair running, or the layout.
351
+ let packed = match inn.table.get_at(s, GLOBAL, META, REPAIR)? {
352
+ None => false,
353
+ Some(c) => crate::index::packed_state(c.value())?,
354
+ };
355
+ let t = index.rows(packed)?;
201
356
  let mut r = self.resolve()?;
202
- if self.k == 0 || (r.terms.is_empty() && r.phrases.is_empty() && r.fuzzy.is_empty()) {
357
+ if self.k == 0 || r.is_empty() {
203
358
  return Ok((Vec::new(), SearchStats::default()));
204
359
  }
205
- let counter = |q: &[u8]| -> Result<i64> {
206
- Ok(t.get_at(s, STATS_ROW, STATS, q)?
207
- .and_then(|c| c.as_i64())
208
- .unwrap_or(0))
360
+ // The statistics it scores with: its own, or the ones it was given.
361
+ let given = self.given.as_ref().map(|g| &g.0);
362
+ let gathered;
363
+ let stats = match given {
364
+ Some(g) => {
365
+ self.matches(&r, g)?;
366
+ g
367
+ }
368
+ None => {
369
+ gathered = self.gather(t, s, &mut r)?;
370
+ &gathered
371
+ }
209
372
  };
210
- let n = counter(DOCS)?;
211
- if n <= 0 {
373
+ let Some(bm) = stats.bm25(inn.opts.get_k1(), inn.opts.get_b()) else {
212
374
  return Ok((Vec::new(), SearchStats::default()));
213
- }
214
- let bm = Bm25 {
215
- n: n as f64,
216
- avglen: (counter(LEN)?.max(0) as f64 / n as f64).max(f64::MIN_POSITIVE),
217
- k1: inn.opts.get_k1(),
218
- b: inn.opts.get_b(),
219
375
  };
220
- let mut df_of: HashMap<String, i64> = HashMap::new();
221
- for term in r.terms.iter().chain(
222
- r.phrases
223
- .iter()
224
- .flat_map(|p| p.terms.iter().map(|(t, _)| t)),
225
- ) {
226
- if !df_of.contains_key(term) {
227
- let df = t
228
- .get_at(s, &post_row(term), DF, N)?
229
- .and_then(|c| c.as_i64())
230
- .unwrap_or(0);
231
- df_of.insert(term.clone(), df);
232
- }
233
- }
234
- // Each fuzzy term's expansions, from the whole dictionary (not only `id_prefix`'s
235
- // documents), as the ranking statistics are.
236
- let mut expanded: Vec<Vec<Expansion>> = Vec::with_capacity(r.fuzzy.len());
237
- let mut fuzzy_stats = Vec::with_capacity(r.fuzzy.len());
238
- for f in &r.fuzzy {
239
- let (exps, cut) = expand(
240
- t,
241
- s,
242
- &f.term,
243
- f.edits,
244
- self.prefix_length,
245
- self.max_expansions,
246
- )?;
247
- if self.highlight {
248
- let set: BTreeSet<String> = exps.iter().map(|e| e.term.clone()).collect();
249
- for &c in &f.clauses {
250
- r.wants.push((c, Want::Terms(set.clone())));
251
- }
252
- }
253
- fuzzy_stats.push(FuzzyStats {
254
- clause: f.clauses[0],
255
- term: f.term.clone(),
256
- expansions: exps.len(),
257
- cut,
258
- });
259
- expanded.push(exps);
260
- }
376
+ // Given statistics: the terms' postings here, which its walks step through.
377
+ let here = match given {
378
+ Some(g) => Some(Here::read(t, s, g)?),
379
+ None => None,
380
+ };
381
+ let dfs = Dfs {
382
+ score: &stats.df,
383
+ here: here.as_ref().map(|h| &h.df),
384
+ };
385
+ let postings = here.as_ref().map(|h| h.fuzzy.as_slice());
386
+ let fuzzy_stats = self.fuzzy_stats(&mut r, stats);
261
387
  let prefix = self.prefix.as_deref();
262
388
  // The phrases, scored up front (D309 §4.2): their bounds are their actual maxima.
263
389
  let mut phrase_scores = Vec::with_capacity(r.phrases.len());
264
390
  for phrase in &r.phrases {
265
- phrase_scores.push(score_phrase(t, s, &bm, &df_of, phrase, prefix)?);
391
+ phrase_scores.push(score_phrase(t, s, &bm, dfs, phrase, prefix, packed)?);
266
392
  }
267
393
  let (fam, q) = (inn.source.family.as_str(), inn.source.qualifier.as_slice());
268
394
  // A stale hit (its source deleted around the index) is skipped and the next one takes
269
395
  // its place, so a run that met stale hits runs again for that many more.
270
396
  let mut want = self.k;
271
397
  loop {
272
- let mut clauses = Vec::with_capacity(r.terms.len() + r.phrases.len());
273
- for term in &r.terms {
274
- let df = df_of[term];
275
- if df > 0 {
276
- clauses.push(Scored::term(t, s, &bm, term, df, prefix)?);
277
- }
278
- }
279
- for exps in &expanded {
280
- if !exps.is_empty() {
281
- // Lucene's blended statistics (TopTermsBlendedFreqScoringRewrite): every
282
- // kept expansion scores with the largest df among them, so a rare
283
- // misspelling's idf no longer lifts it above the common word it misspells
284
- // (term frequency and length still count).
285
- let df = exps.iter().map(|e| e.df).max().expect("not empty");
286
- let e: Vec<(&str, i64, u64, f64)> = exps
287
- .iter()
288
- .map(|e| (e.term.as_str(), df, e.df.max(0) as u64, e.boost))
289
- .collect();
290
- clauses.push(Scored::fuzzy(t, s, &bm, &e, prefix)?);
291
- }
292
- }
293
- for ps in &phrase_scores {
294
- clauses.push(Scored::phrase(ps.clone()));
295
- }
296
- let ranked = crate::maxscore::top_k(t, s, &bm, clauses, want)?;
398
+ // One document loop per layout ([`Layout`]): a version 1 index's is the code it
399
+ // was.
400
+ let ranked = match packed {
401
+ true => rank::<Packed>(
402
+ t,
403
+ s,
404
+ &bm,
405
+ &r.terms,
406
+ dfs,
407
+ &stats.fuzzy,
408
+ postings,
409
+ &phrase_scores,
410
+ prefix,
411
+ want,
412
+ )?,
413
+ false => rank::<Cells>(
414
+ t,
415
+ s,
416
+ &bm,
417
+ &r.terms,
418
+ dfs,
419
+ &stats.fuzzy,
420
+ postings,
421
+ &phrase_scores,
422
+ prefix,
423
+ want,
424
+ )?,
425
+ };
297
426
  let complete = ranked.len() < want;
298
427
  let mut hits = Vec::with_capacity(self.k);
299
428
  let mut stats = SearchStats {
@@ -317,6 +446,104 @@ impl<'a> Search<'a> {
317
446
  }
318
447
  }
319
448
 
449
+ /// The checks before any read: the query parses, and `max_expansions` isn't 0.
450
+ fn check(&self) -> Result<()> {
451
+ self.query.check()?;
452
+ if self.max_expansions == 0 {
453
+ return Err(Error::InvalidArgument(
454
+ "max_expansions must be at least 1".into(),
455
+ ));
456
+ }
457
+ Ok(())
458
+ }
459
+
460
+ /// The index's statistics for the resolved query `r`, at `s`. Its fuzzy terms move
461
+ /// into them.
462
+ fn gather(&self, t: &Rows, s: &Snapshot, r: &mut Resolved) -> Result<Stats> {
463
+ let counter = |q: &[u8]| -> Result<i64> {
464
+ Ok(t.get_at(s, STATS_ROW, STATS, q)?
465
+ .and_then(|c| c.as_i64())
466
+ .unwrap_or(0))
467
+ };
468
+ let docs = counter(DOCS)?;
469
+ let len = counter(LEN)?;
470
+ let mut df: HashMap<String, i64> = HashMap::new();
471
+ for term in r.all_terms() {
472
+ if !df.contains_key(term) {
473
+ df.insert(term.clone(), term_df(t, s, term)?);
474
+ }
475
+ }
476
+ // Each fuzzy term's expansions, from the whole dictionary (not only `id_prefix`'s
477
+ // documents), as the ranking statistics are.
478
+ let mut fuzzy = Vec::with_capacity(r.fuzzy.len());
479
+ for f in std::mem::take(&mut r.fuzzy) {
480
+ let (expansions, cut) = expand(
481
+ t,
482
+ s,
483
+ &f.term,
484
+ f.edits,
485
+ self.prefix_length,
486
+ self.max_expansions,
487
+ )?;
488
+ fuzzy.push(Fuzzy {
489
+ clauses: f.clauses,
490
+ term: f.term,
491
+ edits: f.edits,
492
+ expansions,
493
+ cut,
494
+ });
495
+ }
496
+ Ok(Stats {
497
+ docs,
498
+ len,
499
+ max_expansions: self.max_expansions,
500
+ prefix_length: self.prefix_length,
501
+ df,
502
+ fuzzy,
503
+ })
504
+ }
505
+
506
+ /// `InvalidArgument` unless `given` holds the statistics of the resolved query `r`,
507
+ /// read with this search's fuzzy options.
508
+ fn matches(&self, r: &Resolved, given: &Stats) -> Result<()> {
509
+ let terms: BTreeSet<&String> = r.all_terms().collect();
510
+ let same = given.max_expansions == self.max_expansions
511
+ && given.prefix_length == self.prefix_length
512
+ && terms.len() == given.df.len()
513
+ && terms.iter().all(|t| given.df.contains_key(*t))
514
+ && given.fuzzy.len() == r.fuzzy.len()
515
+ && given
516
+ .fuzzy
517
+ .iter()
518
+ .zip(&r.fuzzy)
519
+ .all(|(g, f)| g.term == f.term && g.edits == f.edits && g.clauses == f.clauses);
520
+ match same {
521
+ true => Ok(()),
522
+ false => Err(other_query()),
523
+ }
524
+ }
525
+
526
+ /// What [`SearchStats::fuzzy`] reports of `stats`' fuzzy terms; with highlighting, each
527
+ /// one's expansions are added to what its clauses look for.
528
+ fn fuzzy_stats(&self, r: &mut Resolved, stats: &Stats) -> Vec<FuzzyStats> {
529
+ let mut out = Vec::with_capacity(stats.fuzzy.len());
530
+ for f in &stats.fuzzy {
531
+ if self.highlight {
532
+ let set: BTreeSet<String> = f.expansions.iter().map(|e| e.term.clone()).collect();
533
+ for &c in &f.clauses {
534
+ r.wants.push((c, Want::Terms(set.clone())));
535
+ }
536
+ }
537
+ out.push(FuzzyStats {
538
+ clause: f.clauses[0],
539
+ term: f.term.clone(),
540
+ expansions: f.expansions.len(),
541
+ cut: f.cut,
542
+ });
543
+ }
544
+ out
545
+ }
546
+
320
547
  /// A hit on `id`, its source holding `value`: with its text and matches when
321
548
  /// highlighting.
322
549
  fn hit(&self, r: &Resolved, id: Vec<u8>, score: f64, value: &[u8]) -> Hit {
@@ -365,6 +592,39 @@ impl<'a> Search<'a> {
365
592
  self.run_with_stats_async().await.map(|(hits, _)| hits)
366
593
  }
367
594
 
595
+ /// [`query_stats`](Self::query_stats) as a future, as [`run_async`](Self::run_async).
596
+ ///
597
+ /// # Errors
598
+ /// As [`run`](Self::run).
599
+ #[cfg(feature = "async")]
600
+ pub async fn query_stats_async(self) -> Result<QueryStats> {
601
+ self.check()?;
602
+ let index = self.index;
603
+ let owned;
604
+ let s = match self.snapshot {
605
+ Some(s) => s,
606
+ None => {
607
+ owned = index.inner.db.snapshot()?;
608
+ &owned
609
+ }
610
+ };
611
+ let packed = match index
612
+ .inner
613
+ .table
614
+ .get_at_async(s, GLOBAL, META, REPAIR)
615
+ .await?
616
+ {
617
+ None => false,
618
+ Some(c) => crate::index::packed_state(c.value())?,
619
+ };
620
+ let t = index.rows(packed)?;
621
+ let mut r = self.resolve()?;
622
+ let mut budget = crate::maxscore::Budget::new();
623
+ Ok(QueryStats(
624
+ self.gather_async(t, s, &mut r, &mut budget).await?,
625
+ ))
626
+ }
627
+
368
628
  /// [`run_with_stats`](Self::run_with_stats) as a future, as
369
629
  /// [`run_async`](Self::run_async).
370
630
  ///
@@ -372,13 +632,7 @@ impl<'a> Search<'a> {
372
632
  /// As [`run`](Self::run).
373
633
  #[cfg(feature = "async")]
374
634
  pub async fn run_with_stats_async(self) -> Result<(Vec<Hit>, SearchStats)> {
375
- use crate::maxscore::{Nonblocking, Polling, TopK};
376
- self.query.check()?;
377
- if self.max_expansions == 0 {
378
- return Err(Error::InvalidArgument(
379
- "max_expansions must be at least 1".into(),
380
- ));
381
- }
635
+ self.check()?;
382
636
  let index = self.index;
383
637
  let inn = &*index.inner;
384
638
  let owned;
@@ -389,141 +643,86 @@ impl<'a> Search<'a> {
389
643
  &owned
390
644
  }
391
645
  };
392
- let t = &inn.table;
393
- if t.get_at_async(s, GLOBAL, META, REPAIR).await?.is_some() {
394
- return Err(Error::Busy);
395
- }
396
- let mut r = self.resolve()?;
397
- if self.k == 0 || (r.terms.is_empty() && r.phrases.is_empty() && r.fuzzy.is_empty()) {
398
- return Ok((Vec::new(), SearchStats::default()));
399
- }
400
- let counter = |q: &'static [u8]| async move {
401
- Ok::<i64, Error>(
402
- t.get_at_async(s, STATS_ROW, STATS, q)
403
- .await?
404
- .and_then(|c| c.as_i64())
405
- .unwrap_or(0),
406
- )
646
+ let packed = match inn.table.get_at_async(s, GLOBAL, META, REPAIR).await? {
647
+ None => false,
648
+ Some(c) => crate::index::packed_state(c.value())?,
407
649
  };
408
- let n = counter(DOCS).await?;
409
- if n <= 0 {
650
+ let t = index.rows(packed)?;
651
+ let mut r = self.resolve()?;
652
+ if self.k == 0 || r.is_empty() {
410
653
  return Ok((Vec::new(), SearchStats::default()));
411
654
  }
412
- let bm = Bm25 {
413
- n: n as f64,
414
- avglen: (counter(LEN).await?.max(0) as f64 / n as f64).max(f64::MIN_POSITIVE),
415
- k1: inn.opts.get_k1(),
416
- b: inn.opts.get_b(),
417
- };
418
- let mut df_of: HashMap<String, i64> = HashMap::new();
419
- // Collected first: an iterator chain with closures held across an `.await` makes the
420
- // future not `Send`.
421
- let terms: Vec<String> = r
422
- .terms
423
- .iter()
424
- .chain(
425
- r.phrases
426
- .iter()
427
- .flat_map(|p| p.terms.iter().map(|(t, _)| t)),
428
- )
429
- .cloned()
430
- .collect();
431
- for term in terms {
432
- if let std::collections::hash_map::Entry::Vacant(e) = df_of.entry(term) {
433
- let df = t
434
- .get_at_async(s, &post_row(e.key()), DF, N)
435
- .await?
436
- .and_then(|c| c.as_i64())
437
- .unwrap_or(0);
438
- e.insert(df);
439
- }
440
- }
441
655
  // One step budget for the search's work outside MaxScore (ai1249's R1 on #1642): the
442
656
  // fuzzy walks, the phrase position walks and their lengths. Shared, so a poll does
443
657
  // at most a budget's work across them, not a budget per loop.
444
658
  let mut budget = crate::maxscore::Budget::new();
445
- let mut expanded: Vec<Vec<Expansion>> = Vec::with_capacity(r.fuzzy.len());
446
- let mut fuzzy_stats = Vec::with_capacity(r.fuzzy.len());
447
- for f in &r.fuzzy {
448
- let (exps, cut) = crate::fuzzy::expand_async(
449
- t,
450
- s,
451
- &f.term,
452
- f.edits,
453
- self.prefix_length,
454
- self.max_expansions,
455
- &mut budget,
456
- )
457
- .await?;
458
- if self.highlight {
459
- let set: BTreeSet<String> = exps.iter().map(|e| e.term.clone()).collect();
460
- for &c in &f.clauses {
461
- r.wants.push((c, Want::Terms(set.clone())));
462
- }
659
+ let given = self.given.as_ref().map(|g| &g.0);
660
+ let gathered;
661
+ let stats = match given {
662
+ Some(g) => {
663
+ self.matches(&r, g)?;
664
+ g
463
665
  }
464
- fuzzy_stats.push(FuzzyStats {
465
- clause: f.clauses[0],
466
- term: f.term.clone(),
467
- expansions: exps.len(),
468
- cut,
469
- });
470
- expanded.push(exps);
471
- }
666
+ None => {
667
+ gathered = self.gather_async(t, s, &mut r, &mut budget).await?;
668
+ &gathered
669
+ }
670
+ };
671
+ let Some(bm) = stats.bm25(inn.opts.get_k1(), inn.opts.get_b()) else {
672
+ return Ok((Vec::new(), SearchStats::default()));
673
+ };
674
+ let here = match given {
675
+ Some(g) => Some(Here::read_async(t, s, g).await?),
676
+ None => None,
677
+ };
678
+ let dfs = Dfs {
679
+ score: &stats.df,
680
+ here: here.as_ref().map(|h| &h.df),
681
+ };
682
+ let postings = here.as_ref().map(|h| h.fuzzy.as_slice());
683
+ let fuzzy_stats = self.fuzzy_stats(&mut r, stats);
472
684
  let prefix = self.prefix.as_deref();
473
685
  let mut phrase_scores = Vec::with_capacity(r.phrases.len());
474
686
  for phrase in &r.phrases {
475
- phrase_scores
476
- .push(score_phrase_async(t, s, &bm, &df_of, phrase, prefix, &mut budget).await?);
687
+ phrase_scores.push(
688
+ score_phrase_async(t, s, &bm, dfs, phrase, prefix, packed, &mut budget).await?,
689
+ );
477
690
  }
478
691
  let (fam, q) = (inn.source.family.as_str(), inn.source.qualifier.as_slice());
479
692
  let mut want = self.k;
480
693
  loop {
481
- let mut clauses: Vec<Scored<'_, Nonblocking>> =
482
- Vec::with_capacity(r.terms.len() + r.phrases.len());
483
- for term in &r.terms {
484
- let df = df_of[term];
485
- if df > 0 {
486
- let w = crate::maxscore::walk_async(
694
+ let ranked = match packed {
695
+ true => {
696
+ rank_async::<Packed>(
487
697
  t,
488
698
  s,
489
699
  &bm,
490
- term,
491
- bm.idf(df),
492
- df.max(0) as u64,
700
+ &r.terms,
701
+ dfs,
702
+ &stats.fuzzy,
703
+ postings,
704
+ &phrase_scores,
493
705
  prefix,
706
+ want,
494
707
  )
495
- .await?;
496
- clauses.push(Scored::of_term(w));
708
+ .await?
497
709
  }
498
- }
499
- for exps in &expanded {
500
- if !exps.is_empty() {
501
- // Lucene's blended statistics, as `run_with_stats`.
502
- let df = exps.iter().map(|e| e.df).max().expect("not empty");
503
- let mut walks = Vec::with_capacity(exps.len());
504
- for e in exps {
505
- walks.push(
506
- crate::maxscore::walk_async(
507
- t,
508
- s,
509
- &bm,
510
- &e.term,
511
- e.boost * bm.idf(df),
512
- e.df.max(0) as u64,
513
- prefix,
514
- )
515
- .await?,
516
- );
517
- }
518
- clauses.push(Scored::of_fuzzy(walks));
710
+ false => {
711
+ rank_async::<Cells>(
712
+ t,
713
+ s,
714
+ &bm,
715
+ &r.terms,
716
+ dfs,
717
+ &stats.fuzzy,
718
+ postings,
719
+ &phrase_scores,
720
+ prefix,
721
+ want,
722
+ )
723
+ .await?
519
724
  }
520
- }
521
- for ps in &phrase_scores {
522
- clauses.push(Scored::phrase(ps.clone()));
523
- }
524
- let mut run = TopK::new(clauses, want);
525
- std::future::poll_fn(|cx| run.run(t, s, &bm, &mut Polling::new(cx))).await?;
526
- let ranked = run.finish();
725
+ };
527
726
  let complete = ranked.len() < want;
528
727
  let mut hits = Vec::with_capacity(self.k);
529
728
  let mut stats = SearchStats {
@@ -547,6 +746,65 @@ impl<'a> Search<'a> {
547
746
  }
548
747
  }
549
748
 
749
+ /// [`gather`](Self::gather) as a future: the fuzzy walks spend `budget`.
750
+ #[cfg(feature = "async")]
751
+ async fn gather_async(
752
+ &self,
753
+ t: &Rows,
754
+ s: &Snapshot,
755
+ r: &mut Resolved,
756
+ budget: &mut crate::maxscore::Budget,
757
+ ) -> Result<Stats> {
758
+ let counter = |q: &'static [u8]| async move {
759
+ Ok::<i64, Error>(
760
+ t.get_at_async(s, STATS_ROW, STATS, q)
761
+ .await?
762
+ .and_then(|c| c.as_i64())
763
+ .unwrap_or(0),
764
+ )
765
+ };
766
+ let docs = counter(DOCS).await?;
767
+ let len = counter(LEN).await?;
768
+ let mut df: HashMap<String, i64> = HashMap::new();
769
+ // Collected first: an iterator chain with closures held across an `.await` makes the
770
+ // future not `Send`.
771
+ let terms: Vec<String> = r.all_terms().cloned().collect();
772
+ for term in terms {
773
+ if let std::collections::hash_map::Entry::Vacant(e) = df.entry(term) {
774
+ let n = term_df_async(t, s, e.key()).await?;
775
+ e.insert(n);
776
+ }
777
+ }
778
+ let mut fuzzy = Vec::with_capacity(r.fuzzy.len());
779
+ for f in std::mem::take(&mut r.fuzzy) {
780
+ let (expansions, cut) = crate::fuzzy::expand_async(
781
+ t,
782
+ s,
783
+ &f.term,
784
+ f.edits,
785
+ self.prefix_length,
786
+ self.max_expansions,
787
+ budget,
788
+ )
789
+ .await?;
790
+ fuzzy.push(Fuzzy {
791
+ clauses: f.clauses,
792
+ term: f.term,
793
+ edits: f.edits,
794
+ expansions,
795
+ cut,
796
+ });
797
+ }
798
+ Ok(Stats {
799
+ docs,
800
+ len,
801
+ max_expansions: self.max_expansions,
802
+ prefix_length: self.prefix_length,
803
+ df,
804
+ fuzzy,
805
+ })
806
+ }
807
+
550
808
  /// The query's distinct terms, phrases and fuzzy terms, normalised and tokenised as the
551
809
  /// clauses say. A term a clause yields twice counts once; a one-term phrase is a term.
552
810
  /// With [`highlight`](Self::highlight), also what each clause looks for (its fuzzy
@@ -663,6 +921,127 @@ impl<'a> Search<'a> {
663
921
  }
664
922
  }
665
923
 
924
+ /// The top `want` documents of the query's clauses, by MaxScore, over the layout `L`. A
925
+ /// term, or a fuzzy term's expansion, with no postings here adds no clause.
926
+ #[allow(clippy::too_many_arguments)]
927
+ #[inline(always)]
928
+ fn rank<L: Layout>(
929
+ t: &Rows,
930
+ s: &Snapshot,
931
+ bm: &Bm25,
932
+ terms: &BTreeSet<String>,
933
+ dfs: Dfs<'_>,
934
+ fuzzy: &[Fuzzy],
935
+ postings: Option<&[Vec<i64>]>,
936
+ phrase_scores: &[BTreeMap<Vec<u8>, f64>],
937
+ prefix: Option<&[u8]>,
938
+ want: usize,
939
+ ) -> Result<Vec<(Vec<u8>, f64)>> {
940
+ let mut clauses = Vec::with_capacity(terms.len() + phrase_scores.len());
941
+ for term in terms {
942
+ let (df, here) = dfs.both(term);
943
+ if here > 0 {
944
+ clauses.push(Scored::<Blocking, L>::term(
945
+ t,
946
+ s,
947
+ bm,
948
+ term,
949
+ df,
950
+ here as u64,
951
+ prefix,
952
+ )?);
953
+ }
954
+ }
955
+ for (i, f) in fuzzy.iter().enumerate() {
956
+ let e = expansions(f, i, postings);
957
+ if !e.is_empty() {
958
+ clauses.push(Scored::fuzzy(t, s, bm, &e, prefix)?);
959
+ }
960
+ }
961
+ for ps in phrase_scores {
962
+ clauses.push(Scored::phrase(ps.clone()));
963
+ }
964
+ crate::maxscore::top_k(t, s, bm, clauses, want)
965
+ }
966
+
967
+ /// The `i`th fuzzy term's expansions with postings here, as [`Scored::fuzzy`] takes them:
968
+ /// `(term, df, postings, boost)`. Lucene's blended statistics
969
+ /// (TopTermsBlendedFreqScoringRewrite): every kept expansion scores with the largest `df`
970
+ /// among them, so a rare misspelling's idf no longer lifts it above the common word it
971
+ /// misspells (term frequency and length still count).
972
+ fn expansions<'f>(
973
+ f: &'f Fuzzy,
974
+ i: usize,
975
+ postings: Option<&[Vec<i64>]>,
976
+ ) -> Vec<(&'f str, i64, u64, f64)> {
977
+ let Some(df) = f.expansions.iter().map(|e| e.df).max() else {
978
+ return Vec::new();
979
+ };
980
+ f.expansions
981
+ .iter()
982
+ .enumerate()
983
+ .filter_map(|(j, e)| {
984
+ let here = postings.map_or(e.df, |p| p[i][j]);
985
+ (here > 0).then_some((e.term.as_str(), df, here as u64, e.boost))
986
+ })
987
+ .collect()
988
+ }
989
+
990
+ /// [`rank`] as a future (#1560).
991
+ #[cfg(feature = "async")]
992
+ #[allow(clippy::too_many_arguments)]
993
+ async fn rank_async<L: Layout>(
994
+ t: &Rows,
995
+ s: &Snapshot,
996
+ bm: &Bm25,
997
+ terms: &BTreeSet<String>,
998
+ dfs: Dfs<'_>,
999
+ fuzzy: &[Fuzzy],
1000
+ postings: Option<&[Vec<i64>]>,
1001
+ phrase_scores: &[BTreeMap<Vec<u8>, f64>],
1002
+ prefix: Option<&[u8]>,
1003
+ want: usize,
1004
+ ) -> Result<Vec<(Vec<u8>, f64)>> {
1005
+ use crate::maxscore::{Nonblocking, Polling, TopK};
1006
+ let mut clauses: Vec<Scored<'_, Nonblocking, L>> =
1007
+ Vec::with_capacity(terms.len() + phrase_scores.len());
1008
+ for term in terms {
1009
+ let (df, here) = dfs.both(term);
1010
+ if here > 0 {
1011
+ let w = crate::maxscore::walk_async(t, s, bm, term, bm.idf(df), here as u64, prefix)
1012
+ .await?;
1013
+ clauses.push(Scored::of_term(w));
1014
+ }
1015
+ }
1016
+ for (i, f) in fuzzy.iter().enumerate() {
1017
+ let e = expansions(f, i, postings);
1018
+ if !e.is_empty() {
1019
+ let mut walks = Vec::with_capacity(e.len());
1020
+ for (term, df, postings, boost) in e {
1021
+ walks.push(
1022
+ crate::maxscore::walk_async(
1023
+ t,
1024
+ s,
1025
+ bm,
1026
+ term,
1027
+ boost * bm.idf(df),
1028
+ postings,
1029
+ prefix,
1030
+ )
1031
+ .await?,
1032
+ );
1033
+ }
1034
+ clauses.push(Scored::of_fuzzy(walks));
1035
+ }
1036
+ }
1037
+ for ps in phrase_scores {
1038
+ clauses.push(Scored::phrase(ps.clone()));
1039
+ }
1040
+ let mut run = TopK::new(clauses, want);
1041
+ std::future::poll_fn(|cx| run.run(t, s, bm, &mut Polling::new(cx))).await?;
1042
+ Ok(run.finish())
1043
+ }
1044
+
666
1045
  impl Phrase {
667
1046
  /// What highlighting looks for: a one-term phrase is that term.
668
1047
  fn want(&self) -> Option<Want> {
@@ -681,88 +1060,676 @@ impl Phrase {
681
1060
  /// is the sum of its terms' (D309 §4.3). Its frequency is its exact occurrences at slop 0,
682
1061
  /// and its sloppy frequency (`Σ 1 / (distance + 1)` over its matches, D309 rev 6 §B) above
683
1062
  /// that.
1063
+ ///
1064
+ /// A join in document order (#1586): the lead term's position row is walked, and each other
1065
+ /// term is brought to the lead's document ([`Joined`]). Positions are decoded only for a
1066
+ /// document every term has, into buffers reused from one document to the next.
684
1067
  fn score_phrase(
685
1068
  t: &Rows,
686
1069
  s: &Snapshot,
687
1070
  bm: &Bm25,
688
- df_of: &HashMap<String, i64>,
1071
+ dfs: Dfs<'_>,
689
1072
  phrase: &Phrase,
690
1073
  prefix: Option<&[u8]>,
1074
+ packed: bool,
691
1075
  ) -> Result<BTreeMap<Vec<u8>, f64>> {
692
- let mut scores = BTreeMap::new();
693
- let Some(plan) = PhrasePlan::new(bm, df_of, phrase) else {
694
- return Ok(scores);
1076
+ let Some(plan) = PhrasePlan::new(bm, dfs, phrase) else {
1077
+ return Ok(BTreeMap::new());
695
1078
  };
696
- let terms = &phrase.terms;
697
- let mut by_term: BTreeMap<&str, BTreeMap<Vec<u8>, Vec<u32>>> = BTreeMap::new();
698
- let lead_term = terms[plan.lead].0.as_str();
699
- by_term.insert(lead_term, read_positions(t, s, lead_term, None, prefix)?);
700
- for (term, _) in terms {
701
- if by_term.contains_key(term.as_str()) {
702
- continue;
1079
+ let row = post_row(&phrase.terms[plan.lead].0);
1080
+ let cells = cells_of(t, s, &row, POS, prefix).cells()?;
1081
+ if packed {
1082
+ let lead = MergedLead::new(t, s, &row, cells, prefix)?;
1083
+ join::<Packed>(t, s, bm, dfs, phrase, prefix, &plan, lead)
1084
+ } else {
1085
+ join::<Cells>(t, s, bm, dfs, phrase, prefix, &plan, cells)
1086
+ }
1087
+ }
1088
+
1089
+ /// The lead term's positions in document order: its position cells in a version 1 index
1090
+ /// (the walk the join had before #1585, monomorphized to the same code), the merged stream
1091
+ /// in a version 2 one.
1092
+ trait Lead {
1093
+ /// A posting of the lead's, lent until the next step.
1094
+ type At<'a>: At
1095
+ where
1096
+ Self: 'a;
1097
+
1098
+ /// The next document with the term.
1099
+ fn next(&mut self) -> Result<Option<Self::At<'_>>>;
1100
+ }
1101
+
1102
+ /// One posting of a [`Lead`]: its document and its encoded positions there.
1103
+ trait At {
1104
+ fn doc(&self) -> &[u8];
1105
+ fn positions(&self) -> &[u8];
1106
+ }
1107
+
1108
+ impl At for pigeonhole::CellEntry<'_> {
1109
+ #[inline(always)]
1110
+ fn doc(&self) -> &[u8] {
1111
+ self.qualifier
1112
+ }
1113
+
1114
+ #[inline(always)]
1115
+ fn positions(&self) -> &[u8] {
1116
+ self.cell.value()
1117
+ }
1118
+ }
1119
+
1120
+ impl At for (&[u8], &[u8]) {
1121
+ fn doc(&self) -> &[u8] {
1122
+ self.0
1123
+ }
1124
+
1125
+ fn positions(&self) -> &[u8] {
1126
+ self.1
1127
+ }
1128
+ }
1129
+
1130
+ impl<'t> Lead for pigeonhole::RowCells<'t> {
1131
+ type At<'a>
1132
+ = pigeonhole::CellEntry<'a>
1133
+ where
1134
+ Self: 'a;
1135
+
1136
+ #[inline(always)]
1137
+ fn next(&mut self) -> Result<Option<Self::At<'_>>> {
1138
+ Ok(pigeonhole::RowCells::next(self)?)
1139
+ }
1140
+ }
1141
+
1142
+ /// A version 2 index's lead: its position cells over its blocks.
1143
+ struct MergedLead<'t> {
1144
+ cells: pigeonhole::RowCells<'t>,
1145
+ merged: Merged<'t>,
1146
+ /// The posting handed out last, passed at the next call.
1147
+ on: Option<Tier>,
1148
+ }
1149
+
1150
+ impl<'t> MergedLead<'t> {
1151
+ fn new(
1152
+ t: &'t Rows,
1153
+ s: &Snapshot,
1154
+ row: &[u8],
1155
+ cells: pigeonhole::RowCells<'t>,
1156
+ prefix: Option<&[u8]>,
1157
+ ) -> Result<Self> {
1158
+ Ok(MergedLead {
1159
+ cells,
1160
+ merged: Merged::new(t, s, row, POS, prefix)?,
1161
+ on: None,
1162
+ })
1163
+ }
1164
+ }
1165
+
1166
+ impl<'t> Lead for MergedLead<'t> {
1167
+ type At<'a>
1168
+ = (&'a [u8], &'a [u8])
1169
+ where
1170
+ Self: 'a;
1171
+
1172
+ fn next(&mut self) -> Result<Option<Self::At<'_>>> {
1173
+ if let Some(tier) = self.on.take() {
1174
+ self.merged.skip(tier);
703
1175
  }
704
- let keep = &by_term[lead_term];
705
- let got = read_positions(t, s, term, Some(keep), prefix)?;
706
- by_term.insert(term, got);
1176
+ sync(
1177
+ self.merged
1178
+ .settle::<Blocking>(&mut self.cells, &mut (), None),
1179
+ )?;
1180
+ self.on = self.merged.head();
1181
+ Ok(self
1182
+ .on
1183
+ .map(|tier| (self.merged.id(tier), self.merged.positions(tier))))
707
1184
  }
708
- for (doc, lead_ps) in &by_term[lead_term] {
709
- let Some(freq) = plan.freq(phrase, &by_term, doc, lead_ps) else {
1185
+ }
1186
+
1187
+ impl MergedLead<'_> {
1188
+ /// [`Lead::next`] without blocking.
1189
+ #[cfg(feature = "async")]
1190
+ async fn next_async(&mut self) -> Result<Option<(&[u8], &[u8])>> {
1191
+ use crate::maxscore::{Nonblocking, Polling};
1192
+ if let Some(tier) = self.on.take() {
1193
+ self.merged.skip(tier);
1194
+ }
1195
+ let (merged, cells) = (&mut self.merged, &mut self.cells);
1196
+ std::future::poll_fn(|cx| merged.settle::<Nonblocking>(cells, &mut Polling::new(cx), None))
1197
+ .await?;
1198
+ self.on = self.merged.head();
1199
+ Ok(self
1200
+ .on
1201
+ .map(|tier| (self.merged.id(tier), self.merged.positions(tier))))
1202
+ }
1203
+ }
1204
+
1205
+ /// [`score_phrase`]'s join, over the lead's stream.
1206
+ #[allow(clippy::too_many_arguments)]
1207
+ fn join<L: Layout>(
1208
+ t: &Rows,
1209
+ s: &Snapshot,
1210
+ bm: &Bm25,
1211
+ dfs: Dfs<'_>,
1212
+ phrase: &Phrase,
1213
+ prefix: Option<&[u8]>,
1214
+ plan: &PhrasePlan,
1215
+ mut lead: impl Lead,
1216
+ ) -> Result<BTreeMap<Vec<u8>, f64>> {
1217
+ let mut scores = BTreeMap::new();
1218
+ let lead_term = phrase.terms[plan.lead].0.as_str();
1219
+ let mut others = plan.others::<L>(dfs, phrase, prefix);
1220
+ // The lead's postings, for the length of each document the phrase is in.
1221
+ let mut lens = Joined::<L>::new(lead_term, POST, dfs.here(lead_term), None, prefix);
1222
+ let mut lists: Vec<Vec<u32>> = vec![Vec::new(); others.len() + 1];
1223
+ 'docs: while let Some(e) = lead.next()? {
1224
+ let doc = e.doc();
1225
+ for (o, list) in others.iter_mut().zip(&mut lists[1..]) {
1226
+ // A document without every term can't hold the phrase.
1227
+ if !o.at(t, s, doc)? {
1228
+ continue 'docs;
1229
+ }
1230
+ decode_positions(&o.value, list)?;
1231
+ }
1232
+ decode_positions(e.positions(), &mut lists[0])?;
1233
+ let Some(freq) = plan.freq(phrase, &lists) else {
710
1234
  continue;
711
1235
  };
712
- let len = match t.get_at(s, &post_row(lead_term), POST, doc)? {
713
- Some(c) => c.as_u64(),
714
- None => return Err(corrupt("a position has no posting")),
715
- };
716
- scores.insert(doc.clone(), plan.score(bm, freq, len)?);
1236
+ if !lens.at(t, s, doc)? {
1237
+ return Err(corrupt("a position has no posting"));
1238
+ }
1239
+ scores.insert(doc.to_vec(), plan.score(bm, freq, lens.number)?);
717
1240
  }
718
1241
  Ok(scores)
719
1242
  }
720
1243
 
721
- /// [`score_phrase`] as a future (#1560): the same positions and lengths, read without
722
- /// blocking.
1244
+ /// [`score_phrase`] as a future (#1560): the same join, read without blocking.
723
1245
  #[cfg(feature = "async")]
1246
+ #[allow(clippy::too_many_arguments)]
724
1247
  async fn score_phrase_async(
725
1248
  t: &Rows,
726
1249
  s: &Snapshot,
727
1250
  bm: &Bm25,
728
- df_of: &HashMap<String, i64>,
1251
+ dfs: Dfs<'_>,
729
1252
  phrase: &Phrase,
730
1253
  prefix: Option<&[u8]>,
1254
+ packed: bool,
731
1255
  budget: &mut crate::maxscore::Budget,
732
1256
  ) -> Result<BTreeMap<Vec<u8>, f64>> {
733
- let mut scores = BTreeMap::new();
734
- let Some(plan) = PhrasePlan::new(bm, df_of, phrase) else {
735
- return Ok(scores);
1257
+ let Some(plan) = PhrasePlan::new(bm, dfs, phrase) else {
1258
+ return Ok(BTreeMap::new());
736
1259
  };
737
- let terms = &phrase.terms;
738
- let mut by_term: BTreeMap<&str, BTreeMap<Vec<u8>, Vec<u32>>> = BTreeMap::new();
739
- let lead_term = terms[plan.lead].0.as_str();
740
- let lead = read_positions_async(t, s, lead_term, None, prefix, budget).await?;
741
- by_term.insert(lead_term, lead);
742
- for (term, _) in terms {
743
- if by_term.contains_key(term.as_str()) {
744
- continue;
1260
+ let row = post_row(&phrase.terms[plan.lead].0);
1261
+ let cells = cells_of(t, s, &row, POS, prefix).cells()?;
1262
+ if packed {
1263
+ let lead = AsyncLead::Merged(MergedLead::new(t, s, &row, cells, prefix)?);
1264
+ join_async::<Packed>(t, s, bm, dfs, phrase, prefix, &plan, lead, budget).await
1265
+ } else {
1266
+ let lead = AsyncLead::Cells(cells);
1267
+ join_async::<Cells>(t, s, bm, dfs, phrase, prefix, &plan, lead, budget).await
1268
+ }
1269
+ }
1270
+
1271
+ /// The async join's lead: a [`Lead`] by a match. A trait's async method with a lent item
1272
+ /// gives a future that isn't `Send` for every lifetime, which `run_async` promises.
1273
+ // One a phrase, held in the search's future: boxing the larger variant would only add an
1274
+ // allocation.
1275
+ #[cfg(feature = "async")]
1276
+ #[allow(clippy::large_enum_variant)]
1277
+ enum AsyncLead<'t> {
1278
+ Cells(pigeonhole::RowCells<'t>),
1279
+ Merged(MergedLead<'t>),
1280
+ }
1281
+
1282
+ /// One posting of an [`AsyncLead`].
1283
+ #[cfg(feature = "async")]
1284
+ enum AsyncAt<'a> {
1285
+ Cell(pigeonhole::CellEntry<'a>),
1286
+ Merged((&'a [u8], &'a [u8])),
1287
+ }
1288
+
1289
+ #[cfg(feature = "async")]
1290
+ impl AsyncLead<'_> {
1291
+ async fn next(&mut self) -> Result<Option<AsyncAt<'_>>> {
1292
+ Ok(match self {
1293
+ AsyncLead::Cells(cells) => cells.next_async().await?.map(AsyncAt::Cell),
1294
+ AsyncLead::Merged(lead) => lead.next_async().await?.map(AsyncAt::Merged),
1295
+ })
1296
+ }
1297
+ }
1298
+
1299
+ #[cfg(feature = "async")]
1300
+ impl AsyncAt<'_> {
1301
+ fn doc(&self) -> &[u8] {
1302
+ match self {
1303
+ AsyncAt::Cell(e) => e.doc(),
1304
+ AsyncAt::Merged(e) => e.doc(),
745
1305
  }
746
- let keep = Some(&by_term[lead_term]);
747
- let got = read_positions_async(t, s, term, keep, prefix, budget).await?;
748
- by_term.insert(term, got);
749
1306
  }
750
- for (doc, lead_ps) in &by_term[lead_term] {
751
- let Some(freq) = plan.freq(phrase, &by_term, doc, lead_ps) else {
752
- continue;
1307
+
1308
+ fn positions(&self) -> &[u8] {
1309
+ match self {
1310
+ AsyncAt::Cell(e) => e.positions(),
1311
+ AsyncAt::Merged(e) => e.positions(),
1312
+ }
1313
+ }
1314
+ }
1315
+
1316
+ /// [`join`] as a future.
1317
+ #[cfg(feature = "async")]
1318
+ #[allow(clippy::too_many_arguments)]
1319
+ async fn join_async<'t, L: Layout>(
1320
+ t: &'t Rows,
1321
+ s: &Snapshot,
1322
+ bm: &Bm25,
1323
+ dfs: Dfs<'_>,
1324
+ phrase: &Phrase,
1325
+ prefix: Option<&[u8]>,
1326
+ plan: &PhrasePlan,
1327
+ mut lead: AsyncLead<'t>,
1328
+ budget: &mut crate::maxscore::Budget,
1329
+ ) -> Result<BTreeMap<Vec<u8>, f64>> {
1330
+ let mut scores = BTreeMap::new();
1331
+ let lead_term = phrase.terms[plan.lead].0.as_str();
1332
+ let mut others = plan.others::<L>(dfs, phrase, prefix);
1333
+ let mut lens = Joined::<L>::new(lead_term, POST, dfs.here(lead_term), None, prefix);
1334
+ let mut lists: Vec<Vec<u32>> = vec![Vec::new(); others.len() + 1];
1335
+ 'docs: loop {
1336
+ budget.spend(1).await;
1337
+ let Some(e) = lead.next().await? else {
1338
+ break;
753
1339
  };
754
- // A cached get resolves at once: without a budget, a phrase over a hub term's
755
- // documents would never yield (ai1249's R1).
756
- budget.spend(crate::maxscore::LOOKUP_STEPS).await;
757
- let len = match t.get_at_async(s, &post_row(lead_term), POST, doc).await? {
758
- Some(c) => c.as_u64(),
759
- None => return Err(corrupt("a position has no posting")),
1340
+ let doc = e.doc();
1341
+ for (o, list) in others.iter_mut().zip(&mut lists[1..]) {
1342
+ if !o.at_async(t, s, doc, budget).await? {
1343
+ continue 'docs;
1344
+ }
1345
+ decode_positions(&o.value, list)?;
1346
+ }
1347
+ decode_positions(e.positions(), &mut lists[0])?;
1348
+ let Some(freq) = plan.freq(phrase, &lists) else {
1349
+ continue;
760
1350
  };
761
- scores.insert(doc.clone(), plan.score(bm, freq, len)?);
1351
+ // Its reads spend the budget themselves: a cached get resolves at once, and
1352
+ // without one a phrase over a hub term's documents would never yield (ai1249's R1).
1353
+ if !lens.at_async(t, s, doc, budget).await? {
1354
+ return Err(corrupt("a position has no posting"));
1355
+ }
1356
+ scores.insert(doc.to_vec(), plan.score(bm, freq, lens.number)?);
762
1357
  }
763
1358
  Ok(scores)
764
1359
  }
765
1360
 
1361
+ /// The read of a posting row's `family`, restricted to ids starting with `prefix`.
1362
+ fn cells_of<'t>(
1363
+ t: &'t Rows,
1364
+ s: &Snapshot,
1365
+ row: &[u8],
1366
+ family: &'static str,
1367
+ prefix: Option<&[u8]>,
1368
+ ) -> pigeonhole::RowRead<'t> {
1369
+ let read = t.row(row).family(family).snapshot(s);
1370
+ match prefix {
1371
+ Some(p) => read.qualifier_prefix(p),
1372
+ None => read,
1373
+ }
1374
+ }
1375
+
1376
+ /// One of a phrase's posting-row families in the join (#1586): a term's cells in the
1377
+ /// documents the lead's walk asks for, which come in ascending order. The other terms'
1378
+ /// positions are read this way, and so are the lead's own postings, for the length of a
1379
+ /// document the phrase is in.
1380
+ ///
1381
+ /// Reached by point reads or by the row's own walk, whichever costs less, at a point read's
1382
+ /// price of [`LOOKUP_IN_STEPS`](crate::maxscore::LOOKUP_IN_STEPS) steps (perf287's measure,
1383
+ /// #1368). So a rare lead beside a common word reads the common word's row at the lead's
1384
+ /// documents only, and two common words are merged a step at a time.
1385
+ /// - **Another term's positions:** the lead's `df` says how many documents will be asked
1386
+ /// for, so the choice is made up front.
1387
+ /// - **The lead's postings:** asked for only where the phrase occurs, which isn't known, so
1388
+ /// by MaxScore's rule for a non-essential clause (`Walk::lookup`, ski-rental): point reads
1389
+ /// until they'd cost more than stepping through what's left of the row, then the walk for
1390
+ /// good.
1391
+ struct Joined<'t, L: Layout> {
1392
+ row: Vec<u8>,
1393
+ family: &'static str,
1394
+ prefix: Option<Vec<u8>>,
1395
+ /// The row's walk, opened when the join switches to it.
1396
+ cells: Option<pigeonhole::RowCells<'t>>,
1397
+ /// The document the walk stands on, once it has stepped. A buffer, reused.
1398
+ doc: Vec<u8>,
1399
+ /// The cell of the document last found ([`at`](Self::at) returned `true`): its value
1400
+ /// (a buffer, reused), and the value as a number, if it is one.
1401
+ value: Vec<u8>,
1402
+ number: Option<u64>,
1403
+ /// Whether the walk has run off the row's end.
1404
+ ended: bool,
1405
+ /// The row's postings (the term's `df`), the steps the walk has taken, and the point
1406
+ /// reads done.
1407
+ postings: u64,
1408
+ stepped: u64,
1409
+ lookups: u64,
1410
+ advancing: bool,
1411
+ /// In a version 2 index: the row's blocks under its cells, opened at the first document
1412
+ /// asked for.
1413
+ merged: Option<Box<Merged<'t>>>,
1414
+ /// The layout, as a type ([`Layout`]): a version 1 join is the code it was.
1415
+ layout: std::marker::PhantomData<L>,
1416
+ }
1417
+
1418
+ impl<'t, L: Layout> Joined<'t, L> {
1419
+ /// `asked` is how many documents the join will ask for, where that's known: the
1420
+ /// lead's `df`, for another term's positions. Then the choice between point reads and
1421
+ /// the walk is made here, once, and the walk isn't paid for after point reads already
1422
+ /// were (ski-rental's price for not knowing). `None` for the lead's own postings, asked
1423
+ /// for only where the phrase occurs.
1424
+ ///
1425
+ /// Under an `id_prefix` the lead's `df` counts documents outside the prefix too, so
1426
+ /// `asked` over-estimates and the walk can be chosen where point reads would have cost
1427
+ /// less: slower then, never a different result (ai1249's S1 on #1997).
1428
+ fn new(
1429
+ term: &str,
1430
+ family: &'static str,
1431
+ postings: i64,
1432
+ asked: Option<i64>,
1433
+ prefix: Option<&[u8]>,
1434
+ ) -> Self {
1435
+ let postings = postings.max(0) as u64;
1436
+ let advancing = asked.is_some_and(|n| {
1437
+ (n.max(0) as u64).saturating_mul(crate::maxscore::LOOKUP_IN_STEPS) > postings
1438
+ });
1439
+ Joined {
1440
+ row: post_row(term),
1441
+ family,
1442
+ prefix: prefix.map(<[u8]>::to_vec),
1443
+ cells: None,
1444
+ doc: Vec::new(),
1445
+ value: Vec::new(),
1446
+ number: None,
1447
+ ended: false,
1448
+ postings,
1449
+ stepped: 0,
1450
+ lookups: 0,
1451
+ advancing,
1452
+ merged: None,
1453
+ layout: std::marker::PhantomData,
1454
+ }
1455
+ }
1456
+
1457
+ /// Whether a cell of this join's family is a tombstone (a version 2 index's deleted
1458
+ /// posting): no posting, and it hides the block's.
1459
+ fn tombstone(&self, value: &[u8], number: Option<u64>) -> bool {
1460
+ if self.family == POST {
1461
+ number == Some(TOMBSTONE)
1462
+ } else {
1463
+ value.is_empty()
1464
+ }
1465
+ }
1466
+
1467
+ /// Opens the row's blocks, once (a version 2 index).
1468
+ fn open_merged(&mut self, t: &'t Rows, s: &Snapshot) -> Result<()> {
1469
+ if self.merged.is_none() {
1470
+ self.merged = Some(Box::new(Merged::new(
1471
+ t,
1472
+ s,
1473
+ &self.row,
1474
+ self.family,
1475
+ self.prefix.as_deref(),
1476
+ )?));
1477
+ }
1478
+ Ok(())
1479
+ }
1480
+
1481
+ /// Keeps the block tier's posting for `doc`, if it stands on it.
1482
+ fn keep_block(&mut self, doc: &[u8]) -> bool {
1483
+ let m = self.merged.as_ref().expect("opened");
1484
+ if !m.block_has(doc) {
1485
+ return false;
1486
+ }
1487
+ self.value.clear();
1488
+ if self.family == POST {
1489
+ self.number = m.post(Tier::Block).ok();
1490
+ } else {
1491
+ self.value.extend_from_slice(m.positions(Tier::Block));
1492
+ self.number = None;
1493
+ }
1494
+ true
1495
+ }
1496
+
1497
+ /// [`at`](Self::at) in a version 2 index. The block tier always advances to `doc` (a
1498
+ /// block passed costs a key compare); the cell tier is reached by point reads or by its
1499
+ /// walk, by the rule it had. The cell wins, and a tombstone means no posting.
1500
+ ///
1501
+ /// So in point-read mode the block tier still steps: through a hub term's blocks, one
1502
+ /// key compare each and no decode. That is the cheap side, and not a thing to turn
1503
+ /// into point reads (ai1249 on #2009).
1504
+ fn at_merged(&mut self, t: &'t Rows, s: &Snapshot, doc: &[u8]) -> Result<bool> {
1505
+ self.open_merged(t, s)?;
1506
+ let m = self.merged.as_mut().expect("opened above");
1507
+ sync(m.blocks_to::<Blocking>(&mut (), doc))?;
1508
+ if !self.walks() {
1509
+ if let Some(c) = t.get_at(s, &self.row, self.family, doc)? {
1510
+ if self.tombstone(c.value(), c.as_u64()) {
1511
+ return Ok(false);
1512
+ }
1513
+ Self::keep(&mut self.value, &mut self.number, (c.value(), c.as_u64()));
1514
+ return Ok(true);
1515
+ }
1516
+ return Ok(self.keep_block(doc));
1517
+ }
1518
+ self.open(t, s)?;
1519
+ let cells = self.cells.as_mut().expect("opened above");
1520
+ let m = self.merged.as_mut().expect("opened above");
1521
+ sync(m.cells_to::<Blocking>(cells, &mut (), doc))?;
1522
+ self.stepped = m.stepped;
1523
+ if m.cell_side(doc) == Side::Here {
1524
+ return Ok(match self.family == POST {
1525
+ true => match m.cell_post()? {
1526
+ Some(v) => {
1527
+ self.number = Some(v);
1528
+ true
1529
+ }
1530
+ None => false,
1531
+ },
1532
+ false => match m.cell_positions() {
1533
+ Some(ps) => {
1534
+ self.value.clear();
1535
+ self.value.extend_from_slice(ps);
1536
+ true
1537
+ }
1538
+ None => false,
1539
+ },
1540
+ });
1541
+ }
1542
+ Ok(self.keep_block(doc))
1543
+ }
1544
+
1545
+ /// [`at_merged`](Self::at_merged) without blocking.
1546
+ #[cfg(feature = "async")]
1547
+ async fn at_merged_async(
1548
+ &mut self,
1549
+ t: &'t Rows,
1550
+ s: &Snapshot,
1551
+ doc: &[u8],
1552
+ budget: &mut crate::maxscore::Budget,
1553
+ ) -> Result<bool> {
1554
+ use crate::maxscore::{Nonblocking, Polling};
1555
+ self.open_merged(t, s)?;
1556
+ let m = self.merged.as_mut().expect("opened above");
1557
+ std::future::poll_fn(|cx| m.blocks_to::<Nonblocking>(&mut Polling::new(cx), doc)).await?;
1558
+ if !self.walks() {
1559
+ budget.spend(crate::maxscore::LOOKUP_STEPS).await;
1560
+ if let Some(c) = t.get_at_async(s, &self.row, self.family, doc).await? {
1561
+ if self.tombstone(c.value(), c.as_u64()) {
1562
+ return Ok(false);
1563
+ }
1564
+ Self::keep(&mut self.value, &mut self.number, (c.value(), c.as_u64()));
1565
+ return Ok(true);
1566
+ }
1567
+ return Ok(self.keep_block(doc));
1568
+ }
1569
+ budget.spend(1).await;
1570
+ self.open(t, s)?;
1571
+ let cells = self.cells.as_mut().expect("opened above");
1572
+ let m = self.merged.as_mut().expect("opened above");
1573
+ std::future::poll_fn(|cx| m.cells_to::<Nonblocking>(cells, &mut Polling::new(cx), doc))
1574
+ .await?;
1575
+ self.stepped = m.stepped;
1576
+ if m.cell_side(doc) == Side::Here {
1577
+ return Ok(match self.family == POST {
1578
+ true => match m.cell_post()? {
1579
+ Some(v) => {
1580
+ self.number = Some(v);
1581
+ true
1582
+ }
1583
+ None => false,
1584
+ },
1585
+ false => match m.cell_positions() {
1586
+ Some(ps) => {
1587
+ self.value.clear();
1588
+ self.value.extend_from_slice(ps);
1589
+ true
1590
+ }
1591
+ None => false,
1592
+ },
1593
+ });
1594
+ }
1595
+ Ok(self.keep_block(doc))
1596
+ }
1597
+
1598
+ /// Whether the next document is reached by the row's walk: decided once per document,
1599
+ /// and for good once it says yes.
1600
+ fn walks(&mut self) -> bool {
1601
+ if !self.advancing {
1602
+ self.lookups += 1;
1603
+ let left = self.postings.saturating_sub(self.stepped);
1604
+ self.advancing = self
1605
+ .lookups
1606
+ .saturating_mul(crate::maxscore::LOOKUP_IN_STEPS)
1607
+ > left;
1608
+ }
1609
+ self.advancing
1610
+ }
1611
+
1612
+ /// Whether the walk has to move to reach `doc`: not once it has ended, or stands at or
1613
+ /// past `doc`.
1614
+ fn behind(&self, doc: &[u8]) -> bool {
1615
+ !self.ended && (self.cells.is_none() || self.doc.as_slice() < doc)
1616
+ }
1617
+
1618
+ /// Whether the walk, standing at or past `doc`, stands on it.
1619
+ fn here(&self, doc: &[u8]) -> bool {
1620
+ !self.ended && self.doc.as_slice() == doc
1621
+ }
1622
+
1623
+ /// Keeps the cell found: its value, and the value as a number.
1624
+ fn keep(value: &mut Vec<u8>, number: &mut Option<u64>, found: (&[u8], Option<u64>)) {
1625
+ value.clear();
1626
+ value.extend_from_slice(found.0);
1627
+ *number = found.1;
1628
+ }
1629
+
1630
+ /// Opens the row's walk, once.
1631
+ fn open(&mut self, t: &'t Rows, s: &Snapshot) -> Result<()> {
1632
+ if self.cells.is_none() {
1633
+ let cells = cells_of(t, s, &self.row, self.family, self.prefix.as_deref()).cells()?;
1634
+ self.cells = Some(cells);
1635
+ }
1636
+ Ok(())
1637
+ }
1638
+
1639
+ /// Whether the term has a cell for `doc`, kept in `value` and `number` if so. `doc`s
1640
+ /// ascend.
1641
+ fn at(&mut self, t: &'t Rows, s: &Snapshot, doc: &[u8]) -> Result<bool> {
1642
+ if L::MERGED {
1643
+ return self.at_merged(t, s, doc);
1644
+ }
1645
+ if !self.walks() {
1646
+ return Ok(match t.get_at(s, &self.row, self.family, doc)? {
1647
+ Some(c) => {
1648
+ Self::keep(&mut self.value, &mut self.number, (c.value(), c.as_u64()));
1649
+ true
1650
+ }
1651
+ None => false,
1652
+ });
1653
+ }
1654
+ if self.behind(doc) {
1655
+ // A posting passed costs a key compare: only the one stood on is copied.
1656
+ self.open(t, s)?;
1657
+ let cells = self.cells.as_mut().expect("opened above");
1658
+ loop {
1659
+ self.stepped += 1;
1660
+ let Some(e) = cells.next()? else {
1661
+ self.ended = true;
1662
+ break;
1663
+ };
1664
+ if e.qualifier < doc {
1665
+ continue;
1666
+ }
1667
+ self.doc.clear();
1668
+ self.doc.extend_from_slice(e.qualifier);
1669
+ Self::keep(
1670
+ &mut self.value,
1671
+ &mut self.number,
1672
+ (e.cell.value(), e.cell.as_u64()),
1673
+ );
1674
+ break;
1675
+ }
1676
+ }
1677
+ Ok(self.here(doc))
1678
+ }
1679
+
1680
+ /// [`at`](Self::at) without blocking: point reads as futures, and the walk by seeking
1681
+ /// (a cold row then reads only the blocks it lands in, perf287's T1 on #1560). A seek
1682
+ /// counts one step, so the switch to walking comes a little later than the sync join's.
1683
+ #[cfg(feature = "async")]
1684
+ async fn at_async(
1685
+ &mut self,
1686
+ t: &'t Rows,
1687
+ s: &Snapshot,
1688
+ doc: &[u8],
1689
+ budget: &mut crate::maxscore::Budget,
1690
+ ) -> Result<bool> {
1691
+ if L::MERGED {
1692
+ return self.at_merged_async(t, s, doc, budget).await;
1693
+ }
1694
+ if !self.walks() {
1695
+ budget.spend(crate::maxscore::LOOKUP_STEPS).await;
1696
+ return Ok(
1697
+ match t.get_at_async(s, &self.row, self.family, doc).await? {
1698
+ Some(c) => {
1699
+ Self::keep(&mut self.value, &mut self.number, (c.value(), c.as_u64()));
1700
+ true
1701
+ }
1702
+ None => false,
1703
+ },
1704
+ );
1705
+ }
1706
+ if self.behind(doc) {
1707
+ budget.spend(1).await;
1708
+ self.open(t, s)?;
1709
+ let cells = self.cells.as_mut().expect("opened above");
1710
+ let (family, at) = (self.family, &mut self.doc);
1711
+ let (value, number) = (&mut self.value, &mut self.number);
1712
+ // Only when behind `doc`, so the seek never stands on `doc` already (a seek
1713
+ // from a posting lands after it).
1714
+ let found = std::future::poll_fn(|cx| match cells.poll_seek(cx, family, doc) {
1715
+ std::task::Poll::Ready(Ok(Some(e))) => {
1716
+ at.clear();
1717
+ at.extend_from_slice(e.qualifier);
1718
+ Self::keep(value, number, (e.cell.value(), e.cell.as_u64()));
1719
+ std::task::Poll::Ready(Ok(true))
1720
+ }
1721
+ std::task::Poll::Ready(Ok(None)) => std::task::Poll::Ready(Ok(false)),
1722
+ std::task::Poll::Ready(Err(e)) => std::task::Poll::Ready(Err(e)),
1723
+ std::task::Poll::Pending => std::task::Poll::Pending,
1724
+ })
1725
+ .await?;
1726
+ self.stepped += 1;
1727
+ self.ended = !found;
1728
+ }
1729
+ Ok(self.here(doc))
1730
+ }
1731
+ }
1732
+
766
1733
  /// What a phrase scores with, past its reads: its idf (the sum of its terms'), its lead term
767
1734
  /// (the rarest: the others narrow its documents), and each term's group (a repeated word's
768
1735
  /// terms share one, so the sloppy matcher keeps them apart).
@@ -770,47 +1737,74 @@ struct PhrasePlan {
770
1737
  idf: f64,
771
1738
  lead: usize,
772
1739
  groups: Vec<usize>,
1740
+ /// Each term's place in the join's position lists: 0 for the lead term, then the other
1741
+ /// distinct terms in the phrase's order. A repeated word's terms share one.
1742
+ slots: Vec<usize>,
773
1743
  }
774
1744
 
775
1745
  impl PhrasePlan {
776
- /// `None` when a term isn't in the index: no document can hold the phrase.
777
- fn new(bm: &Bm25, df_of: &HashMap<String, i64>, phrase: &Phrase) -> Option<Self> {
1746
+ /// `None` when a term has no postings here: no document here can hold the phrase. The
1747
+ /// idf is from the `df`s it scores with, and the lead the term with the fewest postings
1748
+ /// here.
1749
+ fn new(bm: &Bm25, dfs: Dfs<'_>, phrase: &Phrase) -> Option<Self> {
778
1750
  let terms = &phrase.terms;
779
- if terms.iter().any(|(term, _)| df_of[term] <= 0) {
1751
+ if terms.iter().any(|(term, _)| dfs.here(term) <= 0) {
780
1752
  return None;
781
1753
  }
782
- let idf: f64 = terms.iter().map(|(term, _)| bm.idf(df_of[term])).sum();
1754
+ let idf: f64 = terms.iter().map(|(term, _)| bm.idf(dfs.score(term))).sum();
783
1755
  let lead = (0..terms.len())
784
- .min_by_key(|&i| df_of[&terms[i].0])
1756
+ .min_by_key(|&i| dfs.here(&terms[i].0))
785
1757
  .expect("a phrase has terms");
786
1758
  let groups = terms
787
1759
  .iter()
788
1760
  .map(|(term, _)| terms.iter().position(|(t, _)| t == term).expect("itself"))
789
1761
  .collect();
790
- Some(PhrasePlan { idf, lead, groups })
1762
+ let mut distinct = vec![terms[lead].0.as_str()];
1763
+ let slots = terms
1764
+ .iter()
1765
+ .map(|(term, _)| {
1766
+ distinct.iter().position(|t| t == term).unwrap_or_else(|| {
1767
+ distinct.push(term);
1768
+ distinct.len() - 1
1769
+ })
1770
+ })
1771
+ .collect();
1772
+ Some(PhrasePlan {
1773
+ idf,
1774
+ lead,
1775
+ groups,
1776
+ slots,
1777
+ })
791
1778
  }
792
1779
 
793
- /// The phrase's frequency in `doc`, from its terms' positions there; `None` when it
794
- /// doesn't occur (a term is missing, or no match).
795
- fn freq(
1780
+ /// The join's other terms: the distinct terms besides the lead, in `slots`' order.
1781
+ fn others<'t, L: Layout>(
796
1782
  &self,
1783
+ dfs: Dfs<'_>,
797
1784
  phrase: &Phrase,
798
- by_term: &BTreeMap<&str, BTreeMap<Vec<u8>, Vec<u32>>>,
799
- doc: &[u8],
800
- lead_ps: &[u32],
801
- ) -> Option<f64> {
1785
+ prefix: Option<&[u8]>,
1786
+ ) -> Vec<Joined<'t, L>> {
1787
+ let mut others: Vec<Joined<'t, L>> = Vec::new();
1788
+ for ((term, _), &slot) in phrase.terms.iter().zip(&self.slots) {
1789
+ if slot == others.len() + 1 {
1790
+ let asked = Some(dfs.here(&phrase.terms[self.lead].0));
1791
+ others.push(Joined::new(term, POS, dfs.here(term), asked, prefix));
1792
+ }
1793
+ }
1794
+ others
1795
+ }
1796
+
1797
+ /// The phrase's frequency in a document every term is in, from the join's position
1798
+ /// lists there (`slots`); `None` when it doesn't occur.
1799
+ fn freq(&self, phrase: &Phrase, by_slot: &[Vec<u32>]) -> Option<f64> {
802
1800
  let terms = &phrase.terms;
803
- let lists: Option<Vec<&[u32]>> = terms
804
- .iter()
805
- .map(|(term, _)| by_term[term.as_str()].get(doc).map(Vec::as_slice))
806
- .collect();
807
- // A document without every term can't hold the phrase.
808
- let lists = lists?;
1801
+ let lead_ps = by_slot[0].as_slice();
1802
+ let lists = || self.slots.iter().map(|&slot| by_slot[slot].as_slice());
809
1803
  let lead_off = terms[self.lead].1;
810
1804
  let freq = if phrase.slop == 0 {
811
1805
  let mut n = 0u32;
812
1806
  'start: for &p in lead_ps {
813
- for ((_, off), ps) in terms.iter().zip(&lists) {
1807
+ for ((_, off), ps) in terms.iter().zip(lists()) {
814
1808
  let Some(at) = (p + off).checked_sub(lead_off) else {
815
1809
  continue 'start;
816
1810
  };
@@ -822,11 +1816,10 @@ impl PhrasePlan {
822
1816
  }
823
1817
  f64::from(n)
824
1818
  } else {
825
- let walks: Vec<(&[u32], u32, usize)> = lists
826
- .iter()
1819
+ let walks: Vec<(&[u32], u32, usize)> = lists()
827
1820
  .zip(terms)
828
1821
  .zip(&self.groups)
829
- .map(|((ps, (_, off)), g)| (*ps, *off, *g))
1822
+ .map(|((ps, (_, off)), g)| (ps, *off, *g))
830
1823
  .collect();
831
1824
  crate::sloppy::sloppy_freq(&walks, phrase.slop)
832
1825
  };
@@ -840,59 +1833,3 @@ impl PhrasePlan {
840
1833
  Ok(self.idf * bm.tf_factor(freq, f64::from(len)))
841
1834
  }
842
1835
  }
843
-
844
- /// A term's positions by document, for the documents in `keep` (all when `None`).
845
- fn read_positions(
846
- t: &Rows,
847
- s: &Snapshot,
848
- term: &str,
849
- keep: Option<&BTreeMap<Vec<u8>, Vec<u32>>>,
850
- prefix: Option<&[u8]>,
851
- ) -> Result<BTreeMap<Vec<u8>, Vec<u32>>> {
852
- let mut out = BTreeMap::new();
853
- let mut read = t.row(&post_row(term)).family(POS).snapshot(s);
854
- if let Some(p) = prefix {
855
- read = read.qualifier_prefix(p);
856
- }
857
- let mut cells = read.cells()?;
858
- while let Some(e) = cells.next()? {
859
- if keep.is_some_and(|k| !k.contains_key(e.qualifier)) {
860
- continue;
861
- }
862
- let mut ps = Vec::new();
863
- decode_positions(e.cell.value(), &mut ps)?;
864
- out.insert(e.qualifier.to_vec(), ps);
865
- }
866
- Ok(out)
867
- }
868
-
869
- /// [`read_positions`] as a future: the position row walked with [`RowCells::next_async`].
870
- #[cfg(feature = "async")]
871
- async fn read_positions_async(
872
- t: &Rows,
873
- s: &Snapshot,
874
- term: &str,
875
- keep: Option<&BTreeMap<Vec<u8>, Vec<u32>>>,
876
- prefix: Option<&[u8]>,
877
- budget: &mut crate::maxscore::Budget,
878
- ) -> Result<BTreeMap<Vec<u8>, Vec<u32>>> {
879
- let mut out = BTreeMap::new();
880
- let mut read = t.row(&post_row(term)).family(POS).snapshot(s);
881
- if let Some(p) = prefix {
882
- read = read.qualifier_prefix(p);
883
- }
884
- let mut cells = read.cells()?;
885
- loop {
886
- budget.spend(1).await;
887
- let Some(e) = cells.next_async().await? else {
888
- break;
889
- };
890
- if keep.is_some_and(|k| !k.contains_key(e.qualifier)) {
891
- continue;
892
- }
893
- let mut ps = Vec::new();
894
- decode_positions(e.cell.value(), &mut ps)?;
895
- out.insert(e.qualifier.to_vec(), ps);
896
- }
897
- Ok(out)
898
- }