kevy_rt/runtime_run.rs
1//! [`Runtime::run`] — validate config, build the cross-shard mesh and
2//! every [`Shard`], spawn one thread per core, and join. Cold startup
3//! path (runs once per process); split out of `runtime.rs` for the
4//! 500-LOC house rule and decomposed into per-stage helpers.
5
6use crate::Commands;
7use crate::message::{Inbound, PubSubPatternReg, PubSubReg};
8use crate::runtime::Runtime;
9use crate::shard::{CachePadded, Shard};
10use kevy_map::KevyMap;
11use kevy_persist::Aof;
12use kevy_ring::{Consumer, Producer};
13use kevy_store::Store;
14use kevy_sys::{Poller, Waker, tcp_listen_reuseport, waker};
15use std::collections::{HashMap, VecDeque};
16use std::io;
17use std::sync::atomic::{AtomicBool, AtomicU64};
18use std::sync::{Arc, RwLock};
19
20/// Cross-shard shared state built once before any shard spawns: the
21/// per-core-pair SPSC ring mesh, wakers, park flags, inbox-dirty
22/// bitmaps, and the pub/sub registries.
23struct Shared {
24 /// `outboxes[i][j]` = shard i's producer half toward shard j.
25 outboxes: Vec<Vec<Option<Producer<Inbound>>>>,
26 /// `inboxes[j][i]` = shard j's consumer half from shard i.
27 inboxes: Vec<Vec<Option<Consumer<Inbound>>>>,
28 wakers: Vec<Arc<Waker>>,
29 parked: Vec<Arc<CachePadded<AtomicBool>>>,
30 inbound_dirty: Vec<Arc<CachePadded<AtomicU64>>>,
31 /// Shared pub/sub channel registry (one per server, read on every
32 /// PUBLISH) + the pattern registry (empty in steady state — the
33 /// channel-only PUBLISH path skips the walk when so).
34 pubsub: PubSubReg,
35 pubsub_patterns: PubSubPatternReg,
36}
37
38impl Shared {
39 fn build(n: usize, ring_capacity: usize) -> io::Result<Shared> {
40 // One lock-free SPSC ring per ordered core-pair (i→j): the producer
41 // goes to shard i's outbox[j], the consumer to shard j's inbox[i].
42 // There is no self-ring — a shard runs its own commands inline,
43 // never over a ring.
44 let mut outboxes: Vec<Vec<Option<Producer<Inbound>>>> =
45 (0..n).map(|_| (0..n).map(|_| None).collect()).collect();
46 let mut inboxes: Vec<Vec<Option<Consumer<Inbound>>>> =
47 (0..n).map(|_| (0..n).map(|_| None).collect()).collect();
48 for i in 0..n {
49 for j in 0..n {
50 if i == j {
51 continue;
52 }
53 let (p, c) = kevy_ring::ring::<Inbound>(ring_capacity);
54 outboxes[i][j] = Some(p);
55 inboxes[j][i] = Some(c);
56 }
57 }
58 let mut wakers: Vec<Arc<Waker>> = Vec::with_capacity(n);
59 for _ in 0..n {
60 wakers.push(Arc::new(waker()?));
61 }
62 let parked: Vec<Arc<CachePadded<AtomicBool>>> =
63 (0..n).map(|_| Arc::new(CachePadded::new(AtomicBool::new(false)))).collect();
64 // Per-shard inbox-dirty bitmaps (one u64 bit per peer src).
65 // Senders OR a bit on the target's dirty word; the target's
66 // `drain_inbound_core` swaps and short-circuits when 0.
67 assert!(
68 n <= 64,
69 "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.",
70 );
71 // Pad each Arc<AtomicU64> to a full 64-byte cache
72 // line. A `perf c2c` diagnostic showed cross-shard fetch_or vs. owner
73 // swap on adjacent atomics bounced cache lines between cores.
74 let inbound_dirty: Vec<Arc<CachePadded<AtomicU64>>> =
75 (0..n).map(|_| Arc::new(CachePadded::new(AtomicU64::new(0)))).collect();
76 Ok(Shared {
77 outboxes,
78 inboxes,
79 wakers,
80 parked,
81 inbound_dirty,
82 pubsub: Arc::new(RwLock::new(HashMap::new())),
83 pubsub_patterns: Arc::new(RwLock::new(Vec::new())),
84 })
85 }
86}
87
88impl<C: Commands> Runtime<C> {
89 /// Spawn one thread per shard and run until `stop` is set.
90 pub fn run(mut self, stop: Arc<AtomicBool>) -> io::Result<()> {
91 let n = self.nshards;
92 // Single global bio thread. Spawn BEFORE shards so
93 // every shard's first overwrite already has a live consumer. The
94 // held `bio_send` is cloned into every Store below; shutdown
95 // ordering (shards join → Stores drop their Senders → this fn's
96 // `bio_send` drops → channel closes → bio thread exits → its
97 // `join()` below completes) guards against process tear-down
98 // while a final large free is in flight (`madvise`/`munmap`
99 // need the process alive). See `crate::bio` for the rationale.
100 let (bio_send, bio_handle) = crate::bio::spawn();
101 self.validate_port_ranges(n)?;
102 let mut shared = Shared::build(n, self.ring_capacity)?;
103 self.reconcile_layout(n)?;
104 // UDS listener: only ONE per server (no SO_REUSEPORT for AF_UNIX),
105 // so it lives on shard 0. Bound up-front so a bind failure aborts
106 // before any shard spawns.
107 let mut unix_listener: Option<kevy_sys::Socket> = None;
108 if let Some(p) = self.unix_socket_path.as_ref() {
109 let path_bytes = p.to_string_lossy();
110 unix_listener = Some(kevy_sys::unix_listen(path_bytes.as_bytes(), 1024)?);
111 }
112 // Build every shard up front so a bind/open failure aborts before
113 // we spawn.
114 let shards = self.build_shards(n, &mut shared, &bio_send, unix_listener)?;
115 let (use_uring, uring_forced) = reactor_choice();
116 let mut handles = Vec::with_capacity(n);
117 for shard in shards {
118 let stop = stop.clone();
119 handles.push(std::thread::spawn(move || {
120 run_shard_thread(shard, stop, use_uring, uring_forced);
121 }));
122 }
123 for h in handles {
124 let _ = h.join();
125 }
126 // Bio shutdown: see the bio-spawn comment above.
127 drop(bio_send);
128 let _ = bio_handle.join();
129 Ok(())
130 }
131
132 /// Reject a cluster / replication port range that overflows u16 up
133 /// front (loud) instead of wrapping a listener onto a low/privileged
134 /// port while CLUSTER SLOTS advertises 65536+.
135 fn validate_port_ranges(&self, n: usize) -> io::Result<()> {
136 if let Some(base) = self.cluster_port_base
137 && base as usize + n > u16::MAX as usize + 1
138 {
139 return Err(io::Error::new(
140 io::ErrorKind::InvalidInput,
141 format!(
142 "cluster port range {base}..={} exceeds 65535 ({n} shards)",
143 base as usize + n - 1
144 ),
145 ));
146 }
147 // Same overflow check for the replication port range
148 // (`base + 0 .. base + n`). See Issue Ledger I2 for the
149 // per-shard listener decision.
150 if let Some(base) = self.replication_port_base
151 && base as usize + n > u16::MAX as usize + 1
152 {
153 return Err(io::Error::new(
154 io::ErrorKind::InvalidInput,
155 format!(
156 "replication port range {base}..={} exceeds 65535 ({n} shards)",
157 base as usize + n - 1
158 ),
159 ));
160 }
161 Ok(())
162 }
163
164 /// Reconcile the on-disk shard layout (count + routing) before any
165 /// shard loads its files; a mismatch re-homes every key once, here.
166 /// Skipped for a pure in-memory run against a dir with no kevy files.
167 /// Cluster mode always records the layout even with AOF off and an
168 /// empty dir: a later SAVE writes slot-distributed `dump-{i}.rdb`, and
169 /// without a meta a non-cluster restart would read them as KevyHash
170 /// and silently strand every key.
171 fn reconcile_layout(&self, n: usize) -> io::Result<()> {
172 if self.enable_aof
173 || self.cluster_port_base.is_some()
174 || crate::reshard::has_kevy_files(&self.data_dir)
175 {
176 let routing = if self.cluster_port_base.is_some() {
177 kevy_persist::Routing::Slots
178 } else {
179 kevy_persist::Routing::KevyHash
180 };
181 crate::reshard::ensure_layout(
182 &self.data_dir,
183 n,
184 routing,
185 &self.commands,
186 self.resolved_tier_budget(),
187 &self.tier_root(),
188 )?;
189 }
190 Ok(())
191 }
192
193 /// Advertised cluster topology (None = cluster off). A 0.0.0.0 bind
194 /// advertises 127.0.0.1 — an unroutable redirect target would strand
195 /// every cluster client (single-machine scope; no announce-ip knob).
196 fn cluster_topo(&self) -> Option<crate::cluster::ClusterTopo> {
197 self.cluster_port_base.map(|base| crate::cluster::ClusterTopo {
198 ip: if self.ip == [0, 0, 0, 0] { [127, 0, 0, 1] } else { self.ip },
199 port_base: base,
200 })
201 }
202
203 /// Build all `n` shards: per-shard listeners + store + the flat
204 /// `Shard` field-init. Field-by-field comments live with the struct
205 /// definition in [`crate::shard`].
206 // LOC-WAIVER: flat per-shard construction table — listener/socket
207 // setup then one line per Shard field; no control flow to split.
208 fn build_shards(
209 &mut self,
210 n: usize,
211 shared: &mut Shared,
212 bio_send: &kevy_store::BioDropSender,
213 mut unix_listener: Option<kevy_sys::Socket>,
214 ) -> io::Result<Vec<Shard<C>>> {
215 let topo = self.cluster_topo();
216 let mut shards = Vec::with_capacity(n);
217 for id in 0..n {
218 let arms_accept = self.accept_shards.is_none_or(|k| id < k);
219 // Off-accept-set shards skip the SO_REUSEPORT bind so
220 // the kernel routes new conns only to the armed subset.
221 let listener = if arms_accept {
222 Some(tcp_listen_reuseport(self.ip, self.port, 1024)?)
223 } else {
224 None
225 };
226 // Cluster mode: a second, deterministic per-shard listener at
227 // port_base + id (plain bind — exactly one owner per port).
228 let cluster_listener = match self.cluster_port_base {
229 Some(base) => Some(kevy_sys::tcp_listen(self.ip, base + id as u16, 1024)?),
230 None => None,
231 };
232 // Replication listener (per Issue Ledger I2): per-shard
233 // deterministic port, same `tcp_listen` (no SO_REUSEPORT)
234 // pattern as cluster. A replica's shard-aware client will
235 // connect to every `base + id` to mirror the full keyspace.
236 let replication_listener = match self.replication_port_base {
237 Some(base) => Some(kevy_sys::tcp_listen(self.ip, base + id as u16, 1024)?),
238 None => None,
239 };
240 let aof = if self.enable_aof {
241 Some(Aof::open_with_repair(
242 &kevy_persist::layout::aof_path(&self.data_dir, id),
243 self.appendfsync,
244 self.replay_resync,
245 )?)
246 } else {
247 None
248 };
249 let mut store = Store::new();
250 // The reactor loop refreshes the store clock once per batch, so
251 // lazy expiry can trust the cached clock (skip per-command
252 // `Instant::now()`).
253 store.set_cached_clock(true);
254 // Hand the bio-drop channel sender to the store so
255 // SET overwrites of heavy values (Arc<[u8]> ≥ 256 B, non-empty
256 // collections) get freed off-reactor. Sender clone is cheap
257 // (`Arc::clone`); the bio thread is shared across all shards
258 // (single global thread, mirrors valkey `bio.c`).
259 store.set_bio_drop_sender(bio_send.clone());
260 // Tiering: the process budget — resolved
261 // bytes from the builder (`[tiering]` TOML/CLI/env full
262 // surface), or the minimal `KEVY_TIER_BUDGET` plain-bytes
263 // env knob — split evenly across shards; per-shard cold
264 // tier under `<tier root>/<id>`.
265 if let Some(total) = self.resolved_tier_budget() {
266 store.enable_tiering(
267 &self.tier_root().join(id.to_string()),
268 Self::per_shard_tier_budget(total, n),
269 )?;
270 }
271 self.commands.on_shard_init(&mut store);
272 shards.push(Shard {
273 #[cfg(target_os = "linux")]
274 aof_offload: Default::default(),
275 aof_lane: Default::default(),
276 pending_fsync_policy: None,
277 held_responses: Vec::new(),
278 rewrite_handoff: None,
279 rewrite_rate_mark: None,
280 rewrite_calm_ticks: 0,
281 xshard_inflight: 0,
282 id,
283 nshards: n,
284 cluster: topo.clone(),
285 cluster_listener,
286 // UDS: only shard 0 holds the (single) unix listener.
287 unix_listener: if id == 0 { unix_listener.take() } else { None },
288 store,
289 commands: self.commands.clone(),
290 poller: Poller::new()?,
291 listener,
292 waker: shared.wakers[id].clone(),
293 inboxes: std::mem::take(&mut shared.inboxes[id]),
294 outboxes: std::mem::take(&mut shared.outboxes[id]),
295 backlog: (0..n).map(|_| VecDeque::new()).collect(),
296 wakers: shared.wakers.clone(),
297 conns: KevyMap::new(),
298 arm_pending: Vec::new(),
299 closing_uring_conns: Vec::new(),
300 fd_to_conn: KevyMap::new(),
301 // Conn ids stride by shard count from a per-shard
302 // start, so every id is unique across the whole
303 // instance (CLIENT ID / CLIENT KILL ID contract) and
304 // still allocation-free per accept.
305 next_conn_id: id as u64 + 1,
306 conn_id_step: n as u64,
307 events: Vec::with_capacity(1024),
308 read_buf: vec![0u8; 64 * 1024],
309 pending_wakes: 0,
310 backlog_nonempty: 0,
311 request_batch_nonempty: 0,
312 publish_batch_nonempty: 0,
313 parked: shared.parked.clone(),
314 inbound_dirty: shared.inbound_dirty.clone(),
315 data_dir: self.data_dir.clone(),
316 aof,
317 replicate: if self.enable_replication || self.feed_enabled {
318 let budget = if self.feed_enabled {
319 self.replication_buffer_size.max(self.feed_buffer_size)
320 } else {
321 self.replication_buffer_size
322 };
323 let boot = kevy_persist::feed_meta::load_feed_boot(&self.data_dir, id)?;
324 let mut src = kevy_replicate::source::ReplicationSource::new(
325 usize::try_from(budget).unwrap_or(usize::MAX),
326 );
327 src.set_next_offset(boot.next_offset);
328 Some(kevy_replicate::feed::FeedSource::new(boot.generation, src))
329 } else {
330 None
331 },
332 replication_listener,
333 replicas: Vec::new(),
334 slots: kevy_replicate::slot::SlotTable::new(),
335 replication_reconnect_window_ms: self.replication_reconnect_window_ms,
336 replication_epoch: std::time::Instant::now(),
337 replica_inbox: self.replica_inboxes.get_mut(id).and_then(Option::take),
338 replica_snapshot_buf: Vec::new(),
339 replica_applied_next: 0,
340 repl_waiters: Vec::new(),
341 seen_promotion_epoch: None,
342 persist: crate::persist_worker::PersistWorker::new(),
343 auto_aof_rewrite_pct: self.auto_aof_rewrite_pct,
344 auto_aof_rewrite_bytes: self.auto_aof_rewrite_bytes,
345 auto_aof_rewrite_interval_secs: self.auto_aof_rewrite_interval_secs,
346 replay_resync: self.replay_resync,
347 auto_aof_rewrite_min_size: self.auto_aof_rewrite_min_size,
348 dirty: Vec::new(),
349 pubsub: shared.pubsub.clone(),
350 pubsub_patterns: shared.pubsub_patterns.clone(),
351 psub_local: HashMap::new(),
352 subs_by_channel: HashMap::new(),
353 publish_batch: (0..n).map(|_| Vec::new()).collect(),
354 request_batch: (0..n).map(|_| Vec::new()).collect(),
355 // Seed from the live config at construction, not default():
356 // these flags were otherwise blind until the first 100 ms
357 // shard tick, so a write landing before that never fired
358 // its keyspace notification (CI-visible flake; a real
359 // startup gap for any pre-configured notify_keyspace_events).
360 notify_flags: self.commands.live_runtime_config().notify_flags.unwrap_or_default(),
361 spin_limit: self.spin_limit,
362 arms_accept: self.accept_shards.is_none_or(|n| id < n),
363 max_clients_per_shard: if self.max_clients == 0 {
364 0
365 } else {
366 self.max_clients.div_ceil(n)
367 },
368 rejected_connections: 0,
369 input_hard_limit: std::env::var("KEVY_DEBUG_INPUT_LIMIT")
370 .ok()
371 .and_then(|v| v.parse().ok())
372 .unwrap_or(crate::CLIENT_INPUT_HARD_LIMIT),
373 // `Poller::wait` takes the timeout as `i32` (POSIX
374 // poll/epoll convention). The config knob is `u32` —
375 // we clamp to i32::MAX, far above any sane park-timeout.
376 park_timeout_ms: self.park_timeout_ms.min(i32::MAX as u32) as i32,
377 tick_check_every: self.tick_check_every,
378 slowlog: crate::exec_slowlog::SlowlogState::new(
379 self.slowlog_slower_than_micros,
380 self.slowlog_max_len,
381 ),
382 blocked: crate::blocked::BlockedClients::new(),
383 origin_blocks: std::collections::HashMap::new(),
384 xwaiters: crate::block_xshard::XShardWaiters::default(),
385 serve_confirm: std::collections::HashMap::new(),
386 reply_scratch: Vec::with_capacity(4096),
387 argv_pool: kevy_resp::ArgvPool::new(),
388 });
389 }
390 Ok(shards)
391 }
392}
393
394/// Reactor selection on Linux:
395/// KEVY_IO_URING unset → auto: try io_uring, fall back to epoll if the
396/// host can't build the ring (probe below) — startup never fails.
397/// KEVY_IO_URING=0/off/no/false → force the epoll readiness reactor.
398/// KEVY_IO_URING=<anything else> → force io_uring (no fallback; a
399/// setup failure then surfaces loudly — for benchmarks / tests).
400/// The probe creates+drops a real ring with the run_uring parameters, so
401/// it catches a seccomp-blocked io_uring_setup (Docker's default profile)
402/// and pre-5.19 kernels before any shard loads data. (macOS = kqueue.)
403#[cfg(target_os = "linux")]
404fn reactor_choice() -> (bool, bool) {
405 match std::env::var("KEVY_IO_URING").ok().as_deref() {
406 Some("0") | Some("off") | Some("no") | Some("false") => (false, true),
407 Some(_) => (true, true),
408 None => {
409 let avail = crate::uring_reactor::io_uring_available();
410 eprintln!(
411 "kevy: reactor = {} (io_uring {})",
412 if avail { "io_uring" } else { "epoll" },
413 if avail {
414 "available"
415 } else {
416 "unavailable — kernel <5.19 or seccomp; using epoll"
417 },
418 );
419 (avail, false)
420 }
421 }
422}
423
424/// Non-Linux: always the readiness reactor (kqueue on macOS).
425#[cfg(not(target_os = "linux"))]
426fn reactor_choice() -> (bool, bool) {
427 (false, false)
428}
429
430/// One shard thread's body: pick the reactor and run it to completion.
431///
432/// Per-shard ring setup is attempted BEFORE committing to the
433/// io_uring path. The global probe proves one ring builds; N shards
434/// need N rings, and a late failure (ENOMEM under pressure) used to
435/// kill the shard thread and leave a half-dead server (found via
436/// GH-runner CI: blocking_cross_shard hangs). Auto mode now degrades
437/// that shard to epoll, loudly. A forced KEVY_IO_URING=1 keeps the
438/// old fail-loud contract.
439fn run_shard_thread<C: Commands>(
440 shard: Shard<C>,
441 stop: Arc<AtomicBool>,
442 use_uring: bool,
443 uring_forced: bool,
444) {
445 let id = shard.id;
446 #[cfg(target_os = "linux")]
447 let res = if use_uring {
448 match crate::uring_reactor::build_uring() {
449 Ok(pair) => shard.run_uring(pair, stop),
450 Err(e) if !uring_forced => {
451 eprintln!(
452 "kevy: shard {id}: io_uring setup failed ({e}); \
453 falling back to the epoll reactor for this shard"
454 );
455 shard.run(stop)
456 }
457 Err(e) => Err(e),
458 }
459 } else {
460 shard.run(stop)
461 };
462 #[cfg(not(target_os = "linux"))]
463 let res = {
464 let _ = (use_uring, uring_forced);
465 shard.run(stop)
466 };
467 if let Err(e) = res {
468 eprintln!("kevy: shard {id} exited with error: {e}");
469 }
470}