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 /// Monotone count of records ever pushed into `queue`. The uring
136 /// driver's Always reply-gate (S2) compares this watermark against
137 /// the fsync-proven durable watermark; unlike file offsets it never
138 /// resets across a rewrite swap, so held replies cannot wedge.
139 pub(crate) queued_seq: u64,
140}
141
142/// Handoff between the two halves of a non-blocking rewrite: the serialized
143/// keyspace image (produced under the store lock) and the temp path to spill
144/// it to (off-lock). See [`Aof::begin_concurrent_rewrite`].
145pub struct RewritePlan {
146 /// The compacted AOF image (magic + one command stream per key).
147 pub body: Vec<u8>,
148 /// Same-directory temp file to spill `body` to before the final swap.
149 pub tmp: PathBuf,
150 /// Keys captured in `body` (for the resulting [`RewriteStats`]).
151 pub keys: u64,
152}
153
154/// Result of an [`Aof::rewrite_from`] call. Surfaced by `BGREWRITEAOF` /
155/// `INFO persistence`.
156#[derive(Debug, Clone, Copy)]
157pub struct RewriteStats {
158 /// Keys dumped into the new AOF.
159 pub keys: u64,
160 /// New AOF size in bytes.
161 pub bytes: u64,
162}
163
164impl Aof {
165 /// The on-disk record format this file currently speaks.
166 ///
167 /// A `V1` answer means a 3.x binary can still open this file — the
168 /// downgrade window `UPGRADING.md` describes is a *state*, and this
169 /// is where an embedder reads it instead of telling their users
170 /// "assume it closed" (an embedder's dogfood ask: their `doctor`
171 /// command wanted to say "you can still swap the binary back" and
172 /// could not, because this was `pub(crate)`).
173 #[must_use]
174 pub fn format(&self) -> crate::AofFormat {
175 self.format
176 }
177
178 /// Open (creating if needed) `path` for appending. New files get the
179 /// 9-byte `AOF_MAGIC` header so replays can identify the file as
180 /// kevy-managed. Pre-existing files (legacy bare-RESP or already-
181 /// magic'd) are left untouched.
182 pub fn open(path: &Path, fsync: Fsync) -> io::Result<Self> {
183 Self::open_with_repair(path, fsync, false)
184 }
185
186 /// [`Self::open`] with the repair policy explicit: under `resync`,
187 /// interior corrupt regions are left in place (the resync replay hops
188 /// them deterministically each boot until a rewrite compacts them
189 /// away) and only the bytes after the LAST recoverable record are
190 /// quarantined + truncated — so a mid-file corruption no longer costs
191 /// the good tail behind it.
192 pub fn open_with_repair(path: &Path, fsync: Fsync, resync: bool) -> io::Result<Self> {
193 let mut file = OpenOptions::new().create(true).append(true).open(path)?;
194 let mut size = file.metadata().map_or(0, |m| m.len());
195 let mut quarantined = None;
196 let mut format = crate::AofFormat::V2;
197 if size == 0 {
198 // Fresh file: stamp the (v2) magic header so the replayer can
199 // distinguish kevy-written AOFs from accidental writes.
200 file.write_all(crate::record::AOF2_MAGIC)?;
201 file.sync_data()?;
202 size = crate::record::AOF2_MAGIC.len() as u64;
203 } else {
204 // Existing file: keep appending in ITS format. V1 (magic'd or
205 // legacy bare-RESP) upgrades to V2 at the next rewrite.
206 format = crate::replay::sniff_format(path)?;
207 quarantined = crate::aof_util::repair_tail(path, &mut file, &mut size, resync)?;
208 }
209 Ok(Aof {
210 in_txn: false,
211 file: BufWriter::with_capacity(AOF_BUF_CAP, file),
212 path: path.to_path_buf(),
213 fsync,
214 dirty: false,
215 last_sync: Instant::now(),
216 size_bytes: size,
217 size_at_last_rewrite: size,
218 rewrites_total: 0,
219 deferred: false,
220 rewrite_tee: None,
221 tee_spare: None,
222 swap_trash: None,
223 swap_hold: false,
224 open_quarantine: quarantined,
225 last_rewrite_at: Instant::now(),
226 format,
227 scratch: Vec::new(),
228 queue: None,
229 queued_offset: size,
230 queued_seq: 0,
231 })
232 }
233
234 /// The quarantine file `open` wrote while repairing a dropped tail, if
235 /// any. `None` after a clean open.
236 #[inline]
237 pub fn open_quarantine(&self) -> Option<&Path> {
238 self.open_quarantine.as_deref()
239 }
240
241 /// When the last rewrite (or the open) finished — the staleness anchor
242 /// [`crate::RewritePolicy`] measures from.
243 #[inline]
244 pub(crate) fn last_rewrite_at(&self) -> Instant {
245 self.last_rewrite_at
246 }
247
248 /// The fsync policy this AOF was opened with (or last switched to).
249 /// Mostly for tests / INFO output; the hot path doesn't read this.
250 #[inline]
251 pub fn fsync_policy(&self) -> Fsync {
252 self.fsync
253 }
254
255 /// Switch the fsync policy at runtime (called by `CONFIG SET
256 /// appendfsync`). When tightening to `Always`, also flushes + fsyncs
257 /// any bytes still in the BufWriter so the new "every write is on
258 /// disk before reply" contract is honoured starting on the next
259 /// append, not after the dirty backlog clears.
260 pub fn set_fsync(&mut self, fsync: Fsync) -> io::Result<()> {
261 let upgrading_to_always =
262 matches!(fsync, Fsync::Always) && !matches!(self.fsync, Fsync::Always);
263 self.fsync = fsync;
264 if upgrading_to_always {
265 self.flush_queued()?;
266 }
267 if upgrading_to_always && self.dirty {
268 self.file.flush()?;
269 self.file.get_ref().sync_data()?;
270 self.dirty = false;
271 self.last_sync = Instant::now();
272 }
273 Ok(())
274 }
275
276 /// Write the encoded scratch frame straight to the file (the
277 /// non-queued path): V2 = length + CRC header then payload, V1 = bare.
278 fn write_scratch_to_file(&mut self) -> io::Result<()> {
279 match self.format {
280 crate::AofFormat::V2 => {
281 self.file.write_all(&(self.scratch.len() as u32).to_le_bytes())?;
282 self.file.write_all(&crate::crc32c::crc32c(&self.scratch).to_le_bytes())?;
283 self.file.write_all(&self.scratch)
284 }
285 crate::AofFormat::V1 => self.file.write_all(&self.scratch),
286 }
287 }
288
289 /// Append one command, applying the fsync policy. V2 files get the
290 /// checksummed record envelope; a V1 file keeps its bare-RESP form
291 /// until a rewrite upgrades it.
292 pub fn append<A: ArgvView + ?Sized>(&mut self, args: &A) -> io::Result<()> {
293 // One multibulk encode either way: V2 wraps the scratch bytes in an
294 // envelope, V1 writes them bare. The tee is ALWAYS V2 — its bytes
295 // land in the rewrite output, which is V2 by contract.
296 self.scratch.clear();
297 write_multibulk(&mut self.scratch, args)?;
298 if let Some(q) = &mut self.queue {
299 // Queued mode: the same bytes, into the driver's chunk.
300 match self.format {
301 crate::AofFormat::V2 => {
302 q.extend_from_slice(&(self.scratch.len() as u32).to_le_bytes());
303 q.extend_from_slice(&crate::crc32c::crc32c(&self.scratch).to_le_bytes());
304 q.extend_from_slice(&self.scratch);
305 }
306 crate::AofFormat::V1 => q.extend_from_slice(&self.scratch),
307 }
308 self.queued_seq += 1;
309 } else {
310 self.write_scratch_to_file()?;
311 }
312 if let Some(tee) = &mut self.rewrite_tee {
313 crate::record::write_record(tee, &self.scratch)?;
314 }
315 let overhead = match self.format {
316 crate::AofFormat::V2 => crate::record::RECORD_HEADER as u64,
317 crate::AofFormat::V1 => 0,
318 };
319 self.size_bytes =
320 self.size_bytes.saturating_add(estimate_multibulk_bytes(args)).saturating_add(overhead);
321 match self.fsync {
322 // Inside a group-commit window, defer the fsync to `end_group`
323 // (one per batch, still before the batch's replies). Outside
324 // one, fsync per command — the safe default for every path.
325 // Queued appends live in the driver's chunk, not the file: a
326 // sync here would durabilize nothing. The ring fsync owns
327 // durability there; mark dirty so the driver can see it.
328 Fsync::Always if self.deferred || self.queue.is_some() => self.dirty = true,
329 Fsync::Always => {
330 self.file.flush()?;
331 self.file.get_ref().sync_data()?;
332 }
333 Fsync::EverySec | Fsync::No => self.dirty = true,
334 }
335 Ok(())
336 }
337
338 /// Empty the log (after a snapshot has captured the full state). The
339 /// post-truncate file keeps the `AOF_MAGIC` header so replays of
340 /// the freshly-trimmed log still identify as kevy-managed.
341 pub fn truncate(&mut self) -> io::Result<()> {
342 self.flush_queued()?;
343 self.file.flush()?;
344 let f = self.file.get_mut();
345 f.set_len(0)?;
346 f.seek(SeekFrom::Start(0))?; // harmless under O_APPEND; keeps len/pos coherent
347 f.write_all(crate::record::AOF2_MAGIC)?;
348 f.sync_all()?;
349 self.dirty = false;
350 self.format = crate::AofFormat::V2; // an empty log restarts in v2
351 self.size_bytes = crate::record::AOF2_MAGIC.len() as u64;
352 self.queued_offset = self.size_bytes;
353 self.size_at_last_rewrite = crate::record::AOF2_MAGIC.len() as u64;
354 self.last_rewrite_at = Instant::now();
355 Ok(())
356 }
357
358 /// Estimated current AOF size in bytes (file content as of last append).
359 #[inline]
360 pub fn size_bytes(&self) -> u64 {
361 self.size_bytes
362 }
363
364 /// AOF size at the most recent rewrite (or open). Auto-trigger compares
365 /// `(size_bytes - size_at_last_rewrite) * 100 / size_at_last_rewrite` to
366 /// the `auto_aof_rewrite_percentage` knob.
367 #[inline]
368 pub fn size_at_last_rewrite(&self) -> u64 {
369 self.size_at_last_rewrite
370 }
371
372 /// Re-anchor the growth-rule baseline to `bytes` — the live image's
373 /// estimated rewrite size ([`crate::estimate_rewrite_size`]), called
374 /// by open paths after replay. `open` alone can only baseline at the
375 /// file's current size, which for a short-lived process re-opening
376 /// the same directory resets the growth ratio every run and lets the
377 /// log grow without bound; anchoring to the live estimate keeps the
378 /// +pct% rule meaning "the log is pct% history" across processes.
379 /// Ignored while a rewrite is in flight (its completion sets the
380 /// true post-rewrite size).
381 pub fn anchor_rewrite_baseline(&mut self, bytes: u64) {
382 if !self.is_rewriting() {
383 self.size_at_last_rewrite = bytes.max(crate::record::AOF2_MAGIC.len() as u64);
384 }
385 }
386
387 /// Successful rewrite count since `Self::open`. Surfaced in INFO.
388 #[inline]
389 pub fn rewrites_total(&self) -> u64 {
390 self.rewrites_total
391 }
392
393 /// BGREWRITEAOF: rebuild a compact AOF from `store`'s current state and
394 /// atomically swap it in.
395 ///
396 /// **Synchronous** — the calling shard blocks for the rewrite's
397 /// duration. Each shard owns its own AOF, so the shards' rewrites
398 /// proceed independently; per-shard blocking matches Redis's `BGSAVE`
399 /// cost in a typical single-key-per-shard workload. Concurrent
400 /// (rewrite-during-writes) incrementalisation is deliberately not
401 /// attempted here.
402 ///
403 /// Writes to a `<path>.rewrite` temp file with fsync, then `rename(2)`s
404 /// it over the live AOF. The append handle is reopened against the new
405 /// file before this call returns, so subsequent `append` calls land in
406 /// the rewritten log.
407 pub fn rewrite_from(&mut self, store: &Store) -> io::Result<RewriteStats> {
408 // Flush any pending writes to the OLD file first so the snapshot
409 // accounts for everything the caller intended to durabilise.
410 self.flush_queued()?;
411 self.file.flush()?;
412
413 let tmp = crate::aof_util::rewrite_tmp_path(&self.path);
414 let (keys, bytes) = crate::dump_aof(&tmp, store)?;
415
416 // Atomic replacement. After this, the OLD file descriptor in
417 // `self.file` is open against an unlinked inode; new writes would
418 // go nowhere visible. Reopen against the new path.
419 std::fs::rename(&tmp, &self.path)?;
420 let f = OpenOptions::new().append(true).open(&self.path)?;
421 self.file = BufWriter::with_capacity(AOF_BUF_CAP, f);
422 self.format = crate::AofFormat::V2; // the rewrite output always is
423 self.size_bytes = bytes;
424 self.queued_offset = bytes;
425 self.size_at_last_rewrite = bytes;
426 self.last_rewrite_at = Instant::now();
427 self.dirty = false;
428 self.rewrites_total = self.rewrites_total.saturating_add(1);
429 Ok(RewriteStats { keys, bytes })
430 }
431
432 /// Is a non-blocking rewrite mid-flight (between
433 /// [`Self::begin_concurrent_rewrite`] and `finish`/`abort`)? While true,
434 /// don't start another rewrite — `append` is teeing into the diff buffer.
435 #[inline]
436 pub fn is_rewriting(&self) -> bool {
437 self.rewrite_tee.is_some()
438 }
439}