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
@@ -0,0 +1,431 @@
1
+ //! A search's ranking statistics as a value (#1722, ICR 0138): what one index's search
2
+ //! scores with, read on its own ([`Search::query_stats`](crate::Search::query_stats)),
3
+ //! merged across the indexes a collection is split into ([`QueryStats::merge`]), and handed
4
+ //! back to each one's search ([`Search::stats`](crate::Search::stats)).
5
+ //!
6
+ //! A search always runs this way: a single index's search reads its statistics, then ranks
7
+ //! with them, so a search given another index's numbers runs the same code.
8
+
9
+ use std::collections::{HashMap, HashSet};
10
+
11
+ use crate::error::{Error, Result};
12
+ use crate::fuzzy::{Expansion, finish};
13
+ use crate::maxscore::Bm25;
14
+
15
+ /// [`QueryStats::to_bytes`]' version, its first byte.
16
+ const VERSION: u8 = 1;
17
+
18
+ /// The statistics one search ranks with: the document count and total length, each query
19
+ /// term's document frequency, and each fuzzy term's expansions. Opaque: they come from
20
+ /// [`Search::query_stats`](crate::Search::query_stats) or [`merge`](Self::merge), and go to
21
+ /// [`Search::stats`](crate::Search::stats).
22
+ ///
23
+ /// This is how a text index split across several databases (a cluster's partitions) is
24
+ /// searched with the scores one index over every document would give:
25
+ /// 1. each part's [`query_stats`](crate::Search::query_stats), every part included, each
26
+ /// read at one snapshot of its database;
27
+ /// 2. [`merge`](Self::merge) of them all;
28
+ /// 3. each part's search with the merged statistics ([`stats`](crate::Search::stats));
29
+ /// 4. the parts' hits merged by score descending, then id ascending, and cut at `k`.
30
+ ///
31
+ /// Scores are then the ones one index would compute, up to float rounding in the order a
32
+ /// document's clauses are added. Two limits:
33
+ /// - **A fuzzy term whose expansions were cut** ([`cut`](Self::cut)) may keep other terms
34
+ /// than one index would: a part leaves out a term it ranks past
35
+ /// [`max_expansions`](crate::Search::max_expansions), and the merge can't bring it back.
36
+ /// A larger `max_expansions` makes a cut rarer.
37
+ /// - **The parts' snapshots are separate**, so a write landing between steps 1 and 3 is in
38
+ /// one step and not the other.
39
+ ///
40
+ /// ```
41
+ /// use pigeonhole::{Family, Options, Pigeonhole};
42
+ /// use pigeonhole_text::{Index, IndexOptions, QueryStats, Source};
43
+ ///
44
+ /// # fn main() -> pigeonhole_text::Result<()> {
45
+ /// # let dir = pigeonhole::doc_support::temp_dir();
46
+ /// let db = Pigeonhole::open(dir.join("app.phdb"), Options::default().shards(1))?;
47
+ /// let docs = db.table("docs")?.family("body", Family::default()).create_if_missing()?;
48
+ /// let index = |name: &str| {
49
+ /// Index::create(&db, name, Source::new(&docs, "body", b"text"), IndexOptions::new())
50
+ /// };
51
+ /// // One collection split in two, and the same documents in one index.
52
+ /// let (a, b, whole) = (index("a")?, index("b")?, index("whole")?);
53
+ /// for (id, text) in [(&b"d1"[..], "memory store"), (b"d2", "vector store")] {
54
+ /// a.put(id, text)?;
55
+ /// whole.put(id, text)?;
56
+ /// }
57
+ /// for (id, text) in [(&b"d3"[..], "memory memory"), (b"d4", "store")] {
58
+ /// b.put(id, text)?;
59
+ /// whole.put(id, text)?;
60
+ /// }
61
+ /// let q = "memory store";
62
+ /// let stats = QueryStats::merge([a.search(q, 10).query_stats()?, b.search(q, 10).query_stats()?])?;
63
+ /// assert_eq!(stats.documents(), 4);
64
+ /// let mut hits = a.search(q, 10).stats(stats.clone()).run()?;
65
+ /// hits.extend(b.search(q, 10).stats(stats).run()?);
66
+ /// hits.sort_by(|x, y| y.score.total_cmp(&x.score).then_with(|| x.id.cmp(&y.id)));
67
+ /// let one = whole.search(q, 10).run()?;
68
+ /// assert_eq!(hits.len(), one.len());
69
+ /// for (h, o) in hits.iter().zip(&one) {
70
+ /// assert_eq!(h.id, o.id);
71
+ /// assert!((h.score - o.score).abs() <= 1e-9 * o.score.abs());
72
+ /// }
73
+ /// # Ok(())
74
+ /// # }
75
+ /// ```
76
+ #[derive(Debug, Clone)]
77
+ pub struct QueryStats(pub(crate) Stats);
78
+
79
+ /// [`QueryStats`]' contents.
80
+ #[derive(Debug, Clone)]
81
+ pub(crate) struct Stats {
82
+ /// The documents, and their lengths summed (the `S` row's counters).
83
+ pub(crate) docs: i64,
84
+ pub(crate) len: i64,
85
+ /// The search's fuzzy options, which decide the expansions: statistics merge only with
86
+ /// others read under the same ones.
87
+ pub(crate) max_expansions: usize,
88
+ pub(crate) prefix_length: usize,
89
+ /// Each query term's `df`, and each phrase term's.
90
+ pub(crate) df: HashMap<String, i64>,
91
+ /// Each fuzzy term's expansions, in the order the query's clauses yield them.
92
+ pub(crate) fuzzy: Vec<Fuzzy>,
93
+ }
94
+
95
+ /// A fuzzy term's part of [`Stats`].
96
+ #[derive(Debug, Clone)]
97
+ pub(crate) struct Fuzzy {
98
+ /// The clauses that yield it.
99
+ pub(crate) clauses: Vec<usize>,
100
+ pub(crate) term: String,
101
+ pub(crate) edits: u8,
102
+ /// Its expansions in [`finish`]'s order, each `df` the statistic it scores with.
103
+ pub(crate) expansions: Vec<Expansion>,
104
+ /// Whether `max_expansions` left matching terms out, here or in any part merged.
105
+ pub(crate) cut: bool,
106
+ }
107
+
108
+ /// The error for statistics that don't belong to the search or to each other.
109
+ pub(crate) fn other_query() -> Error {
110
+ Error::InvalidArgument(
111
+ "the query statistics are for another query or other fuzzy options".into(),
112
+ )
113
+ }
114
+
115
+ impl Stats {
116
+ /// BM25 over these statistics, or `None` for no documents (nothing matches).
117
+ pub(crate) fn bm25(&self, k1: f64, b: f64) -> Option<Bm25> {
118
+ (self.docs > 0).then(|| {
119
+ let n = self.docs as f64;
120
+ Bm25 {
121
+ n,
122
+ avglen: (self.len.max(0) as f64 / n).max(f64::MIN_POSITIVE),
123
+ k1,
124
+ b,
125
+ }
126
+ })
127
+ }
128
+
129
+ /// Whether `other` holds the statistics of the same terms and fuzzy terms, read under
130
+ /// the same fuzzy options.
131
+ pub(crate) fn same_query(&self, other: &Stats) -> bool {
132
+ self.max_expansions == other.max_expansions
133
+ && self.prefix_length == other.prefix_length
134
+ && self.df.len() == other.df.len()
135
+ && self.df.keys().all(|t| other.df.contains_key(t))
136
+ && self.fuzzy.len() == other.fuzzy.len()
137
+ && self
138
+ .fuzzy
139
+ .iter()
140
+ .zip(&other.fuzzy)
141
+ .all(|(f, g)| f.term == g.term && f.edits == g.edits && f.clauses == g.clauses)
142
+ }
143
+
144
+ /// Adds `other`'s counts to these, and its expansions to each fuzzy term's (not cut
145
+ /// again: [`QueryStats::merge`] does that once, at the end).
146
+ fn add(&mut self, other: Stats) -> Result<()> {
147
+ if !self.same_query(&other) {
148
+ return Err(other_query());
149
+ }
150
+ self.docs = self.docs.saturating_add(other.docs);
151
+ self.len = self.len.saturating_add(other.len);
152
+ for (term, df) in other.df {
153
+ let mine = self.df.get_mut(&term).expect("the same terms");
154
+ *mine = mine.saturating_add(df);
155
+ }
156
+ for (f, g) in self.fuzzy.iter_mut().zip(other.fuzzy) {
157
+ f.cut |= g.cut;
158
+ let at: HashMap<String, usize> = f
159
+ .expansions
160
+ .iter()
161
+ .enumerate()
162
+ .map(|(i, e)| (e.term.clone(), i))
163
+ .collect();
164
+ for e in g.expansions {
165
+ match at.get(&e.term) {
166
+ Some(&i) => {
167
+ let mine = &mut f.expansions[i];
168
+ // A term's distance from the fuzzy term (so its boost) is the same
169
+ // wherever it's read.
170
+ if mine.distance != e.distance {
171
+ return Err(other_query());
172
+ }
173
+ mine.df = mine.df.saturating_add(e.df);
174
+ }
175
+ None => f.expansions.push(e),
176
+ }
177
+ }
178
+ }
179
+ Ok(())
180
+ }
181
+ }
182
+
183
+ impl QueryStats {
184
+ /// The statistics of every part together: the counts summed, and each fuzzy term's
185
+ /// expansions joined and cut again to
186
+ /// [`max_expansions`](crate::Search::max_expansions) by the search's own order (the
187
+ /// closest, then the highest summed `df`, then bytewise).
188
+ ///
189
+ /// # Errors
190
+ /// `InvalidArgument` for no parts, or parts of different queries or fuzzy options.
191
+ pub fn merge(parts: impl IntoIterator<Item = QueryStats>) -> Result<QueryStats> {
192
+ let mut parts = parts.into_iter();
193
+ let Some(QueryStats(mut all)) = parts.next() else {
194
+ return Err(Error::InvalidArgument(
195
+ "there are no query statistics to merge".into(),
196
+ ));
197
+ };
198
+ for QueryStats(part) in parts {
199
+ all.add(part)?;
200
+ }
201
+ for f in &mut all.fuzzy {
202
+ let (kept, cut) = finish(std::mem::take(&mut f.expansions), all.max_expansions);
203
+ f.expansions = kept;
204
+ f.cut |= cut;
205
+ }
206
+ Ok(QueryStats(all))
207
+ }
208
+
209
+ /// The documents they count.
210
+ pub fn documents(&self) -> u64 {
211
+ self.0.docs.max(0) as u64
212
+ }
213
+
214
+ /// Whether a fuzzy term of the query's clause `clause` (an index into
215
+ /// [`Query::clauses`](crate::Query::clauses)) had its expansions cut, in any part
216
+ /// merged or by the merge. `false` for a clause that isn't fuzzy.
217
+ pub fn cut(&self, clause: usize) -> bool {
218
+ self.0
219
+ .fuzzy
220
+ .iter()
221
+ .any(|f| f.cut && f.clauses.contains(&clause))
222
+ }
223
+
224
+ /// A versioned encoding, for sending to another process: its first byte is the version.
225
+ /// [`from_bytes`](Self::from_bytes) checks what a search's scores depend on, so bytes
226
+ /// from another process can't make a search rank with NaN.
227
+ pub fn to_bytes(&self) -> Vec<u8> {
228
+ let s = &self.0;
229
+ let mut out = vec![VERSION];
230
+ put_i64(&mut out, s.docs);
231
+ put_i64(&mut out, s.len);
232
+ put_len(&mut out, s.max_expansions);
233
+ put_len(&mut out, s.prefix_length);
234
+ let mut terms: Vec<(&String, &i64)> = s.df.iter().collect();
235
+ terms.sort();
236
+ put_len(&mut out, terms.len());
237
+ for (term, df) in terms {
238
+ put_str(&mut out, term);
239
+ put_i64(&mut out, *df);
240
+ }
241
+ put_len(&mut out, s.fuzzy.len());
242
+ for f in &s.fuzzy {
243
+ put_str(&mut out, &f.term);
244
+ out.push(f.edits);
245
+ out.push(u8::from(f.cut));
246
+ put_len(&mut out, f.clauses.len());
247
+ for &c in &f.clauses {
248
+ put_len(&mut out, c);
249
+ }
250
+ put_len(&mut out, f.expansions.len());
251
+ for e in &f.expansions {
252
+ put_str(&mut out, &e.term);
253
+ out.push(e.distance);
254
+ put_i64(&mut out, e.df);
255
+ out.extend_from_slice(&e.boost.to_bits().to_le_bytes());
256
+ }
257
+ }
258
+ out
259
+ }
260
+
261
+ /// Statistics from [`to_bytes`](Self::to_bytes).
262
+ ///
263
+ /// # Errors
264
+ /// `InvalidArgument` for a version this build doesn't read (a newer build's), or bytes
265
+ /// that don't parse. That includes numbers out of range: a negative count, a `df` above
266
+ /// the documents, a boost outside (0, 1], more expansions than `max_expansions`, or a
267
+ /// term or expansion listed twice.
268
+ pub fn from_bytes(bytes: &[u8]) -> Result<QueryStats> {
269
+ let mut r = Reader(bytes);
270
+ let version = r.u8()?;
271
+ if version != VERSION {
272
+ return Err(Error::InvalidArgument(format!(
273
+ "query statistics of version {version}; this build reads version {VERSION}"
274
+ )));
275
+ }
276
+ let docs = r.i64()?;
277
+ let len = r.i64()?;
278
+ let max_expansions = r.len()?;
279
+ let prefix_length = r.len()?;
280
+ if max_expansions == 0 {
281
+ return Err(unparsed("max_expansions is 0"));
282
+ }
283
+ // The ranges a search's scores need (audit120's S1 on #2025): `idf` is the log of
284
+ // a number at or under 0 for a `df` above the documents, so such bytes are refused
285
+ // rather than ranked with NaN.
286
+ if docs < 0 || len < 0 {
287
+ return Err(unparsed("a count is negative"));
288
+ }
289
+ let df_in_range = |df: i64| (0..=docs).contains(&df);
290
+ let mut df = HashMap::new();
291
+ for _ in 0..r.len()? {
292
+ let term = r.string()?;
293
+ let n = r.i64()?;
294
+ if !df_in_range(n) {
295
+ return Err(unparsed("a df is negative or above the documents"));
296
+ }
297
+ if df.insert(term, n).is_some() {
298
+ return Err(unparsed("a term is listed twice"));
299
+ }
300
+ }
301
+ let mut fuzzy = Vec::new();
302
+ for _ in 0..r.len()? {
303
+ let term = r.string()?;
304
+ let edits = r.u8()?;
305
+ let cut = match r.u8()? {
306
+ 0 => false,
307
+ 1 => true,
308
+ _ => return Err(unparsed("a cut flag isn't 0 or 1")),
309
+ };
310
+ if edits > 2 {
311
+ return Err(unparsed("a fuzzy term allows more than 2 edits"));
312
+ }
313
+ let mut clauses = Vec::new();
314
+ for _ in 0..r.len()? {
315
+ clauses.push(r.len()?);
316
+ }
317
+ if clauses.is_empty() {
318
+ return Err(unparsed("a fuzzy term has no clause"));
319
+ }
320
+ // A part's expansions and a merge's are cut to `max_expansions` (audit120 on
321
+ // #2025). Both counts come from the bytes, so nothing is reserved from them: the
322
+ // vector grows as expansions parse, and bytes that claim more than they hold end
323
+ // early (audit120's must on #2029). One listed twice is found through a set of
324
+ // the terms seen, so the check is linear in the bytes (audit120 on #2029).
325
+ let count = r.len()?;
326
+ if count > max_expansions {
327
+ return Err(unparsed(
328
+ "a fuzzy term has more expansions than max_expansions",
329
+ ));
330
+ }
331
+ let mut expansions: Vec<Expansion> = Vec::new();
332
+ let mut seen = HashSet::new();
333
+ for _ in 0..count {
334
+ let term = r.string()?;
335
+ let distance = r.u8()?;
336
+ let df = r.i64()?;
337
+ let boost = f64::from_bits(r.u64()?);
338
+ // A boost is `1 − distance / shorter`, kept only above 0 (`fuzzy::boost`).
339
+ if distance > edits || !(boost > 0.0 && boost <= 1.0) || !df_in_range(df) {
340
+ return Err(unparsed(
341
+ "an expansion's distance, boost or df is out of range",
342
+ ));
343
+ }
344
+ if !seen.insert(term.clone()) {
345
+ return Err(unparsed("an expansion is listed twice"));
346
+ }
347
+ expansions.push(Expansion {
348
+ term,
349
+ distance,
350
+ df,
351
+ boost,
352
+ });
353
+ }
354
+ fuzzy.push(Fuzzy {
355
+ clauses,
356
+ term,
357
+ edits,
358
+ expansions,
359
+ cut,
360
+ });
361
+ }
362
+ if !r.0.is_empty() {
363
+ return Err(unparsed("bytes follow the statistics"));
364
+ }
365
+ Ok(QueryStats(Stats {
366
+ docs,
367
+ len,
368
+ max_expansions,
369
+ prefix_length,
370
+ df,
371
+ fuzzy,
372
+ }))
373
+ }
374
+ }
375
+
376
+ /// The error for bytes [`QueryStats::from_bytes`] can't parse.
377
+ fn unparsed(what: &str) -> Error {
378
+ Error::InvalidArgument(format!("query statistics don't parse: {what}"))
379
+ }
380
+
381
+ fn put_i64(out: &mut Vec<u8>, v: i64) {
382
+ out.extend_from_slice(&v.to_le_bytes());
383
+ }
384
+
385
+ fn put_len(out: &mut Vec<u8>, n: usize) {
386
+ out.extend_from_slice(&(n as u64).to_le_bytes());
387
+ }
388
+
389
+ fn put_str(out: &mut Vec<u8>, s: &str) {
390
+ put_len(out, s.len());
391
+ out.extend_from_slice(s.as_bytes());
392
+ }
393
+
394
+ /// [`QueryStats::from_bytes`]' cursor.
395
+ struct Reader<'a>(&'a [u8]);
396
+
397
+ impl<'a> Reader<'a> {
398
+ fn take(&mut self, n: usize) -> Result<&'a [u8]> {
399
+ if self.0.len() < n {
400
+ return Err(unparsed("they end early"));
401
+ }
402
+ let (head, rest) = self.0.split_at(n);
403
+ self.0 = rest;
404
+ Ok(head)
405
+ }
406
+
407
+ fn u8(&mut self) -> Result<u8> {
408
+ Ok(self.take(1)?[0])
409
+ }
410
+
411
+ fn u64(&mut self) -> Result<u64> {
412
+ Ok(u64::from_le_bytes(
413
+ self.take(8)?.try_into().expect("8 bytes"),
414
+ ))
415
+ }
416
+
417
+ fn i64(&mut self) -> Result<i64> {
418
+ Ok(self.u64()? as i64)
419
+ }
420
+
421
+ /// A length, count or option. Nothing is allocated by a count (each item is read in
422
+ /// turn), so a corrupt one fails when the bytes run out.
423
+ fn len(&mut self) -> Result<usize> {
424
+ usize::try_from(self.u64()?).map_err(|_| unparsed("a length is out of range"))
425
+ }
426
+
427
+ fn string(&mut self) -> Result<String> {
428
+ let n = self.len()?;
429
+ String::from_utf8(self.take(n)?.to_vec()).map_err(|_| unparsed("a term isn't UTF-8"))
430
+ }
431
+ }
@@ -6,7 +6,7 @@ optional = true
6
6
  version = "0.3"
