kevy_store/lib.rs
1//! kevy-store — the keyspace.
2//!
3//! A single-threaded, multi-type keyspace with lazy expiration. Each Redis data
4//! type is backed by a modern `std` structure — behaviour-compatible, but **not**
5//! Redis's legacy encodings:
6//!
7//! | Type | Backing structure |
8//! |------|-------------------|
9//! | String | `Vec<u8>` |
10//! | Hash / Set | `HashMap` / `HashSet` (hashbrown Swiss table) |
11//! | List | `VecDeque` (ring buffer, O(1) ends) |
12//! | Sorted set | `HashMap` + `BTreeSet<(score, member)>` (a B-tree, not a skiplist) |
13//!
14//! Wrong-type access returns [`StoreError::WrongType`]. The API is `&mut self`
15//! and lock-free, so a thread-per-core runtime ([kevy-rt]) can own one shard per
16//! core with no locking. Part of the [kevy] key–value server.
17//!
18//! `maxmemory` enforcement + 8 eviction policies live in [`evict`]; toggle via
19//! [`Store::set_max_memory`]. With `maxmemory == 0` (the default) the hot-path
20//! cost collapses to a single predicted-not-taken branch, matching the
21//! "unlimited" mode in Redis byte-for-byte.
22//!
23//! [kevy]: https://crates.io/crates/kevy
24//! [kevy-rt]: https://crates.io/crates/kevy-rt
25//!
26//! # Example
27//!
28//! ```
29//! use kevy_store::Store;
30//!
31//! use std::borrow::Cow;
32//! let mut s = Store::new();
33//! s.set(b"greeting", b"hello".to_vec(), None, false, false);
34//! assert_eq!(s.get(b"greeting").unwrap(), Some(Cow::Borrowed(&b"hello"[..])));
35//!
36//! s.hset(b"user:1", &[(b"name".to_vec(), b"alice".to_vec())]).unwrap();
37//! assert_eq!(s.hget(b"user:1", b"name").unwrap(), Some(&b"alice"[..]));
38//!
39//! // A string command on a hash key is a type error, as in Redis.
40//! assert_eq!(s.get(b"user:1"), Err(kevy_store::StoreError::WrongType));
41//! ```
42#![forbid(unsafe_code)]
43
44mod accounting;
45mod bitmap;
46mod clock;
47mod entry;
48pub mod evict;
49pub mod expire;
50pub use expire::ExpireStats;
51pub(crate) use entry::Entry;
52mod hash;
53mod keyspace;
54mod list;
55mod list_ops;
56mod set;
57mod small_set;
58pub use small_set::{SmallSetData, SmallSetIter};
59mod small_hash;
60pub use small_hash::{SmallHashData, SmallHashIter};
61mod small_list;
62pub use small_list::{SmallListData, SmallListIter};
63mod small_zset;
64pub use small_zset::{SmallZSetData, SmallZSetIter};
65mod snapshot;
66pub use snapshot::SnapshotView;
67mod stream;
68mod string;
69mod string_rmw;
70mod types;
71pub use types::{EvictionPolicy, RenameOutcome, StoreError};
72mod util;
73mod value;
74mod zset;
75mod zset_flags;
76pub use zset_flags::{ZaddFlags, ZaddReport};
77pub use stream::{
78 AutoclaimResult, ConsumerGroup, ConsumerState, EntryBatch, GroupCreateMode,
79 LoadedGroup, LoadedPelEntry, LoadedStreamEntry, PelEntry, PendingExtended,
80 PendingExtendedRow, PendingSummary, ReadGroupId, StreamData, StreamId, StreamIdError,
81 XAddIdSpec, XClaimOpts, now_unix_ms, parse_explicit_id, parse_range_end,
82 parse_range_start, parse_xadd_id,
83};
84pub use string::GetReply;
85pub use util::glob_match;
86pub use value::*;
87
88pub(crate) use clock::{deadline_at, now_ns, pack_deadline, remaining_ms};
89use kevy_map::KevyMap;
90
91/// Feed kevy's monotonic clock on `wasm32-unknown-unknown`, which has no
92/// `Instant`. The embedding host advances time (ns since an arbitrary fixed
93/// epoch, e.g. `Date.now() * 1e6`) before TTL-sensitive ops and once per
94/// reaper tick. No-op concept on native targets, where the OS clock is the
95/// source — hence wasm-only.
96#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
97pub use clock::set_clock_ns;
98/// Feed kevy's wall clock (Unix-epoch millis, e.g. `Date.now()`) on
99/// `wasm32-unknown-unknown`, where `SystemTime::now()` traps. Used by `XADD`
100/// auto-IDs and `EXPIREAT`/`PEXPIREAT`.
101#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
102pub use clock::set_wall_clock_ms;
103
104
105/// A single-database keyspace.
106///
107/// The keyspace map is a [`KevyMap`] — a pure-Rust open-addressing Swiss
108/// table tuned for kevy's per-shard, single-trust-domain keyspace. The
109/// hasher is [`kevy_hash::KevyHash`] (one-call inlinable; no DoS hardening
110/// since the shard is single-threaded with no cross-trust keys). Owning the
111/// table also exposes bucket addresses for software prefetch on the batch
112/// driver.
113#[derive(Default)]
114pub struct Store {
115 pub(crate) map: KevyMap<SmallBytes, Entry>,
116 /// Coarse cached monotonic clock (ns since [`epoch`]), refreshed by the
117 /// reactor loop / reaper tick via [`Self::refresh_clock`]. Lazy expiry on
118 /// the read path (`live_entry`) compares deadlines against this instead of
119 /// calling `Instant::now()` per access — the Redis cached-`mstime` model.
120 /// `0` (the `Default`) reads as "epoch" → keys look live until the first
121 /// refresh, the safe direction (expires at most one refresh-interval late,
122 /// never early — writes stamp deadlines from a *fresh* clock).
123 pub(crate) cached_ns: u64,
124 /// Whether lazy expiry trusts `Self::cached_ns` (set by a reactor/reaper
125 /// that calls [`Self::refresh_clock`]) instead of reading a fresh clock per
126 /// access. Enabled by the server reactor and the embedded background
127 /// reaper; left `false` (the `Default`) for manual-reaper / bare-`Store`
128 /// use, where nothing refreshes the cache so each access reads fresh —
129 /// preserving "lazy expiry works without an explicit tick".
130 pub(crate) cached_clock: bool,
131 /// Live byte estimate (dynamic per-entry weights + [`ENTRY_OVERHEAD`] per
132 /// key). Compared against [`Self::maxmemory`] to drive eviction.
133 pub(crate) used_memory: u64,
134 /// Soft byte ceiling. `0` = unlimited; the entire accounting + eviction
135 /// machinery short-circuits to a single not-taken branch in that case.
136 pub(crate) maxmemory: u64,
137 /// Active eviction policy. Only consulted when `used_memory > maxmemory`.
138 pub(crate) eviction_policy: EvictionPolicy,
139 /// Total keys evicted by [`Self::try_evict_after_write`] — surfaced via
140 /// `INFO memory` / `MEMORY STATS`.
141 pub(crate) evictions_total: u64,
142 /// Monotonic access counter; the upper 32 bits are unused, the lower 32
143 /// stamp `Entry::lru_clock` on each access while eviction is enabled.
144 pub(crate) clock_counter: u64,
145 /// `used_memory` peak across the shard's lifetime; surfaced as
146 /// `used_memory_peak` in `INFO memory`.
147 pub(crate) used_memory_peak: u64,
148 /// Keys expired since startup (lazy reap path AND
149 /// [`Self::tick_expire`]). Surfaced via `INFO keyspace` / `MEMORY STATS`
150 /// once those fields land.
151 pub(crate) expired_keys_total: u64,
152 /// Count of live keys carrying a TTL — the size of Redis's "expire set"
153 /// (`INFO keyspace`'s `expires=`). Maintained in O(1) at every TTL
154 /// transition (`insert_entry` / `remove_entry` deltas + the in-place
155 /// EXPIRE / PERSIST / SET sites) so the gauge never pays an O(n) keyspace
156 /// scan; [`Self::ttl_pending_count`] is the O(n) ground truth used to
157 /// assert this counter never drifts.
158 pub(crate) expires: u64,
159 /// `WATCH` version counters — present only for keys that have been
160 /// `WATCH`-ed at least once. [`Self::record_watch`] inserts the entry
161 /// (version 0 = "never written since first watch"); every subsequent
162 /// write on this shard calls [`Self::bump_if_watched`] which increments
163 /// only if the key is present in the map. Keys never `WATCH`-ed pay
164 /// one empty-map hashmap lookup per write (~10 ns).
165 ///
166 /// The map grows monotonically — entries are never evicted, even
167 /// when no conn is currently watching the key. For high-key-churn
168 /// workloads this can become a memory item; v1.x acceptable since
169 /// the entry is `Vec<u8>` + `u64` (~ 30 B + key length) and only
170 /// touched on writes / WATCH calls.
171 pub(crate) watch_versions: std::collections::HashMap<Vec<u8>, u64>,
172 /// Optional handle to the runtime's bio thread (v1.25 A.3). Set by
173 /// `kevy-rt::Runtime::run` via [`Self::set_bio_drop_sender`] before
174 /// the shard reactor loop starts. `None` = inline drop (bare-Store
175 /// embedders, snapshots-loader programs, the test harness — anything
176 /// without a kevy-rt runtime around it). Reads on the hot path are
177 /// one `Option::as_ref` branch; the steady-state inline-drop path
178 /// pays nothing beyond that branch.
179 pub(crate) bio_drop_sender: Option<value::BioDropSender>,
180 /// v1.25 A.2 batch-send buffer. Heavy `Value`s displaced by SET
181 /// overwrites accumulate here instead of paying one mpsc send per
182 /// drop; flushed in one `mpsc::Sender::send` at the end of every
183 /// reactor iteration (via [`Self::flush_pending_drops`], invoked
184 /// from `kevy-rt`'s epoll + io_uring reactor loops before the AOF
185 /// fsync window). Amortising the channel cost over N drops lets
186 /// the heap-heavy threshold sit at 1 KB — small enough that the
187 /// Axis I 256 B – 16 KB SET tail benefits, big enough that
188 /// sub-µs small-class drops still go inline (the push + flush
189 /// branch would cost more than the inline free).
190 ///
191 /// **Latency window**: drops sit in this buffer ≤ one reactor
192 /// iteration (10s of µs at busy-poll, ≤ park-timeout at idle —
193 /// 50 ms by default). On a reactor with no traffic the buffer
194 /// stays small (no new SETs to displace anything); on a reactor
195 /// with sustained writes the per-iter flush fires fast enough
196 /// that worst-case stall is bounded by `MAX_PENDING_DROPS`.
197 ///
198 /// **Bounded growth**: at `MAX_PENDING_DROPS` items the
199 /// `maybe_offload_drop` path force-flushes — protects against
200 /// pathological "thousand SETs in one iter never flush" cases
201 /// (would otherwise hold thousands of Box<Value>s in RAM until
202 /// the iter ends).
203 pub(crate) pending_drops: Vec<Box<Value>>,
204}
205
206/// Maximum [`Store::pending_drops`] depth before forcing a flush
207/// inside `maybe_offload_drop` (rather than waiting for the reactor's
208/// per-iter `flush_pending_drops`). Caps memory held in the batch
209/// buffer at ≤ 64 × sizeof(Box<Value>) (≤ 512 B of pointers + whatever
210/// the boxed payloads weigh — which we WANT to ship anyway, since
211/// holding the bio-bound batch defeats the point of off-reactor frees).
212/// 64 picked as: amortises mpsc send cost (~few hundred ns) across
213/// enough drops that per-drop overhead is ≤ 10 ns, while staying small
214/// enough that worst-case bunch-up latency at the bio thread is bounded.
215pub(crate) const MAX_PENDING_DROPS: usize = 64;
216
217impl Store {
218 pub fn new() -> Self {
219 Store::default()
220 }
221
222 /// Refresh the coarse cached clock (`Self::cached_ns`) from a single
223 /// `Instant::now()`. Call once per reactor-loop batch / reaper tick; the
224 /// per-access read path then skips its own clock read. Lazy expiry is
225 /// coarse to this cadence (a key expires ≤ one refresh-interval late,
226 /// never early — writes stamp deadlines from a fresh clock).
227 #[inline]
228 pub fn refresh_clock(&mut self) {
229 self.cached_ns = now_ns();
230 }
231
232 /// Enable/disable trusting the cached clock for lazy expiry (see
233 /// `Self::cached_ns`). Call with `true` only when something refreshes the
234 /// clock regularly (the server reactor per batch, the embedded background
235 /// reaper per tick); leave `false` for manual-reaper mode. Seeds the cache
236 /// when enabling so the first access is accurate.
237 #[inline]
238 pub fn set_cached_clock(&mut self, on: bool) {
239 self.cached_clock = on;
240 if on {
241 self.refresh_clock();
242 }
243 }
244
245 /// Install (or clear, with `maxmemory == 0`) the eviction limit and
246 /// policy. Cheap; safe to call repeatedly (e.g. on `CONFIG SET`).
247 #[inline]
248 pub fn set_max_memory(&mut self, maxmemory: u64, policy: EvictionPolicy) {
249 self.maxmemory = maxmemory;
250 self.eviction_policy = policy;
251 }
252
253 /// Install the runtime's bio-drop channel (v1.25 A.3 + A.2). Called
254 /// once from `kevy-rt::Runtime::run` per shard before the reactor
255 /// loop starts. After install, [`Self::maybe_offload_drop`] (invoked
256 /// from the SET overwrite fast path) accumulates oversize `Value`s
257 /// into a per-shard batch; the reactor calls
258 /// [`Self::flush_pending_drops`] at the end of every iter to ship
259 /// the batch in one mpsc send. Bounded the Axis I 10 KB SET p999/max
260 /// blow-up that synchronous `Box::<[u8]>::drop` of a jemalloc
261 /// large-class slot caused (see `kevy_rt::bio`).
262 #[inline]
263 pub fn set_bio_drop_sender(&mut self, sender: value::BioDropSender) {
264 self.bio_drop_sender = Some(sender);
265 }
266
267 /// Accumulate `old` into the per-shard bio-drop batch buffer
268 /// ([`Store::pending_drops`]) if it's heap-heavy AND a bio channel
269 /// is installed. Otherwise drop inline. The hot path is one branch
270 /// on `bio_drop_sender.is_none()` followed by the variant-cheap
271 /// [`Value::is_heap_heavy`] check; for the `Value::Str(SmallBytes)`
272 /// steady state of typical bench shapes the inline-drop path is
273 /// preserved unchanged.
274 ///
275 /// **v1.25 A.2 batch model**: per-send mpsc cost (atomic +
276 /// cross-thread cacheline) is amortised across the batch by
277 /// [`Self::flush_pending_drops`], which the reactor calls once per
278 /// iter. Force-flushes here when the buffer hits
279 /// [`MAX_PENDING_DROPS`] to bound RAM in-flight.
280 #[inline]
281 pub(crate) fn maybe_offload_drop(&mut self, old: Value) {
282 if self.bio_drop_sender.is_none() {
283 // No channel (bare Store / embedded reaper / tests): the
284 // Value falls out of scope and drops inline. Same
285 // behaviour as v1.24.
286 drop(old);
287 return;
288 }
289 if !old.is_heap_heavy() {
290 // Under-threshold: jemalloc small-class free is sub-µs.
291 // The Vec::push + force-flush branch costs more than the
292 // inline free for this size — leave it inline.
293 drop(old);
294 return;
295 }
296 self.pending_drops.push(Box::new(old));
297 if self.pending_drops.len() >= MAX_PENDING_DROPS {
298 self.flush_pending_drops();
299 }
300 }
301
302 /// Ship the per-shard bio-drop batch buffer to the bio thread in
303 /// one mpsc send. Called from `kevy-rt`'s reactor loop at the end
304 /// of every iteration (both the epoll `Shard::run` and the io_uring
305 /// `Shard::run_uring` paths, just before the AOF fsync window so a
306 /// pending fsync stall doesn't pin a batch-ful of heavy values in
307 /// per-shard memory).
308 ///
309 /// Empty-buffer fast path: zero work, predictable not-taken
310 /// branch. Reactor calls this unconditionally per iter; the steady-
311 /// state cost for a no-SET-overwrite iter is one length check.
312 ///
313 /// `SendError` here means the bio thread has exited (shutdown
314 /// territory — `Runtime::run` has dropped its sender AFTER the
315 /// shard threads joined). Drop the batch inline; the `SendError`
316 /// payload carries the `Vec` back so its `Box<Value>`s run their
317 /// Drop here, preserving correctness.
318 #[inline]
319 pub fn flush_pending_drops(&mut self) {
320 if self.pending_drops.is_empty() {
321 return;
322 }
323 let tx = match self.bio_drop_sender.as_ref() {
324 Some(tx) => tx,
325 // Shouldn't happen — caller (`maybe_offload_drop`) only
326 // pushes when the sender exists. Defensive: if a future
327 // refactor invokes `flush_pending_drops` from somewhere
328 // unconditional, drop the batch inline.
329 None => {
330 self.pending_drops.clear();
331 return;
332 }
333 };
334 let batch = std::mem::take(&mut self.pending_drops);
335 if let Err(_send_err) = tx.send(batch) {
336 // Bio thread is gone (shutdown). The SendError carries
337 // the Vec, which drops here — every Box<Value> runs its
338 // Drop inline. Benign one-time stall during tear-down.
339 }
340 }
341
342 /// Live byte estimate (see field doc).
343 #[inline]
344 pub fn used_memory(&self) -> u64 {
345 self.used_memory
346 }
347
348 /// `used_memory` high-water mark since startup.
349 #[inline]
350 pub fn used_memory_peak(&self) -> u64 {
351 self.used_memory_peak
352 }
353
354 /// Configured `maxmemory` (0 = unlimited).
355 #[inline]
356 pub fn maxmemory(&self) -> u64 {
357 self.maxmemory
358 }
359
360 /// Configured eviction policy.
361 #[inline]
362 pub fn eviction_policy(&self) -> EvictionPolicy {
363 self.eviction_policy
364 }
365
366 /// Total keys evicted since startup.
367 #[inline]
368 pub fn evictions_total(&self) -> u64 {
369 self.evictions_total
370 }
371
372 /// Live keys carrying a TTL (`INFO keyspace`'s `expires=`). O(1) — reads
373 /// the maintained counter, not an O(n) scan (cf. [`Self::ttl_pending_count`]).
374 #[inline]
375 pub fn expires_count(&self) -> usize {
376 self.expires as usize
377 }
378
379 /// Apply a signed delta to the [`Self::expires`] counter, clamped at 0.
380 /// Centralises the saturating arithmetic for every TTL-transition site.
381 #[inline]
382 pub(crate) fn adjust_expires(&mut self, delta: i64) {
383 if delta != 0 {
384 self.expires = (self.expires as i64 + delta).max(0) as u64;
385 }
386 }
387
388 /// `WATCH` — record this key in the version tracker and return its
389 /// current version. Subsequent writes on this shard bump the version
390 /// via [`Self::bump_if_watched`]. Caller (the conn's origin shard)
391 /// stores the returned version; `EXEC` later asks every owning shard
392 /// "is the version still N?" via [`Self::key_version`].
393 ///
394 /// Keys that have never been written stay at version 0 — the first
395 /// write after a `WATCH` bumps to 1, which is what makes the "dirty"
396 /// comparison work (stored 0 ≠ current 1 ⇒ abort EXEC).
397 pub fn record_watch(&mut self, key: &[u8]) -> u64 {
398 *self
399 .watch_versions
400 .entry(key.to_vec())
401 .or_insert(0)
402 }
403
404 /// Read-only version lookup used by `EXEC`'s pre-execution check.
405 /// Returns `0` for keys never `WATCH`-ed (matches the initial value
406 /// `record_watch` would have inserted, so a `WATCH` → no-write →
407 /// `EXEC` sequence sees the stored 0 == current 0 and proceeds).
408 #[inline]
409 pub fn key_version(&self, key: &[u8]) -> u64 {
410 self.watch_versions.get(key).copied().unwrap_or(0)
411 }
412
413 /// Bump the version of `key` if (and only if) it has been `WATCH`-ed at
414 /// least once. Write-side call after every mutation. The empty check
415 /// runs BEFORE the key is hashed — the common nothing-watched case
416 /// pays one branch, not a guaranteed-miss probe.
417 #[inline]
418 pub fn bump_if_watched(&mut self, key: &[u8]) {
419 if self.watch_versions.is_empty() {
420 return;
421 }
422 if let Some(v) = self.watch_versions.get_mut(key) {
423 *v = v.wrapping_add(1);
424 }
425 }
426
427 /// Invalidate every watched key in one shot. Called from `FLUSHDB`
428 /// / `FLUSHALL` execution paths — every WATCH against this shard
429 /// must invalidate so a pending `EXEC` aborts.
430 pub fn bump_all_watched(&mut self) {
431 for v in self.watch_versions.values_mut() {
432 *v = v.wrapping_add(1);
433 }
434 }
435
436 /// Cached weight of `key` (dynamic part + [`ENTRY_OVERHEAD`]). Returns
437 /// `None` when the key is absent or expired (no implicit reap).
438 pub fn estimate_key_bytes(&self, key: &[u8]) -> Option<u64> {
439 self.map.get(key).map(|e| e.weight() + ENTRY_OVERHEAD)
440 }
441
442 /// O(1) precondition check the dispatch layer calls before every write
443 /// command. Returns `Err(OutOfMemory)` only when `maxmemory > 0`, the
444 /// budget is already over, AND the policy is `NoEviction` (Redis
445 /// behaviour). All other policies let the write proceed and recover via
446 /// [`Self::try_evict_after_write`].
447 #[inline]
448 pub fn precheck_for_write(&self) -> Result<(), StoreError> {
449 if self.maxmemory == 0 || self.used_memory <= self.maxmemory {
450 return Ok(());
451 }
452 if self.eviction_policy == EvictionPolicy::NoEviction {
453 return Err(StoreError::OutOfMemory);
454 }
455 Ok(())
456 }
457
458 /// Run after every write command. No-op when disabled or under budget;
459 /// otherwise samples per [`Self::eviction_policy`] and removes keys until
460 /// back under `maxmemory` or no eligible candidate remains. Returns the
461 /// number of keys evicted (0 on the common fast path).
462 #[inline]
463 pub fn try_evict_after_write(&mut self) -> usize {
464 if self.maxmemory == 0 || self.used_memory <= self.maxmemory {
465 return 0;
466 }
467 evict::evict_until_under_limit(self)
468 }
469
470}
471
472/// Apply a signed delta to a `u64` (saturating both directions). Used by
473/// `Store::account_delta` / `reweigh_entry` so the in-place mutators don't
474/// have to repeat the same overflow-guarded match.
475#[inline]
476pub(crate) fn apply_delta(v: &mut u64, delta: i64) {
477 if delta >= 0 {
478 *v = v.saturating_add(delta as u64);
479 } else {
480 *v = v.saturating_sub((-delta) as u64);
481 }
482}
483
484/// Heap bytes a `SmallBytes`-encoded key would own (`&[u8]` mirror of
485/// `SmallBytes::heap_bytes`; 22-byte inline boundary per `kevy-bytes`).
486#[inline]
487pub(crate) fn key_heap_bytes_for(key: &[u8]) -> u64 {
488 if key.len() <= 22 { 0 } else { key.len() as u64 }
489}
490
491#[cfg(test)]
492mod tests;
493#[cfg(test)]
494mod tests_memory;
495#[cfg(test)]
496mod tests_snapshot;
497#[cfg(test)]
498mod tests_string_encoding;