kevy_persist/aof.rs
1//! Append-only command log. Split out from `lib.rs` to keep that file
2//! under the 500-LOC house rule; the snapshot writer/reader stays there.
3
4use std::fs::{File, OpenOptions};
5use std::io::{self, BufWriter, Seek, SeekFrom, Write};
6use std::path::{Path, PathBuf};
7use std::time::Instant;
8
9use kevy_resp::ArgvView;
10use kevy_store::Store;
11
12use crate::{estimate_multibulk_bytes, write_multibulk};
13
14/// 9-byte file-format header written at the start of every kevy-managed
15/// AOF. `replay_aof` strips it before parsing RESP, so
16/// non-kevy bytes accidentally written into the AOF path (e.g. a deploy
17/// pipeline redirecting shell stderr into the file) get the same loud
18/// rejection as any other corrupt frame. Legacy AOFs (no magic) still
19/// replay — the parser only consumes the magic if it sees it.
20///
21/// Public so host-mediated AOF sinks (a browser pump appending kevy
22/// frames to its own storage, for example) can stamp files that stay
23/// byte-compatible with kevy-written logs.
24pub const AOF_MAGIC: &[u8; 9] = b"KEVYAOF1\n";
25
26/// AOF write buffer capacity. `BufWriter`'s default is 8 KiB — a single
27/// 4 KiB value fills it in two writes, so the append path spends ~half
28/// its time in the `write` syscall (perf-measured: SET 4 KiB, 52% in
29/// `write`/`ksys_write`, on both tmpfs and ext4). MMKV's mmap append
30/// pays no syscall at all; a larger buffer amortises the write across
31/// many appends the same way, without changing durability — `EverySec`
32/// still flushes + fsyncs once a second, so the crash window is
33/// unchanged (≤ 1 s) regardless of buffer size. 256 KiB holds ~64 4 KiB
34/// appends per syscall; per-shard cost is one such buffer.
35pub(crate) const AOF_BUF_CAP: usize = 256 * 1024;
36
37/// When to fsync the AOF to disk.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum Fsync {
40 /// fsync after every write — safest, slowest.
41 Always,
42 /// fsync at most once per second (call [`Aof::maybe_sync`] periodically).
43 EverySec,
44 /// Never fsync explicitly; leave it to the OS.
45 No,
46}
47
48/// An append-only command log. Each write command is appended as a RESP
49/// multi-bulk frame; [`crate::replay_aof`] re-applies them on startup.
50///
51/// Durability model (paired with snapshots): a snapshot taken at T0 plus
52/// the AOF of writes in (T0, now] reconstructs the current state. `SAVE`
53/// writes the snapshot then [`Aof::truncate`]s the log, so replay never
54/// double-applies.
55///
56/// Sizes (`size_bytes`, `size_at_last_rewrite`) drive auto-trigger of
57/// [`Aof::rewrite_from`] (BGREWRITEAOF) via the
58/// `auto_aof_rewrite_percentage` + `auto_aof_rewrite_min_size` knobs in
59/// `kevy_config`.
60pub struct Aof {
61 pub(crate) file: BufWriter<File>,
62 /// A begin marker has been written and its commit marker has not.
63 pub(crate) in_txn: bool,
64 pub(crate) path: PathBuf,
65 pub(crate) fsync: Fsync,
66 pub(crate) dirty: bool,
67 pub(crate) last_sync: Instant,
68 /// Estimated bytes currently in the AOF file (existing + appended since
69 /// open). Maintained without fstat() syscalls per append.
70 pub(crate) size_bytes: u64,
71 /// File size right after the most recent [`Self::rewrite_from`] (or
72 /// `Self::open` if never rewritten). Anchor for `auto_aof_rewrite_*`.
73 pub(crate) size_at_last_rewrite: u64,
74 /// Total rewrites successfully completed since open. Surfaced via INFO.
75 pub(crate) rewrites_total: u64,
76 /// Group-commit window: while `true`, an `Fsync::Always` `append` only
77 /// buffers (sets `dirty`) instead of fsyncing per command. The caller
78 /// brackets a batch of writes with [`Self::begin_group`] /
79 /// [`Self::end_group`] and `end_group` does the single fsync **before**
80 /// the batch's replies are sent — preserving "durable before reply"
81 /// while amortizing the per-command `flush()+sync_data()` syscalls.
82 /// Only the multi-command reactor entry points (pipelined socket reads,
83 /// cross-shard request batches) open a group; every other path keeps
84 /// the per-command fsync, so the default is always the safe one.
85 pub(crate) deferred: bool,
86 /// Non-blocking rewrite "diff buffer". While `Some`, every `append` also
87 /// tees its RESP frame here, so writes that land *during* an off-lock
88 /// rewrite are captured and replayed after the compacted snapshot. See
89 /// [`Self::begin_concurrent_rewrite`].
90 pub(crate) rewrite_tee: Option<Vec<u8>>,
91 /// Recycled tee buffer (two-phase rewrite): the worker returns each
92 /// appended generation's buffer CLEARED, and the next generation
93 /// grows into its warm pages instead of faulting a fresh range —
94 /// the reactor-vs-worker mmap churn convicted in the S5-E finding.
95 pub(crate) tee_spare: Option<Vec<u8>>,
96 /// The pre-swap log's graveyard hardlink, awaiting an off-thread
97 /// unlink (see `swap_image` — rename must not drop a multi-GB
98 /// inode's last link on the reactor).
99 pub(crate) swap_trash: Option<PathBuf>,
100 /// Off-thread swap window open: the driver holds queue drains and
101 /// fsyncs while the worker renames over the live path.
102 pub(crate) swap_hold: bool,
103 /// Where `open` quarantined a dropped tail, if it had to repair one —
104 /// surfaced so the store's open report can name the file.
105 open_quarantine: Option<PathBuf>,
106 /// When the last rewrite (or the open, if none yet) finished — the
107 /// anchor for [`RewritePolicy::interval_secs`].
108 pub(crate) last_rewrite_at: Instant,
109 /// The on-disk encoding this file speaks. New files and every rewrite
110 /// output are V2 (checksummed record envelopes); a pre-existing V1
111 /// file keeps appending V1 until its first rewrite upgrades it —
112 /// mixing formats within one file would corrupt it.
113 pub(crate) format: crate::AofFormat,
114 /// Reusable payload buffer for V2 envelope encoding (and the tee,
115 /// which is always V2 because the rewrite output it lands in is).
116 scratch: Vec<u8>,
117 /// `Some` = queued-append mode (RFC v3-aof-offload S1): encoded
118 /// record bytes accumulate here instead of hitting `file`, and the
119 /// DRIVER (the io_uring reactor) drains them via
120 /// [`Aof::take_pending`] as async write SQEs at
121 /// [`Aof::append_offset`]. `None` = every append writes
122 /// synchronously — today's behavior, and the epoll / test default.
123 ///
124 /// Contract for the driver: before any structural file operation
125 /// (truncate, rewrite finish, fsync-policy upgrade to Always) the
126 /// driver must have COMPLETED its in-flight writes; bytes still
127 /// queued HERE are flushed synchronously by those entry points as
128 /// an honest fallback, but bytes already taken are invisible to
129 /// this struct and only the driver can order them.
130 pub(crate) queue: Option<Vec<u8>>,
131 /// File offset where the NEXT taken chunk lands (queued mode):
132 /// advances as chunks are taken, so concurrent chunks carry
133 /// non-overlapping explicit offsets in their SQEs.
134 pub(crate) queued_offset: u64,
135}
136
137/// Handoff between the two halves of a non-blocking rewrite: the serialized
138/// keyspace image (produced under the store lock) and the temp path to spill
139/// it to (off-lock). See [`Aof::begin_concurrent_rewrite`].
140pub struct RewritePlan {
141 /// The compacted AOF image (magic + one command stream per key).
142 pub body: Vec<u8>,
143 /// Same-directory temp file to spill `body` to before the final swap.
144 pub tmp: PathBuf,
145 /// Keys captured in `body` (for the resulting [`RewriteStats`]).
146 pub keys: u64,
147}
148
149/// Result of an [`Aof::rewrite_from`] call. Surfaced by `BGREWRITEAOF` /
150/// `INFO persistence`.
151#[derive(Debug, Clone, Copy)]
152pub struct RewriteStats {
153 /// Keys dumped into the new AOF.
154 pub keys: u64,
155 /// New AOF size in bytes.
156 pub bytes: u64,
157}
158
159impl Aof {
160 /// The on-disk record format this file currently speaks.
161 ///
162 /// A `V1` answer means a 3.x binary can still open this file — the
163 /// downgrade window `UPGRADING.md` describes is a *state*, and this
164 /// is where an embedder reads it instead of telling their users
165 /// "assume it closed" (an embedder's dogfood ask: their `doctor`
166 /// command wanted to say "you can still swap the binary back" and
167 /// could not, because this was `pub(crate)`).
168 #[must_use]
169 pub fn format(&self) -> crate::AofFormat {
170 self.format
171 }
172
173 /// Open (creating if needed) `path` for appending. New files get the
174 /// 9-byte `AOF_MAGIC` header so replays can identify the file as
175 /// kevy-managed. Pre-existing files (legacy bare-RESP or already-
176 /// magic'd) are left untouched.
177 pub fn open(path: &Path, fsync: Fsync) -> io::Result<Self> {
178 Self::open_with_repair(path, fsync, false)
179 }
180
181 /// [`Self::open`] with the repair policy explicit: under `resync`,
182 /// interior corrupt regions are left in place (the resync replay hops
183 /// them deterministically each boot until a rewrite compacts them
184 /// away) and only the bytes after the LAST recoverable record are
185 /// quarantined + truncated — so a mid-file corruption no longer costs
186 /// the good tail behind it.
187 pub fn open_with_repair(path: &Path, fsync: Fsync, resync: bool) -> io::Result<Self> {
188 let mut file = OpenOptions::new().create(true).append(true).open(path)?;
189 let mut size = file.metadata().map_or(0, |m| m.len());
190 let mut quarantined = None;
191 let mut format = crate::AofFormat::V2;
192 if size == 0 {
193 // Fresh file: stamp the (v2) magic header so the replayer can
194 // distinguish kevy-written AOFs from accidental writes.
195 file.write_all(crate::record::AOF2_MAGIC)?;
196 file.sync_data()?;
197 size = crate::record::AOF2_MAGIC.len() as u64;
198 } else {
199 // Existing file: keep appending in ITS format. V1 (magic'd or
200 // legacy bare-RESP) upgrades to V2 at the next rewrite.
201 format = crate::replay::sniff_format(path)?;
202 quarantined = crate::aof_util::repair_tail(path, &mut file, &mut size, resync)?;
203 }
204 Ok(Aof {
205 in_txn: false,
206 file: BufWriter::with_capacity(AOF_BUF_CAP, file),
207 path: path.to_path_buf(),
208 fsync,
209 dirty: false,
210 last_sync: Instant::now(),
211 size_bytes: size,
212 size_at_last_rewrite: size,
213 rewrites_total: 0,
214 deferred: false,
215 rewrite_tee: None,
216 tee_spare: None,
217 swap_trash: None,
218 swap_hold: false,
219 open_quarantine: quarantined,
220 last_rewrite_at: Instant::now(),
221 format,
222 scratch: Vec::new(),
223 queue: None,
224 queued_offset: size,
225 })
226 }
227
228 /// The quarantine file `open` wrote while repairing a dropped tail, if
229 /// any. `None` after a clean open.
230 #[inline]
231 pub fn open_quarantine(&self) -> Option<&Path> {
232 self.open_quarantine.as_deref()
233 }
234
235 /// When the last rewrite (or the open) finished — the staleness anchor
236 /// [`crate::RewritePolicy`] measures from.
237 #[inline]
238 pub(crate) fn last_rewrite_at(&self) -> Instant {
239 self.last_rewrite_at
240 }
241
242 /// The fsync policy this AOF was opened with (or last switched to).
243 /// Mostly for tests / INFO output; the hot path doesn't read this.
244 #[inline]
245 pub fn fsync_policy(&self) -> Fsync {
246 self.fsync
247 }
248
249 /// Switch the fsync policy at runtime (called by `CONFIG SET
250 /// appendfsync`). When tightening to `Always`, also flushes + fsyncs
251 /// any bytes still in the BufWriter so the new "every write is on
252 /// disk before reply" contract is honoured starting on the next
253 /// append, not after the dirty backlog clears.
254 pub fn set_fsync(&mut self, fsync: Fsync) -> io::Result<()> {
255 let upgrading_to_always =
256 matches!(fsync, Fsync::Always) && !matches!(self.fsync, Fsync::Always);
257 self.fsync = fsync;
258 if upgrading_to_always {
259 self.flush_queued()?;
260 }
261 if upgrading_to_always && self.dirty {
262 self.file.flush()?;
263 self.file.get_ref().sync_data()?;
264 self.dirty = false;
265 self.last_sync = Instant::now();
266 }
267 Ok(())
268 }
269
270 /// Write the encoded scratch frame straight to the file (the
271 /// non-queued path): V2 = length + CRC header then payload, V1 = bare.
272 fn write_scratch_to_file(&mut self) -> io::Result<()> {
273 match self.format {
274 crate::AofFormat::V2 => {
275 self.file
276 .write_all(&(self.scratch.len() as u32).to_le_bytes())?;
277 self.file
278 .write_all(&crate::crc32c::crc32c(&self.scratch).to_le_bytes())?;
279 self.file.write_all(&self.scratch)
280 }
281 crate::AofFormat::V1 => self.file.write_all(&self.scratch),
282 }
283 }
284
285 /// Append one command, applying the fsync policy. V2 files get the
286 /// checksummed record envelope; a V1 file keeps its bare-RESP form
287 /// until a rewrite upgrades it.
288 pub fn append<A: ArgvView + ?Sized>(&mut self, args: &A) -> io::Result<()> {
289 // One multibulk encode either way: V2 wraps the scratch bytes in an
290 // envelope, V1 writes them bare. The tee is ALWAYS V2 — its bytes
291 // land in the rewrite output, which is V2 by contract.
292 self.scratch.clear();
293 write_multibulk(&mut self.scratch, args)?;
294 if let Some(q) = &mut self.queue {
295 // Queued mode: the same bytes, into the driver's chunk.
296 match self.format {
297 crate::AofFormat::V2 => {
298 q.extend_from_slice(&(self.scratch.len() as u32).to_le_bytes());
299 q.extend_from_slice(&crate::crc32c::crc32c(&self.scratch).to_le_bytes());
300 q.extend_from_slice(&self.scratch);
301 }
302 crate::AofFormat::V1 => q.extend_from_slice(&self.scratch),
303 }
304 } else {
305 self.write_scratch_to_file()?;
306 }
307 if let Some(tee) = &mut self.rewrite_tee {
308 crate::record::write_record(tee, &self.scratch)?;
309 }
310 let overhead = match self.format {
311 crate::AofFormat::V2 => crate::record::RECORD_HEADER as u64,
312 crate::AofFormat::V1 => 0,
313 };
314 self.size_bytes = self
315 .size_bytes
316 .saturating_add(estimate_multibulk_bytes(args))
317 .saturating_add(overhead);
318 match self.fsync {
319 // Inside a group-commit window, defer the fsync to `end_group`
320 // (one per batch, still before the batch's replies). Outside
321 // one, fsync per command — the safe default for every path.
322 Fsync::Always if self.deferred => self.dirty = true,
323 Fsync::Always => {
324 self.file.flush()?;
325 self.file.get_ref().sync_data()?;
326 }
327 Fsync::EverySec | Fsync::No => self.dirty = true,
328 }
329 Ok(())
330 }
331
332 /// Empty the log (after a snapshot has captured the full state). The
333 /// post-truncate file keeps the `AOF_MAGIC` header so replays of
334 /// the freshly-trimmed log still identify as kevy-managed.
335 pub fn truncate(&mut self) -> io::Result<()> {
336 self.flush_queued()?;
337 self.file.flush()?;
338 let f = self.file.get_mut();
339 f.set_len(0)?;
340 f.seek(SeekFrom::Start(0))?; // harmless under O_APPEND; keeps len/pos coherent
341 f.write_all(crate::record::AOF2_MAGIC)?;
342 f.sync_all()?;
343 self.dirty = false;
344 self.format = crate::AofFormat::V2; // an empty log restarts in v2
345 self.size_bytes = crate::record::AOF2_MAGIC.len() as u64;
346 self.queued_offset = self.size_bytes;
347 self.size_at_last_rewrite = crate::record::AOF2_MAGIC.len() as u64;
348 self.last_rewrite_at = Instant::now();
349 Ok(())
350 }
351
352 /// Estimated current AOF size in bytes (file content as of last append).
353 #[inline]
354 pub fn size_bytes(&self) -> u64 {
355 self.size_bytes
356 }
357
358 /// AOF size at the most recent rewrite (or open). Auto-trigger compares
359 /// `(size_bytes - size_at_last_rewrite) * 100 / size_at_last_rewrite` to
360 /// the `auto_aof_rewrite_percentage` knob.
361 #[inline]
362 pub fn size_at_last_rewrite(&self) -> u64 {
363 self.size_at_last_rewrite
364 }
365
366 /// Re-anchor the growth-rule baseline to `bytes` — the live image's
367 /// estimated rewrite size ([`crate::estimate_rewrite_size`]), called
368 /// by open paths after replay. `open` alone can only baseline at the
369 /// file's current size, which for a short-lived process re-opening
370 /// the same directory resets the growth ratio every run and lets the
371 /// log grow without bound; anchoring to the live estimate keeps the
372 /// +pct% rule meaning "the log is pct% history" across processes.
373 /// Ignored while a rewrite is in flight (its completion sets the
374 /// true post-rewrite size).
375 pub fn anchor_rewrite_baseline(&mut self, bytes: u64) {
376 if !self.is_rewriting() {
377 self.size_at_last_rewrite = bytes.max(crate::record::AOF2_MAGIC.len() as u64);
378 }
379 }
380
381 /// Successful rewrite count since `Self::open`. Surfaced in INFO.
382 #[inline]
383 pub fn rewrites_total(&self) -> u64 {
384 self.rewrites_total
385 }
386
387 /// BGREWRITEAOF: rebuild a compact AOF from `store`'s current state and
388 /// atomically swap it in.
389 ///
390 /// **Synchronous** — the calling shard blocks for the rewrite's
391 /// duration. Each shard owns its own AOF, so the shards' rewrites
392 /// proceed independently; per-shard blocking matches Redis's `BGSAVE`
393 /// cost in a typical single-key-per-shard workload. Concurrent
394 /// (rewrite-during-writes) incrementalisation is deliberately not
395 /// attempted here.
396 ///
397 /// Writes to a `<path>.rewrite` temp file with fsync, then `rename(2)`s
398 /// it over the live AOF. The append handle is reopened against the new
399 /// file before this call returns, so subsequent `append` calls land in
400 /// the rewritten log.
401 pub fn rewrite_from(&mut self, store: &Store) -> io::Result<RewriteStats> {
402 // Flush any pending writes to the OLD file first so the snapshot
403 // accounts for everything the caller intended to durabilise.
404 self.flush_queued()?;
405 self.file.flush()?;
406
407 let tmp = crate::aof_util::rewrite_tmp_path(&self.path);
408 let (keys, bytes) = crate::dump_aof(&tmp, store)?;
409
410 // Atomic replacement. After this, the OLD file descriptor in
411 // `self.file` is open against an unlinked inode; new writes would
412 // go nowhere visible. Reopen against the new path.
413 std::fs::rename(&tmp, &self.path)?;
414 let f = OpenOptions::new().append(true).open(&self.path)?;
415 self.file = BufWriter::with_capacity(AOF_BUF_CAP, f);
416 self.format = crate::AofFormat::V2; // the rewrite output always is
417 self.size_bytes = bytes;
418 self.queued_offset = bytes;
419 self.size_at_last_rewrite = bytes;
420 self.last_rewrite_at = Instant::now();
421 self.dirty = false;
422 self.rewrites_total = self.rewrites_total.saturating_add(1);
423 Ok(RewriteStats { keys, bytes })
424 }
425
426 /// Is a non-blocking rewrite mid-flight (between
427 /// [`Self::begin_concurrent_rewrite`] and `finish`/`abort`)? While true,
428 /// don't start another rewrite — `append` is teeing into the diff buffer.
429 #[inline]
430 pub fn is_rewriting(&self) -> bool {
431 self.rewrite_tee.is_some()
432 }
433}