7
7
  [dependencies.pigeonhole]
8
8
  path = "../pigeonhole"
9
- version = "1.2.2"
9
+ version = "1.3.0"
10
10
  [features]
11
11
  __unstable-hooks = []
12
12
  async = ["pigeonhole/async", "dep:futures-core"]
@@ -25,4 +25,4 @@ name = "pigeonhole-vector"
25
25
  readme = "README.md"
26
26
  repository = "https://github.com/CodingAnarchy/pigeonhole"
27
27
  rust-version = "1.96"
28
- version = "1.2.2"
28
+ version = "1.3.0"
@@ -1,19 +1,23 @@
1
- //! Hold and fault seams for tests (`__unstable-hooks` only). They pause or skip; they never run
2
- //! another path.
1
+ //! Hold and fault seams for tests (`__unstable-hooks` only). They pause or skip, or (one,
2
+ //! [`split_row_bytes`](crate::hooks::split_row_bytes)) change the size a bound is computed
3
+ //! from; they never run another path.
3
4
 
5
+ use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
4
6
  use std::sync::{Arc, Condvar, Mutex, PoisonError};
5
7
 
6
8
  /// Where a test can hold an index operation.
7
9
  #[derive(Debug, Clone, Copy, PartialEq, Eq)]
8
10
  #[non_exhaustive]
