yo_index/map.rs
1//! The raw map: an index and an arena wired together.
2//!
3//! This is the smallest thing that is actually a key value store, and it is the
4//! thing M0's exit gate measures against aki's `f1raw` numbers. There is no
5//! record header yet beyond two lengths, no TTL, no type byte, no version. All
6//! of that arrives in M1 and replaces [`Record`] without the index noticing,
7//! which is the point of keeping the two crates apart.
8//!
9//! Layout of one record in the arena:
10//!
11//! ```text
12//! +--------+--------+-----------+-------------+
13//! | klen | vlen | key bytes | value bytes |
14//! | u32 LE | u32 LE | klen | vlen |
15//! +--------+--------+-----------+-------------+
16//! ```
17//!
18//! Key and value live in one allocation so that a hit is one cache miss for the
19//! bucket and one for the record, not three.
20
21use crate::index::{Index, Keys};
22use crate::scan::Cursor;
23use crate::tagged::Tagged;
24use yo_arena::Arena;
25use yo_common::{Addr, Space, bytes_eq, wyhash};
26
27/// Bytes of length prefix in front of a record.
28const HDR: usize = 8;
29
30/// The least a single [`RawMap::compact_step`] walks.
31///
32/// A segment is two megabytes and evacuating one in a single call was a stop
33/// the world pause in the middle of a batch. At 64 byte values that is around
34/// twenty six thousand records, each one an index probe, a copy and an index
35/// write, and the replies behind it wait for all of them. It is why the write
36/// rows had a p99 of 3.9 milliseconds against Redis at 0.8 while the p50 was
37/// in line: the median command paid nothing and one command in a few thousand
38/// paid for the whole segment.
39///
40/// Sixty four kilobytes is a thirty second of a segment, which puts the worst
41/// call at a few hundred records. Smaller would be smoother and would spend
42/// more of the total on the fixed cost of picking up where the last call left
43/// off; this is the smallest size at which that overhead is still noise.
44///
45/// The budget is spent on how far the cursor moves and not on how many records
46/// move, because a segment can be entirely dead. Charging only for records
47/// that move would let one call walk two megabytes of headers for free, which
48/// is the pause this exists to prevent, just without the copying.
49const EVAC_FLOOR: usize = 64 * 1024;
50
51/// The most, which is a whole segment.
52///
53/// The cap is here so that the scaling below has an end, not because a segment
54/// is a good amount of work to do at once. Reaching it means the collector is
55/// sixteen times past the line it starts at, at which point the pause is the
56/// smaller problem.
57const EVAC_CEILING: usize = yo_arena::SEGMENT_SIZE;
58
59/// How much a caller is willing to pay for the memory a sweep gives back.
60///
61/// Not how hard to work but which trades to accept, which is the part that
62/// turned out to matter: the difference between the three is entirely in which
63/// segment gets picked, and picking badly costs a hundred times more than the
64/// work itself.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66enum Sweep {
67 /// Only when the store as a whole is dirty enough to be worth a sweep.
68 Ordinary,
69 /// However clean the store is overall, as long as this segment is worth
70 /// emptying on its own.
71 Hard,
72}
73
74/// A segment that is partway through being evacuated, and how far it got.
75#[derive(Clone, Copy)]
76struct Evac {
77 seg: usize,
78 off: usize,
79}
80
81/// What compaction has done to a map over its life.
82///
83/// The write amplification of value separation, in the two parts it is actually
84/// made of. Every record the walk steps over costs a liveness probe whether it
85/// is live or not, and every live one it finds costs a copy on top of that, so a
86/// segment full of dead records and a segment full of live ones are different
87/// amounts of work for the same number of bytes. One counter cannot tell those
88/// apart, which is why there are three.
89///
90/// Counted here rather than in the caller because this is the only place that
91/// knows a record moved, and the numbers are wanted per store rather than per
92/// command. They never reset, including across [`RawMap::clear`].
93#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
94pub struct Compaction {
95 /// Records the walk has stepped over, live and dead together.
96 pub walked: u64,
97 /// The ones that were still live and had to be copied somewhere else.
98 pub moved: u64,
99 /// What those copies came to, headers and keys included.
100 pub bytes: u64,
101}
102
103struct Record;
104
105impl Record {
106 #[inline]
107 fn lens(bytes: &[u8]) -> (usize, usize) {
108 let k = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as usize;
109 let v = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) as usize;
110 (k, v)
111 }
112}
113
114/// Arena backed record access, which is what the index probes through.
115struct Records<'a> {
116 arena: &'a Arena,
117}
118
119impl Keys for Records<'_> {
120 #[inline]
121 fn hash_at(&self, addr: Addr) -> u64 {
122 let (klen, _) = Record::lens(self.arena.get(addr, HDR));
123 let bytes = self.arena.get(addr, HDR + klen);
124 wyhash(&bytes[HDR..], 0)
125 }
126
127 #[inline]
128 fn eq_at(&self, addr: Addr, key: &[u8]) -> bool {
129 let bytes = self.arena.get(addr, HDR);
130 let (klen, _) = Record::lens(bytes);
131 if klen != key.len() {
132 return false;
133 }
134 let bytes = self.arena.get(addr, HDR + klen);
135 bytes_eq(&bytes[HDR..], key)
136 }
137}
138
139/// A single shard's key value map: bytes in, bytes out, nothing else.
140///
141/// Not `Sync`, and deliberately so. One of these belongs to one shard thread
142/// and is reached through `ShardLocal`, which is `05` section 1's whole
143/// argument: single ownership means no atomics on the hot path.
144///
145/// ```
146/// let mut m = yo_index::RawMap::new();
147/// assert_eq!(m.set(b"k", b"v"), None);
148/// assert_eq!(m.get(b"k"), Some(&b"v"[..]));
149/// assert_eq!(m.set(b"k", b"w").is_some(), true);
150/// assert_eq!(m.get(b"k"), Some(&b"w"[..]));
151/// assert_eq!(m.del(b"k"), true);
152/// assert_eq!(m.get(b"k"), None);
153/// ```
154pub struct RawMap {
155 index: Index,
156 arena: Arena,
157 /// Where the last `compact_step` stopped, if it stopped partway.
158 evac: Option<Evac>,
159 /// How many times anything in here has been written to.
160 ///
161 /// A caller that resolved a key once and wants to skip resolving it again
162 /// needs to know whether anything could have moved in between, and the
163 /// honest answer is any write at all. Every method that takes `&mut self`
164 /// bumps this, including the in place ones, so the question a caller asks is
165 /// "has this map been written since" and not "has this map been written in a
166 /// way I thought would matter".
167 ///
168 /// It lives here rather than in the caller because there are eleven places
169 /// in `yo-kv` that write to a map and one place here that could be missed,
170 /// and a missed invalidation is a stale answer rather than a slow one.
171 ///
172 /// [`RawMap::value_at_mut`] is the one exception and it is argued for where
173 /// it is written. Everything else, including the in place ones, bumps this.
174 writes: u64,
175 /// The records the caller marked when it wrote them.
176 ///
177 /// A second index of a subset of the keys, which exists so that a caller
178 /// looking for one of them does not have to walk past the ones it is not
179 /// looking for. The only thing that uses it is expiry: a key with a deadline
180 /// is rare in most databases, and both the active expire cycle and the
181 /// `volatile-*` eviction policies were sampling the whole map to find one.
182 ///
183 /// It is here and not in `yo-kv` because this is the only thing that knows
184 /// where a record is. An overwrite can move one, a delete takes one away,
185 /// and compaction moves them between segments, and all three are in this
186 /// file. A set of addresses kept anywhere else would go stale on the third.
187 ///
188 /// What "marked" means is entirely the caller's business. This holds
189 /// addresses and has never heard of a deadline.
190 tagged: Tagged,
191 /// What compaction has cost so far.
192 compaction: Compaction,
193}
194
195impl RawMap {
196 /// An empty map.
197 pub fn new() -> RawMap {
198 RawMap {
199 index: Index::new(),
200 arena: Arena::new(),
201 evac: None,
202 writes: 0,
203 tagged: Tagged::new(),
204 compaction: Compaction::default(),
205 }
206 }
207
208 /// What compaction has done to this map since it was made.
209 ///
210 /// A running total and not a rate, so two reads either side of a load say
211 /// what that load cost. See [`Compaction`] for what the three numbers are
212 /// and why they are not one.
213 #[inline]
214 #[must_use]
215 pub const fn compaction(&self) -> Compaction {
216 self.compaction
217 }
218
219 /// How many times this map has been written to.
220 ///
221 /// Two reads of this with the same value either side of some work mean
222 /// nothing in the map moved, so an address or a slot resolved before the
223 /// first read is still the right one after the second. It never goes
224 /// backwards, including across [`RawMap::clear`].
225 #[inline]
226 #[must_use]
227 pub const fn writes(&self) -> u64 {
228 self.writes
229 }
230
231 /// How many keys are stored.
232 #[inline]
233 pub fn len(&self) -> usize {
234 self.index.len()
235 }
236
237 /// Whether the map is empty.
238 #[inline]
239 pub fn is_empty(&self) -> bool {
240 self.index.is_empty()
241 }
242
243 /// Throw everything away and give the memory back.
244 ///
245 /// A fresh index and a fresh arena rather than a walk that deletes each key
246 /// in turn. Deleting one at a time would leave an arena the size of the
247 /// data that used to be in it and an index still grown to fit it, and the
248 /// one thing a client that has just said `FLUSHALL` is entitled to expect is
249 /// the memory back.
250 pub fn clear(&mut self) {
251 // Carried across the reset and bumped, because a counter that went back
252 // to zero here could land on a value a memo was already holding and
253 // read as "nothing moved" on the one call where everything did.
254 let writes = self.writes;
255 let compaction = self.compaction;
256 *self = RawMap::new();
257 self.writes = writes + 1;
258 // Carried for a plainer reason: it is what this store has spent, and a
259 // `FLUSHALL` does not give any of it back.
260 self.compaction = compaction;
261 }
262
263 /// The hash this map files `key` under.
264 ///
265 /// Public because the batch walk in `04` section 3 hashes on the first walk
266 /// and looks up on the second, and the alternative is hashing every key
267 /// twice to keep the seed a private detail.
268 #[inline]
269 #[must_use]
270 pub fn hash_of(key: &[u8]) -> u64 {
271 wyhash(key, 0)
272 }
273
274 /// Ask the cache for the bucket `hash` will be looked up in.
275 #[inline]
276 pub fn prefetch(&self, hash: u64) {
277 self.index.prefetch(hash);
278 }
279
280 /// The value stored under `key`.
281 #[inline]
282 pub fn get(&self, key: &[u8]) -> Option<&[u8]> {
283 self.get_hashed(Self::hash_of(key), key)
284 }
285
286 /// The value stored under `key`, whose hash the caller already has.
287 ///
288 /// The second walk's entry point. `hash` has to be [`RawMap::hash_of`] of
289 /// this key: a hash from somewhere else is not unsafe, it just misses.
290 #[inline]
291 pub fn get_hashed(&self, hash: u64, key: &[u8]) -> Option<&[u8]> {
292 let addr = self.index.get(hash, key, &Records { arena: &self.arena })?;
293 Some(self.value_at(addr))
294 }
295
296 /// Where `key`'s record is, for a caller that has to look at it twice.
297 ///
298 /// A `GET` has to know whether the key is past its deadline before it can
299 /// answer, and then has to read the value it just decided about. Asking
300 /// [`RawMap::get`] twice is two hashes and two probes for one record, and a
301 /// probe is the expensive half of a command. This hands back the address
302 /// instead, and [`RawMap::value_at`] reads it with no probe at all.
303 ///
304 /// The address is good until the next write to this map. Anything that
305 /// inserts, deletes or compacts can move a record, and an address held
306 /// across one of those reads whatever is at that spot now. Hold it for the
307 /// length of one command and no longer.
308 #[inline]
309 pub fn find(&self, key: &[u8]) -> Option<Addr> {
310 self.find_hashed(Self::hash_of(key), key)
311 }
312
313 /// [`RawMap::find`] for a caller that already hashed the key.
314 #[inline]
315 pub fn find_hashed(&self, hash: u64, key: &[u8]) -> Option<Addr> {
316 self.index.get(hash, key, &Records { arena: &self.arena })
317 }
318
319 /// The value at an address this map handed out, with no probe.
320 ///
321 /// See [`RawMap::find`] for how long an address is worth holding.
322 #[inline]
323 #[must_use]
324 pub fn value_at(&self, addr: Addr) -> &[u8] {
325 let (klen, vlen) = Record::lens(self.arena.get(addr, HDR));
326 &self.arena.get(addr, HDR + klen + vlen)[HDR + klen..]
327 }
328
329 /// The value at an address, to be overwritten in place, without counting as
330 /// a write.
331 ///
332 /// This is the one method taking a mutable borrow that leaves
333 /// [`RawMap::writes`] where it was, and that is a deliberate exception to
334 /// the rule stated on the counter rather than an oversight in it.
335 ///
336 /// It is sound because nothing moves. The record already exists, the caller
337 /// already holds its address, there is no allocation and no index write, so
338 /// every address and every number read out of a record before the call is
339 /// still right afterwards. That is a stronger guarantee than the counter is
340 /// asking about, and it is one this method can actually make.
341 ///
342 /// It exists because the conservative answer costs more here than it
343 /// protects. The eviction clock is written back on nearly every read, under
344 /// eight of the ten policies including the default, so counting it as a write
345 /// would invalidate the caller's memo on every single command rather than on
346 /// every write. That is a measured nineteen nanoseconds a command on single
347 /// key `SADD`, given up to avoid thinking once about three bytes written
348 /// inside a record that is not going anywhere.
349 ///
350 /// The length cannot change, for the same reason it cannot in
351 /// [`RawMap::value_mut`], and an address is only good until the next real
352 /// write, for the same reason it is in [`RawMap::find`].
353 #[inline]
354 pub fn value_at_mut(&mut self, addr: Addr) -> &mut [u8] {
355 let (klen, vlen) = Record::lens(self.arena.get(addr, HDR));
356 &mut self.arena.get_mut(addr, HDR + klen + vlen)[HDR + klen..]
357 }
358
359 /// The value stored under `key`, to be overwritten where it lies.
360 ///
361 /// The length cannot change, which is the whole reason this is safe to
362 /// offer. `INCR` on an integer encoded string is a probe, an add and a
363 /// store, and the store is eight bytes back into the record it came from
364 /// (`08` section 2). Going through [`RawMap::set`] instead would write a
365 /// fresh record and free the old one on every increment, which is an arena
366 /// append and a dead byte per operation for a value whose size never moves.
367 ///
368 /// There is no reader to tear. A map belongs to one shard thread and is not
369 /// `Sync`, so the only code that can observe a half written value is the
370 /// code doing the writing. When a replica stream or a snapshot reader starts
371 /// walking the arena from another thread, this becomes an epoch question and
372 /// the write becomes an install rather than an overwrite.
373 #[inline]
374 pub fn value_mut(&mut self, key: &[u8]) -> Option<&mut [u8]> {
375 self.value_mut_hashed(Self::hash_of(key), key)
376 }
377
378 /// [`RawMap::value_mut`] for a caller that already hashed the key.
379 #[inline]
380 pub fn value_mut_hashed(&mut self, hash: u64, key: &[u8]) -> Option<&mut [u8]> {
381 self.writes += 1;
382 let addr = self.index.get(hash, key, &Records { arena: &self.arena })?;
383 let (klen, vlen) = Record::lens(self.arena.get(addr, HDR));
384 Some(&mut self.arena.get_mut(addr, HDR + klen + vlen)[HDR + klen..])
385 }
386
387 /// Store `val` under `key`, returning the length of the value it replaced.
388 pub fn set(&mut self, key: &[u8], val: &[u8]) -> Option<usize> {
389 self.set_with(
390 key,
391 val.len(),
392 |_| {},
393 |buf| {
394 buf.copy_from_slice(val);
395 false
396 },
397 )
398 }
399
400 /// The largest record this map can store, key and value and header together.
401 ///
402 /// A value past this belongs in the log region rather than the arena, which
403 /// is `06` section 2's business and not this crate's.
404 #[inline]
405 #[must_use]
406 pub const fn max_record() -> usize {
407 yo_arena::MAX_ALLOC
408 }
409
410 /// Bytes of record header in front of the key.
411 #[inline]
412 #[must_use]
413 pub const fn header_len() -> usize {
414 HDR
415 }
416
417 /// Store a `vlen` byte value under `key`, written by `fill`.
418 ///
419 /// The same thing [`RawMap::set`] does, except that the caller writes
420 /// straight into the record instead of building the value somewhere else
421 /// first and having it copied in. A string with a one byte encoding tag in
422 /// front of it would otherwise be assembled in a scratch buffer and then
423 /// memcpy'd again, and two copies for one `SET` is one too many on a path
424 /// that is trying to be ten times faster than Redis.
425 ///
426 /// `fill` is handed exactly `vlen` bytes of uninitialised-looking storage.
427 /// It is arena memory that has been handed out before and freed, so its
428 /// contents are arbitrary and every byte of it must be written. What it
429 /// answers is whether this record should be marked, which is what
430 /// [`RawMap::sample_tagged`] later draws from. A caller with no use for that
431 /// answers `false` and pays a branch.
432 ///
433 /// `peek` is handed the value that was already under `key`, if there was
434 /// one, before anything is written over it. It exists because the caller
435 /// keeps counts that depend on what the old value was, and this is the only
436 /// place those bytes can be read for free: both paths through here have
437 /// already loaded the old record's header to find out how long it is, so the
438 /// value is in cache and would otherwise cost a second lookup to see. A
439 /// caller with nothing to ask passes an empty closure and pays nothing.
440 ///
441 /// # Panics
442 ///
443 /// If the whole record would exceed [`RawMap::max_record`].
444 pub fn set_with<P, F>(&mut self, key: &[u8], vlen: usize, peek: P, fill: F) -> Option<usize>
445 where
446 P: FnOnce(&[u8]),
447 F: FnOnce(&mut [u8]) -> bool,
448 {
449 self.writes += 1;
450 assert!(key.len() <= u32::MAX as usize, "key too long");
451 assert!(vlen <= u32::MAX as usize, "value too long");
452 let total = HDR + key.len() + vlen;
453 let h = wyhash(key, 0);
454
455 // A key that is already here, in a record exactly the size the new value
456 // needs, is written over where it lies. No allocation, no dead bytes, no
457 // index write, and nothing for compaction to collect later.
458 //
459 // This used to say the in place path had to wait for epochs, because a
460 // reader that had already resolved the address would see a torn value.
461 // That was never a rule this map kept: `value_mut` is the same write and
462 // `INCR` has been doing it since the day it was written, for the same
463 // reason given there. A map belongs to one shard thread and is not
464 // `Sync`, so the only code that can see a half written value is the code
465 // writing it. When a replica stream or a snapshot reader starts walking
466 // the arena from another thread, both of these become an install rather
467 // than an overwrite, together.
468 //
469 // Exactly the size and not merely small enough. A shorter value in a
470 // longer record would leave the header disagreeing with the space the
471 // record occupies, and compaction walks a segment by stepping over each
472 // record by the length in its header, so the walk would land in the
473 // middle of the next one.
474 //
475 // Overwriting a key with a value the same size as the last one is what
476 // half of the world's caches do, and it is what every SET benchmark
477 // does. On gamingpc it was 25 percent of SET throughput at pipeline 16
478 // and 37 percent of MSET, all of it spent making garbage and then
479 // collecting it.
480 if let Some(addr) = self.index.get(h, key, &Records { arena: &self.arena }) {
481 let (klen, old_vlen) = Record::lens(self.arena.get(addr, HDR));
482 debug_assert_eq!(klen, key.len(), "the index matched a different key");
483 // Before `fill`, because the in place path writes over exactly the
484 // bytes `peek` is being handed. Once, and here rather than next to
485 // the free below, because this is the branch that knows the key was
486 // there and both paths out of it go past this line.
487 peek(&self.arena.get(addr, HDR + klen + old_vlen)[HDR + klen..]);
488 if old_vlen == vlen {
489 let rec = self.arena.get_mut(addr, total);
490 let tag = fill(&mut rec[HDR + klen..]);
491 // The record did not move, so this is the only thing that can
492 // have changed about where it stands: `PERSIST` on a key whose
493 // value is the same length is exactly this branch.
494 self.retag(addr, tag);
495 return Some(vlen);
496 }
497 }
498
499 let (addr, buf) = self
500 .arena
501 .alloc(total)
502 .expect("record is larger than a segment");
503 buf[0..4].copy_from_slice(&(key.len() as u32).to_le_bytes());
504 buf[4..8].copy_from_slice(&(vlen as u32).to_le_bytes());
505 // The arena hands back a run padded up to its alignment, so index to
506 // `total` rather than to the end of the slice.
507 buf[HDR..HDR + key.len()].copy_from_slice(key);
508 let tag = fill(&mut buf[HDR + key.len()..total]);
509
510 let old = {
511 let recs = Records { arena: &self.arena };
512 self.index.insert(h, key, addr, &recs)
513 };
514 // After the insert and not before, because the address the old record
515 // was at is only known once the index has handed it back, and tagging
516 // the new one first would put both in the set for the width of the call
517 // if they happened to be the same address, which they cannot be, but the
518 // order that does not depend on that is the one to write.
519 if let Some(prev) = old {
520 self.tagged.remove(prev);
521 }
522 if tag {
523 self.tagged.insert(addr);
524 } else {
525 // Nothing to take out. `addr` is a run the arena has just handed
526 // back, and nothing is ever freed while it is still marked: a delete
527 // unmarks before it frees, an overwrite unmarks the record it
528 // replaces on the line above, and compaction moves the mark before
529 // it frees the copy it moved from. So a fresh address is never in
530 // the set, and this is the common path, which is every `SET` on a
531 // database that has any deadline in it at all.
532 debug_assert!(
533 !self.tagged.contains(addr),
534 "the arena handed out an address that is still marked"
535 );
536 }
537 match old {
538 Some(prev) => {
539 let (pk, pv) = Record::lens(self.arena.get(prev, HDR));
540 self.arena.free(prev, HDR + pk + pv);
541 Some(pv)
542 }
543 None => None,
544 }
545 }
546
547 /// Put `addr` in the marked set, or take it out, to match `tag`.
548 ///
549 /// For the in place path, which is the one where the record was already
550 /// there and could already have been marked. It cannot tell whether the mark
551 /// changed without asking, because a deadline is eight bytes in the record
552 /// and a value eight bytes shorter with a deadline is the same length as a
553 /// value without one, so a write that lands in place is not proof that the
554 /// mark stayed put.
555 ///
556 /// On a database where nothing is marked the ask is one comparison against a
557 /// zero length, which is what the overwhelming majority of servers pay.
558 #[inline]
559 fn retag(&mut self, addr: Addr, tag: bool) {
560 if tag {
561 self.tagged.insert(addr);
562 } else {
563 self.tagged.remove(addr);
564 }
565 }
566
567 /// Remove `key`, returning whether it was there.
568 #[inline]
569 pub fn del(&mut self, key: &[u8]) -> bool {
570 self.del_with(key, |_| {})
571 }
572
573 /// Remove `key`, showing its value to `peek` first, and return whether it
574 /// was there.
575 ///
576 /// The sibling of [`RawMap::set_with`], and it exists for the same reason.
577 /// This already reads the record's header to find out how long it is before
578 /// handing the bytes back to the arena, so the value is in cache and a
579 /// caller who keeps a count that depends on what was removed can read it
580 /// here for the price of a closure call. Asking with a [`RawMap::get`] first
581 /// would be a second lookup for a question this one already knows the answer
582 /// to. `peek` is not called when the key was not there.
583 pub fn del_with<P: FnOnce(&[u8])>(&mut self, key: &[u8], peek: P) -> bool {
584 self.writes += 1;
585 let h = wyhash(key, 0);
586 let addr = {
587 let recs = Records { arena: &self.arena };
588 self.index.remove(h, key, &recs)
589 };
590 match addr {
591 Some(a) => {
592 let (k, v) = Record::lens(self.arena.get(a, HDR));
593 peek(&self.arena.get(a, HDR + k + v)[HDR + k..]);
594 self.tagged.remove(a);
595 self.arena.free(a, HDR + k + v);
596 true
597 }
598 None => false,
599 }
600 }
601
602 /// Whether `key` is present.
603 #[inline]
604 pub fn contains(&self, key: &[u8]) -> bool {
605 let h = wyhash(key, 0);
606 self.index.contains(h, key, &Records { arena: &self.arena })
607 }
608
609 /// The key and the value at an address this map handed out.
610 ///
611 /// The pair rather than either one alone, because they are one contiguous
612 /// read: the header says how long the key is and the value starts where the
613 /// key ends, so asking for both costs what asking for one costs.
614 #[inline]
615 #[must_use]
616 pub fn entry_at(&self, addr: Addr) -> (&[u8], &[u8]) {
617 let (klen, vlen) = Record::lens(self.arena.get(addr, HDR));
618 let bytes = self.arena.get(addr, HDR + klen + vlen);
619 (&bytes[HDR..HDR + klen], &bytes[HDR + klen..])
620 }
621
622 /// Walk a batch of the map, and say where the next batch starts.
623 ///
624 /// This is `SCAN`. `budget` is how many entries the caller would like, and
625 /// it is a floor and not a ceiling: the walk stops at the first bucket
626 /// boundary past it, so a batch of ten can come back with fifteen. Redis's
627 /// `COUNT` behaves the same way and for the same reason, which is that a
628 /// bucket is the smallest unit a cursor can name.
629 ///
630 /// A budget of zero still does one bucket, so a caller that keeps passing
631 /// the cursor back always finishes rather than spinning on the same number.
632 ///
633 /// The guarantee, in full: a key that is present for the whole walk is
634 /// handed to `out` at least once. A key added or removed partway through may
635 /// or may not appear, and a key may appear twice. The reasoning is in
636 /// [`Cursor`], and the part worth knowing here is that none of it depends on
637 /// the map holding still between calls.
638 pub fn scan(&self, from: Cursor, budget: usize, mut out: impl FnMut(&[u8], &[u8])) -> Cursor {
639 // The index and the arena are separate fields, so the walk can hold one
640 // and the closure the other. That is what keeps this allocation free:
641 // there is no list of addresses in between.
642 let arena = &self.arena;
643 let mut at = from;
644 let mut seen = 0usize;
645 loop {
646 at = self.index.scan(at, |addr| {
647 let (klen, vlen) = Record::lens(arena.get(addr, HDR));
648 let bytes = arena.get(addr, HDR + klen + vlen);
649 out(&bytes[HDR..HDR + klen], &bytes[HDR + klen..]);
650 seen += 1;
651 });
652 if at.is_end() || seen >= budget {
653 return at;
654 }
655 }
656 }
657
658 /// Entries picked at random, for eviction sampling, until `out` says stop.
659 ///
660 /// The key, the value and the address of each, because a caller choosing a
661 /// victim needs all three: the value to score it, the key to delete it, and
662 /// the address to delete it by without a second probe. `out` answers whether
663 /// to keep going. [`Index::sample`] is where the argument for all of it lives,
664 /// including why the budget is the caller's and why this can hand back
665 /// nothing at all.
666 pub fn sample(&self, r: u64, mut out: impl FnMut(&[u8], &[u8], Addr) -> bool) {
667 let arena = &self.arena;
668 self.index.sample(r, |addr| {
669 let (klen, vlen) = Record::lens(arena.get(addr, HDR));
670 let bytes = arena.get(addr, HDR + klen + vlen);
671 out(&bytes[HDR..HDR + klen], &bytes[HDR + klen..], addr)
672 });
673 }
674
675 /// The index, for stats and for compaction.
676 pub fn index(&self) -> &Index {
677 &self.index
678 }
679
680 /// The arena, for stats and for compaction.
681 pub fn arena(&self) -> &Arena {
682 &self.arena
683 }
684
685 /// Bytes held by index structure plus arena segments.
686 pub fn memory_bytes(&self) -> usize {
687 self.index.memory_bytes()
688 + self.arena.reserved_bytes() as usize
689 + self.tagged.memory_bytes()
690 }
691
692 /// How many records are marked.
693 ///
694 /// Exact, and kept exact by every write path, so a caller can branch on a
695 /// zero here rather than starting a sweep that was never going to find
696 /// anything.
697 #[inline]
698 #[must_use]
699 pub fn tagged_len(&self) -> usize {
700 self.tagged.len()
701 }
702
703 /// Whether the record at `addr` is marked.
704 ///
705 /// For a test and for a debug assertion. Nothing on a hot path asks this:
706 /// the mark is written from the record's own bytes, so anything holding the
707 /// record already knows.
708 #[must_use]
709 pub fn is_tagged(&self, addr: Addr) -> bool {
710 self.tagged.contains(addr)
711 }
712
713 /// Walk marked records from wherever `r` lands, until `out` says stop.
714 ///
715 /// [`RawMap::sample`] for the marked subset, and the reason the subset
716 /// exists. A database of ten million keys where a thousand carry a deadline
717 /// gives the expire cycle a thousand candidates to draw from instead of ten
718 /// million, and the cycle stops costing anything at all in the case that
719 /// matters most, which is the one where the answer is that there is nothing
720 /// to do.
721 pub fn sample_tagged(&self, r: u64, mut out: impl FnMut(&[u8], &[u8], Addr) -> bool) {
722 let arena = &self.arena;
723 self.tagged.sample(r, |addr| {
724 let (klen, vlen) = Record::lens(arena.get(addr, HDR));
725 let bytes = arena.get(addr, HDR + klen + vlen);
726 out(&bytes[HDR..HDR + klen], &bytes[HDR + klen..], addr)
727 });
728 }
729
730 /// Move every live record out of `seg` and into the current segment, then
731 /// put the segment back on the arena's free list.
732 ///
733 /// Copy, rewrite the index entry, done. No forwarding pointers and no read
734 /// barrier, which is the F2 shape from `05` section 3.2 and is what an
735 /// allocation having exactly one referent buys.
736 ///
737 /// The walk is over the segment and not over the index. Both find the same
738 /// records, and the index walk is the one written in the spec, but it reads
739 /// the whole index to compact two megabytes: fine when this only ran in a
740 /// test, wrong once the event loop calls it, because the pause would then
741 /// grow with the size of the database rather than with the size of a
742 /// segment. Walking the segment costs one index probe per record in it and
743 /// does not care how many keys exist elsewhere.
744 ///
745 /// Records sit back to back from the header to the segment's bump, each one
746 /// rounded up to the arena's alignment, and every arena allocation is a
747 /// record, so the next one is always a known distance away. A record is
748 /// live when the index still points at this copy of it, and dead when it
749 /// points somewhere else or at nothing, which is exactly what an overwrite
750 /// and a delete leave behind.
751 ///
752 /// The reclaim at the end is the part that makes the space usable again.
753 /// Moving the records out only makes a segment empty, and an empty segment
754 /// that nothing ever bumps through again is still two megabytes the process
755 /// is holding.
756 pub fn compact_segment(&mut self, seg: usize) -> usize {
757 self.writes += 1;
758 if seg == self.arena.current_segment() {
759 // Its bump is a cursor, not a checkpoint, and reclaiming it would
760 // take the ground out from under the next allocation.
761 return 0;
762 }
763 let (moved, _) = self.evacuate(seg, yo_arena::HEADER_SIZE, usize::MAX);
764 self.arena.reclaim(seg);
765 moved
766 }
767
768 /// Walk `seg` from `from`, moving live records out, and stop once the walk
769 /// has covered `budget` bytes of it. Says how many records moved and where
770 /// to start again.
771 ///
772 /// The record that straddles the budget is finished rather than cut in
773 /// half, so the walk can go a little past what was asked for. The overrun
774 /// is one record and the budget is thousands of bytes.
775 ///
776 /// Nothing here reclaims. A segment is only empty once the walk reaches the
777 /// bump, and the caller is the one that knows whether it did.
778 fn evacuate(&mut self, seg: usize, from: usize, budget: usize) -> (usize, usize) {
779 let base = (seg as u64) << yo_arena::SEGMENT_SHIFT;
780 let bump = self.arena.recorded_bump(seg) as usize;
781 let stop = from.saturating_add(budget).min(bump);
782
783 let mut moved = 0;
784 let mut off = from;
785 while off < stop {
786 let old = Addr::new(Space::Arena, base + off as u64);
787 let (klen, vlen) = Record::lens(self.arena.get(old, HDR));
788 let total = HDR + klen + vlen;
789 off += total.next_multiple_of(yo_arena::ALIGN);
790 self.compaction.walked += 1;
791
792 let hash = {
793 let bytes = self.arena.get(old, HDR + klen);
794 wyhash(&bytes[HDR..], 0)
795 };
796 let live = {
797 let bytes = self.arena.get(old, HDR + klen);
798 let key = &bytes[HDR..];
799 let recs = Records { arena: &self.arena };
800 self.index.get(hash, key, &recs) == Some(old)
801 };
802 if !live {
803 continue;
804 }
805
806 let new = self.arena.copy_within(old, total);
807 let bytes = self.arena.get(new, HDR + klen);
808 let key = &bytes[HDR..];
809 let recs = Records { arena: &self.arena };
810 let ok = self.index.relocate(hash, key, new, &recs);
811 debug_assert!(ok, "compaction lost an entry the index just handed us");
812 // The one place a record moves without anybody writing to it, and
813 // therefore the one place the tagged set would go stale if this line
814 // were not here.
815 if self.tagged.remove(old) {
816 self.tagged.insert(new);
817 }
818 self.arena.free(old, total);
819 moved += 1;
820 self.compaction.moved += 1;
821 self.compaction.bytes += total as u64;
822 }
823 (moved, off)
824 }
825
826 /// How much to walk on this call, given how far behind the collector is.
827 ///
828 /// A fixed budget has to be either a good pause or a good collection rate
829 /// and it cannot be both. At 64 kilobytes a segment takes thirty two calls,
830 /// and a pipelined flood of writes makes garbage faster than one call per
831 /// batch gets it back: measured with variable sized values at pipeline 16,
832 /// the tail came down from 2.6 milliseconds to 1.6 and the process held 18
833 /// MB more, because segments queued up waiting their turn to be walked.
834 ///
835 /// So the floor is what a command can be asked to wait for, and the depth
836 /// of that queue is what says how much more than the floor is needed to
837 /// keep up. One candidate is a store that is keeping up and pays the floor.
838 /// Nine is a store nine segments behind, and it walks nine slices.
839 ///
840 /// The queue and not the dead byte total. Dead bytes were tried first,
841 /// measured against the point compaction starts at, and that ratio cannot
842 /// see a backlog at all: the threshold is a fraction of what the arena
843 /// holds, so a collector that falls behind grows the arena, which raises
844 /// the threshold, which puts the ratio back where it was. It sat at the
845 /// floor through the whole flood and the 18 MB stayed exactly where it was.
846 /// A count of segments has no such denominator.
847 ///
848 /// Linear in the depth and not squared. This is a controller in a loop with
849 /// its own input, and a term that grows faster than the error is how one of
850 /// those starts to oscillate.
851 fn budget(&self) -> usize {
852 let behind = self.arena.candidate_count().max(1);
853 EVAC_FLOOR.saturating_mul(behind).min(EVAC_CEILING)
854 }
855
856 /// Do one bounded slice of compaction, and say how many records moved.
857 ///
858 /// `None` means there was no candidate and there is nothing in flight. It
859 /// is not the same as `Some(0)`, which is a slice that walked only records
860 /// that had already been overwritten: that one made progress and cost
861 /// something, and a caller deciding whether to go round again needs to be
862 /// told so.
863 ///
864 /// This is the whole maintenance contract: a bounded amount of work per
865 /// call, so a caller that runs it once per batch never pays for a full pass
866 /// over the arena and never pays for a whole segment either. Finding out
867 /// there is nothing to do is one comparison against the running dead byte
868 /// total.
869 ///
870 /// A segment takes as many calls as it takes. Each one picks up where the
871 /// last stopped and only the call that reaches the end gives the two
872 /// megabytes back, so the space comes back in one lump at the end while the
873 /// cost of getting it back is spread over the batches in between. That is
874 /// the trade: a segment stays around a little longer than it used to, and
875 /// no single command waits for the whole of it.
876 ///
877 /// The segment in flight is finished before another is chosen, rather than
878 /// asking which segment is worst on every call. Otherwise a segment that is
879 /// three quarters evacuated could be put down in favour of a worse one and
880 /// never picked up, and the arena would fill with segments that are nearly
881 /// empty and never reclaimed.
882 pub fn compact_step(&mut self) -> Option<usize> {
883 self.compact(Sweep::Ordinary)
884 }
885
886 /// One slice of compaction for a store that has run out of room.
887 ///
888 /// The same work, choosing between segments the way
889 /// [`Arena::any_candidate`](yo_arena::Arena::any_candidate) chooses rather
890 /// than the way [`Arena::worst_candidate`](yo_arena::Arena::worst_candidate)
891 /// does, so a store that is clean overall still collects the parts of it
892 /// that are not. The reason is written on `any_candidate`.
893 ///
894 /// A segment already in flight is finished first either way, so switching
895 /// between this and [`RawMap::compact_step`] cannot leave a segment half
896 /// evacuated forever.
897 pub fn compact_hard(&mut self) -> Option<usize> {
898 self.compact(Sweep::Hard)
899 }
900
901 fn compact(&mut self, sweep: Sweep) -> Option<usize> {
902 self.writes += 1;
903 let (seg, from) = match self.evac {
904 Some(e) => (e.seg, e.off),
905 None => {
906 let pick = match sweep {
907 Sweep::Ordinary => self.arena.worst_candidate()?,
908 Sweep::Hard => self.arena.any_candidate()?,
909 };
910 (pick, yo_arena::HEADER_SIZE)
911 }
912 };
913 if seg == self.arena.current_segment() {
914 self.evac = None;
915 return Some(0);
916 }
917
918 // After the choice and not before it. The count is a walk over the
919 // segment headers, and a store with nothing to collect should not pay
920 // for one on every batch to be told there is nothing to collect.
921 let budget = self.budget();
922 let (moved, off) = self.evacuate(seg, from, budget);
923 if off >= self.arena.recorded_bump(seg) as usize {
924 self.arena.reclaim(seg);
925 self.evac = None;
926 } else {
927 self.evac = Some(Evac { seg, off });
928 }
929 Some(moved)
930 }
931}
932
933impl Default for RawMap {
934 fn default() -> RawMap {
935 RawMap::new()
936 }
937}
938
939#[cfg(test)]
940mod tests {
941 use super::*;
942 use std::collections::{HashMap, HashSet};
943
944 /// `key:` and the index zero padded to twelve digits.
945 ///
946 /// Written out by hand rather than with `format!`, which produces the same
947 /// bytes. Formatting is a lot of machinery for twelve digits, and Miri pays
948 /// per operation rather than per instruction, so under the interpreter one
949 /// `format!` costs a couple of milliseconds. `grows_through_many_splits`
950 /// calls this once per set, get, delete and contains, which is ten thousand
951 /// calls on its own, and that is twenty seconds of the ninety five this
952 /// crate's Miri shard used to take.
953 fn key(i: usize) -> Vec<u8> {
954 let mut k = *b"key:000000000000";
955 let mut n = i;
956 let mut p = k.len() - 1;
957 while n > 0 {
958 k[p] = b'0' + (n % 10) as u8;
959 n /= 10;
960 p -= 1;
961 }
962 k.to_vec()
963 }
964
965 /// `v` and the index, unpadded, which is what `format!("v{i}")` gives.
966 fn val(i: usize) -> Vec<u8> {
967 let mut v = vec![b'v'];
968 if i == 0 {
969 v.push(b'0');
970 return v;
971 }
972 let start = v.len();
973 let mut n = i;
974 while n > 0 {
975 v.push(b'0' + (n % 10) as u8);
976 n /= 10;
977 }
978 v[start..].reverse();
979 v
980 }
981
982 // Miri is a few hundred times slower than the machine, so the counts below
983 // shrink under it. They stay large enough to force directory doublings,
984 // segment splits and overflow chains, which is what these tests are for.
985 // Only the scale goes away, not the coverage.
986 // Three thousand and not fewer. `splits() > 4` is the assertion and the
987 // splits go 1, 1, 2, 3, 3, 5 at 800, 1200, 1500, 2000, 2500 and 3000 keys,
988 // so this is already the smallest count that grows the directory the number
989 // of times the test asks about.
990 #[cfg(miri)]
991 const GROW_N: usize = 3_000;
992 #[cfg(not(miri))]
993 const GROW_N: usize = 200_000;
994
995 #[cfg(miri)]
996 const ADVERSARIAL_N: u64 = 1_000;
997 #[cfg(not(miri))]
998 const ADVERSARIAL_N: u64 = 50_000;
999
1000 // Big values so that a handful of records fills a 2 MiB segment and
1001 // compaction has something to do without a hundred thousand writes.
1002 #[cfg(miri)]
1003 const COMPACT_VAL: usize = 65_536;
1004 #[cfg(miri)]
1005 const COMPACT_N: usize = 200;
1006 #[cfg(not(miri))]
1007 const COMPACT_VAL: usize = 1024;
1008 #[cfg(not(miri))]
1009 const COMPACT_N: usize = 8_000;
1010
1011 #[test]
1012 fn set_get_del() {
1013 let mut m = RawMap::new();
1014 assert!(m.is_empty());
1015 assert_eq!(m.set(b"a", b"1"), None);
1016 assert_eq!(m.get(b"a"), Some(&b"1"[..]));
1017 assert_eq!(m.len(), 1);
1018 assert_eq!(m.set(b"a", b"22"), Some(1));
1019 assert_eq!(m.get(b"a"), Some(&b"22"[..]));
1020 assert_eq!(m.len(), 1);
1021 assert!(m.del(b"a"));
1022 assert!(!m.del(b"a"));
1023 assert_eq!(m.get(b"a"), None);
1024 assert!(m.is_empty());
1025 }
1026
1027 #[test]
1028 fn a_value_can_be_overwritten_where_it_lies() {
1029 let mut m = RawMap::new();
1030 m.set(b"n", &7u64.to_le_bytes());
1031 m.set(b"other", b"untouched");
1032 let before = m.arena().live_bytes();
1033
1034 let v = m.value_mut(b"n").expect("the key is there");
1035 v.copy_from_slice(&8u64.to_le_bytes());
1036
1037 assert_eq!(m.get(b"n"), Some(&8u64.to_le_bytes()[..]));
1038 assert_eq!(m.get(b"other"), Some(&b"untouched"[..]));
1039 // The point of the whole method: no second record and nothing dead.
1040 assert_eq!(m.arena().live_bytes(), before);
1041 assert_eq!(m.len(), 2);
1042
1043 assert!(m.value_mut(b"missing").is_none());
1044 }
1045
1046 /// A key overwritten with a value the same size stays in the record it is
1047 /// already in, and one overwritten with a different size does not.
1048 ///
1049 /// The first is the shape every SET benchmark and half the world's caches
1050 /// have: the same keys, the same value size, over and over. Writing a fresh
1051 /// record for each of those makes a dead one to go with it, and compaction
1052 /// then spends a quarter of the server's write throughput copying live
1053 /// records out from between them.
1054 #[test]
1055 fn an_overwrite_of_the_same_size_makes_no_garbage() {
1056 let mut m = RawMap::new();
1057 m.set(b"k", b"12345678");
1058 m.set(b"other", b"untouched");
1059 let live = m.arena().live_bytes();
1060 let dead = m.arena().dead_bytes_total();
1061
1062 for i in 0..1000u32 {
1063 let v = format!("{i:08}");
1064 assert_eq!(m.set(b"k", v.as_bytes()), Some(8));
1065 }
1066
1067 assert_eq!(m.get(b"k"), Some(&b"00000999"[..]));
1068 assert_eq!(m.get(b"other"), Some(&b"untouched"[..]));
1069 assert_eq!(m.len(), 2);
1070 assert_eq!(m.arena().live_bytes(), live, "a thousand writes, no growth");
1071 assert_eq!(m.arena().dead_bytes_total(), dead, "and nothing dead");
1072
1073 // A different length cannot go in the same hole, because the record has
1074 // to be as long as its header says it is.
1075 assert_eq!(m.set(b"k", b"123456789"), Some(8));
1076 assert_eq!(m.get(b"k"), Some(&b"123456789"[..]));
1077 assert!(
1078 m.arena().dead_bytes_total() > dead,
1079 "the old record is dead"
1080 );
1081 }
1082
1083 /// An expiring value and a plain one are different record lengths, so the
1084 /// one does not get written over the other.
1085 ///
1086 /// This is the case the in place path has to refuse rather than the case it
1087 /// is for, and it is the one that would corrupt a record if it took it: the
1088 /// value here is a keyspace record, whose deadline is inside the value, so
1089 /// two values of the same visible length are two different record lengths.
1090 #[test]
1091 fn a_longer_value_moves_and_the_index_follows_it() {
1092 let mut m = RawMap::new();
1093 m.set(b"k", b"aaaa");
1094 let first = m
1095 .index()
1096 .get(RawMap::hash_of(b"k"), b"k", &Records { arena: m.arena() });
1097
1098 m.set(b"k", b"aaaaaaaa");
1099 let second = m
1100 .index()
1101 .get(RawMap::hash_of(b"k"), b"k", &Records { arena: m.arena() });
1102
1103 assert_ne!(first, second, "a longer value needs a new record");
1104 assert_eq!(m.get(b"k"), Some(&b"aaaaaaaa"[..]));
1105 }
1106
1107 #[test]
1108 fn empty_key_and_empty_value() {
1109 let mut m = RawMap::new();
1110 m.set(b"", b"");
1111 assert_eq!(m.get(b""), Some(&b""[..]));
1112 m.set(b"x", b"");
1113 assert_eq!(m.get(b"x"), Some(&b""[..]));
1114 assert_eq!(m.len(), 2);
1115 }
1116
1117 #[test]
1118 fn grows_through_many_splits() {
1119 let mut m = RawMap::new();
1120 const N: usize = GROW_N;
1121 for i in 0..N {
1122 m.set(&key(i), &val(i));
1123 }
1124 assert_eq!(m.len(), N);
1125 assert!(
1126 m.index().splits() > 4,
1127 "expected real growth, saw {} splits",
1128 m.index().splits()
1129 );
1130 for i in 0..N {
1131 assert_eq!(
1132 m.get(&key(i)),
1133 Some(val(i).as_slice()),
1134 "lost key {i} after {} splits",
1135 m.index().splits()
1136 );
1137 }
1138 for i in (0..N).step_by(3) {
1139 assert!(m.del(&key(i)), "delete missed key {i}");
1140 }
1141 for i in 0..N {
1142 assert_eq!(
1143 m.contains(&key(i)),
1144 i % 3 != 0,
1145 "wrong presence for key {i}"
1146 );
1147 }
1148 }
1149
1150 #[test]
1151 fn compaction_preserves_everything() {
1152 let mut m = RawMap::new();
1153 // Enough to fill several arena segments with 1 KiB values.
1154 let val = vec![b'z'; COMPACT_VAL];
1155 const N: usize = COMPACT_N;
1156 for i in 0..N {
1157 m.set(&key(i), &val);
1158 }
1159 // Kill half, which pushes the early segments over the dead ratio.
1160 for i in (0..N).step_by(2) {
1161 m.del(&key(i));
1162 }
1163 let candidates = m.arena().compaction_candidates();
1164 assert!(
1165 !candidates.is_empty(),
1166 "expected at least one segment past the dead ratio"
1167 );
1168 for seg in candidates {
1169 m.compact_segment(seg);
1170 }
1171 for i in 0..N {
1172 let want = if i % 2 == 0 { None } else { Some(val.clone()) };
1173 assert_eq!(m.get(&key(i)).map(|v| v.to_vec()), want, "key {i}");
1174 }
1175 }
1176
1177 /// A mark follows its record wherever the record goes.
1178 ///
1179 /// The whole reason the marked set lives in this file. Compaction moves a
1180 /// record to a new address without anybody writing to it, so a set of
1181 /// addresses kept by a caller would be pointing at freed space afterwards,
1182 /// and the sample would read whatever the arena handed out next.
1183 #[test]
1184 fn compaction_carries_the_marks_with_it() {
1185 let mut m = RawMap::new();
1186 let val = vec![b'z'; COMPACT_VAL];
1187 const N: usize = COMPACT_N;
1188 for i in 0..N {
1189 m.set_with(
1190 &key(i),
1191 val.len(),
1192 |_| {},
1193 |b| {
1194 b.copy_from_slice(&val);
1195 i % 3 == 0
1196 },
1197 );
1198 }
1199 let want = (0..N).filter(|i| i % 3 == 0).count();
1200 assert_eq!(m.tagged_len(), want);
1201
1202 for i in (0..N).step_by(2) {
1203 m.del(&key(i));
1204 }
1205 let want = (0..N).filter(|i| i % 3 == 0 && i % 2 == 1).count();
1206 assert_eq!(m.tagged_len(), want, "a delete takes the mark with it");
1207
1208 for seg in m.arena().compaction_candidates() {
1209 m.compact_segment(seg);
1210 }
1211 assert_eq!(
1212 m.tagged_len(),
1213 want,
1214 "and compaction moves it rather than losing it"
1215 );
1216
1217 // Every mark points at a record that is still there and is one of the
1218 // ones that was marked, which is what a stale address would fail.
1219 let mut seen = 0;
1220 m.sample_tagged(0, |k, _, addr| {
1221 assert!(m.get(k).is_some(), "a mark on a key that is gone");
1222 let i: usize = std::str::from_utf8(&k[4..]).unwrap().parse().unwrap();
1223 assert!(
1224 i.is_multiple_of(3) && !i.is_multiple_of(2),
1225 "key {i} was never marked"
1226 );
1227 assert!(m.is_tagged(addr));
1228 seen += 1;
1229 true
1230 });
1231 assert_eq!(seen, want);
1232 }
1233
1234 /// A mark goes on and comes off with the record's own bytes, which is how
1235 /// PERSIST works: the value is the same length, so the record does not move
1236 /// and only the mark changes.
1237 #[test]
1238 fn a_mark_goes_on_and_comes_off_in_place() {
1239 let mut m = RawMap::new();
1240 let mark = |m: &mut RawMap, on: bool| {
1241 m.set_with(
1242 b"k",
1243 1,
1244 |_| {},
1245 |b| {
1246 b[0] = b'v';
1247 on
1248 },
1249 )
1250 };
1251 mark(&mut m, true);
1252 assert_eq!(m.tagged_len(), 1);
1253 mark(&mut m, true);
1254 assert_eq!(m.tagged_len(), 1, "marking twice is marking once");
1255 mark(&mut m, false);
1256 assert_eq!(m.tagged_len(), 0);
1257 mark(&mut m, true);
1258 assert_eq!(m.tagged_len(), 1);
1259 assert!(m.del(b"k"));
1260 assert_eq!(m.tagged_len(), 0);
1261 }
1262
1263 /// The bug this exists for: overwriting a key writes a new record and only
1264 /// counts the old one dead, so without compaction a server that rewrites
1265 /// the same keys holds every version of every one of them forever. Measured
1266 /// on a real server before this, 400000 sets over 100000 keys came to 742
1267 /// bytes a key for 64 byte values.
1268 #[test]
1269 fn rewriting_the_same_keys_stops_growing() {
1270 let mut m = RawMap::new();
1271 let val = vec![b'z'; COMPACT_VAL];
1272 const N: usize = COMPACT_N;
1273
1274 for i in 0..N {
1275 m.set(&key(i), &val);
1276 m.compact_step();
1277 }
1278 let after_first_pass = m.arena().reserved_bytes();
1279
1280 // Nine more passes over the same keys, writing the same amount of data
1281 // nine more times and keeping exactly as much of it.
1282 for _ in 0..9 {
1283 for i in 0..N {
1284 m.set(&key(i), &val);
1285 m.compact_step();
1286 }
1287 }
1288 let after_ten = m.arena().reserved_bytes();
1289
1290 assert!(
1291 after_ten <= after_first_pass * 2,
1292 "held {after_ten} after ten passes against {after_first_pass} after one, \
1293 which is the grow forever shape"
1294 );
1295 assert!(
1296 after_ten < m.arena().live_bytes() * 2,
1297 "held {after_ten} for {} live, which is more than the ratio allows",
1298 m.arena().live_bytes()
1299 );
1300 for i in 0..N {
1301 assert_eq!(
1302 m.get(&key(i)).map(<[u8]>::to_vec),
1303 Some(val.clone()),
1304 "key {i}"
1305 );
1306 }
1307 }
1308
1309 /// A segment is evacuated over several calls, and it comes back only on the
1310 /// call whose walk reaches the end of it.
1311 ///
1312 /// This is what the budget is for. One call used to copy every live record
1313 /// in two megabytes, around twenty six thousand of them at 64 byte values,
1314 /// and the whole batch of replies queued behind it waited for all of them.
1315 /// That is where a p99 of 3.9 milliseconds on the write rows came from
1316 /// while the p50 was in line with Redis: the median command paid nothing
1317 /// and one command in a few thousand paid for a segment.
1318 ///
1319 /// The loop is also what catches a walk that restarts instead of resuming.
1320 /// A restart would move records and look like progress, and it would spend
1321 /// every call re-walking the dead space it made on the last one, so the
1322 /// cursor would never reach the bump and the segment would never come back.
1323 #[test]
1324 fn a_segment_comes_back_over_several_calls() {
1325 let mut m = RawMap::new();
1326 let val = vec![b'z'; COMPACT_VAL];
1327 const N: usize = COMPACT_N;
1328 for i in 0..N {
1329 m.set(&key(i), &val);
1330 }
1331 // Every other key, so the early segments are well past the dead ratio
1332 // and there is still a live half to copy out.
1333 for i in (0..N).step_by(2) {
1334 m.del(&key(i));
1335 }
1336
1337 let rec = (HDR + key(0).len() + COMPACT_VAL).next_multiple_of(yo_arena::ALIGN);
1338 let per_call = m.budget() / rec + 1;
1339 let free = m.arena().free_segments();
1340
1341 let moved = m.compact_step().expect("half of it is dead");
1342 assert!(
1343 moved <= per_call,
1344 "one call moved {moved} records and the budget is {per_call}"
1345 );
1346 assert_eq!(
1347 m.arena().free_segments(),
1348 free,
1349 "a segment came back before the walk reached the end of it"
1350 );
1351
1352 let mut calls = 1;
1353 while m.arena().free_segments() == free {
1354 m.compact_step()
1355 .expect("the segment in flight is not finished");
1356 calls += 1;
1357 assert!(calls < 1000, "the walk is not getting any further along");
1358 }
1359 assert!(calls > 2, "the whole segment came back in {calls} calls");
1360
1361 for i in 0..N {
1362 let want = if i % 2 == 0 { None } else { Some(val.clone()) };
1363 assert_eq!(m.get(&key(i)).map(<[u8]>::to_vec), want, "key {i}");
1364 }
1365 }
1366
1367 /// A store barely holding any garbage collects nothing until it is asked to.
1368 ///
1369 /// The global ratio is the reason [`RawMap::compact_hard`] exists. A server
1370 /// under a memory limit needs the pages back whether or not the store as a
1371 /// whole is dirty enough to be worth a sweep, and a server that is not under
1372 /// one should not pay for copying that buys it a few kilobytes.
1373 ///
1374 /// The per segment ratio is a different question and the hard path keeps it.
1375 /// What is being asked for here is a store that is clean overall and has one
1376 /// part of it that is not, which is why the deletes are a run and not a
1377 /// stride: records land in the order they were written, so a run of them
1378 /// empties out the segments it lands in rather than taking a tenth off every
1379 /// segment and leaving none of them worth moving.
1380 #[test]
1381 fn a_store_with_little_dead_in_it_only_collects_when_pushed() {
1382 let mut m = RawMap::new();
1383 let val = vec![b'z'; COMPACT_VAL];
1384 const N: usize = COMPACT_N;
1385 const DEAD: usize = N / 10;
1386 for i in 0..N {
1387 m.set(&key(i), &val);
1388 }
1389 // A tenth of the keys, which is under the eighth of everything held that
1390 // compaction normally waits for.
1391 for i in 0..DEAD {
1392 m.del(&key(i));
1393 }
1394
1395 assert_eq!(m.compact_step(), None, "not worth collecting");
1396 let free = m.arena().free_segments();
1397 let mut calls = 0;
1398 while m.arena().free_segments() == free {
1399 assert!(
1400 m.compact_hard().is_some(),
1401 "there is a segment holding something dead"
1402 );
1403 calls += 1;
1404 assert!(calls < 1000, "the walk is not getting any further along");
1405 }
1406 // Everything still reads back, which is the thing that matters: the
1407 // records that were live in the segment that came back were moved and
1408 // their index entries were moved with them.
1409 for i in 0..N {
1410 let want = if i < DEAD { None } else { Some(val.clone()) };
1411 assert_eq!(m.get(&key(i)).map(<[u8]>::to_vec), want, "key {i}");
1412 }
1413 }
1414
1415 /// A store with a little dead spread thinly through it collects nothing,
1416 /// however hard it is asked.
1417 ///
1418 /// One key in fifty, so no segment is anywhere near worth emptying. There is
1419 /// no pressure high enough to make copying forty nine bytes to get one back
1420 /// the right move, because a caller under pressure has something cheaper it
1421 /// could be doing with the same effort.
1422 #[test]
1423 fn a_barely_dead_store_collects_nothing_however_hard_it_is_asked() {
1424 let mut m = RawMap::new();
1425 let val = vec![b'z'; COMPACT_VAL];
1426 const N: usize = COMPACT_N;
1427 for i in 0..N {
1428 m.set(&key(i), &val);
1429 }
1430 for i in (0..N).step_by(50) {
1431 m.del(&key(i));
1432 }
1433
1434 assert_eq!(m.compact_step(), None, "not worth collecting");
1435 assert_eq!(m.compact_hard(), None, "fifty bytes moved for one back");
1436 }
1437
1438 /// Compaction says what it walked past and what it had to copy.
1439 ///
1440 /// The two are separate because they cost different things and because the
1441 /// gap between them is the useful part: a walk that steps over a thousand
1442 /// records and copies two got its segment back cheaply, and one that copies
1443 /// nine hundred of them paid nearly the price of the writes twice over.
1444 #[test]
1445 fn compaction_counts_what_it_walked_and_what_it_moved() {
1446 let mut m = RawMap::new();
1447 let val = vec![b'z'; COMPACT_VAL];
1448 const N: usize = COMPACT_N;
1449 for i in 0..N {
1450 m.set(&key(i), &val);
1451 }
1452 assert_eq!(
1453 m.compaction(),
1454 Compaction::default(),
1455 "a load with nothing dead in it has nothing to collect"
1456 );
1457
1458 // Half of them dead, so a walk over a segment should find about half of
1459 // what it steps over still live.
1460 for i in (0..N).step_by(2) {
1461 m.del(&key(i));
1462 }
1463 for _ in 0..200 {
1464 m.compact_step();
1465 }
1466 let c = m.compaction();
1467 assert!(c.walked > 0, "the walk did not step over anything");
1468 assert!(c.moved > 0, "everything it stepped over was dead");
1469 assert!(c.moved < c.walked, "nothing it stepped over was dead");
1470 assert!(
1471 c.bytes >= c.moved * COMPACT_VAL as u64,
1472 "{} records moved and only {} bytes with them",
1473 c.moved,
1474 c.bytes
1475 );
1476
1477 // What a store has spent is not something a flush gives back.
1478 m.clear();
1479 assert_eq!(m.compaction(), c, "the bill was thrown away with the data");
1480 }
1481
1482 /// The budget grows with how far behind the collector is.
1483 ///
1484 /// A store with one segment waiting pays the floor, which is the pause a
1485 /// command can be asked to wait for. One with a queue of them walks a slice
1486 /// per segment in the queue, which is what keeps a pipelined write flood
1487 /// from outrunning one call per batch and leaving the process holding the
1488 /// segments that never got their turn.
1489 #[test]
1490 fn the_budget_scales_with_the_backlog() {
1491 let mut m = RawMap::new();
1492 let val = vec![b'z'; COMPACT_VAL];
1493 const N: usize = COMPACT_N;
1494 for i in 0..N {
1495 m.set(&key(i), &val);
1496 }
1497 assert_eq!(m.budget(), EVAC_FLOOR, "nothing is waiting yet");
1498
1499 for i in 0..N {
1500 m.del(&key(i));
1501 }
1502 let flooded = m.budget();
1503 assert!(
1504 flooded >= EVAC_FLOOR * m.arena().candidate_count(),
1505 "{} segments are waiting and the budget is {flooded}",
1506 m.arena().candidate_count()
1507 );
1508 assert!(
1509 flooded > EVAC_FLOOR,
1510 "every segment is dead and the budget is still the floor"
1511 );
1512 assert!(flooded <= EVAC_CEILING, "walked past a whole segment");
1513 }
1514
1515 /// A segment that is partway through being evacuated is finished before a
1516 /// worse one is started.
1517 ///
1518 /// Writes keep coming while a segment is being walked and they make dead
1519 /// space elsewhere, so the answer to "which segment is worst" moves around
1520 /// underneath a walk that takes thirty calls. Asking it again on every call
1521 /// would let a segment be put down at nine tenths done in favour of one
1522 /// that is slightly worse, and the arena would fill up with segments that
1523 /// are nearly empty and never reclaimed.
1524 ///
1525 /// Here the first quarter of the keyspace is deleted so that the segment at
1526 /// the front is the only candidate, one call starts on it, and then the
1527 /// back half goes too so that another segment ties with it mid walk. The
1528 /// tie goes to the later segment, so a walk that asked again would move to
1529 /// it and leave the first one part done.
1530 #[test]
1531 fn the_segment_in_flight_is_finished_first() {
1532 let mut m = RawMap::new();
1533 let val = vec![b'z'; COMPACT_VAL];
1534 const N: usize = COMPACT_N;
1535 for i in 0..N {
1536 m.set(&key(i), &val);
1537 }
1538 for i in 0..N / 4 {
1539 m.del(&key(i));
1540 }
1541
1542 let free = m.arena().free_segments();
1543 let first = m.arena().worst_candidate().expect("the front is all dead");
1544 m.compact_step().expect("there is a candidate");
1545
1546 for i in N / 2..N {
1547 m.del(&key(i));
1548 }
1549 let worse = m.arena().worst_candidate().expect("the back is all dead");
1550 assert_ne!(worse, first, "the test needs the answer to have moved");
1551
1552 while m.arena().free_segments() == free {
1553 m.compact_step()
1554 .expect("the segment in flight is not finished");
1555 }
1556 assert!(
1557 m.arena().is_free(first),
1558 "the segment that was in flight is not the one that came back"
1559 );
1560 assert!(
1561 !m.arena().is_free(worse),
1562 "the walk moved to the segment that tied with it partway through"
1563 );
1564 }
1565
1566 /// A segment that compaction emptied is bumped through again rather than
1567 /// sitting there holding two megabytes.
1568 #[test]
1569 fn an_emptied_segment_is_used_again() {
1570 let mut m = RawMap::new();
1571 let val = vec![b'z'; COMPACT_VAL];
1572 const N: usize = COMPACT_N;
1573 for i in 0..N {
1574 m.set(&key(i), &val);
1575 }
1576 for i in (0..N).step_by(2) {
1577 m.del(&key(i));
1578 }
1579
1580 let before = m.arena().segment_count();
1581 let seg = m.arena().worst_candidate().expect("half of it is dead");
1582 m.compact_segment(seg);
1583 assert_eq!(
1584 m.arena().free_segments(),
1585 1,
1586 "the segment did not come back"
1587 );
1588
1589 // Write until the free segment has to be taken, and the count is where
1590 // it was rather than one higher.
1591 for i in N..N * 2 {
1592 m.set(&key(i), &val);
1593 if m.arena().free_segments() == 0 {
1594 break;
1595 }
1596 }
1597 assert_eq!(
1598 m.arena().segment_count(),
1599 before,
1600 "asked the system for memory while holding an empty segment"
1601 );
1602 }
1603
1604 #[test]
1605 fn adversarial_keys_that_share_low_bits() {
1606 // Keys chosen so that many land in the same bucket index. The point is
1607 // that overflow chaining and splitting both still work when the hash is
1608 // not being kind.
1609 let mut m = RawMap::new();
1610 let mut inserted = Vec::new();
1611 for i in 0..ADVERSARIAL_N {
1612 let k = i.to_le_bytes().to_vec();
1613 m.set(&k, b"v");
1614 inserted.push(k);
1615 }
1616 for k in &inserted {
1617 assert_eq!(m.get(k), Some(&b"v"[..]));
1618 }
1619 assert_eq!(m.len(), inserted.len());
1620 }
1621
1622 /// Whatever memoizes against this counter is only correct if every way of
1623 /// moving something in the map moves it too. A method that mutates and does
1624 /// not is not a slow memo, it is a wrong answer, so this asserts on the whole
1625 /// `&mut self` surface rather than on the ones that look like they matter.
1626 ///
1627 /// The single exception is pinned by the test below this one, so a method
1628 /// added without a decision about which side it falls on fails here.
1629 #[test]
1630 fn every_way_of_writing_moves_the_counter() {
1631 let mut m = RawMap::new();
1632 let mut last = m.writes();
1633 let mut moved = |m: &RawMap, what: &str| {
1634 assert!(m.writes() > last, "{what} did not move the counter");
1635 last = m.writes();
1636 };
1637
1638 m.set(b"k", b"v");
1639 moved(&m, "set");
1640 m.set_with(
1641 b"k",
1642 1,
1643 |_| {},
1644 |b| {
1645 b[0] = b'w';
1646 false
1647 },
1648 );
1649 moved(&m, "set_with");
1650 m.value_mut(b"k");
1651 moved(&m, "value_mut");
1652 m.value_mut_hashed(RawMap::hash_of(b"k"), b"k");
1653 moved(&m, "value_mut_hashed");
1654 m.compact_step();
1655 moved(&m, "compact_step");
1656 m.compact_segment(0);
1657 moved(&m, "compact_segment");
1658 m.del(b"k");
1659 moved(&m, "del");
1660 }
1661
1662 /// The exception, pinned so that it stays a decision rather than becoming a
1663 /// habit. An in place stamp leaves the counter alone, and everything the
1664 /// caller resolved before it is still right after it.
1665 #[test]
1666 fn sampling_hands_back_real_entries_and_stops_when_told() {
1667 let mut m = RawMap::new();
1668 for i in 0..2000u32 {
1669 m.set(format!("k{i}").as_bytes(), format!("v{i}").as_bytes());
1670 }
1671
1672 // Whatever it hands over is really in the map, key and value together,
1673 // and the address it gives is the address that key resolves to.
1674 let mut count = 0usize;
1675 m.sample(0x1234_5678_9abc_def0, |key, val, addr| {
1676 assert_eq!(m.get(key), Some(val));
1677 assert_eq!(m.find(key), Some(addr));
1678 count += 1;
1679 count < 5
1680 });
1681 assert_eq!(count, 5, "it did not stop when it was told to");
1682
1683 // A caller that never says stop still terminates, because the segment is
1684 // the bound and not the caller.
1685 let mut all = 0usize;
1686 m.sample(0, |_, _, _| {
1687 all += 1;
1688 true
1689 });
1690 assert!(all > 0, "it found nothing in a map of two thousand keys");
1691 assert!(
1692 all < m.len(),
1693 "one segment and not the whole map, got {all} of {}",
1694 m.len()
1695 );
1696 }
1697
1698 #[test]
1699 fn sampling_a_sparse_map_still_finds_something() {
1700 // The case a sampler that looked in one bucket would get wrong. Two keys
1701 // in a map sized for two thousand is sixty two empty buckets for every
1702 // two that are worth looking in.
1703 let mut m = RawMap::new();
1704 for i in 0..2000u32 {
1705 m.set(format!("k{i}").as_bytes(), b"v");
1706 }
1707 for i in 0..1998u32 {
1708 m.del(format!("k{i}").as_bytes());
1709 }
1710 assert_eq!(m.len(), 2);
1711
1712 // Not every draw lands in the segment those two are in, so this is about
1713 // whether it ever finds them rather than whether it always does.
1714 let mut found = 0usize;
1715 for r in 0..200u64 {
1716 m.sample(r.wrapping_mul(0x9e37_79b9_7f4a_7c15), |_, _, _| {
1717 found += 1;
1718 true
1719 });
1720 }
1721 assert!(found > 0, "two hundred draws and it never found either key");
1722 }
1723
1724 #[test]
1725 fn stamping_a_value_in_place_is_not_a_write() {
1726 let mut m = RawMap::new();
1727 m.set(b"k", b"hello");
1728 let addr = m.find(b"k").expect("just stored");
1729 let before = m.writes();
1730
1731 m.value_at_mut(addr)[0] = b'j';
1732
1733 assert_eq!(m.writes(), before, "a stamp counted as a write");
1734 assert_eq!(m.get(b"k"), Some(&b"jello"[..]));
1735 // And the address the caller was holding still means what it meant, which
1736 // is the guarantee the counter would otherwise be asked about.
1737 assert_eq!(m.find(b"k"), Some(addr));
1738 assert_eq!(m.value_at(addr), b"jello");
1739 }
1740
1741 /// `clear` replaces the map with a fresh one, and a fresh one starts at
1742 /// zero. A memo taken at write 3 against a map that went back to 0 and
1743 /// climbed to 3 again would read as still valid on the one call where every
1744 /// key in the map had been thrown away.
1745 #[test]
1746 fn clearing_does_not_send_the_counter_backwards() {
1747 let mut m = RawMap::new();
1748 for i in 0..10u32 {
1749 m.set(&i.to_le_bytes(), b"v");
1750 }
1751 let before = m.writes();
1752 m.clear();
1753 assert!(m.writes() > before, "clear went backwards or stood still");
1754 }
1755
1756 /// Enough keys to have split several times, so a walk crosses segments of
1757 /// different local depths rather than staying inside one.
1758 #[cfg(miri)]
1759 const SCAN_N: usize = 400;
1760 #[cfg(not(miri))]
1761 const SCAN_N: usize = 20_000;
1762
1763 #[test]
1764 fn a_walk_of_an_empty_map_ends_on_the_first_call() {
1765 let m = RawMap::new();
1766 let mut seen = 0;
1767 let at = m.scan(Cursor::START, 1000, |_, _| seen += 1);
1768 assert_eq!(seen, 0);
1769 assert!(
1770 at.is_end(),
1771 "an empty map took more than one call to finish"
1772 );
1773 }
1774
1775 /// The plain case, and the one every other guarantee is stated against: no
1776 /// writes during the walk, so every key comes back once and no key comes
1777 /// back twice.
1778 #[test]
1779 fn a_quiet_walk_returns_every_key_exactly_once() {
1780 let mut m = RawMap::new();
1781 for i in 0..SCAN_N {
1782 m.set(&key(i), &val(i));
1783 }
1784
1785 let mut counts: HashMap<Vec<u8>, usize> = HashMap::new();
1786 let mut at = Cursor::START;
1787 let mut calls = 0;
1788 loop {
1789 at = m.scan(at, 1, |k, v| {
1790 // Both borrows are shared, so the walk can look the key up
1791 // while it is handing it over. The pair arriving together is
1792 // the point: a bucket walk that read the header of one record
1793 // and the body of the next would still pass a key only check.
1794 assert_eq!(m.get(k), Some(v), "the value came back on the wrong key");
1795 *counts.entry(k.to_vec()).or_default() += 1;
1796 });
1797 calls += 1;
1798 assert!(calls < 1_000_000, "the cursor is not advancing");
1799 if at.is_end() {
1800 break;
1801 }
1802 }
1803
1804 assert_eq!(
1805 counts.len(),
1806 SCAN_N,
1807 "the walk missed keys or invented them"
1808 );
1809 for i in 0..SCAN_N {
1810 assert_eq!(counts.get(&key(i)).copied(), Some(1), "key {i}");
1811 }
1812 }
1813
1814 /// A budget is a floor and not a ceiling, and asking for everything at once
1815 /// is one call.
1816 #[test]
1817 fn a_budget_big_enough_finishes_in_one_call() {
1818 let mut m = RawMap::new();
1819 for i in 0..SCAN_N {
1820 m.set(&key(i), &val(i));
1821 }
1822
1823 let mut seen = 0;
1824 let at = m.scan(Cursor::START, usize::MAX, |_, _| seen += 1);
1825 assert_eq!(seen, SCAN_N);
1826 assert!(at.is_end());
1827 }
1828
1829 /// The guarantee that matters: the map grows underneath the walk, the
1830 /// directory doubles and segments split, and a key that was there the whole
1831 /// time still comes back.
1832 ///
1833 /// Written the way a client uses it, which is a cursor held across calls
1834 /// with other work happening in between, because the failure this is looking
1835 /// for is a cursor that means one thing before a split and another after.
1836 #[test]
1837 fn a_walk_survives_the_map_growing_underneath_it() {
1838 let mut m = RawMap::new();
1839 // The keys that are there throughout. Named apart from the ones added
1840 // during the walk so the two are easy to tell apart in the assertion.
1841 for i in 0..SCAN_N {
1842 m.set(&key(i), &val(i));
1843 }
1844 let depth_before = m.index().global_depth();
1845
1846 let mut seen: HashSet<Vec<u8>> = HashSet::new();
1847 let mut at = Cursor::START;
1848 let mut added = SCAN_N;
1849 loop {
1850 at = m.scan(at, 8, |k, _| {
1851 seen.insert(k.to_vec());
1852 });
1853 if at.is_end() {
1854 break;
1855 }
1856 // Between one call and the next, which is where a client would be.
1857 for _ in 0..64 {
1858 m.set(&key(added), &val(added));
1859 added += 1;
1860 }
1861 }
1862
1863 assert!(
1864 m.index().global_depth() > depth_before,
1865 "the directory never doubled, so this test proved nothing"
1866 );
1867 for i in 0..SCAN_N {
1868 assert!(
1869 seen.contains(&key(i)),
1870 "key {i} was there throughout and never came back"
1871 );
1872 }
1873 }
1874
1875 /// Deletes during a walk are the other half of the same guarantee. A key
1876 /// that survives to the end still comes back, whatever happened to its
1877 /// neighbours.
1878 #[test]
1879 fn a_walk_survives_keys_being_deleted_underneath_it() {
1880 let mut m = RawMap::new();
1881 for i in 0..SCAN_N {
1882 m.set(&key(i), &val(i));
1883 }
1884
1885 let mut seen: HashSet<Vec<u8>> = HashSet::new();
1886 let mut at = Cursor::START;
1887 let mut next_gone = 1;
1888 loop {
1889 at = m.scan(at, 8, |k, _| {
1890 seen.insert(k.to_vec());
1891 });
1892 if at.is_end() {
1893 break;
1894 }
1895 // Every odd key goes, a few at a time. The even ones are what the
1896 // assertion is about.
1897 for _ in 0..16 {
1898 if next_gone < SCAN_N {
1899 m.del(&key(next_gone));
1900 next_gone += 2;
1901 }
1902 }
1903 }
1904
1905 for i in (0..SCAN_N).step_by(2) {
1906 assert!(
1907 seen.contains(&key(i)),
1908 "key {i} was never deleted and never came back"
1909 );
1910 }
1911 }
1912
1913 /// A cursor names a place in the keyspace and not a place in memory, so a
1914 /// walk started partway through returns everything from there on.
1915 ///
1916 /// The prefix is what says where that is. Starting at prefix `p` resumes in
1917 /// the segment holding `p`, which begins at or before it, so every key whose
1918 /// own prefix is `p` or higher is still ahead of the walk.
1919 #[test]
1920 fn a_walk_that_starts_partway_returns_everything_from_there_on() {
1921 let mut m = RawMap::new();
1922 for i in 0..SCAN_N {
1923 m.set(&key(i), &val(i));
1924 }
1925
1926 let half = 1u64 << (crate::scan::PREFIX_BITS - 1);
1927 let mut seen: HashSet<Vec<u8>> = HashSet::new();
1928 let at = m.scan(Cursor::at(half, 0), usize::MAX, |k, _| {
1929 seen.insert(k.to_vec());
1930 });
1931 assert!(at.is_end());
1932
1933 let mut expected = 0;
1934 for i in 0..SCAN_N {
1935 let k = key(i);
1936 if Cursor::prefix_of(RawMap::hash_of(&k)) >= half {
1937 expected += 1;
1938 assert!(
1939 seen.contains(&k),
1940 "key {i} is past the cursor and did not come back"
1941 );
1942 }
1943 }
1944 // Both halves of the keyspace have keys in them, or the assertion above
1945 // is checking nothing.
1946 assert!(
1947 expected > 0 && expected < SCAN_N,
1948 "the split point was degenerate"
1949 );
1950 }
1951}