diff --git a/README.md b/README.md index 119b4f6..34e4904 100644 --- a/README.md +++ b/README.md @@ -146,7 +146,7 @@ KacheDB implements the standard **RESP2 / RESP3** binary wire protocol. You can | **`PERSIST`** | `PERSIST key` | Removes TTL expiration, making key persistent. | $\mathcal{O}(1)$ | | **`FLUSHDB`** | `FLUSHDB` | Clears all keys and recycles slab pool memory blocks. | $\mathcal{O}(N)$ | | **`FLUSHALL`** | `FLUSHALL` | Clears all keys across all database instances. | $\mathcal{O}(N)$ | -| **`BGREWRITEAOF`** | `BGREWRITEAOF` | Returns an unsupported-command error. | — | +| **`BGREWRITEAOF`** | `BGREWRITEAOF` | Compacts the append-only file in the background when AOF is enabled. | — | | **`INFO`** | `INFO [section]` | Returns real-time telemetry, memory stats, and keyspace diagnostics. | $\mathcal{O}(1)$ | | **`QUIT`** | `QUIT` | Closes the client connection gracefully. | $\mathcal{O}(1)$ | | **`COMMAND`** | `COMMAND DOCS` | Returns Redis protocol capability metadata. | $\mathcal{O}(1)$ | diff --git a/crates/kachedb-cli/src/repl.rs b/crates/kachedb-cli/src/repl.rs index 94bdb92..833cafb 100644 --- a/crates/kachedb-cli/src/repl.rs +++ b/crates/kachedb-cli/src/repl.rs @@ -236,7 +236,7 @@ Available Commands in KacheDB: INFO [section] - Return server runtime, memory, and stats CLIENT SETNAME - Assign connection name CLIENT GETNAME - Get connection name - BGREWRITEAOF - Currently unsupported + BGREWRITEAOF - Compact the append-only file in the background PING [msg] - Ping server QUIT - Close connection • Vector Engine: diff --git a/crates/kachedb-net/src/connection/admin.rs b/crates/kachedb-net/src/connection/admin.rs index 05b4353..41ac502 100644 --- a/crates/kachedb-net/src/connection/admin.rs +++ b/crates/kachedb-net/src/connection/admin.rs @@ -160,10 +160,15 @@ pub fn handle_admin( encode_simple_string(write_buf, "OK"); } Command::BgRewriteAof => { - encode_error( - write_buf, - "ERR BGREWRITEAOF is currently unsupported in this version", - ); + let result = crate::durability::dispatch() + .ok_or(crate::durability::AdmissionError::RewriteDisabled) + .and_then(|writer| writer.request_rewrite()); + match result { + Ok(()) => { + encode_simple_string(write_buf, "Background append only file rewriting started") + } + Err(error) => encode_error(write_buf, &error.to_string()), + } } Command::DBSize => { encode_integer(write_buf, table.len() as i64); diff --git a/crates/kachedb-net/src/connection/tests.rs b/crates/kachedb-net/src/connection/tests.rs index 2e8b5c1..4dbcae4 100644 --- a/crates/kachedb-net/src/connection/tests.rs +++ b/crates/kachedb-net/src/connection/tests.rs @@ -887,7 +887,7 @@ fn test_auth_requirepass_flow() { } #[test] -fn process_incoming_bgrewriteaof_returns_unsupported() { +fn process_incoming_bgrewriteaof_requires_persistence() { let mut conn = Connection::new(); let table = ShardedSwissTable::new(); let mut pool = SlabPool::new(0, 16 * 1024 * 1024).unwrap(); @@ -897,7 +897,7 @@ fn process_incoming_bgrewriteaof_returns_unsupported() { assert!(conn.process_incoming(&table, &mut pool).unwrap()); assert_eq!( conn.write_buf, - b"-ERR BGREWRITEAOF is currently unsupported in this version\r\n+PONG\r\n" + b"-ERR BGREWRITEAOF requires AOF persistence\r\n+PONG\r\n" ); } diff --git a/crates/kachedb-net/src/durability.rs b/crates/kachedb-net/src/durability.rs index 1cfba90..11ee484 100644 --- a/crates/kachedb-net/src/durability.rs +++ b/crates/kachedb-net/src/durability.rs @@ -1,5 +1,8 @@ //! Bounded AOF admission and ordered publication shared by server workers. +use std::fs::File; +use std::path::PathBuf; +use std::sync::atomic::AtomicBool; use std::sync::{Arc, Condvar, Mutex, OnceLock}; use std::time::{Duration, Instant}; @@ -49,6 +52,10 @@ pub enum AdmissionError { Oversized, #[error("ERR persistence failed after publication; mutation outcome is uncertain")] Uncertain, + #[error("ERR BGREWRITEAOF requires AOF persistence")] + RewriteDisabled, + #[error("ERR an AOF rewrite is already in progress")] + RewriteInProgress, } pub enum WriterRequest { @@ -57,14 +64,30 @@ pub enum WriterRequest { done: Option>, permit: Permit, }, - Sync(Sender<()>), + Sync(Sender), + BeginRewrite { + sequence: u64, + cancelled: Arc, + }, + InstallRewrite { + replacement: RewriteFile, + installed: Sender, + }, + AbortRewrite, Stop, } +pub struct RewriteFile { + pub file: File, + pub path: PathBuf, + pub checkpoint: Checkpoint, +} + struct QueueState { used_bytes: usize, used_records: usize, failed: bool, + rewriting: bool, sequence: u64, } @@ -72,7 +95,7 @@ pub struct AofDispatch { tx: Sender, state: Mutex, available: Condvar, - generation: [u8; 16], + rewrite_trigger: OnceLock>, policy: AppendFsync, byte_limit: usize, record_limit: usize, @@ -125,7 +148,7 @@ impl AofDispatch { let dispatch = Arc::new(Self { tx, available: Condvar::new(), - generation: checkpoint.generation, + rewrite_trigger: OnceLock::new(), policy, byte_limit, record_limit, @@ -133,6 +156,7 @@ impl AofDispatch { used_bytes: 0, used_records: 0, failed: false, + rewriting: false, sequence: checkpoint.sequence, }), }); @@ -177,9 +201,9 @@ impl AofDispatch { self.available.notify_all(); } - /// Call under the commit fence. The receiver confirms the checkpoint's - /// log prefix reached disk, including under the asynchronous fsync policies. - pub fn checkpoint(&self) -> Result<(Checkpoint, Receiver<()>), AdmissionError> { + /// Enqueues a sync at the current commit boundary. The writer replies with the + /// checkpoint for the file that actually received the prefix. + pub fn checkpoint(&self) -> Result, AdmissionError> { let state = self.state.lock().unwrap(); if state.failed { return Err(AdmissionError::Unavailable); @@ -188,13 +212,72 @@ impl AofDispatch { self.tx .send(WriterRequest::Sync(send)) .map_err(|_| AdmissionError::Unavailable)?; - Ok(( - Checkpoint { - generation: self.generation, + Ok(receive) + } + + pub fn set_rewrite_trigger(&self, trigger: Sender<()>) { + assert!(self.rewrite_trigger.set(trigger).is_ok()); + } + + pub fn request_rewrite(&self) -> Result<(), AdmissionError> { + let trigger = self + .rewrite_trigger + .get() + .ok_or(AdmissionError::RewriteDisabled)?; + let mut state = self.state.lock().unwrap(); + if state.failed { + return Err(AdmissionError::Unavailable); + } + if state.rewriting { + return Err(AdmissionError::RewriteInProgress); + } + trigger + .try_send(()) + .map_err(|_| AdmissionError::Unavailable)?; + state.rewriting = true; + Ok(()) + } + + /// Call under the commit fence after copying the base. + pub fn begin_rewrite(&self, cancelled: Arc) -> Result { + let state = self.state.lock().unwrap(); + if state.failed { + return Err(AdmissionError::Unavailable); + } + self.tx + .send(WriterRequest::BeginRewrite { sequence: state.sequence, - }, - receive, - )) + cancelled, + }) + .map_err(|_| AdmissionError::Unavailable)?; + Ok(state.sequence) + } + + /// Uses the same FIFO as mutations and checkpoint requests to define cutover. + pub fn install_rewrite( + &self, + replacement: RewriteFile, + ) -> Result, AdmissionError> { + let state = self.state.lock().unwrap(); + if state.failed { + return Err(AdmissionError::Unavailable); + } + let (send, receive) = bounded(1); + self.tx + .send(WriterRequest::InstallRewrite { + replacement, + installed: send, + }) + .map_err(|_| AdmissionError::Unavailable)?; + Ok(receive) + } + + pub fn abort_rewrite(&self) { + let _ = self.tx.send(WriterRequest::AbortRewrite); + } + + pub fn finish_rewrite(&self) { + self.state.lock().unwrap().rewriting = false; } pub fn stop(&self) { @@ -262,6 +345,34 @@ impl Drop for Permit { mod tests { use super::*; + #[test] + fn rewrite_request_admits_one_job_at_a_time() { + let (dispatch, _) = AofDispatch::new( + Checkpoint { + generation: [0; 16], + sequence: 0, + }, + AppendFsync::Always, + ); + let (trigger, requests) = bounded(1); + assert_eq!( + dispatch.request_rewrite(), + Err(AdmissionError::RewriteDisabled) + ); + dispatch.set_rewrite_trigger(trigger); + dispatch.request_rewrite().unwrap(); + assert_eq!( + dispatch.request_rewrite(), + Err(AdmissionError::RewriteInProgress) + ); + requests.recv().unwrap(); + dispatch.finish_rewrite(); + dispatch.request_rewrite().unwrap(); + requests.recv().unwrap(); + dispatch.fail(); + assert_eq!(dispatch.request_rewrite(), Err(AdmissionError::Unavailable)); + } + #[test] fn asynchronous_admission_bounds_bytes_and_records() { for policy in [AppendFsync::EverySec, AppendFsync::No] { @@ -282,7 +393,7 @@ mod tests { )); drop(second); assert!(first.submit(vec![1; 5]).unwrap().is_none()); - assert_eq!(dispatch.checkpoint().unwrap().0.sequence, 18); + let checkpoint_reply = dispatch.checkpoint().unwrap(); assert!(matches!( dispatch.reserve(4), Err(AdmissionError::Saturated) @@ -291,6 +402,15 @@ mod tests { panic!("record must precede checkpoint"); }; assert_eq!(bytes, [1; 5]); + let WriterRequest::Sync(sender) = requests.recv().unwrap() else { + panic!("expected checkpoint request"); + }; + let checkpoint = Checkpoint { + sequence: 18, + ..checkpoint + }; + sender.send(checkpoint).unwrap(); + assert_eq!(checkpoint_reply.recv().unwrap(), checkpoint); drop(permit); assert!(dispatch.reserve(8).is_ok()); assert!(matches!( diff --git a/crates/kachedb-proto-resp/src/command.rs b/crates/kachedb-proto-resp/src/command.rs index 283b8d3..6f10ec0 100644 --- a/crates/kachedb-proto-resp/src/command.rs +++ b/crates/kachedb-proto-resp/src/command.rs @@ -271,6 +271,11 @@ pub(super) fn decode_inline(line: &[u8], consumed: usize) -> ParsedCommandFrame< Ok(Some((Ok(Command::FlushDb), consumed))) } else if cmd_name.eq_ignore_ascii_case(b"FLUSHALL") { Ok(Some((Ok(Command::FlushAll), consumed))) + } else if cmd_name.eq_ignore_ascii_case(b"BGREWRITEAOF") { + Ok(Some(( + decode_bgrewriteaof(parts.next().is_some()), + consumed, + ))) } else { Ok(Some((Ok(Command::Unknown { name: cmd_name }), consumed))) } @@ -280,6 +285,15 @@ pub(super) fn decode_inline(line: &[u8], consumed: usize) -> ParsedCommandFrame< } } +fn decode_bgrewriteaof<'a>(has_arguments: bool) -> Result, RespError> { + if has_arguments { + return Err(RespError::WrongArgumentCount { + command: "BGREWRITEAOF".into(), + }); + } + Ok(Command::BgRewriteAof) +} + /// Parses one Redis wire command, borrowing argument data from the input slice. pub fn parse_command<'a>(src: &'a [u8]) -> Result, usize)>, RespError> { match parse_command_frame(src)? { @@ -659,7 +673,7 @@ impl<'a> Command<'a> { Ok(Command::Unknown { name: cmd_name }) } } else if cmd_name.eq_ignore_ascii_case(b"BGREWRITEAOF") { - Ok(Command::BgRewriteAof) + decode_bgrewriteaof(args.len() > 1) } else if cmd_name.eq_ignore_ascii_case(b"AUTH") { if args.len() == 2 { Ok(Command::Auth { @@ -1444,7 +1458,7 @@ impl<'a> Command<'a> { Ok(Command::Unknown { name: cmd_name }) } } else if cmd_name.eq_ignore_ascii_case(b"BGREWRITEAOF") { - Ok(Command::BgRewriteAof) + decode_bgrewriteaof(args.len() > 1) } else if cmd_name.eq_ignore_ascii_case(b"AUTH") { if args.len() == 2 { let password = extract_required_bytes(&args[1], "AUTH")?; diff --git a/crates/kachedb-server/src/aof.rs b/crates/kachedb-server/src/aof.rs index 9df3f88..2984c37 100644 --- a/crates/kachedb-server/src/aof.rs +++ b/crates/kachedb-server/src/aof.rs @@ -5,6 +5,7 @@ use std::fs::{File, OpenOptions}; use std::io::Write; +use std::os::unix::fs::MetadataExt; use std::path::Path; use std::sync::Arc; use std::thread::{self, JoinHandle}; @@ -12,11 +13,15 @@ use std::time::{Duration, Instant}; use crossbeam_channel::{Receiver, RecvTimeoutError}; use kachedb_net::aof_encode::encode_checked_frame; -pub use kachedb_net::aof_encode::{AOF_HEADER_OVERHEAD, AOF_MAGIC, AofOp, encode_frame}; +#[cfg(test)] +pub use kachedb_net::aof_encode::encode_frame; +pub use kachedb_net::aof_encode::{AOF_HEADER_OVERHEAD, AOF_MAGIC, AofOp}; pub use kachedb_net::durability::AppendFsync; use kachedb_net::durability::{AofDispatch, Checkpoint, WriterRequest}; use thiserror::Error; +use crate::aof_rewrite::{self, Deltas, InstallError}; + #[derive(Debug, Error)] pub enum AofError { #[error("IO error: {0}")] @@ -34,14 +39,16 @@ pub enum AofError { #[error("Unexpected end of AOF file")] #[allow(dead_code)] UnexpectedEof, - #[error("Cannot rewrite AOF for an entry without original key bytes")] - MissingKeyBytes, #[error("Invalid AOF record: {0}")] InvalidRecord(&'static str), + #[error("Invalid embedded AOF base: {0}")] + InvalidBase(String), #[error("AOF replay rejected a mutation: {0}")] Apply(String), #[error("AOF and snapshot cannot be combined: {0}")] Migration(&'static str), + #[error("AOF rewrite was renamed but its directory could not be synced: {0}")] + RewriteInstallUncertain(std::io::Error), #[error("AOF worker terminated unexpectedly")] WriterStopped, #[error("AOF record at byte {offset} is invalid: {source}")] @@ -130,17 +137,30 @@ pub fn open_locked(path: &Path, create: bool) -> Result { .append(true) .create(create) .open(path)?; - if !file.metadata()?.is_file() { + let opened = file.metadata()?; + if !opened.is_file() { return Err(AofError::InvalidRecord("AOF must be a regular file")); } file.try_lock().map_err(std::io::Error::from)?; + let current = std::fs::metadata(path)?; + if (opened.dev(), opened.ino()) != (current.dev(), current.ino()) { + return Err(AofError::InvalidRecord( + "journal was replaced while acquiring its lock", + )); + } Ok(file) } +pub(super) struct WriterOptions { + pub policy: AppendFsync, + pub delta_bytes: usize, +} + /// An opened journal and the worker responsible for its ordered writes. pub struct AofWriter { dispatch: Arc, worker_handle: Option>>, + rewrite_handle: Option>, } impl AofWriter { @@ -164,10 +184,22 @@ impl AofWriter { } let (dispatch, rx) = AofDispatch::new(checkpoint, policy); let worker_dispatch = dispatch.clone(); + let path = path.to_owned(); let worker_handle = thread::Builder::new() .name("kachedb-aof-writer".into()) .spawn(move || { - let result = Self::writer_loop(&mut file, policy, &rx, &worker_dispatch); + let result = Self::writer_loop( + &mut file, + &path, + WriterOptions { + policy, + delta_bytes: aof_rewrite::DELTA_BYTES, + }, + &rx, + &worker_dispatch, + checkpoint, + File::sync_all, + ); if let Err(error) = &result { log::error!("AOF writer failed: {error}"); } @@ -177,6 +209,7 @@ impl AofWriter { Ok(Self { dispatch, worker_handle: Some(worker_handle), + rewrite_handle: None, }) } @@ -184,12 +217,26 @@ impl AofWriter { self.dispatch.clone() } - fn writer_loop( - file: &mut std::fs::File, - policy: AppendFsync, + pub fn enable_rewrite( + &mut self, + path: std::path::PathBuf, + table: Arc, + vectors: &'static kachedb_vector::VectorIndexRegistry, + ) -> Result<(), AofError> { + self.rewrite_handle = Some(aof_rewrite::start(path, self.dispatch(), table, vectors)?); + Ok(()) + } + + pub(super) fn writer_loop( + file: &mut File, + path: &Path, + options: WriterOptions, rx: &Receiver, dispatch: &AofDispatch, + mut checkpoint: Checkpoint, + sync_directory: impl Fn(&File) -> std::io::Result<()>, ) -> Result<(), AofError> { + let mut deltas: Option = None; let mut last_sync = Instant::now(); let mut dirty = false; loop { @@ -210,6 +257,15 @@ impl AofWriter { dispatch.fail(); return Err(error.into()); } + checkpoint.sequence += 1; + if let Some(buffer) = deltas.as_mut() + && !buffer.push(bytes) + { + deltas = None; + log::warn!( + "BGREWRITEAOF: delta budget exceeded, keeping the active journal" + ); + } dirty = done.is_none(); if let Some(done) = done { let _ = done.send(()); @@ -218,10 +274,58 @@ impl AofWriter { } Ok(WriterRequest::Sync(done)) => { file.sync_all()?; - let _ = done.send(()); + let _ = done.send(checkpoint); last_sync = Instant::now(); dirty = false; } + Ok(WriterRequest::BeginRewrite { + sequence, + cancelled, + }) => { + debug_assert!(deltas.is_none()); + if sequence != checkpoint.sequence { + cancelled.store(true, std::sync::atomic::Ordering::Release); + log::error!("BGREWRITEAOF: base sequence differs from the writer sequence"); + } else { + deltas = Some(Deltas::new(sequence, cancelled, options.delta_bytes)); + } + } + Ok(WriterRequest::AbortRewrite) => deltas = None, + Ok(WriterRequest::InstallRewrite { + replacement, + installed, + }) => { + let Some(buffer) = deltas.take() else { + let _ = installed.send(false); + continue; + }; + if buffer.sequence != replacement.checkpoint.sequence + || !buffer.reaches(checkpoint.sequence) + { + log::error!( + "BGREWRITEAOF: replacement and deltas cover different sequences" + ); + let _ = installed.send(false); + continue; + } + let generation = replacement.checkpoint.generation; + match aof_rewrite::install(path, file, replacement, &buffer, &sync_directory) { + Ok(()) => { + checkpoint.generation = generation; + dirty = false; + last_sync = Instant::now(); + let _ = installed.send(true); + } + Err(InstallError::BeforeRename(error)) => { + log::warn!("BGREWRITEAOF: kept the active journal: {error}"); + let _ = installed.send(false); + } + Err(InstallError::AfterRename(error)) => { + dispatch.fail(); + return Err(AofError::RewriteInstallUncertain(error)); + } + } + } Ok(WriterRequest::Stop) => { file.sync_all()?; return Ok(()); @@ -230,7 +334,7 @@ impl AofWriter { Err(RecvTimeoutError::Disconnected) => return Err(AofError::WriterStopped), } if dirty - && policy == AppendFsync::EverySec + && options.policy == AppendFsync::EverySec && last_sync.elapsed() >= Duration::from_secs(1) { file.sync_data()?; @@ -241,11 +345,18 @@ impl AofWriter { } pub fn stop(&mut self) -> Result<(), AofError> { - if let Some(handle) = self.worker_handle.take() { - self.dispatch.stop(); - handle.join().map_err(|_| AofError::WriterStopped)??; + let result = self + .worker_handle + .take() + .map(|handle| { + self.dispatch.stop(); + handle.join().map_err(|_| AofError::WriterStopped)? + }) + .transpose(); + if let Some(handle) = self.rewrite_handle.take() { + handle.join().map_err(|_| AofError::WriterStopped)?; } - Ok(()) + result.map(|_| ()) } } diff --git a/crates/kachedb-server/src/aof_recovery.rs b/crates/kachedb-server/src/aof_recovery.rs index 054a112..94e6fd5 100644 --- a/crates/kachedb-server/src/aof_recovery.rs +++ b/crates/kachedb-server/src/aof_recovery.rs @@ -1,7 +1,7 @@ //! Streaming replay and explicit repair of an append-only journal. use std::fs::{File, OpenOptions}; -use std::io::{BufReader, ErrorKind, Read}; +use std::io::{self, BufReader, ErrorKind, Read}; use std::path::{Path, PathBuf}; use kachedb_core::{ @@ -19,11 +19,14 @@ use kachedb_proto_resp::{Command, parse_command_frame_for_replay}; use kachedb_vector::VectorIndexRegistry; use crate::aof::{AofError, AofFrame, AofOp, decode_frame}; +use crate::aof_rewrite::{BASE_KIND, BaseHeader}; +use crate::snapshot; #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub struct LogState { pub generation: Option<[u8; 16]>, pub requires_snapshot: bool, + pub embedded_base: Option, pub sequence: u64, pub valid_end: u64, pub incomplete_tail: bool, @@ -31,7 +34,7 @@ pub struct LogState { pub fn inspect(path: &Path) -> Result { let mut state = LogState::default(); - scan(path, &mut state, |_, _| Ok(()))?; + scan(path, &mut state, |_| Ok(()))?; Ok(state) } @@ -58,7 +61,18 @@ fn replay_with_hash_from( table.schedule_restored_expirations(&mut wheel); let mut expired = Vec::new(); let mut scheduled = 0; - scan(path, &mut state, |sequence, frame| { + scan(path, &mut state, |item| { + let (sequence, frame) = match item { + ScanItem::Base(header, input) => { + if after_sequence <= header.checkpoint.sequence { + snapshot::hydrate_rewrite_base(input, header.size, table, pool, vectors) + .map_err(|error| AofError::InvalidBase(error.to_string()))?; + table.schedule_restored_expirations(&mut wheel); + } + return Ok(()); + } + ScanItem::Mutation(sequence, frame) => (sequence, frame), + }; if sequence <= after_sequence { return Ok(()); } @@ -137,7 +151,7 @@ pub fn trim_incomplete_tail(path: &Path, state: LogState) -> Result<(), AofError pub fn repair(path: &Path) -> Result, AofError> { let _lock = crate::aof::open_locked(path, false)?; let mut state = LogState::default(); - match scan(path, &mut state, |_, _| Ok(())) { + match scan(path, &mut state, |_| Ok(())) { Ok(()) if !state.incomplete_tail => return Ok(None), Ok(()) => {} Err(AofError::AtOffset { .. }) => {} @@ -170,7 +184,7 @@ pub fn repair(path: &Path) -> Result, AofError> { fn scan( path: &Path, state: &mut LogState, - mut apply: impl FnMut(u64, &AofFrame<'_>) -> Result<(), AofError>, + mut apply: impl FnMut(ScanItem<'_>) -> Result<(), AofError>, ) -> Result<(), AofError> { let file = match File::open(path) { Ok(file) => file, @@ -188,6 +202,13 @@ fn scan( match outcome { Ok(Record::Eof) => return Ok(()), Ok(Record::TornPayload) => { + // Until a generation is established this could be the header + // of a rewritten base, which must never be discarded at startup. + if state.generation.is_none() { + return Err(at_offset(AofError::InvalidRecord( + "incomplete generation marker", + ))); + } state.incomplete_tail = true; return Ok(()); } @@ -197,19 +218,33 @@ fn scan( checked, }) => { if frame.op == AofOp::Generation { - if !checked - || state.generation.is_some() - || !frame.key.is_empty() - || frame.value.len() != 17 - || frame.value[16] > 1 - || (frame.value[16] == 1 && state.sequence != 0) - { + if !checked || state.generation.is_some() || !frame.key.is_empty() { return Err(at_offset(AofError::InvalidRecord( "invalid generation marker", ))); } - state.generation = Some(frame.value[..16].try_into().unwrap()); - state.requires_snapshot = frame.value[16] == 1; + match frame.value.get(16).copied() { + Some(BASE_KIND) if state.valid_end == 0 => { + let header = BaseHeader::decode(frame.value) + .map_err(|error| AofError::InvalidBase(error.to_string()))?; + scan_base(&mut reader, header, &mut apply)?; + state.generation = Some(header.checkpoint.generation); + state.embedded_base = Some(header.checkpoint.sequence); + state.sequence = header.checkpoint.sequence; + state.valid_end += header.size; + } + Some(kind @ (0 | 1)) + if frame.value.len() == 17 && (kind == 0 || state.sequence == 0) => + { + state.generation = Some(frame.value[..16].try_into().unwrap()); + state.requires_snapshot = kind == 1; + } + _ => { + return Err(at_offset(AofError::InvalidRecord( + "invalid generation marker", + ))); + } + } } else { if checked != state.generation.is_some() || (!checked @@ -222,7 +257,7 @@ fn scan( state.sequence = state.sequence.checked_add(1).ok_or_else(|| { at_offset(AofError::InvalidRecord("record sequence overflow")) })?; - apply(state.sequence, &frame).map_err(at_offset)?; + apply(ScanItem::Mutation(state.sequence, &frame)).map_err(at_offset)?; } state.valid_end += size as u64; } @@ -232,6 +267,50 @@ fn scan( } } +enum ScanItem<'a> { + Base(BaseHeader, &'a mut dyn Read), + Mutation(u64, &'a AofFrame<'a>), +} + +fn scan_base( + input: &mut impl Read, + header: BaseHeader, + apply: &mut impl FnMut(ScanItem<'_>) -> Result<(), AofError>, +) -> Result<(), AofError> { + let mut base = ChecksummedReader { + input: input.take(header.size), + checksum: crc32fast::Hasher::new(), + }; + apply(ScanItem::Base(header, &mut base))?; + io::copy(&mut base, &mut io::sink())?; + if base.input.limit() != 0 { + return Err(AofError::InvalidBase( + "unexpected end of embedded payload".into(), + )); + } + let checksum = base.checksum.finalize(); + if checksum != header.checksum { + return Err(AofError::InvalidBase(format!( + "checksum mismatch (expected {:#010x}, calculated {checksum:#010x})", + header.checksum, + ))); + } + Ok(()) +} + +struct ChecksummedReader { + input: R, + checksum: crc32fast::Hasher, +} + +impl Read for ChecksummedReader { + fn read(&mut self, bytes: &mut [u8]) -> io::Result { + let read = self.input.read(bytes)?; + self.checksum.update(&bytes[..read]); + Ok(read) + } +} + enum Record<'a> { Eof, TornPayload, diff --git a/crates/kachedb-server/src/aof_rewrite.rs b/crates/kachedb-server/src/aof_rewrite.rs index b0d5b24..b2f798d 100644 --- a/crates/kachedb-server/src/aof_rewrite.rs +++ b/crates/kachedb-server/src/aof_rewrite.rs @@ -1,212 +1,677 @@ -//! `kachedb-server` — Background AOF Compaction & Rewrite (BGREWRITEAOF). -//! -//! Compacts historical mutation logs into a minimal point-in-time snapshot of current live keys, -//! writing to a temporary file before performing an atomic rename swap. +//! Captures an AOF base in the background and hands installation to the writer. -use std::fs::OpenOptions; -use std::io::Write; +use std::error::Error; +use std::fs::{File, OpenOptions}; +use std::io::{self, Seek, Write}; +use std::os::unix::fs::OpenOptionsExt; use std::path::{Path, PathBuf}; -use std::sync::Arc; -use std::thread; -use std::time::{SystemTime, UNIX_EPOCH}; +use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, +}; +use std::thread::{self, JoinHandle}; +use std::time::Duration; -use kachedb_hash::{ShardedSwissTable, VALUE_TYPE_HASH}; +use crossbeam_channel::{RecvTimeoutError, bounded}; +use kachedb_hash::ShardedSwissTable; +use kachedb_net::aof_encode::encode_checked_frame; +use kachedb_net::durability::{self, AofDispatch, Checkpoint, RewriteFile}; use kachedb_vector::VectorIndexRegistry; -use crate::aof::{AofError, AofOp, encode_frame}; - -/// Background AOF rewrite execution job. -#[allow(dead_code)] -pub struct BgRewriteJob; - -#[allow(dead_code)] -impl BgRewriteJob { - /// Executes the AOF rewrite asynchronously in a background thread. - pub fn start( - target_path: PathBuf, - table: Arc, - _vectors: Arc, - now_sec: u32, - ) { - thread::Builder::new() - .name("kachedb-bgrewriteaof".into()) - .spawn(move || { - let tmp_path = target_path.with_extension("tmp"); - match Self::execute_rewrite(&tmp_path, &table, now_sec) { - Ok(count) => { - if let Err(e) = std::fs::rename(&tmp_path, &target_path) { - log::error!("BGREWRITEAOF: atomic rename failed: {e}"); - } else { - log::info!( - "BGREWRITEAOF: rewrite completed successfully, {count} keys written to {target_path:?}" - ); +use crate::aof::{AofError, AofOp}; +use crate::snapshot; + +pub const BASE_KIND: u8 = 2; +const BASE_HEADER_BYTES: usize = 37; +pub(super) const DELTA_BYTES: usize = 64 * 1024 * 1024; +const DELTA_RECORDS: usize = 65_536; + +#[derive(Clone, Copy)] +pub struct BaseHeader { + pub checkpoint: Checkpoint, + pub size: u64, + pub checksum: u32, +} + +impl BaseHeader { + fn encode(self) -> Vec { + let mut metadata = [0; BASE_HEADER_BYTES]; + metadata[..16].copy_from_slice(&self.checkpoint.generation); + metadata[16] = BASE_KIND; + metadata[17..25].copy_from_slice(&self.checkpoint.sequence.to_le_bytes()); + metadata[25..33].copy_from_slice(&self.size.to_le_bytes()); + metadata[33..37].copy_from_slice(&self.checksum.to_le_bytes()); + encode_checked_frame(AofOp::Generation, &[], &metadata, 0) + } + + pub fn decode(bytes: &[u8]) -> Result { + if bytes.len() != BASE_HEADER_BYTES { + return Err(AofError::InvalidRecord( + "invalid embedded base header length", + )); + } + let size = u64::from_le_bytes(bytes[25..33].try_into().unwrap()); + if size < 8 { + return Err(AofError::InvalidRecord("embedded base is too short")); + } + Ok(Self { + checkpoint: Checkpoint { + generation: bytes[..16].try_into().unwrap(), + sequence: u64::from_le_bytes(bytes[17..25].try_into().unwrap()), + }, + size, + checksum: u32::from_le_bytes(bytes[33..37].try_into().unwrap()), + }) + } +} + +pub fn start( + path: PathBuf, + dispatch: Arc, + table: Arc, + vectors: &'static VectorIndexRegistry, +) -> io::Result> { + let (trigger, requests) = bounded(1); + let worker_dispatch = dispatch.clone(); + let worker = thread::Builder::new() + .name("kachedb-aof-rewrite".into()) + .spawn(move || { + while worker_dispatch.is_healthy() { + match requests.recv_timeout(Duration::from_millis(100)) { + Ok(()) => { + match rewrite(&path, &worker_dispatch, &table, vectors) { + Ok(()) => log::info!("BGREWRITEAOF: installed replacement at {path:?}"), + Err(error) => { + worker_dispatch.abort_rewrite(); + log::warn!("BGREWRITEAOF: rewrite stopped: {error}"); + } } + worker_dispatch.finish_rewrite(); } - Err(e) => { - log::error!("BGREWRITEAOF: rewrite failed: {e}"); - let _ = std::fs::remove_file(&tmp_path); - } - } - }) - .expect("failed to spawn bgrewriteaof thread"); - } - - fn execute_rewrite( - tmp_path: &Path, - table: &ShardedSwissTable, - now_sec: u32, - ) -> Result { - let mut file = OpenOptions::new() - .create(true) - .write(true) - .truncate(true) - .open(tmp_path)?; - - let ts = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_secs(); - - let mut count = 0; - let mut buf = Vec::with_capacity(64 * 1024); - - // Iterate through all table shards - for shard_idx in 0..table.shard_count() { - // Workers keep published slots alive until unlinking under the shard write lock. - let entries = unsafe { table.snapshot_shard_with_payloads(shard_idx, now_sec) }?; - for item in entries { - if !item.has_key { - return Err(AofError::MissingKeyBytes); - } - if item.value_type == VALUE_TYPE_HASH { - let frame_bytes = - encode_frame(AofOp::HSet, &item.key_bytes, &item.val_bytes, ts); - buf.extend_from_slice(&frame_bytes); - } else { - let frame_bytes = - encode_frame(AofOp::Set, &item.key_bytes, &item.val_bytes, ts); - buf.extend_from_slice(&frame_bytes); - } - if item.expire_at > 0 { - let expire_str = item.expire_at.to_string(); - let exp_frame = - encode_frame(AofOp::Expire, &item.key_bytes, expire_str.as_bytes(), ts); - buf.extend_from_slice(&exp_frame); - } - count += 1; - - if buf.len() >= 64 * 1024 { - file.write_all(&buf)?; - buf.clear(); + Err(RecvTimeoutError::Timeout) => {} + Err(RecvTimeoutError::Disconnected) => break, } } + })?; + dispatch.set_rewrite_trigger(trigger); + Ok(worker) +} + +fn rewrite( + path: &Path, + dispatch: &AofDispatch, + table: &ShardedSwissTable, + vectors: &VectorIndexRegistry, +) -> Result<(), Box> { + let cancelled = Arc::new(AtomicBool::new(false)); + let (view, sequence) = durability::with_commit_fence(|| { + let view = snapshot::capture_view(table, vectors, 0)?; + let sequence = dispatch.begin_rewrite(cancelled.clone())?; + Ok::<_, snapshot::SnapshotError>((view, sequence)) + })?; + let mut generation = [0; 16]; + crate::crypto::generate_random_bytes(&mut generation)?; + let checkpoint = Checkpoint { + generation, + sequence, + }; + let (temporary, replacement) = prepare(path, view, checkpoint, &cancelled)?; + let result = durability::with_commit_fence(|| dispatch.install_rewrite(replacement))?.recv()?; + drop(temporary); + if !result { + return Err("writer abandoned the replacement".into()); + } + Ok(()) +} + +struct Temporary(PathBuf); + +impl Drop for Temporary { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} + +fn prepare( + target: &Path, + view: snapshot::SnapshotView, + checkpoint: Checkpoint, + cancelled: &AtomicBool, +) -> Result<(Temporary, RewriteFile), Box> { + let mut suffix = [0; 8]; + crate::crypto::generate_random_bytes(&mut suffix)?; + let mut path = target.as_os_str().to_owned(); + path.push(format!(".rewrite-{:016x}.tmp", u64::from_le_bytes(suffix))); + let path = PathBuf::from(path); + let mut file = OpenOptions::new() + .read(true) + .write(true) + .create_new(true) + .mode(0o600) + .open(&path)?; + let temporary = Temporary(path.clone()); + file.try_lock().map_err(io::Error::from)?; + + let placeholder = BaseHeader { + checkpoint, + size: 0, + checksum: 0, + } + .encode(); + file.write_all(&placeholder)?; + let (size, checksum) = snapshot::write_rewrite_base( + &mut CancellableWrite { + file: &mut file, + cancelled, + }, + view, + )?; + file.rewind()?; + file.write_all( + &BaseHeader { + checkpoint, + size, + checksum, + } + .encode(), + )?; + file.seek(io::SeekFrom::End(0))?; + Ok(( + temporary, + RewriteFile { + file, + path, + checkpoint, + }, + )) +} + +struct CancellableWrite<'a> { + file: &'a mut File, + cancelled: &'a AtomicBool, +} + +impl Write for CancellableWrite<'_> { + fn write(&mut self, buf: &[u8]) -> io::Result { + if self.cancelled.load(Ordering::Acquire) { + return Err(io::Error::other( + "delta budget exceeded or AOF writer stopped", + )); + } + self.file.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.file.flush() + } +} + +pub struct Deltas { + pub sequence: u64, + records: Vec>, + bytes: usize, + limit: usize, + cancelled: Arc, +} + +impl Deltas { + pub fn new(sequence: u64, cancelled: Arc, limit: usize) -> Self { + Self { + sequence, + records: Vec::new(), + bytes: 0, + limit, + cancelled, } + } - if !buf.is_empty() { - file.write_all(&buf)?; - buf.clear(); + pub fn push(&mut self, record: Vec) -> bool { + if record.len() > self.limit - self.bytes || self.records.len() == DELTA_RECORDS { + return false; } + self.bytes += record.len(); + self.records.push(record); + true + } + + pub fn reaches(&self, sequence: u64) -> bool { + sequence.checked_sub(self.sequence) == Some(self.records.len() as u64) + } +} + +impl Drop for Deltas { + fn drop(&mut self) { + self.cancelled.store(true, Ordering::Release); + } +} + +pub enum InstallError { + BeforeRename(io::Error), + AfterRename(io::Error), +} - file.flush()?; - file.sync_all()?; - Ok(count) +pub fn install( + target: &Path, + active: &mut File, + replacement: RewriteFile, + deltas: &Deltas, + sync_directory: impl FnOnce(&File) -> io::Result<()>, +) -> Result<(), InstallError> { + install_with_rename( + target, + active, + replacement, + deltas, + |from, to| std::fs::rename(from, to), + sync_directory, + ) +} + +fn install_with_rename( + target: &Path, + active: &mut File, + mut replacement: RewriteFile, + deltas: &Deltas, + rename: impl FnOnce(&Path, &Path) -> io::Result<()>, + sync_directory: impl FnOnce(&File) -> io::Result<()>, +) -> Result<(), InstallError> { + let parent = target + .parent() + .filter(|path| !path.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + let directory = File::open(parent).map_err(InstallError::BeforeRename)?; + for record in &deltas.records { + replacement + .file + .write_all(record) + .map_err(InstallError::BeforeRename)?; } + replacement + .file + .sync_all() + .map_err(InstallError::BeforeRename)?; + rename(&replacement.path, target).map_err(InstallError::BeforeRename)?; + // Retain the new inode lock while syncing the rename. The writer never appends + // again if this final sync fails. + *active = replacement.file; + sync_directory(&directory).map_err(InstallError::AfterRename) } #[cfg(test)] mod tests { + use std::fs; + use std::os::unix::process::ExitStatusExt; + use std::process::Command; + + use crossbeam_channel::unbounded; + use kachedb_core::SlabPool; + use kachedb_hash::{VALUE_TYPE_STRING, hash_key}; + use kachedb_net::durability::{AppendFsync, WriterRequest}; + use super::*; - use crate::aof_recovery::replay; - use kachedb_core::{SlabClassType, SlabPool, resolve_slot_ptr}; - use kachedb_hash::{HashSlotFrame, VALUE_TYPE_STRING, hash_key}; + use crate::{ + aof::{AofWriter, WriterOptions}, + aof_recovery, + }; - #[test] - fn test_aof_rewrite_preserves_strings_hashes_and_ttl() { - let dir = std::env::temp_dir(); - let path = dir.join(format!( - "test_aof_rewrite_{}.kaof", - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos() - )); + const OLD: Checkpoint = Checkpoint { + generation: [1; 16], + sequence: 1, + }; + const NEW: Checkpoint = Checkpoint { + generation: [2; 16], + sequence: 1, + }; + + struct TestDirectory(PathBuf); + + impl TestDirectory { + fn new() -> Self { + let mut id = [0; 8]; + crate::crypto::generate_random_bytes(&mut id).unwrap(); + let path = std::env::temp_dir().join(format!( + "kachedb-rewrite-test-{:016x}", + u64::from_le_bytes(id), + )); + fs::create_dir(&path).unwrap(); + Self(path) + } + + fn journal(&self) -> PathBuf { + self.0.join("appendonly.aof") + } + } + + impl Drop for TestDirectory { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + fn put(key: &[u8], value: &[u8], deadline: u32) -> Vec { + let mut payload = vec![VALUE_TYPE_STRING]; + payload.extend_from_slice(&deadline.to_le_bytes()); + payload.extend_from_slice(value); + encode_checked_frame(AofOp::Put, key, &payload, 100) + } + + fn old_journal(path: &Path) -> File { + let mut file = crate::aof::open_locked(path, true).unwrap(); + let mut generation = OLD.generation.to_vec(); + generation.push(0); + file.write_all(&encode_checked_frame( + AofOp::Generation, + &[], + &generation, + 0, + )) + .unwrap(); + file.write_all(&put(b"key", b"base", 500)).unwrap(); + file.sync_all().unwrap(); + file + } + fn staged(path: &Path) -> (Temporary, RewriteFile) { + let table = ShardedSwissTable::new(); let mut pool = SlabPool::new(0, 4 * 1024 * 1024).unwrap(); + aof_recovery::restore_value( + &table, + &mut pool, + hash_key(b"key"), + b"key", + VALUE_TYPE_STRING, + b"base", + 500, + ) + .unwrap(); + let view = snapshot::capture_view(&table, &VectorIndexRegistry::new(), 0).unwrap(); + prepare(path, view, NEW, &AtomicBool::new(false)).unwrap() + } + + fn assert_recovery(path: &Path, checkpoint: Checkpoint, embedded: Option, value: &[u8]) { + let inspected = aof_recovery::inspect(path).unwrap(); + assert_eq!(inspected.generation, Some(checkpoint.generation)); + assert_eq!(inspected.embedded_base, embedded); + assert_eq!(inspected.sequence, checkpoint.sequence); let table = ShardedSwissTable::new(); + let mut pool = SlabPool::new(0, 4 * 1024 * 1024).unwrap(); + let replayed = + aof_recovery::replay_from(path, 0, &table, &mut pool, &VectorIndexRegistry::new()) + .unwrap(); + assert_eq!(replayed, inspected); + let actual = unsafe { + table.with_read_lock_entry(hash_key(b"key"), b"key", 100, |entry, value| { + (value.to_vec(), entry.expire_at_secs) + }) + }; + assert_eq!(actual, Some((value.to_vec(), 500))); + } + + #[test] + fn writer_installs_deltas_before_acknowledging_a_new_checkpoint() { + let directory = TestDirectory::new(); + let path = directory.journal(); + let mut old = old_journal(&path); + let (_temporary, replacement) = staged(&path); + let (dispatch, _) = AofDispatch::new(OLD, AppendFsync::Always); + let (send, receive) = unbounded(); + let (installed, result) = bounded(1); + let (synced, checkpoint) = bounded(1); + let (done, acknowledged) = bounded(1); + send.send(WriterRequest::BeginRewrite { + sequence: 1, + cancelled: Arc::new(AtomicBool::new(false)), + }) + .unwrap(); + let bytes = put(b"key", b"delta", 500); + let permit = dispatch.reserve(bytes.len()).unwrap(); + send.send(WriterRequest::Record { + bytes, + done: Some(done), + permit, + }) + .unwrap(); + send.send(WriterRequest::InstallRewrite { + replacement, + installed, + }) + .unwrap(); + send.send(WriterRequest::Sync(synced)).unwrap(); + send.send(WriterRequest::Stop).unwrap(); + + AofWriter::writer_loop( + &mut old, + &path, + WriterOptions { + policy: AppendFsync::Always, + delta_bytes: DELTA_BYTES, + }, + &receive, + &dispatch, + OLD, + File::sync_all, + ) + .unwrap(); + assert!(acknowledged.recv().is_ok()); + assert!(result.recv().unwrap()); + assert_eq!( + checkpoint.recv().unwrap(), + Checkpoint { sequence: 2, ..NEW } + ); + assert_recovery(&path, Checkpoint { sequence: 2, ..NEW }, Some(1), b"delta"); + } - // 1. Insert a string key with TTL = 500 - let str_key = b"session:token:abc"; - let str_val = b"jwt_payload_data"; - let str_block = pool.allocate(SlabClassType::AppSmall).unwrap(); - unsafe { - let ptr = resolve_slot_ptr(str_block).unwrap(); - std::ptr::copy_nonoverlapping(str_val.as_ptr(), ptr, str_val.len()); + #[test] + fn directory_sync_failure_after_rename_marks_persistence_unavailable() { + let directory = TestDirectory::new(); + let path = directory.journal(); + let mut old = old_journal(&path); + let (_temporary, replacement) = staged(&path); + let (dispatch, _) = AofDispatch::new(OLD, AppendFsync::Always); + let (send, receive) = unbounded(); + let (installed, result) = bounded(1); + send.send(WriterRequest::BeginRewrite { + sequence: 1, + cancelled: Arc::new(AtomicBool::new(false)), + }) + .unwrap(); + let bytes = put(b"key", b"delta", 500); + let permit = dispatch.reserve(bytes.len()).unwrap(); + send.send(WriterRequest::Record { + bytes, + done: None, + permit, + }) + .unwrap(); + send.send(WriterRequest::InstallRewrite { + replacement, + installed, + }) + .unwrap(); + let error = AofWriter::writer_loop( + &mut old, + &path, + WriterOptions { + policy: AppendFsync::Always, + delta_bytes: DELTA_BYTES, + }, + &receive, + &dispatch, + OLD, + |_| Err(io::Error::other("injected directory sync failure")), + ) + .unwrap_err(); + assert!(matches!(error, AofError::RewriteInstallUncertain(_))); + assert!(result.recv().is_err()); + assert!(matches!( + dispatch.reserve(1), + Err(durability::AdmissionError::Unavailable) + )); + assert_recovery(&path, Checkpoint { sequence: 2, ..NEW }, Some(1), b"delta"); + } + + #[test] + fn aborting_on_delta_exhaustion_preserves_the_active_journal() { + let directory = TestDirectory::new(); + let path = directory.journal(); + let mut old = old_journal(&path); + let (_temporary, replacement) = staged(&path); + let (dispatch, _) = AofDispatch::new(OLD, AppendFsync::No); + let (send, receive) = unbounded(); + let (installed, result) = bounded(1); + let cancelled = Arc::new(AtomicBool::new(false)); + send.send(WriterRequest::BeginRewrite { + sequence: 1, + cancelled: cancelled.clone(), + }) + .unwrap(); + + let records = [put(b"key", b"first", 500), put(b"key", b"overflow", 500)]; + let limit = records[0].len(); + for bytes in records { + let permit = dispatch.reserve(bytes.len()).unwrap(); + send.send(WriterRequest::Record { + bytes, + done: None, + permit, + }) + .unwrap(); } - table.insert_with_ttl_and_key( - hash_key(str_key), - str_key, - str_block, - str_val.len() as u32, - 500, + send.send(WriterRequest::InstallRewrite { + replacement, + installed, + }) + .unwrap(); + let bytes = put(b"key", b"after-abort", 500); + let permit = dispatch.reserve(bytes.len()).unwrap(); + send.send(WriterRequest::Record { + bytes, + done: None, + permit, + }) + .unwrap(); + send.send(WriterRequest::Stop).unwrap(); + + AofWriter::writer_loop( + &mut old, + &path, + WriterOptions { + policy: AppendFsync::No, + delta_bytes: limit, + }, + &receive, + &dispatch, + OLD, + File::sync_all, + ) + .unwrap(); + assert!(!result.recv().unwrap()); + assert!(cancelled.load(Ordering::Acquire)); + assert!(dispatch.is_healthy()); + assert_recovery( + &path, + Checkpoint { sequence: 4, ..OLD }, + None, + b"after-abort", ); + } - // 2. Insert a hash key (`VALUE_TYPE_HASH`) with 2 fields - let hash_key_bytes = b"user:profile:42"; - let hash_block = pool.allocate(SlabClassType::AppSmall).unwrap(); - let slot_bytes = SlabClassType::AppSmall.slot_bytes(); - unsafe { - let ptr = resolve_slot_ptr(hash_block).unwrap(); - let slot = std::slice::from_raw_parts_mut(ptr, slot_bytes); - HashSlotFrame::init(slot).unwrap(); - HashSlotFrame::upsert(slot, b"name", b"Bob").unwrap(); - HashSlotFrame::upsert(slot, b"role", b"staff").unwrap(); + #[test] + fn damaged_embedded_base_is_preserved_by_startup_and_repair() { + let directory = TestDirectory::new(); + let path = directory.journal(); + let mut active = old_journal(&path); + let (_temporary, replacement) = staged(&path); + let deltas = Deltas::new(1, Arc::new(AtomicBool::new(false)), DELTA_BYTES); + assert!(install(&path, &mut active, replacement, &deltas, File::sync_all).is_ok()); + drop(active); + let mut bytes = fs::read(&path).unwrap(); + bytes[kachedb_net::aof_encode::CHECKED_FRAME_OVERHEAD + BASE_HEADER_BYTES] ^= 1; + fs::write(&path, &bytes).unwrap(); + assert!(matches!( + aof_recovery::inspect(&path), + Err(AofError::InvalidBase(_)) + )); + assert!(matches!( + aof_recovery::repair(&path), + Err(AofError::InvalidBase(_)) + )); + assert_eq!(fs::read(&path).unwrap(), bytes); + } + + // Invoked in a child test process, so the simulated SIGKILL leaves actual + // on-disk files and exercises cleanup without running destructors. + #[test] + fn cutover_crash_child() { + let (Some(path), Ok(phase)) = ( + std::env::var_os("KACHEDB_TEST_REWRITE_PATH"), + std::env::var("KACHEDB_TEST_REWRITE_PHASE"), + ) else { + return; + }; + let path = PathBuf::from(path); + let mut active = old_journal(&path); + let (_temporary, replacement) = staged(&path); + let mut deltas = Deltas::new(1, Arc::new(AtomicBool::new(false)), DELTA_BYTES); + let delta = put(b"key", b"delta", 500); + active.write_all(&delta).unwrap(); + active.sync_all().unwrap(); + assert!(deltas.push(delta)); + let _ = install_with_rename( + &path, + &mut active, + replacement, + &deltas, + |from, to| { + if phase == "before-rename" { + kill_self(); + } + fs::rename(from, to) + }, + |directory| { + if phase == "before-directory-sync" { + kill_self(); + } + directory.sync_all()?; + kill_self() + }, + ); + panic!("expected crash at a cutover boundary"); + } + + fn kill_self() -> ! { + assert_eq!(unsafe { libc::kill(libc::getpid(), libc::SIGKILL) }, 0); + loop { + thread::park(); } - table.with_shard_mut(hash_key(hash_key_bytes), |shard| { - shard - .insert_typed_with_key( - hash_key(hash_key_bytes), - hash_key_bytes, - hash_block, - slot_bytes as u32, - 0, - VALUE_TYPE_HASH, - ) + } + + #[test] + fn crash_boundaries_leave_a_recoverable_authoritative_journal() { + for phase in [ + "before-rename", + "before-directory-sync", + "after-directory-sync", + ] { + let directory = TestDirectory::new(); + let path = directory.journal(); + let child = Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "aof_rewrite::tests::cutover_crash_child"]) + .env("KACHEDB_TEST_REWRITE_PATH", &path) + .env("KACHEDB_TEST_REWRITE_PHASE", phase) + .output() .unwrap(); - }); - - // 3. Execute rewrite at now_sec = 100 - let written = BgRewriteJob::execute_rewrite(&path, &table, 100).unwrap(); - assert_eq!(written, 2); - - // 4. Replay into a fresh table - let recovered_table = Arc::new(ShardedSwissTable::new()); - let vectors = VectorIndexRegistry::new(); - let frames = replay(&path, &recovered_table, &mut pool, &vectors).unwrap(); - // 1 Set + 1 Expire + 1 HSet = 3 frames - assert_eq!(frames, 3); - - // Verify string key + TTL - let str_entry = recovered_table - .lookup_checked(hash_key(str_key), 100) - .expect("string key recovered"); - assert_eq!(str_entry.value_type, VALUE_TYPE_STRING); - assert_eq!(str_entry.expire_at_secs, 500); - - // Verify hash key + VALUE_TYPE_HASH + fields - let hash_entry = recovered_table - .lookup_checked(hash_key(hash_key_bytes), 100) - .expect("hash key recovered"); - assert_eq!(hash_entry.value_type, VALUE_TYPE_HASH); - unsafe { - let ptr = resolve_slot_ptr(hash_entry.slab_block_id).unwrap(); - let slot = std::slice::from_raw_parts(ptr, hash_entry.value_len as usize); - assert_eq!(HashSlotFrame::get(slot, b"name"), Some(&b"Bob"[..])); - assert_eq!(HashSlotFrame::get(slot, b"role"), Some(&b"staff"[..])); + assert_eq!( + child.status.signal(), + Some(libc::SIGKILL), + "{phase}: {:?}", + child + ); + if phase == "before-rename" { + assert_recovery(&path, Checkpoint { sequence: 2, ..OLD }, None, b"delta"); + } else { + assert_recovery(&path, Checkpoint { sequence: 2, ..NEW }, Some(1), b"delta"); + } } - - // Verify both keys are visible to SCAN (key_len > 0) - assert_eq!(recovered_table.anonymous_key_count(), 0); - - let _ = std::fs::remove_file(&path); } } diff --git a/crates/kachedb-server/src/snapshot.rs b/crates/kachedb-server/src/snapshot.rs index f26ffd2..6d8df53 100644 --- a/crates/kachedb-server/src/snapshot.rs +++ b/crates/kachedb-server/src/snapshot.rs @@ -32,7 +32,7 @@ //! - Checksum Trailer: `crc32: u32` (4 bytes, IEEE 802.3 CRC32 over all preceding bytes) use std::fs::{File, OpenOptions}; -use std::io::{Read, Write}; +use std::io::{Read, Take, Write}; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; @@ -41,9 +41,11 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; use crc32fast::Hasher; use kachedb_core::pool::SlotAllocator; -use kachedb_hash::{ShardedSwissTable, hash_key}; +use kachedb_hash::{ShardedSwissTable, SnapshotPayloadEntry, hash_key}; use kachedb_net::durability::{self, Checkpoint}; -use kachedb_vector::{VectorEntry, VectorIndexRegistry, index::FlatVectorSnapshot}; +use kachedb_vector::{ + HnswIndex, VectorEntry, VectorIndexRegistry, hnsw::HnswGraph, index::FlatVectorSnapshot, +}; use thiserror::Error; use crate::crypto::{ @@ -153,7 +155,7 @@ pub struct SnapshotStats { /// Internal streaming payload writer supporting transparent chunked AEAD encryption. enum PayloadWriter<'a> { Plain { - file: &'a mut File, + file: &'a mut dyn Write, hasher: &'a mut Hasher, buf: Vec, total_bytes: &'a mut usize, @@ -278,6 +280,39 @@ impl Drop for SnapshotTempFile { } } +pub struct SnapshotView { + flat: Vec, + graphs: Vec<(Vec, Arc, HnswGraph)>, + keys: Vec, +} + +/// Copies owned data while the caller holds the commit fence. +pub fn capture_view( + table: &ShardedSwissTable, + vectors: &VectorIndexRegistry, + now: u32, +) -> Result { + let flat = vectors.snapshot_flat_slots(now); + let graphs = vectors + .hnsw_indexes() + .into_iter() + .map(|(name, index)| { + let graph = index.snapshot_graph(); + (name, index, graph) + }) + .collect(); + let mut keys = Vec::new(); + for shard in 0..table.shard_count() { + // Workers keep published slots alive until unlinking under the shard write lock. + let entries = unsafe { table.snapshot_shard_with_payloads(shard, now) }?; + if entries.iter().any(|entry| !entry.has_key) { + return Err(SnapshotError::MissingKeyBytes); + } + keys.extend(entries); + } + Ok(SnapshotView { flat, graphs, keys }) +} + /// Writes an atomic, point-in-time binary snapshot of all vector indexes and SwissTable keys. pub fn save_snapshot( target_path: &Path, @@ -286,42 +321,17 @@ pub fn save_snapshot( now_sec: u32, encryption: Option<&SnapshotEncryptionConfig>, ) -> Result { - let (flat, graphs, kv_items, checkpoint) = durability::with_commit_fence(|| { - let capture_at = if durability::dispatch().is_some() { - 0 - } else { - now_sec - }; - let flat = vectors.snapshot_flat_slots(capture_at); - let graphs: Vec<_> = vectors - .hnsw_indexes() - .into_iter() - .map(|(name, index)| { - let graph = index.snapshot_graph(); - (name, index, graph) - }) - .collect(); - - let mut items = Vec::new(); - for shard in 0..table.shard_count() { - // Workers keep published slots alive until unlinking under the shard write lock. - let entries = unsafe { table.snapshot_shard_with_payloads(shard, capture_at) }?; - if entries.iter().any(|entry| !entry.has_key) { - return Err(SnapshotError::MissingKeyBytes); - } - items.extend(entries); - } - let checkpoint = durability::dispatch() - .map(|writer| writer.checkpoint()) - .transpose()?; - Ok::<_, SnapshotError>((flat, graphs, items, checkpoint)) + let (view, checkpoint) = durability::with_commit_fence(|| { + let dispatch = durability::dispatch(); + let view = capture_view(table, vectors, if dispatch.is_some() { 0 } else { now_sec })?; + let checkpoint = dispatch.map(|writer| writer.checkpoint()).transpose()?; + Ok::<_, SnapshotError>((view, checkpoint)) })?; let checkpoint = checkpoint - .map(|(checkpoint, synced)| { + .map(|synced| { synced .recv() - .map_err(|_| crate::aof::AofError::WriterStopped)?; - Ok::<_, SnapshotError>(checkpoint) + .map_err(|_| crate::aof::AofError::WriterStopped) }) .transpose()?; @@ -394,6 +404,61 @@ pub fn save_snapshot( writer.write_bytes(&checkpoint.sequence.to_le_bytes())?; } + let (vector_indexes, total_vectors, total_kv_entries) = write_view(&mut writer, view)?; + + // 4. Finish payload writer + writer.finish()?; + + // 5. Checksum Trailer + let checksum = hasher.finalize(); + file.write_all(&checksum.to_le_bytes())?; + total_bytes += 4; + + file.flush()?; + file.sync_all()?; + drop(file); + + // 6. Atomic Rename Swap + std::fs::rename(&temporary.path, target_path)?; + let parent = target_path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + File::open(parent)?.sync_all()?; + + Ok(SnapshotStats { + timestamp_sec: ts, + vector_indexes, + total_vectors, + total_kv_entries, + bytes_written: total_bytes, + checkpoint, + }) +} + +/// Writes the V7 snapshot payload without its external checkpoint or file wrapper. +pub fn write_rewrite_base( + output: &mut dyn Write, + view: SnapshotView, +) -> Result<(u64, u32), SnapshotError> { + let mut checksum = Hasher::new(); + let mut size = 0; + let mut writer = PayloadWriter::Plain { + file: output, + hasher: &mut checksum, + buf: Vec::with_capacity(128 * 1024), + total_bytes: &mut size, + }; + write_view(&mut writer, view)?; + writer.finish()?; + Ok((size as u64, checksum.finalize())) +} + +fn write_view( + writer: &mut PayloadWriter<'_>, + view: SnapshotView, +) -> Result<(usize, usize, usize), SnapshotError> { + let SnapshotView { flat, graphs, keys } = view; // 2. Vector Indexes Section let num_indexes = u32::try_from(flat.len() + graphs.len()) .map_err(|_| SnapshotError::Invalid("too many indexes"))?; @@ -402,7 +467,7 @@ pub fn save_snapshot( let mut total_vectors = 0; for (name, index, graph) in graphs { writer.write_bytes(&[1])?; - total_vectors += hnsw::write_index(&mut writer, &name, &index, &graph)?; + total_vectors += hnsw::write_index(writer, &name, &index, &graph)?; } for FlatVectorSnapshot { name, @@ -464,10 +529,10 @@ pub fn save_snapshot( // 3. KV SwissTable Section let num_kv_entries = - u32::try_from(kv_items.len()).map_err(|_| SnapshotError::Invalid("too many KV entries"))?; + u32::try_from(keys.len()).map_err(|_| SnapshotError::Invalid("too many KV entries"))?; writer.write_bytes(&num_kv_entries.to_le_bytes())?; - for item in kv_items { + for item in keys { writer.write_bytes(&item.key_hash.to_le_bytes())?; let key_len = item.key_bytes.len() as u16; writer.write_bytes(&key_len.to_le_bytes())?; @@ -479,34 +544,7 @@ pub fn save_snapshot( writer.write_bytes(&item.expire_at.to_le_bytes())?; } - // 4. Finish payload writer - writer.finish()?; - - // 5. Checksum Trailer - let checksum = hasher.finalize(); - file.write_all(&checksum.to_le_bytes())?; - total_bytes += 4; - - file.flush()?; - file.sync_all()?; - drop(file); - - // 6. Atomic Rename Swap - std::fs::rename(&temporary.path, target_path)?; - let parent = target_path - .parent() - .filter(|parent| !parent.as_os_str().is_empty()) - .unwrap_or(Path::new(".")); - File::open(parent)?.sync_all()?; - - Ok(SnapshotStats { - timestamp_sec: ts, - vector_indexes: num_indexes as usize, - total_vectors, - total_kv_entries: num_kv_entries as usize, - bytes_written: total_bytes, - checkpoint, - }) + Ok((num_indexes as usize, total_vectors, num_kv_entries as usize)) } /// Hydrates in-memory vector indexes and SwissTable keys from `dump.kdb`. @@ -694,17 +732,131 @@ fn read_checkpoint(payload: &[u8]) -> Result<(Option, &[u8]), Snapsh } } -fn read_presence(payload: &[u8], cursor: &mut usize) -> Result { - let flag = payload.get(*cursor).ok_or(SnapshotError::UnexpectedEof)?; - *cursor += 1; - match flag { - 0 => Ok(false), - 1 => Ok(true), - _ => Err(SnapshotError::Invalid("invalid snapshot presence flag")), +/// Reads a bounded payload from either a standalone snapshot or an embedded AOF base. +pub(super) struct PayloadReader { + input: Take, +} + +impl PayloadReader { + fn new(input: R, size: u64) -> Self { + Self { + input: input.take(size), + } + } + + fn remaining(&self) -> u64 { + self.input.limit() + } + + fn fill(&mut self, bytes: &mut [u8]) -> Result<(), SnapshotError> { + self.input.read_exact(bytes).map_err(|error| { + if error.kind() == std::io::ErrorKind::UnexpectedEof { + SnapshotError::UnexpectedEof + } else { + error.into() + } + }) + } + + fn array(&mut self) -> Result<[u8; N], SnapshotError> { + let mut bytes = [0; N]; + self.fill(&mut bytes)?; + Ok(bytes) + } + + fn bytes(&mut self, size: usize) -> Result, SnapshotError> { + self.check_remaining(size)?; + let mut value = Vec::new(); + value + .try_reserve_exact(size) + .map_err(|_| SnapshotError::Invalid("cannot reserve snapshot entry"))?; + value.resize(size, 0); + self.fill(&mut value)?; + Ok(value) + } + + fn check_remaining(&self, size: usize) -> Result<(), SnapshotError> { + if size as u64 > self.remaining() { + return Err(SnapshotError::UnexpectedEof); + } + Ok(()) + } + + fn byte(&mut self) -> Result { + Ok(self.array::<1>()?[0]) + } + + fn present(&mut self) -> Result { + match self.byte()? { + 0 => Ok(false), + 1 => Ok(true), + _ => Err(SnapshotError::Invalid("invalid snapshot presence flag")), + } + } + + fn u32(&mut self) -> Result { + Ok(u32::from_le_bytes(self.array()?)) + } + + fn key(&mut self) -> Result, SnapshotError> { + let len = usize::from(u16::from_le_bytes(self.array()?)); + self.bytes(len) + } + + fn payload(&mut self) -> Result>, SnapshotError> { + if !self.present()? { + return Ok(None); + } + let size = self.u32()? as usize; + self.bytes(size).map(Some) + } + + fn param(&mut self) -> Result { + usize::try_from(u64::from_le_bytes(self.array()?)) + .map_err(|_| SnapshotError::Invalid("HNSW parameter out of range")) + } + + fn count(&mut self, min_size: usize) -> Result { + let count = self.u32()? as usize; + if count as u64 > self.remaining() / min_size as u64 { + return Err(SnapshotError::UnexpectedEof); + } + Ok(count) + } + + fn node_id(&mut self, count: usize) -> Result { + let id = self.u32()?; + if id as usize >= count { + return Err(SnapshotError::Invalid("invalid HNSW node ID")); + } + Ok(id) + } + + fn floats( + &mut self, + dim: usize, + decode: fn([u8; 4]) -> f32, + ) -> Result, SnapshotError> { + let size = dim + .checked_mul(4) + .ok_or(SnapshotError::Invalid("vector dimension out of range"))?; + self.check_remaining(size)?; + let mut vector = Vec::new(); + vector + .try_reserve_exact(dim) + .map_err(|_| SnapshotError::Invalid("cannot reserve snapshot vector"))?; + let mut chunk = [0; 4096]; + let mut remaining = size; + while remaining != 0 { + let size = remaining.min(chunk.len()); + self.fill(&mut chunk[..size])?; + vector.extend(chunk[..size].as_chunks::<4>().0.iter().copied().map(decode)); + remaining -= size; + } + Ok(vector) } } -/// Helper function to hydrate vector indexes and SwissTable keys from an unencrypted payload byte slice. fn hydrate_payload( payload: &[u8], version: u8, @@ -712,287 +864,134 @@ fn hydrate_payload( pool: &mut impl SlotAllocator, vectors: &VectorIndexRegistry, ) -> Result<(usize, usize, usize), SnapshotError> { - let mut cursor = 0; - let content_len = payload.len(); + hydrate_view( + PayloadReader::new(payload, payload.len() as u64), + version, + table, + pool, + vectors, + ) +} - // 1. Vector Section - if cursor + 4 > content_len { - return Err(SnapshotError::UnexpectedEof); - } - let num_indexes = u32::from_le_bytes([ - payload[cursor], - payload[cursor + 1], - payload[cursor + 2], - payload[cursor + 3], - ]) as usize; - cursor += 4; +pub fn hydrate_rewrite_base( + input: &mut dyn Read, + size: u64, + table: &ShardedSwissTable, + pool: &mut impl SlotAllocator, + vectors: &VectorIndexRegistry, +) -> Result<(), SnapshotError> { + hydrate_view(PayloadReader::new(input, size), 7, table, pool, vectors)?; + Ok(()) +} +fn hydrate_view( + mut reader: PayloadReader, + version: u8, + table: &ShardedSwissTable, + pool: &mut impl SlotAllocator, + vectors: &VectorIndexRegistry, +) -> Result<(usize, usize, usize), SnapshotError> { + let num_indexes = reader.count(if version >= 7 { 11 } else { 10 })?; let mut total_vectors = 0; for _ in 0..num_indexes { if version >= 7 { - let kind = payload.get(cursor).ok_or(SnapshotError::UnexpectedEof)?; - cursor += 1; - match kind { + match reader.byte()? { 0 => {} 1 => { - let (remaining, count) = hnsw::read_index(&payload[cursor..], vectors)?; - cursor = content_len - remaining.len(); - total_vectors += count; + total_vectors += hnsw::read_index(&mut reader, vectors)?; continue; } _ => return Err(SnapshotError::Invalid("unknown vector index kind")), } } - if cursor + 10 > content_len { - return Err(SnapshotError::UnexpectedEof); - } - let name_len = u16::from_le_bytes([payload[cursor], payload[cursor + 1]]) as usize; - cursor += 2; - if cursor + name_len + 8 > content_len { - return Err(SnapshotError::UnexpectedEof); - } - let name = payload[cursor..cursor + name_len].to_vec(); - cursor += name_len; - - let dim = u32::from_le_bytes([ - payload[cursor], - payload[cursor + 1], - payload[cursor + 2], - payload[cursor + 3], - ]) as usize; - cursor += 4; - - let num_entries = u32::from_le_bytes([ - payload[cursor], - payload[cursor + 1], - payload[cursor + 2], - payload[cursor + 3], - ]) as usize; - cursor += 4; - - let min_slot_size = if version >= 7 { 1 } else { 20 }; - if num_entries > (content_len - cursor) / min_slot_size { - return Err(SnapshotError::UnexpectedEof); - } + let name = reader.key()?; + let dim = reader.u32()? as usize; + let num_entries = reader.count(if version >= 7 { 1 } else { 20 })?; let mut slots = Vec::new(); slots .try_reserve_exact(num_entries) .map_err(|_| SnapshotError::Invalid("cannot reserve flat vector slots"))?; for _ in 0..num_entries { - if version >= 7 { - let flag = read_presence(payload, &mut cursor)?; - if !flag { - slots.push(None); - continue; - } - } - if cursor + 6 > content_len { - return Err(SnapshotError::UnexpectedEof); + if version >= 7 && !reader.present()? { + slots.push(None); + continue; } - let key_len = u16::from_le_bytes([payload[cursor], payload[cursor + 1]]) as usize; - cursor += 2; - if cursor + key_len + 4 > content_len { - return Err(SnapshotError::UnexpectedEof); + let key = reader.key()?; + if key.is_empty() || dim == 0 { + return Err(SnapshotError::Invalid("empty flat vector key or dimension")); } - let key = payload[cursor..cursor + key_len].to_vec(); - cursor += key_len; - - let entry_dim = u32::from_le_bytes([ - payload[cursor], - payload[cursor + 1], - payload[cursor + 2], - payload[cursor + 3], - ]) as usize; - cursor += 4; - - if entry_dim != dim { + if reader.u32()? as usize != dim { return Err(SnapshotError::Invalid("vector has the wrong dimension")); } - let vec_bytes_len = entry_dim * 4; - if cursor + vec_bytes_len + 1 > content_len { - return Err(SnapshotError::UnexpectedEof); - } let decode = if version >= 7 { f32::from_le_bytes } else { f32::from_ne_bytes }; - let vector = payload[cursor..cursor + vec_bytes_len] - .as_chunks::<4>() - .0 - .iter() - .copied() - .map(decode) - .collect(); - cursor += vec_bytes_len; - - let p_opt = if read_presence(payload, &mut cursor)? { - if cursor + 4 > content_len { - return Err(SnapshotError::UnexpectedEof); - } - let p_len = u32::from_le_bytes([ - payload[cursor], - payload[cursor + 1], - payload[cursor + 2], - payload[cursor + 3], - ]) as usize; - cursor += 4; - if cursor + p_len > content_len { - return Err(SnapshotError::UnexpectedEof); - } - let p = payload[cursor..cursor + p_len].to_vec(); - cursor += p_len; - Some(p) - } else { - None - }; - - if cursor + 13 > content_len { - return Err(SnapshotError::UnexpectedEof); - } - let expire_at_secs = u32::from_le_bytes([ - payload[cursor], - payload[cursor + 1], - payload[cursor + 2], - payload[cursor + 3], - ]); - cursor += 4; - - let tag_mask = u64::from_le_bytes([ - payload[cursor], - payload[cursor + 1], - payload[cursor + 2], - payload[cursor + 3], - payload[cursor + 4], - payload[cursor + 5], - payload[cursor + 6], - payload[cursor + 7], - ]); - cursor += 8; - - let parent_key = if read_presence(payload, &mut cursor)? { - if cursor + 2 > content_len { - return Err(SnapshotError::UnexpectedEof); - } - let pk_len = u16::from_le_bytes([payload[cursor], payload[cursor + 1]]) as usize; - cursor += 2; - if cursor + pk_len > content_len { - return Err(SnapshotError::UnexpectedEof); - } - let pk = payload[cursor..cursor + pk_len].to_vec(); - cursor += pk_len; - Some(pk) + let vector = reader.floats(dim, decode)?; + let payload = reader.payload()?; + let expire_at_secs = reader.u32()?; + let tag_mask = u64::from_le_bytes(reader.array()?); + let parent_key = if reader.present()? { + Some(reader.key()?) } else { None }; - - if key.is_empty() || dim == 0 { - return Err(SnapshotError::Invalid("empty flat vector key or dimension")); - } slots.push(Some(VectorEntry { key, vector, - payload: p_opt, + payload, expire_at_secs, tag_mask, parent_key, })); total_vectors += 1; } - - let dimension = (dim != 0).then_some(dim); if !vectors.restore_flat_slots(FlatVectorSnapshot { name, - dimension, + dimension: (dim != 0).then_some(dim), slots, }) { return Err(SnapshotError::Invalid("duplicate flat index or key")); } } - // 2. Hydrate SwissTable KV Section - let mut total_kv = 0; - if cursor + 4 <= content_len { - let num_kv = u32::from_le_bytes([ - payload[cursor], - payload[cursor + 1], - payload[cursor + 2], - payload[cursor + 3], - ]) as usize; - cursor += 4; - - if version < 5 && num_kv > 0 { + let total_kv = if version < 7 && reader.remaining() == 0 { + 0 + } else { + let count = reader.u32()? as usize; + if version < 5 && count > 0 { return Err(SnapshotError::MissingKeyBytes); } - for _ in 0..num_kv { - if cursor + 8 + 2 > content_len { - return Err(SnapshotError::UnexpectedEof); - } - let key_hash = u64::from_le_bytes([ - payload[cursor], - payload[cursor + 1], - payload[cursor + 2], - payload[cursor + 3], - payload[cursor + 4], - payload[cursor + 5], - payload[cursor + 6], - payload[cursor + 7], - ]); - cursor += 8; - - let key_len = u16::from_le_bytes([payload[cursor], payload[cursor + 1]]) as usize; - cursor += 2; - if cursor + key_len + 1 + 4 > content_len { - return Err(SnapshotError::UnexpectedEof); - } - let key_bytes = &payload[cursor..cursor + key_len]; - cursor += key_len; + for _ in 0..count { + let key_hash = u64::from_le_bytes(reader.array()?); + let key = reader.key()?; if version == 5 { - if key_bytes.is_empty() { + if key.is_empty() { return Err(SnapshotError::MissingKeyBytes); } - if hash_key(key_bytes) != key_hash { + if hash_key(&key) != key_hash { return Err(SnapshotError::LegacyKeyDigestMismatch); } } - - let value_type = payload[cursor]; - cursor += 1; - - let val_len = u32::from_le_bytes([ - payload[cursor], - payload[cursor + 1], - payload[cursor + 2], - payload[cursor + 3], - ]) as usize; - cursor += 4; - - if cursor + val_len + 4 > content_len { - return Err(SnapshotError::UnexpectedEof); + let value_type = reader.byte()?; + let len = reader.u32()? as usize; + if kachedb_core::SlabClassType::for_size(len).is_none() { + return Err(SnapshotError::Invalid( + "KV value exceeds the largest slab slot", + )); } - let val_bytes = &payload[cursor..cursor + val_len]; - cursor += val_len; - - let expire_at = u32::from_le_bytes([ - payload[cursor], - payload[cursor + 1], - payload[cursor + 2], - payload[cursor + 3], - ]); - cursor += 4; - + let value = reader.bytes(len)?; + let deadline = reader.u32()?; crate::aof_recovery::restore_value( - table, pool, key_hash, key_bytes, value_type, val_bytes, expire_at, + table, pool, key_hash, &key, value_type, &value, deadline, )?; - total_kv += 1; } - } else if version >= 7 { - return Err(SnapshotError::UnexpectedEof); - } - if cursor != content_len { + count + }; + if reader.remaining() != 0 { return Err(SnapshotError::Invalid("trailing snapshot bytes")); } - Ok((num_indexes, total_vectors, total_kv)) } diff --git a/crates/kachedb-server/src/snapshot_hnsw.rs b/crates/kachedb-server/src/snapshot_hnsw.rs index 41327ba..170eda0 100644 --- a/crates/kachedb-server/src/snapshot_hnsw.rs +++ b/crates/kachedb-server/src/snapshot_hnsw.rs @@ -1,11 +1,12 @@ //! Snapshot encoding for HNSW parameters, stored vectors and graph topology. use std::collections::HashSet; +use std::io::Read; use kachedb_vector::hnsw::{HnswGraph, HnswNode}; use kachedb_vector::{HnswIndex, QuantizationMode, VectorIndexRegistry, VectorMetric}; -use super::{PayloadWriter, SnapshotError}; +use super::{PayloadReader, PayloadWriter, SnapshotError}; pub(super) fn write_index( writer: &mut PayloadWriter<'_>, @@ -86,11 +87,10 @@ fn write_key(writer: &mut PayloadWriter<'_>, key: &[u8]) -> Result<(), SnapshotE writer.write_bytes(key) } -pub(super) fn read_index<'a>( - bytes: &'a [u8], +pub(super) fn read_index( + cursor: &mut PayloadReader, vectors: &VectorIndexRegistry, -) -> Result<(&'a [u8], usize), SnapshotError> { - let mut cursor = Cursor(bytes); +) -> Result { let name = cursor.key()?; let dim = cursor.u32()? as usize; let m = cursor.param()?; @@ -124,7 +124,7 @@ pub(super) fn read_index<'a>( .map_err(|_| SnapshotError::Invalid("cannot reserve HNSW nodes"))?; for id in 0..node_count { let node = if cursor.present()? { - Some(read_node(&mut cursor, id as u32, dim, quantization)?) + Some(read_node(cursor, id as u32, dim, quantization)?) } else { None }; @@ -164,11 +164,11 @@ pub(super) fn read_index<'a>( layers.push(layer); } - if vectors.has_hnsw(name) { + if vectors.has_hnsw(&name) { return Err(SnapshotError::Invalid("duplicate HNSW index name")); } let index = vectors.create_hnsw( - name, + &name, dim, m, ef_construction, @@ -185,11 +185,11 @@ pub(super) fn read_index<'a>( }) { return Err(SnapshotError::Invalid("duplicate HNSW vector key")); } - Ok((cursor.0, restored)) + Ok(restored) } fn read_node( - cursor: &mut Cursor<'_>, + cursor: &mut PayloadReader, id: u32, dim: usize, quantization: QuantizationMode, @@ -200,37 +200,19 @@ fn read_node( } let expire_at_secs = cursor.u32()?; let max_layer = usize::from(cursor.byte()?); - let payload = if cursor.present()? { - let size = cursor.u32()? as usize; - Some(cursor.take(size)?.to_vec()) - } else { - None - }; + let payload = cursor.payload()?; let (vector_fp32, vector_sq8) = match quantization { - QuantizationMode::None => { - let len = dim - .checked_mul(4) - .ok_or(SnapshotError::Invalid("HNSW dimension out of range"))?; - let vector = cursor - .take(len)? - .as_chunks::<4>() - .0 - .iter() - .copied() - .map(f32::from_le_bytes) - .collect(); - (Some(vector), None) - } + QuantizationMode::None => (Some(cursor.floats(dim, f32::from_le_bytes)?), None), QuantizationMode::SQ8 => { let min = f32::from_le_bytes(cursor.array()?); let max = f32::from_le_bytes(cursor.array()?); - let bytes = cursor.take(dim)?.to_vec(); + let bytes = cursor.bytes(dim)?; (None, Some((bytes, min, max))) } }; Ok(HnswNode { id, - key: key.to_vec(), + key, vector_fp32, vector_sq8, payload, @@ -238,62 +220,3 @@ fn read_node( max_layer, }) } - -struct Cursor<'a>(&'a [u8]); - -impl<'a> Cursor<'a> { - fn take(&mut self, size: usize) -> Result<&'a [u8], SnapshotError> { - let (bytes, remainder) = self - .0 - .split_at_checked(size) - .ok_or(SnapshotError::UnexpectedEof)?; - self.0 = remainder; - Ok(bytes) - } - - fn array(&mut self) -> Result<[u8; N], SnapshotError> { - Ok(self.take(N)?.try_into().unwrap()) - } - - fn byte(&mut self) -> Result { - Ok(self.take(1)?[0]) - } - - fn present(&mut self) -> Result { - match self.byte()? { - 0 => Ok(false), - 1 => Ok(true), - _ => Err(SnapshotError::Invalid("invalid HNSW presence flag")), - } - } - - fn u32(&mut self) -> Result { - Ok(u32::from_le_bytes(self.array()?)) - } - - fn key(&mut self) -> Result<&'a [u8], SnapshotError> { - let len = usize::from(u16::from_le_bytes(self.array()?)); - self.take(len) - } - - fn param(&mut self) -> Result { - usize::try_from(u64::from_le_bytes(self.array()?)) - .map_err(|_| SnapshotError::Invalid("HNSW parameter out of range")) - } - - fn count(&mut self, min_size: usize) -> Result { - let count = self.u32()? as usize; - if count > self.0.len() / min_size { - return Err(SnapshotError::UnexpectedEof); - } - Ok(count) - } - - fn node_id(&mut self, count: usize) -> Result { - let id = self.u32()?; - if id as usize >= count { - return Err(SnapshotError::Invalid("invalid HNSW node ID")); - } - Ok(id) - } -} diff --git a/crates/kachedb-server/src/storage.rs b/crates/kachedb-server/src/storage.rs index 224240c..5addb15 100644 --- a/crates/kachedb-server/src/storage.rs +++ b/crates/kachedb-server/src/storage.rs @@ -3,6 +3,7 @@ use std::error::Error; use std::io::ErrorKind; use std::os::unix::fs::MetadataExt; +use std::sync::Arc; use std::time::{SystemTime, UNIX_EPOCH}; use kachedb_hash::ShardedSwissTable; @@ -17,8 +18,8 @@ use crate::snapshot::{self, SnapshotEncryptionConfig}; pub fn start( config: &ServerConfig, - table: &ShardedSwissTable, - vectors: &VectorIndexRegistry, + table: &Arc, + vectors: &'static VectorIndexRegistry, encryption: &SnapshotEncryptionConfig, ) -> Result<(RecoveryPools, Option), Box> { let bytes = config @@ -57,7 +58,9 @@ pub fn start( } let log = aof_recovery::inspect(&config.aof_path)?; - let snapshot = if config.snapshot_enabled { + // A rewritten journal carries its own authoritative base, including when + // the external snapshot still belongs to the generation before the rename. + let snapshot = if config.snapshot_enabled && log.embedded_base.is_none() { snapshot::load_snapshot_for_recovery( &config.snapshot_path, table, @@ -74,7 +77,9 @@ pub fn start( } let base = snapshot.as_ref().and_then(|stats| stats.checkpoint); let promote_snapshot = snapshot.is_some() && base.is_none(); - let after_sequence = base.map_or(0, |checkpoint| checkpoint.sequence); + let after_sequence = base.map_or(log.embedded_base.unwrap_or(0), |checkpoint| { + checkpoint.sequence + }); let replayed = aof_recovery::replay_from(&config.aof_path, after_sequence, table, &mut pools, vectors)?; @@ -108,6 +113,7 @@ pub fn start( checkpoint, initialize, )?; + writer.enable_rewrite(config.aof_path.clone(), table.clone(), vectors)?; durability::set_dispatch(writer.dispatch()); // Persist the new pairing before admitting a single mutation against a snapshot base. if promote_snapshot diff --git a/crates/kachedb-server/tests/durability.rs b/crates/kachedb-server/tests/durability.rs index fab4631..d4a37fc 100644 --- a/crates/kachedb-server/tests/durability.rs +++ b/crates/kachedb-server/tests/durability.rs @@ -436,3 +436,128 @@ fn invalid_persistence_sources_fail_before_startup() { assert!(String::from_utf8_lossy(&failure.stderr).contains("checksum mismatch")); assert_eq!(fs::read(&journal).unwrap(), bad_frame); } + +#[test] +fn background_rewrite_preserves_live_writes_and_recovers_with_an_old_snapshot() { + use std::os::unix::fs::MetadataExt; + + let store = Store::new("background-rewrite"); + let snapshot = store.0.join("snapshot.kdb"); + let journal = store.0.join("journal.kaof"); + let port = free_port(); + let (mut server, mut client) = Running::start(&mut store.server(port, true), port); + let ok = Reply::Simple("OK".into()); + let vector = [1.0_f32.to_ne_bytes(), 0.0_f32.to_ne_bytes()].concat(); + assert_eq!( + client.request(&[b"SET", b"ttl", b"preserved", b"EX", b"300"]), + ok + ); + assert_eq!( + client.request(&[b"HSET", b"hash", b"field", b"value"]), + Reply::Count(1) + ); + assert_eq!( + client.request(&[ + b"VINDEX", + b"CREATE", + b"ann", + b"DIM", + b"2", + b"QUANTIZATION", + b"SQ8" + ]), + ok + ); + assert_eq!( + client.request(&[b"VADD", b"ann", b"root", b"2", &vector, b"PAYLOAD", b"data"]), + Reply::Count(1) + ); + assert_eq!( + client.request(&[ + b"VADD", b"flat", b"root", b"2", &vector, b"TAGS", b"7", b"PARENT", b"doc" + ]), + Reply::Count(1) + ); + let ann = client.request(&[b"VSEARCH", b"ann", &vector]); + let flat = client.request(&[b"VSEARCH", b"flat", &vector, b"FILTER", b"7"]); + assert!(matches!(ann, Reply::List(ref rows) if rows.len() == 1)); + assert!(matches!(flat, Reply::List(ref rows) if rows.len() == 1)); + drop(client); + assert!(server.exit(libc::SIGTERM).success()); + let old_snapshot = fs::read(&snapshot).unwrap(); + + let port = free_port(); + let (mut server, mut client) = Running::start(&mut store.server(port, true), port); + let value = [b'x'; 4096]; + for _ in 0..64 { + assert_eq!(client.request(&[b"SET", b"churn", &value]), ok); + } + let before = fs::metadata(&journal).unwrap(); + let mut concurrent_client = Client::connect(port).unwrap(); + thread::scope(|scope| { + let writer = scope.spawn(move || { + for n in 1..=64 { + assert_eq!( + concurrent_client.request(&[b"INCR", b"counter"]), + Reply::Count(n) + ); + } + }); + assert_eq!( + client.request(&[b"BGREWRITEAOF"]), + Reply::Simple("Background append only file rewriting started".into()) + ); + let deadline = Instant::now() + Duration::from_secs(5); + loop { + let after = fs::metadata(&journal).unwrap(); + if after.ino() != before.ino() { + assert!(after.len() < before.len()); + break; + } + assert!( + Instant::now() < deadline, + "background rewrite did not install" + ); + thread::sleep(Duration::from_millis(10)); + } + writer.join().unwrap(); + }); + assert_eq!( + client.request(&[b"MSET", b"later", b"a", b"later2", b"b"]), + ok + ); + drop(client); + let _ = server.exit(libc::SIGKILL); + assert_eq!(fs::read(&snapshot).unwrap(), old_snapshot); + + let port = free_port(); + let (_server, mut client) = Running::start(&mut store.server(port, true), port); + assert_eq!( + client.request(&[b"GET", b"counter"]), + Reply::Bulk(Some(b"64".to_vec())) + ); + assert_eq!( + client.request(&[b"MGET", b"later", b"later2"]), + Reply::List(vec![ + Reply::Bulk(Some(b"a".to_vec())), + Reply::Bulk(Some(b"b".to_vec())), + ]) + ); + assert_eq!( + client.request(&[b"GET", b"churn"]), + Reply::Bulk(Some(value.to_vec())) + ); + assert!(matches!( + client.request(&[b"TTL", b"ttl"]), + Reply::Count(1..=300) + )); + assert_eq!( + client.request(&[b"HGET", b"hash", b"field"]), + Reply::Bulk(Some(b"value".to_vec())) + ); + assert_eq!(client.request(&[b"VSEARCH", b"ann", &vector]), ann); + assert_eq!( + client.request(&[b"VSEARCH", b"flat", &vector, b"FILTER", b"7"]), + flat + ); +} diff --git a/docs/commands/server-introspection.md b/docs/commands/server-introspection.md index d1f2543..2649952 100644 --- a/docs/commands/server-introspection.md +++ b/docs/commands/server-introspection.md @@ -13,7 +13,7 @@ KacheDB provides self-describing runtime introspection compatible with modern Re | **`AUTH`** | `AUTH [username] ` | Authenticates the connection when `requirepass` is configured. | | **`CLIENT`** | `CLIENT ` | Inspects and configures client connection state. | | **`COMMAND`** | `COMMAND [DOCS]` | Returns server capability descriptors for client auto-discovery. | -| **`BGREWRITEAOF`** | `BGREWRITEAOF` | Returns an unsupported-command error. | +| **`BGREWRITEAOF`** | `BGREWRITEAOF` | Starts background AOF compaction when AOF is enabled. | | **`QUIT`** | `QUIT` | Gracefully closes the client connection. | --- @@ -151,15 +151,11 @@ OK ### `BGREWRITEAOF` -Background AOF rewrite is currently unavailable. The command returns a RESP error and leaves the connection open. +Compacts the active AOF in the background. AOF persistence must be enabled, and one rewrite can run at a time. Normal writes continue while the replacement is built. The command acknowledges that the job started. The server log reports when it finishes or aborts. -#### Syntax ```text BGREWRITEAOF ++Background append only file rewriting started ``` -#### RESP error reply -```text --ERR BGREWRITEAOF is currently unsupported in this version -``` - +The writer installs the new file only after it has synced the captured base and subsequent mutations. The installed AOF can recover even when an external snapshot belongs to the previous generation. [AOF durability and repair](../getting-started/configuration.md#aof-durability-and-repair) diff --git a/docs/getting-started/configuration.md b/docs/getting-started/configuration.md index 186604a..5eb1720 100644 --- a/docs/getting-started/configuration.md +++ b/docs/getting-started/configuration.md @@ -124,13 +124,15 @@ Set `appendfsync` in the configuration file or pass `--appendfsync` when launchi A rejected admission leaves the data unchanged. An error reporting an uncertain outcome means the change was already published and its record may be on disk. The server rejects further writes once it detects AOF failure. Successful checkpoints and clean shutdowns sync the journal under every policy. +[Background compaction](../commands/server-introspection.md#bgrewriteaof) writes a self-contained base and collects up to 64 MiB or 65,536 later records while the active journal continues receiving writes. If the delta budget is exhausted, the server abandons the rewrite and keeps the active journal. After a successful swap, startup uses the embedded base. Its integrity is checked by CRC32, and it is stored in plaintext like the rest of the AOF. + Startup validates journal framing and requires a compatible snapshot when the journal depends on one. It automatically removes an incomplete final record only when the length header is intact and checksummed. For framing damage or an ambiguous tail, stop the server and use the offline repair command: ```bash kachedb-server --aof-repair --aof-file /var/lib/kachedb/kachedb.aof ``` -Repair writes a separate copy of the original journal, then truncates at the end of the last valid frame. All records after that point are discarded. If the retained prefix ends before a required snapshot checkpoint, startup reports the mismatch. +Repair writes a separate copy of the original journal, then truncates at the end of the last valid frame. A damaged embedded base payload requires recovery from another copy. All records after that point are discarded. If the retained prefix ends before a required snapshot checkpoint, startup reports the mismatch. ---