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