kevy_store/expire.rs
1//! Active TTL reaper — Redis's `activeExpireCycle`, adapted to the
2//! thread-per-core / single-shard `Store`.
3//!
4//! Lazy expiry (in `live_entry[_mut]`) still handles the common case where
5//! the next access to a TTL'd key removes it. The active reaper exists for
6//! the harder case: a key has TTL but is never touched again, so without an
7//! explicit sweep it would sit in the map until the next FLUSH or eviction.
8//!
9//! Entry point: [`Store::tick_expire`]. The shard runtime calls it at the
10//! configured `[expiry].hz` cadence (default 10 Hz / every 100 ms);
11//! embedded users without a runtime call it themselves from whatever event
12//! loop they have (mandatory for WASM, which has no threads).
13
14#[cfg(not(feature = "std"))]
15use crate::nostd_prelude::*;
16use crate::{Store, now_ns};
17
18/// What [`Store::tick_expire`] saw and did. Surfaced for tests, INFO
19/// keyspace, and (eventually) Wave 2 task #4's crash-safe verifier.
20#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
21pub struct ExpireStats {
22 /// Total TTL-bearing keys sampled across all rounds.
23 pub sampled: u32,
24 /// How many of those were past their deadline and got removed.
25 pub expired: u32,
26 /// Rounds executed before the loop exited (either `max_rounds` reached
27 /// or in-batch expire-rate dropped below the continuation threshold).
28 pub rounds: u32,
29}
30
31/// Continuation threshold: when an in-batch expire-rate is above this
32/// percentage, run another round (the keyspace is "expiry-heavy"). Mirrors
33/// Redis's 25% from `activeExpireCycle`.
34const EXPIRE_RATE_CONTINUATION: u32 = 25;
35
36/// Sample a single round of up to `samples` TTL-bearing keys starting at a
37/// random bucket; remove any that are past their deadline. Returns
38/// `(sampled, expired)` counts for this round. Walking is `O(visited)` —
39/// bounded by `2 * map.capacity()` to keep a sparsely-populated table from
40/// spinning the inner scan forever.
41pub(crate) fn sample_round(store: &mut Store, samples: usize, now: u64) -> (u32, u32) {
42 let cap = store.map.capacity();
43 if cap == 0 || store.map.is_empty() {
44 return (0, 0);
45 }
46 // Random start derived from the access-ordinal clock; Fibonacci-hash
47 // multiplier shifts the sampling window every call so we don't re-visit
48 // the same bucket range twice in a row. (No-quality PRNG needed for
49 // sampling, just want to spread starting positions.)
50 store.clock_counter = store.clock_counter.wrapping_add(1);
51 let start = (store.clock_counter.wrapping_mul(0x9E37_79B9_7F4A_7C15) as usize) % cap;
52 let (sampled, victims) = collect_victims(store, samples, now, start);
53 let expired = victims.len() as u32;
54 for k in &victims {
55 store.note_expired(k);
56 store.remove_entry(k);
57 }
58 // Active-expire-driven removals are still expirations from the shard's
59 // perspective — surface them under the same counter `MEMORY STATS` /
60 // `INFO memory` already exposes.
61 if expired > 0 {
62 store.expired_keys_total = store.expired_keys_total.saturating_add(u64::from(expired));
63 }
64 (sampled, expired)
65}
66
67/// The sampling walk of [`sample_round`]: visit up to `8 * samples` buckets
68/// from `start`, sample up to `samples` TTL-bearing keys, and return
69/// `(sampled, past-deadline victim keys)`.
70///
71/// Single-pass walk from `start`, bounded in *visited entries*, not just
72/// in TTL-bearing samples: without the bound, a keyspace with few (or
73/// zero) TTL'd keys made every round walk to the end of the table
74/// looking for them — measured at 6 % of server CPU on a 300k-key
75/// TTL-free shard under a pinned 8-shard profile, for a reaper
76/// with nothing to reap. With it, a TTL-free round costs O(samples)
77/// buckets; sparse-TTL keyspaces sample fewer keys per round and rely
78/// on the rotating random start (plus lazy expiry) for coverage —
79/// the same time-boxing trade Redis's activeExpireCycle makes.
80fn collect_victims(store: &Store, samples: usize, now: u64, start: usize) -> (u32, Vec<Vec<u8>>) {
81 let mut victims: Vec<Vec<u8>> = Vec::with_capacity(samples);
82 let mut sampled = 0u32;
83 let visit_cap = samples.saturating_mul(8);
84 let mut visited = 0usize;
85 for (k, e) in store.map.iter_from_bucket(start) {
86 visited += 1;
87 if sampled as usize >= samples || visited > visit_cap {
88 break;
89 }
90 let Some(deadline_ns) = e.expire_at_ns else {
91 continue;
92 };
93 sampled += 1;
94 if deadline_ns.get() <= now {
95 victims.push(k.to_vec());
96 }
97 }
98 (sampled, victims)
99}
100
101impl Store {
102 /// Run up to `max_rounds` of active-expiry sampling against this shard.
103 ///
104 /// Per round: sample `samples_per_round` TTL-bearing keys at random and
105 /// drop any whose deadline has passed. Stop early as soon as the
106 /// in-batch expire-rate drops below 25 % (Redis's `activeExpireCycle`
107 /// continuation threshold) — that's the signal the keyspace doesn't
108 /// have a "thick band" of expired keys to clean up right now.
109 ///
110 /// Cost when there are no TTL-bearing keys at all: one map-emptiness
111 /// check + a single bucket-iter probe per round. Designed so the active
112 /// reaper is never a tax on TTL-free workloads.
113 pub fn tick_expire(&mut self, samples_per_round: usize, max_rounds: u32) -> ExpireStats {
114 // Refresh the coarse cached clock every tick (the read path's lazy
115 // expiry compares against it) — even when there's nothing to reap.
116 self.refresh_clock();
117 // Skip the sampling loop entirely when no key
118 // carries a TTL. `expires` is the O(1)-maintained count of
119 // TTL-bearing keys (incremented/decremented in `adjust_expires`).
120 // The standard redis-benchmark workload sets no TTLs, so
121 // `expires == 0` is the common case — saving up to `max_rounds *
122 // samples_per_round` probe lookups per tick (~256 at the default
123 // 16×16 budget). For TTL-bearing workloads (cache patterns) this
124 // adds one comparison; the bigger "splay / skip-list" reaper
125 // structure that the task entry mentioned would only beat the
126 // current random-sample algorithm at very high TTL fractions,
127 // and is left as a future workload-driven follow-up.
128 if samples_per_round == 0 || max_rounds == 0 || self.map.is_empty() || self.expires == 0 {
129 return ExpireStats::default();
130 }
131 self.run_expire_rounds(samples_per_round, max_rounds)
132 }
133
134 /// The round loop of [`Self::tick_expire`]: run [`sample_round`] up to
135 /// `max_rounds` times, stopping early on the 25 % continuation gate or
136 /// after 3 consecutive zero-sample rounds.
137 fn run_expire_rounds(&mut self, samples_per_round: usize, max_rounds: u32) -> ExpireStats {
138 let now = now_ns();
139 let mut total_sampled = 0u32;
140 let mut total_expired = 0u32;
141 let mut rounds = 0u32;
142 // Single-pass sample_round can return sampled=0 when the random
143 // start lands in an empty bucket region (sparse tables / unlucky
144 // starts). Allow 3 consecutive zero-sample rounds before declaring
145 // the keyspace TTL-free this tick, so a small table doesn't miss
146 // its expired keys for several ticks.
147 let mut consecutive_zero = 0u32;
148 for _ in 0..max_rounds {
149 let (sampled, expired) = sample_round(self, samples_per_round, now);
150 rounds += 1;
151 total_sampled = total_sampled.saturating_add(sampled);
152 total_expired = total_expired.saturating_add(expired);
153 if sampled == 0 {
154 consecutive_zero += 1;
155 if consecutive_zero >= 3 {
156 break;
157 }
158 continue;
159 }
160 consecutive_zero = 0;
161 // Continuation gate: only push another round if THIS round was
162 // expiry-heavy. A round that finds nothing expired-enough exits.
163 if expired * 100 < sampled * EXPIRE_RATE_CONTINUATION {
164 break;
165 }
166 }
167 ExpireStats { sampled: total_sampled, expired: total_expired, rounds }
168 }
169
170 /// Total keys expired (by lazy reap OR active reaper). Surfaced via
171 /// `INFO keyspace` and `MEMORY STATS` once those grow the field.
172 #[inline]
173 pub fn expired_keys_total(&self) -> u64 {
174 self.expired_keys_total
175 }
176}
177
178#[cfg(test)]
179mod tests {
180 use super::*;
181 use crate::value::SmallBytes;
182 use core::time::Duration;
183
184 #[test]
185 fn tick_expire_drops_past_deadline() {
186 let mut s = Store::new();
187 s.set(b"k1", b"v".to_vec(), Some(Duration::from_millis(1)), false, false);
188 s.set(b"k2", b"v".to_vec(), Some(Duration::from_millis(1)), false, false);
189 s.set(b"perm", b"v".to_vec(), None, false, false);
190 // Two flake sources, both observed on virtualized CI runners:
191 // a single tick may legitimately miss a key (the sampling walk is
192 // time-boxed with a rotating start — the a635d65 trade; coverage
193 // comes from repeated ticks), and on a starved macOS VM the
194 // monotonic clock (`Instant`, mach_absolute_time) can advance far
195 // slower than the wall-clock `sleep`, so a 1 ms deadline may not
196 // have passed yet. Sleep-and-tick until converged (bounded), like
197 // the production reaper drives it — the eventual contract.
198 for _ in 0..500 {
199 s.tick_expire(20, 16);
200 if s.dbsize() == 1 {
201 break;
202 }
203 std::thread::sleep(Duration::from_millis(10));
204 }
205 assert_eq!(s.dbsize(), 1, "perm survives, both TTL'd keys reaped");
206 assert!(s.expired_keys_total() >= 2);
207 }
208
209 #[test]
210 fn tick_expire_no_op_on_fresh_ttls() {
211 let mut s = Store::new();
212 s.set(b"k1", b"v".to_vec(), Some(Duration::from_hours(1)), false, false);
213 s.set(b"k2", b"v".to_vec(), Some(Duration::from_hours(1)), false, false);
214 let stats = s.tick_expire(20, 16);
215 assert_eq!(stats.expired, 0, "no fresh TTL should expire");
216 // sampled may be 0..=2 depending on how many our walk hit
217 assert_eq!(s.dbsize(), 2);
218 }
219
220 #[test]
221 fn tick_expire_no_op_on_ttl_free_keyspace() {
222 let mut s = Store::new();
223 for i in 0..50 {
224 s.set(format!("k{i}").as_bytes(), b"v".to_vec(), None, false, false);
225 }
226 let stats = s.tick_expire(20, 16);
227 assert_eq!(stats.expired, 0);
228 assert_eq!(stats.sampled, 0, "no TTL'd keys ⇒ nothing sampled");
229 // Loop tolerates up to 3 consecutive zero-sample rounds (the
230 // unlucky-start guard) before exiting, so a TTL-free keyspace
231 // costs at most 3 cheap bucket-iter passes per tick.
232 assert!(stats.rounds <= 3, "got {}", stats.rounds);
233 }
234
235 #[test]
236 fn tick_expire_zero_args_short_circuit() {
237 let mut s = Store::new();
238 s.set(b"k", b"v".to_vec(), Some(Duration::from_millis(1)), false, false);
239 std::thread::sleep(Duration::from_millis(5));
240 assert_eq!(s.tick_expire(0, 16), ExpireStats::default());
241 assert_eq!(s.tick_expire(20, 0), ExpireStats::default());
242 // store still has the expired key (active reaper disabled).
243 assert_eq!(s.dbsize(), 1);
244 }
245
246 #[test]
247 fn tick_expire_loops_on_heavy_batch() {
248 let mut s = Store::new();
249 // 40 TTL'd keys (all expired) + 1 perm. A single tick samples from
250 // a random bucket window, so we may need several ticks for full
251 // coverage of a 40-key keyspace — that matches how `activeExpire`
252 // converges in production (10 ticks/sec until everything's cleaned).
253 for i in 0..40 {
254 s.set(
255 format!("k{i}").as_bytes(),
256 b"v".to_vec(),
257 Some(Duration::from_millis(1)),
258 false,
259 false,
260 );
261 }
262 s.set(b"perm", b"v".to_vec(), None, false, false);
263 // Sleep-and-tick until converged: on a starved CI VM the monotonic
264 // clock can lag the wall-clock sleep, so a fixed pre-sleep + a
265 // bounded dry tick loop under-counts (see
266 // tick_expire_drops_past_deadline).
267 let mut total_expired = 0u32;
268 let mut any_round_ge_2 = false;
269 for _ in 0..500 {
270 let stats = s.tick_expire(20, 16);
271 total_expired += stats.expired;
272 if stats.rounds >= 2 {
273 any_round_ge_2 = true;
274 }
275 if s.dbsize() == 1 {
276 break;
277 }
278 std::thread::sleep(Duration::from_millis(10));
279 }
280 assert_eq!(total_expired, 40);
281 assert!(any_round_ge_2, "at least one heavy-batch tick should loop");
282 assert_eq!(s.dbsize(), 1);
283 let _ = SmallBytes::from_slice(b"k0"); // touch SmallBytes import
284 }
285}