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