Skip to main content

kevy_rt/
runtime.rs

1//! The public entry point: configure and run the thread-per-core server.
2
3use crate::Commands;
4use crate::message::{Inbound, PubSubPatternReg, PubSubReg};
5use crate::shard::Shard;
6use kevy_map::KevyMap;
7use kevy_persist::{Aof, Fsync};
8use kevy_ring::{Consumer, Producer};
9use kevy_store::Store;
10use kevy_sys::{Poller, Waker, tcp_listen_reuseport, waker};
11use std::collections::{HashMap, VecDeque};
12use std::io;
13use std::path::PathBuf;
14use std::sync::atomic::{AtomicBool, AtomicU64};
15use std::sync::{Arc, RwLock};
16
17/// Default slots in each per-core-pair SPSC ring. A full ring spills
18/// to a local backlog (see [`Shard`]), so this only bounds the
19/// lock-free fast path, not capacity. Overridable via the
20/// `[advanced] ring_capacity` config field threaded through
21/// [`Runtime::with_advanced`].
22const DEFAULT_RING_CAPACITY: usize = 1024;
23
24/// The public entry point: configure and run the thread-per-core server.
25pub struct Runtime<C: Commands> {
26    pub(crate) ip: [u8; 4],
27    pub(crate) port: u16,
28    pub(crate) nshards: usize,
29    pub(crate) commands: C,
30    /// Directory for per-shard snapshot files (`dump-<id>.rdb`) and AOF logs.
31    pub(crate) data_dir: PathBuf,
32    /// Whether the append-only log is enabled.
33    pub(crate) enable_aof: bool,
34    /// fsync policy for the AOF. Default `EverySec` matches Redis.
35    pub(crate) appendfsync: Fsync,
36    /// auto-trigger BGREWRITEAOF when AOF grew this many % above the size
37    /// at the previous rewrite. `0` disables. Default `100` (matches Redis).
38    pub(crate) auto_aof_rewrite_pct: u32,
39    /// Floor below which auto-rewrite is skipped. Default `64 MiB`.
40    pub(crate) auto_aof_rewrite_min_size: u64,
41    /// Reactor SPSC ring slot count. See [`DEFAULT_RING_CAPACITY`].
42    pub(crate) ring_capacity: usize,
43    /// Reactor busy-poll iter limit before parking. Stored as `u32`
44    /// for the per-shard counter; the [`Shard`] field carries it
45    /// forward into the loop.
46    pub(crate) spin_limit: u32,
47    /// Reactor blocking-wait timeout in ms when parked.
48    pub(crate) park_timeout_ms: u32,
49    /// Wall-clock-read throttle for the tick check (TTL reaper / live
50    /// config refresh / auto-AOF-rewrite).
51    pub(crate) tick_check_every: u32,
52    /// `[slowlog].slower_than_micros`. Default: `-1` (OFF — zero
53    /// hot-path cost: every command would otherwise pay an
54    /// `Instant::now()` pair around dispatch). Set to `10_000` to match
55    /// Redis's default 10 ms threshold; see [`Self::with_slowlog`] /
56    /// `CONFIG SET slowlog-log-slower-than 10000`.
57    pub(crate) slowlog_slower_than_micros: i64,
58    /// `[slowlog].max_len`. Per-shard cap.
59    pub(crate) slowlog_max_len: u32,
60    /// Single-node cluster mode: slot-based key routing (CRC16 `{hashtag}`
61    /// → contiguous ranges) + one deterministic extra listener per shard at
62    /// `cluster_port_base + id`. `None` = off (default, zero change).
63    pub(crate) cluster_port_base: Option<u16>,
64    /// v3-cluster replication: when `true`, each shard runs a
65    /// `ReplicationSource` with `replication_buffer_size` byte budget;
66    /// every applied mutation is pushed to the backlog. The TCP
67    /// listener + streaming loop arrive in subsequent tasks (T1.12+);
68    /// this batch only wires the producer side. Default `false`.
69    pub(crate) enable_replication: bool,
70    /// Per-shard backlog byte budget when `enable_replication` is set.
71    /// Fed from `[replication] replication_buffer_size`. Default
72    /// `256 MiB` (matches the kevy-config default).
73    pub(crate) replication_buffer_size: u64,
74    /// v3-cluster replication listener: shard `i` binds at
75    /// `replication_port_base + i` (mirrors cluster listener pattern;
76    /// per Issue Ledger I2). `None` = no listener (producer side runs
77    /// without a network surface, backlog accumulates and evicts —
78    /// useful for benchmarks). Default `None`.
79    pub(crate) replication_port_base: Option<u16>,
80    /// Per-shard SlotTable reconnect-window in ms (T1.15). After a
81    /// streaming replica disconnects, its `(replica_id, sent_offset)`
82    /// is recorded in the shard's `slots` map; slots past this age
83    /// are reaped on the next shard tick. Default `60_000` (60 s)
84    /// matches the kevy-config default.
85    pub(crate) replication_reconnect_window_ms: u32,
86    /// Per-shard replica inboxes installed by
87    /// [`Self::with_replica_inboxes`]. Each entry is consumed
88    /// (via `Option::take`) when its shard is constructed, so the
89    /// receiver flows from this Vec to the matching `Shard.replica_inbox`.
90    /// Empty when no replica mode is configured.
91    pub(crate) replica_inboxes: Vec<Option<crate::replica_inbox::ReplicaInboxReceiver>>,
92    /// v1.25 UDS: when `Some(path)`, ALSO bind a Unix-domain stream
93    /// listener at `path` on shard 0 (single global socket, like valkey's
94    /// `unixsocket` config). Lets benches/local clients skip TCP loopback
95    /// overhead. TCP listener stays bound regardless.
96    #[allow(dead_code)] // consumed during run() via take-into-Shard
97    pub(crate) unix_socket_path: Option<PathBuf>,
98}
99
100impl<C: Commands> Runtime<C> {
101    #[must_use]
102    pub fn new(ip: [u8; 4], port: u16, nshards: usize, commands: C) -> Self {
103        Runtime {
104            ip,
105            port,
106            nshards: nshards.max(1),
107            commands,
108            data_dir: PathBuf::from("."),
109            enable_aof: true,
110            appendfsync: Fsync::EverySec,
111            auto_aof_rewrite_pct: 100,
112            auto_aof_rewrite_min_size: 64 * 1024 * 1024,
113            ring_capacity: DEFAULT_RING_CAPACITY,
114            spin_limit: 256,
115            park_timeout_ms: 50,
116            tick_check_every: 256,
117            slowlog_slower_than_micros: -1,
118            slowlog_max_len: 128,
119            cluster_port_base: None,
120            enable_replication: false,
121            replica_inboxes: Vec::new(),
122            replication_buffer_size: 256 * 1024 * 1024,
123            replication_port_base: None,
124            replication_reconnect_window_ms: 60_000,
125            unix_socket_path: None,
126        }
127    }
128
129
130    /// Spawn one thread per shard and run until `stop` is set.
131    /// v1.25 UDS: also bind a Unix-domain stream listener at `path`. Lets
132    /// local clients (and benchmarks) skip the TCP loopback round-trip.
133    /// Bound on shard 0 only (no SO_REUSEPORT for AF_UNIX, single global
134    /// socket like valkey's `unixsocket` config). TCP listener stays
135    /// bound at the configured `port` regardless.
136    #[must_use]
137    pub fn with_unix_socket(mut self, path: PathBuf) -> Self {
138        self.unix_socket_path = Some(path);
139        self
140    }
141
142    pub fn run(mut self, stop: Arc<AtomicBool>) -> io::Result<()> {
143        let n = self.nshards;
144
145        // v1.25 A.3 (B2: single global bio thread, per
146        // `bench/V125-DECISIONS-PENDING.md`). Spawn BEFORE shards so
147        // every shard's first overwrite already has a live consumer.
148        // The held `bio_send` is moved into the shard loop below
149        // (`store.set_bio_drop_sender`); shutdown ordering is:
150        //   1. shards return → their `Store`s drop → their cloned
151        //      Sender halves drop
152        //   2. this fn's local `bio_send` is dropped here at end of
153        //      scope → channel closes → bio thread's `recv()` returns
154        //      Err → bio thread exits
155        //   3. `bio_handle.join()` blocks until that exit so a final
156        //      large free isn't truncated by process tear-down
157        // (`madvise` returning the page to the kernel still needs the
158        // process alive). See `crate::bio` for the full rationale.
159        let (bio_send, bio_handle) = crate::bio::spawn();
160
161        // Cluster binds shard `i` at `port_base + i`; reject a range that
162        // overflows u16 up front (loud) instead of wrapping a listener onto
163        // a low/privileged port while CLUSTER SLOTS advertises 65536+.
164        if let Some(base) = self.cluster_port_base
165            && base as usize + n > u16::MAX as usize + 1
166        {
167            return Err(io::Error::new(
168                io::ErrorKind::InvalidInput,
169                format!(
170                    "cluster port range {base}..={} exceeds 65535 ({n} shards)",
171                    base as usize + n - 1
172                ),
173            ));
174        }
175
176        // Same overflow check for the replication port range
177        // (`base + 0 .. base + n`). See Issue Ledger I2 for the
178        // per-shard listener decision.
179        if let Some(base) = self.replication_port_base
180            && base as usize + n > u16::MAX as usize + 1
181        {
182            return Err(io::Error::new(
183                io::ErrorKind::InvalidInput,
184                format!(
185                    "replication port range {base}..={} exceeds 65535 ({n} shards)",
186                    base as usize + n - 1
187                ),
188            ));
189        }
190
191        // One lock-free SPSC ring per ordered core-pair (i→j): the producer goes
192        // to shard i's outbox[j], the consumer to shard j's inbox[i]. There is no
193        // self-ring — a shard runs its own commands inline, never over a ring.
194        let mut outboxes: Vec<Vec<Option<Producer<Inbound>>>> =
195            (0..n).map(|_| (0..n).map(|_| None).collect()).collect();
196        let mut inboxes: Vec<Vec<Option<Consumer<Inbound>>>> =
197            (0..n).map(|_| (0..n).map(|_| None).collect()).collect();
198        for i in 0..n {
199            for j in 0..n {
200                if i == j {
201                    continue;
202                }
203                let (p, c) = kevy_ring::ring::<Inbound>(self.ring_capacity);
204                outboxes[i][j] = Some(p);
205                inboxes[j][i] = Some(c);
206            }
207        }
208
209        let mut wakers: Vec<Arc<Waker>> = Vec::with_capacity(n);
210        for _ in 0..n {
211            wakers.push(Arc::new(waker()?));
212        }
213        let parked: Vec<Arc<crate::shard::CachePadded<AtomicBool>>> = (0..n)
214            .map(|_| Arc::new(crate::shard::CachePadded::new(AtomicBool::new(false))))
215            .collect();
216        // Per-shard inbox-dirty bitmaps (one u64 bit per peer src).
217        // Senders OR a bit on the target's dirty word; the target's
218        // `drain_inbound_core` swaps and short-circuits when 0.
219        assert!(
220            n <= 64,
221            "kevy-rt: shard count {n} exceeds 64 — inbound_dirty bitmap holds one bit per peer in a u64. Reduce --threads or extend to a multi-word bitmap.",
222        );
223        // A2 (2026-06-20): pad each Arc<AtomicU64> to a full 64-byte cache
224        // line. H1 c2c diagnostic showed cross-shard fetch_or vs. owner
225        // swap on adjacent atomics bounced cache lines between cores.
226        let inbound_dirty: Vec<Arc<crate::shard::CachePadded<AtomicU64>>> = (0..n)
227            .map(|_| Arc::new(crate::shard::CachePadded::new(AtomicU64::new(0))))
228            .collect();
229
230        // Shared pub/sub channel registry (one per server, read on every PUBLISH).
231        let pubsub: PubSubReg = Arc::new(RwLock::new(HashMap::new()));
232        // Shared pub/sub pattern registry. Empty in steady state — the
233        // channel-only PUBLISH path skips the walk when so.
234        let pubsub_patterns: PubSubPatternReg = Arc::new(RwLock::new(Vec::new()));
235
236        // Reconcile the on-disk shard layout (count + routing) before any
237        // shard loads its files; a mismatch re-homes every key once, here.
238        // Skipped for a pure in-memory run against a dir with no kevy files.
239        // Cluster mode always records the layout even with AOF off and an
240        // empty dir: a later SAVE writes slot-distributed `dump-{i}.rdb`, and
241        // without a meta a non-cluster restart would read them as KevyHash
242        // and silently strand every key.
243        if self.enable_aof
244            || self.cluster_port_base.is_some()
245            || crate::reshard::has_kevy_files(&self.data_dir)
246        {
247            let routing = if self.cluster_port_base.is_some() {
248                kevy_persist::Routing::Slots
249            } else {
250                kevy_persist::Routing::KevyHash
251            };
252            crate::reshard::ensure_layout(&self.data_dir, n, routing, &self.commands)?;
253        }
254
255        // Advertised cluster topology (None = cluster off). A 0.0.0.0 bind
256        // advertises 127.0.0.1 — an unroutable redirect target would strand
257        // every cluster client (single-machine scope; no announce-ip knob).
258        let topo = self.cluster_port_base.map(|base| crate::cluster::ClusterTopo {
259            ip: if self.ip == [0, 0, 0, 0] { [127, 0, 0, 1] } else { self.ip },
260            port_base: base,
261        });
262
263        // Build every shard up front so a bind/open failure aborts before we spawn.
264        let mut shards = Vec::with_capacity(n);
265        // UDS listener: only ONE per server (no SO_REUSEPORT for AF_UNIX), so
266        // it lives on shard 0. Bound up-front so a bind failure aborts before
267        // any shard spawns.
268        let mut unix_listener: Option<kevy_sys::Socket> = None;
269        if let Some(p) = self.unix_socket_path.as_ref() {
270            let path_bytes = p.to_string_lossy();
271            unix_listener = Some(kevy_sys::unix_listen(path_bytes.as_bytes(), 1024)?);
272        }
273        for id in 0..n {
274            let listener = tcp_listen_reuseport(self.ip, self.port, 1024)?;
275            // Cluster mode: a second, deterministic per-shard listener at
276            // port_base + id (plain bind — exactly one owner per port).
277            let cluster_listener = match self.cluster_port_base {
278                Some(base) => Some(kevy_sys::tcp_listen(self.ip, base + id as u16, 1024)?),
279                None => None,
280            };
281            // Replication listener (per Issue Ledger I2): per-shard
282            // deterministic port, same `tcp_listen` (no SO_REUSEPORT)
283            // pattern as cluster. A replica's shard-aware client will
284            // connect to every `base + id` to mirror the full keyspace.
285            let replication_listener = match self.replication_port_base {
286                Some(base) => Some(kevy_sys::tcp_listen(self.ip, base + id as u16, 1024)?),
287                None => None,
288            };
289            let aof = if self.enable_aof {
290                Some(Aof::open(
291                    &kevy_persist::layout::aof_path(&self.data_dir, id),
292                    self.appendfsync,
293                )?)
294            } else {
295                None
296            };
297            let mut store = Store::new();
298            // The reactor loop refreshes the store clock once per batch, so
299            // lazy expiry can trust the cached clock (skip per-command
300            // `Instant::now()`).
301            store.set_cached_clock(true);
302            // v1.25 A.3: hand the bio-drop channel sender to the store so
303            // SET overwrites of heavy values (Arc<[u8]> ≥ 256 B, non-empty
304            // collections) get freed off-reactor. Sender clone is cheap
305            // (`Arc::clone`); the bio thread is shared across all shards
306            // (B2 single-global, mirrors valkey `bio.c`).
307            store.set_bio_drop_sender(bio_send.clone());
308            self.commands.on_shard_init(&mut store);
309            shards.push(Shard {
310                id,
311                nshards: n,
312                cluster: topo.clone(),
313                cluster_listener,
314                // UDS: only shard 0 holds the (single) unix listener.
315                unix_listener: if id == 0 { unix_listener.take() } else { None },
316                store,
317                commands: self.commands.clone(),
318                poller: Poller::new()?,
319                listener,
320                waker: wakers[id].clone(),
321                inboxes: std::mem::take(&mut inboxes[id]),
322                outboxes: std::mem::take(&mut outboxes[id]),
323                backlog: (0..n).map(|_| VecDeque::new()).collect(),
324                wakers: wakers.clone(),
325                conns: KevyMap::new(),
326                arm_pending: Vec::new(),
327                closing_uring_conns: Vec::new(),
328                fd_to_conn: KevyMap::new(),
329                next_conn_id: 1,
330                events: Vec::with_capacity(1024),
331                read_buf: vec![0u8; 64 * 1024],
332                pending_wakes: 0,
333                backlog_nonempty: 0,
334                request_batch_nonempty: 0,
335                publish_batch_nonempty: 0,
336                parked: parked.clone(),
337                inbound_dirty: inbound_dirty.clone(),
338                data_dir: self.data_dir.clone(),
339                aof,
340                replicate: if self.enable_replication {
341                    Some(kevy_replicate::source::ReplicationSource::new(
342                        usize::try_from(self.replication_buffer_size)
343                            .unwrap_or(usize::MAX),
344                    ))
345                } else {
346                    None
347                },
348                replication_listener,
349                replicas: Vec::new(),
350                slots: kevy_replicate::slot::SlotTable::new(),
351                replication_reconnect_window_ms: self.replication_reconnect_window_ms,
352                replication_epoch: std::time::Instant::now(),
353                replica_inbox: self.replica_inboxes.get_mut(id).and_then(Option::take),
354                replica_snapshot_buf: Vec::new(),
355                persist: crate::persist_worker::PersistWorker::new(),
356                auto_aof_rewrite_pct: self.auto_aof_rewrite_pct,
357                auto_aof_rewrite_min_size: self.auto_aof_rewrite_min_size,
358                dirty: Vec::new(),
359                pubsub: pubsub.clone(),
360                pubsub_patterns: pubsub_patterns.clone(),
361                psub_local: HashMap::new(),
362                subs_by_channel: HashMap::new(),
363                publish_batch: (0..n).map(|_| Vec::new()).collect(),
364                request_batch: (0..n).map(|_| Vec::new()).collect(),
365                // Seed from the live config at construction, not default():
366                // these flags were otherwise blind until the first 100 ms
367                // shard tick, so a write landing before that never fired
368                // its keyspace notification (CI-visible flake; a real
369                // startup gap for any pre-configured notify_keyspace_events).
370                notify_flags: self
371                    .commands
372                    .live_runtime_config()
373                    .notify_flags
374                    .unwrap_or_default(),
375                spin_limit: self.spin_limit,
376                // `Poller::wait` takes the timeout as `i32` (POSIX
377                // poll/epoll convention). The config knob is `u32` —
378                // we clamp to i32::MAX, far above any sane park-timeout.
379                park_timeout_ms: self.park_timeout_ms.min(i32::MAX as u32) as i32,
380                tick_check_every: self.tick_check_every,
381                slowlog: crate::exec_slowlog::SlowlogState::new(
382                    self.slowlog_slower_than_micros,
383                    self.slowlog_max_len,
384                ),
385                blocked: crate::blocked::BlockedClients::new(),
386                origin_blocks: std::collections::HashMap::new(),
387                xwaiters: crate::block_xshard::XShardWaiters::default(),
388                reply_scratch: Vec::with_capacity(4096),
389                argv_pool: kevy_resp::ArgvPool::new(),
390            });
391        }
392
393        // Reactor selection on Linux:
394        //   KEVY_IO_URING unset → auto: try io_uring, fall back to epoll if the
395        //     host can't build the ring (probe below) — startup never fails.
396        //   KEVY_IO_URING=0/off/no/false → force the epoll readiness reactor.
397        //   KEVY_IO_URING=<anything else> → force io_uring (no fallback; a
398        //     setup failure then surfaces loudly — for benchmarks / tests).
399        // The probe creates+drops a real ring with the run_uring parameters, so
400        // it catches a seccomp-blocked io_uring_setup (Docker's default profile)
401        // and pre-5.19 kernels before any shard loads data. (macOS = kqueue.)
402        #[cfg(target_os = "linux")]
403        let use_uring = match std::env::var("KEVY_IO_URING").ok().as_deref() {
404            Some("0") | Some("off") | Some("no") | Some("false") => false,
405            Some(_) => true,
406            None => {
407                let avail = crate::uring_reactor::io_uring_available();
408                eprintln!(
409                    "kevy: reactor = {} (io_uring {})",
410                    if avail { "io_uring" } else { "epoll" },
411                    if avail { "available" } else { "unavailable — kernel <5.19 or seccomp; using epoll" },
412                );
413                avail
414            }
415        };
416
417        // v1.18.0: the replication listener + accept path is wired only
418        // through the epoll/kqueue reactor (`shard.run`); the io_uring
419        // T1.12.5: io_uring + replication is now supported. The
420        // replication-adjacent work (accept / read / write / pump /
421        // slot+view+watermark ticks) is poll-driven from the io_uring
422        // reactor's tick path (mostly per-tick @ 10 Hz, with
423        // `pump_replication` + `reap_closed_replicas` per-iter via
424        // their own early returns when nothing's live). Throughput
425        // path stays io_uring-native — only replica metadata uses
426        // polling. See `Shard::run_uring`.
427
428        let mut handles = Vec::with_capacity(n);
429        for shard in shards {
430            let stop = stop.clone();
431            let id = shard.id;
432            handles.push(std::thread::spawn(move || {
433                #[cfg(target_os = "linux")]
434                let res = if use_uring { shard.run_uring(stop) } else { shard.run(stop) };
435                #[cfg(not(target_os = "linux"))]
436                let res = shard.run(stop);
437                if let Err(e) = res {
438                    eprintln!("kevy: shard {id} exited with error: {e}");
439                }
440            }));
441        }
442        for h in handles {
443            let _ = h.join();
444        }
445        // v1.25 A.3 shutdown: every shard has joined → every cloned
446        // sender on every Store has been dropped. Drop the last live
447        // sender (this fn's `bio_send`) so the channel closes; the bio
448        // thread's `recv()` returns Err and it exits its loop. The
449        // `join()` then blocks until that exit completes — guarding
450        // against process tear-down while a final large free is in
451        // flight (an unsafe wrt `madvise`/`munmap` semantics — the
452        // kernel needs the process alive to actually release pages).
453        drop(bio_send);
454        let _ = bio_handle.join();
455        Ok(())
456    }
457}