Skip to main content

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
14use crate::Store;
15use std::time::Instant;
16
17/// What [`Store::tick_expire`] saw and did. Surfaced for tests, INFO
18/// keyspace, and (eventually) Wave 2 task #4's crash-safe verifier.
19#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
20pub struct ExpireStats {
21    /// Total TTL-bearing keys sampled across all rounds.
22    pub sampled: u32,
23    /// How many of those were past their deadline and got removed.
24    pub expired: u32,
25    /// Rounds executed before the loop exited (either `max_rounds` reached
26    /// or in-batch expire-rate dropped below the continuation threshold).
27    pub rounds: u32,
28}
29
30/// Continuation threshold: when an in-batch expire-rate is above this
31/// percentage, run another round (the keyspace is "expiry-heavy"). Mirrors
32/// Redis's 25% from `activeExpireCycle`.
33const EXPIRE_RATE_CONTINUATION: u32 = 25;
34
35/// Sample a single round of up to `samples` TTL-bearing keys starting at a
36/// random bucket; remove any that are past their deadline. Returns
37/// `(sampled, expired)` counts for this round. Walking is `O(visited)` —
38/// bounded by `2 * map.capacity()` to keep a sparsely-populated table from
39/// spinning the inner scan forever.
40pub(crate) fn sample_round(
41    store: &mut Store,
42    samples: usize,
43    now: Instant,
44) -> (u32, u32) {
45    let cap = store.map.capacity();
46    if cap == 0 || store.map.is_empty() {
47        return (0, 0);
48    }
49    // Random start derived from the access-ordinal clock; Fibonacci-hash
50    // multiplier shifts the sampling window every call so we don't re-visit
51    // the same bucket range twice in a row. (No-quality PRNG needed for
52    // sampling, just want to spread starting positions.)
53    store.clock_counter = store.clock_counter.wrapping_add(1);
54    let start = (store
55        .clock_counter
56        .wrapping_mul(0x9E37_79B9_7F4A_7C15) as usize)
57        % cap;
58    let mut victims: Vec<Vec<u8>> = Vec::with_capacity(samples);
59    let mut sampled = 0u32;
60    // Single-pass walk from `start` to end. Sparse tables / unlucky starts
61    // may sample fewer than `samples` per round; that's fine — the next
62    // tick picks a different random start, so over time the keyspace is
63    // covered uniformly. Avoids the double-count a `chain(wrap)` would
64    // create when the same bucket range is visited twice.
65    {
66        for (k, e) in store.map.iter_from_bucket(start) {
67            if sampled as usize >= samples {
68                break;
69            }
70            let Some(deadline_ns) = e.expire_at_ns else {
71                continue;
72            };
73            sampled += 1;
74            if crate::unpack_deadline(deadline_ns) <= now {
75                victims.push(k.to_vec());
76            }
77        }
78    }
79    let expired = victims.len() as u32;
80    for k in &victims {
81        store.remove_entry(k);
82    }
83    // Active-expire-driven removals are still expirations from the shard's
84    // perspective — surface them under the same counter `MEMORY STATS` /
85    // `INFO memory` already exposes.
86    if expired > 0 {
87        store.expired_keys_total = store
88            .expired_keys_total
89            .saturating_add(expired as u64);
90    }
91    let _ = sampled; // silence unused warning if all returned early
92    (sampled, expired)
93}
94
95impl Store {
96    /// Run up to `max_rounds` of active-expiry sampling against this shard.
97    ///
98    /// Per round: sample `samples_per_round` TTL-bearing keys at random and
99    /// drop any whose deadline has passed. Stop early as soon as the
100    /// in-batch expire-rate drops below 25 % (Redis's `activeExpireCycle`
101    /// continuation threshold) — that's the signal the keyspace doesn't
102    /// have a "thick band" of expired keys to clean up right now.
103    ///
104    /// Cost when there are no TTL-bearing keys at all: one map-emptiness
105    /// check + a single bucket-iter probe per round. Designed so the active
106    /// reaper is never a tax on TTL-free workloads.
107    pub fn tick_expire(&mut self, samples_per_round: usize, max_rounds: u32) -> ExpireStats {
108        if samples_per_round == 0 || max_rounds == 0 || self.map.is_empty() {
109            return ExpireStats::default();
110        }
111        let now = Instant::now();
112        let mut total_sampled = 0u32;
113        let mut total_expired = 0u32;
114        let mut rounds = 0u32;
115        // Single-pass sample_round can return sampled=0 when the random
116        // start lands in an empty bucket region (sparse tables / unlucky
117        // starts). Allow 3 consecutive zero-sample rounds before declaring
118        // the keyspace TTL-free this tick, so a small table doesn't miss
119        // its expired keys for several ticks.
120        let mut consecutive_zero = 0u32;
121        for _ in 0..max_rounds {
122            let (sampled, expired) = sample_round(self, samples_per_round, now);
123            rounds += 1;
124            total_sampled = total_sampled.saturating_add(sampled);
125            total_expired = total_expired.saturating_add(expired);
126            if sampled == 0 {
127                consecutive_zero += 1;
128                if consecutive_zero >= 3 {
129                    break;
130                }
131                continue;
132            }
133            consecutive_zero = 0;
134            // Continuation gate: only push another round if THIS round was
135            // expiry-heavy. A round that finds nothing expired-enough exits.
136            if expired * 100 < sampled * EXPIRE_RATE_CONTINUATION {
137                break;
138            }
139        }
140        ExpireStats {
141            sampled: total_sampled,
142            expired: total_expired,
143            rounds,
144        }
145    }
146
147    /// Total keys expired (by lazy reap OR active reaper). Surfaced via
148    /// `INFO keyspace` and `MEMORY STATS` once those grow the field.
149    #[inline]
150    pub fn expired_keys_total(&self) -> u64 {
151        self.expired_keys_total
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158    use crate::value::SmallBytes;
159    use std::time::Duration;
160
161    #[test]
162    fn tick_expire_drops_past_deadline() {
163        let mut s = Store::new();
164        s.set(b"k1", b"v".to_vec(), Some(Duration::from_millis(1)), false, false);
165        s.set(b"k2", b"v".to_vec(), Some(Duration::from_millis(1)), false, false);
166        s.set(b"perm", b"v".to_vec(), None, false, false);
167        std::thread::sleep(Duration::from_millis(20));
168        let stats = s.tick_expire(20, 16);
169        assert_eq!(stats.expired, 2, "both TTL'd keys should be reaped");
170        assert!(stats.sampled >= 2);
171        assert_eq!(s.dbsize(), 1, "perm survives");
172        assert!(s.expired_keys_total() >= 2);
173    }
174
175    #[test]
176    fn tick_expire_no_op_on_fresh_ttls() {
177        let mut s = Store::new();
178        s.set(b"k1", b"v".to_vec(), Some(Duration::from_secs(3600)), false, false);
179        s.set(b"k2", b"v".to_vec(), Some(Duration::from_secs(3600)), false, false);
180        let stats = s.tick_expire(20, 16);
181        assert_eq!(stats.expired, 0, "no fresh TTL should expire");
182        // sampled may be 0..=2 depending on how many our walk hit
183        assert_eq!(s.dbsize(), 2);
184    }
185
186    #[test]
187    fn tick_expire_no_op_on_ttl_free_keyspace() {
188        let mut s = Store::new();
189        for i in 0..50 {
190            s.set(format!("k{i}").as_bytes(), b"v".to_vec(), None, false, false);
191        }
192        let stats = s.tick_expire(20, 16);
193        assert_eq!(stats.expired, 0);
194        assert_eq!(stats.sampled, 0, "no TTL'd keys ⇒ nothing sampled");
195        // Loop tolerates up to 3 consecutive zero-sample rounds (the
196        // unlucky-start guard) before exiting, so a TTL-free keyspace
197        // costs at most 3 cheap bucket-iter passes per tick.
198        assert!(stats.rounds <= 3, "got {}", stats.rounds);
199    }
200
201    #[test]
202    fn tick_expire_zero_args_short_circuit() {
203        let mut s = Store::new();
204        s.set(b"k", b"v".to_vec(), Some(Duration::from_millis(1)), false, false);
205        std::thread::sleep(Duration::from_millis(5));
206        assert_eq!(s.tick_expire(0, 16), ExpireStats::default());
207        assert_eq!(s.tick_expire(20, 0), ExpireStats::default());
208        // store still has the expired key (active reaper disabled).
209        assert_eq!(s.dbsize(), 1);
210    }
211
212    #[test]
213    fn tick_expire_loops_on_heavy_batch() {
214        let mut s = Store::new();
215        // 40 TTL'd keys (all expired) + 1 perm. A single tick samples from
216        // a random bucket window, so we may need several ticks for full
217        // coverage of a 40-key keyspace — that matches how `activeExpire`
218        // converges in production (10 ticks/sec until everything's cleaned).
219        for i in 0..40 {
220            s.set(
221                format!("k{i}").as_bytes(),
222                b"v".to_vec(),
223                Some(Duration::from_millis(1)),
224                false,
225                false,
226            );
227        }
228        s.set(b"perm", b"v".to_vec(), None, false, false);
229        std::thread::sleep(Duration::from_millis(20));
230        let mut total_expired = 0u32;
231        let mut any_round_ge_2 = false;
232        for _ in 0..20 {
233            let stats = s.tick_expire(20, 16);
234            total_expired += stats.expired;
235            if stats.rounds >= 2 {
236                any_round_ge_2 = true;
237            }
238            if s.dbsize() == 1 {
239                break;
240            }
241        }
242        assert_eq!(total_expired, 40);
243        assert!(any_round_ge_2, "at least one heavy-batch tick should loop");
244        assert_eq!(s.dbsize(), 1);
245        let _ = SmallBytes::from_slice(b"k0"); // touch SmallBytes import
246    }
247}