9
11
  pub enum Hold {
10
- /// A split, after its 2-means snapshot read and before its transaction (rev 4 N1).
12
+ /// A split, after its 2-means snapshot read and before its transaction (rev 4 N1); for a
13
+ /// list split a page at a time (#1824), before its first page's transaction.
11
14
  SplitBeforeCommit,
12
15
  /// An insert's transaction, after its reads and writes and before its commit.
13
16
  PlaceBeforeCommit,
14
17
  /// A delete's transaction, after its reads and writes and before its commit.
15
18
  DeleteBeforeCommit,
16
- /// A phase 2 transaction, after its reads and writes and before its commit.
19
+ /// A phase 2 transaction, or one moving a later page of a long list's split (#1824),
20
+ /// after its reads and writes and before its commit.
17
21
  ReassignBeforeCommit,
18
22
  /// A merge, after its commit and before it reloads the shared centroid cache: the
19
23
  /// cache still names the merged-away list (D311 T8's stale-cache writes).
@@ -38,6 +42,9 @@ pub struct Armed {
38
42
  static ARMED: Mutex<Option<(Hold, Gate)>> = Mutex::new(None);
39
43
  static SKIP_REBALANCE: Mutex<bool> = Mutex::new(false);
40
44
  static FAIL_AFTER_SPLIT: Mutex<bool> = Mutex::new(false);
45
+ static SPLIT_HELD: AtomicUsize = AtomicUsize::new(0);
46
+ /// `u64::MAX`: not set.
47
+ static SPLIT_ROW_BYTES: AtomicU64 = AtomicU64::new(u64::MAX);
41
48
 
42
49
  /// Holds the next operation that reaches `at` (one at a time, process-wide).
43
50
  pub fn arm(at: Hold) -> Armed {
@@ -128,6 +135,17 @@ pub(crate) fn failing_after_split() -> bool {
128
135
  .unwrap_or_else(PoisonError::into_inner)
129
136
  }
130
137
 
138
+ /// The most vectors one read of a split or its phase 2 has held at once (a list read
139
+ /// whole, a sample or a page, #1824), process-wide since the last call, which resets it.
140
+ /// Inspection only.
141
+ pub fn take_split_held() -> usize {
142
+ SPLIT_HELD.swap(0, Ordering::Relaxed)
143
+ }
144
+
145
+ pub(crate) fn note_split_held(n: usize) {
146
+ SPLIT_HELD.fetch_max(n, Ordering::Relaxed);
147
+ }
148
+
131
149
  /// Whether two handles share one index's state (its centroid cache, queue and rebalancer):
132
150
  /// clones of one open, or opens the process registry joined (#1268 item 8). Inspection only.
133
151
  pub fn shares_state(a: &crate::Index, b: &crate::Index) -> bool {
@@ -141,3 +159,14 @@ pub fn shares_state(a: &crate::Index, b: &crate::Index) -> bool {
141
159
  pub fn rebalancer_thread_started(index: &crate::Index) -> bool {
142
160
  index.inner().thread_started()
143
161
  }
162
+
163
+ /// Counts a list row as `bytes` (process-wide; `None` restores the 4 MiB) in a split's bound
164
+ /// on what it reads whole (#1824, #1879), so a test reaches a split a page at a time without
165
+ /// writing 16 MiB's worth. `Some(0)` leaves the bound at four split lengths.
166
+ pub fn split_row_bytes(bytes: Option<u64>) {
167
+ SPLIT_ROW_BYTES.store(bytes.unwrap_or(u64::MAX), Ordering::SeqCst);
168
+ }
169
+
170
+ pub(crate) fn split_row_bytes_set() -> Option<u64> {
171
+ Some(SPLIT_ROW_BYTES.load(Ordering::SeqCst)).filter(|b| *b != u64::MAX)
172
+ }