synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-store / src / wal2.rs
| 1 | //! WAL v2: pre-written log of 4 KiB-aligned batches with inline blobs. Since ADR 0003 A2 |
| 2 | //! the log is a sequence of segment files (`wal.v2.log`, then `wal.v2.000002.log`, ...; |
| 3 | //! see [`crate::segment`]), each in the format below. |
| 4 | //! |
| 5 | //! Why: on this host's ext4/NVMe, writing into space that is already written and synced |
| 6 | //! and then calling `fdatasync` measured 0.81 to 1.11 ms median (4 KiB to 1 MiB), while |
| 7 | //! any append, `fallocate`d write, or new file plus `fsync` needs a journal commit and |
| 8 | //! measured 3.5 to 6.4 ms median (`docs/PHASE5_GROUP_COMMIT.md`, |
| 9 | //! `evidence/phase5-group-commit/floor.json`). v2 therefore |
| 10 | //! keeps every durable commit inside pre-written space, stores blobs inside the log |
| 11 | //! instead of one file each, and commits a whole batch with one `pwrite` and one |
| 12 | //! `fdatasync`. |
| 13 | //! |
| 14 | //! Layout (per segment file): |
| 15 | //! * The file is zero-filled ahead of the write position in chunks (`sync_all` after |
| 16 | //! each extension, so size and blocks are durable before any batch lands there). |
| 17 | //! * A batch starts at a 4 KiB-aligned offset with a 64-byte batch header |
| 18 | //! (`SWB2`, version 2, record count, body length, first `WalSeq`, CRC-32C of the |
| 19 | //! header), followed by `record_count` frames and the 8-byte trailer `SWB2END!` (no |
| 20 | //! zero byte in it), then zero padding to the next 4 KiB. The declared body length |
| 21 | //! covers the frames and the trailer. |
| 22 | //! * Each frame keeps the v1 88-byte header layout with `version = 2`. The payload is |
| 23 | //! `u32 meta_len | meta (JSON WalRecord) | u32 blob_count | (digest[32] | u32 len | |
| 24 | //! bytes)*`. `payload_crc32c` is CRC-32C of the payload. `frame_sha256 = |
| 25 | //! SHA-256("SYNAPSE_WAL_FRAME_V2\0" || header[0..56] || payload_sha256)` with |
| 26 | //! `payload_sha256 = SHA-256("SYNAPSE_WAL_PAYLOAD_V2\0" || payload)`, so the payload |
| 27 | //! digest is computed by the submitter in parallel and the writer hashes 120 bytes. |
| 28 | //! * Chunked frames (ADR 0003 G2, flag [`WAL_FLAG_CHUNKED`]): after the inline blobs the |
| 29 | //! payload carries the manifests of its chunked blobs, a chunk table, and the chunk |
| 30 | //! bytes (layout at [`encode_parts`]). Its `payload_sha256` is |
| 31 | //! `SHA-256("SYNAPSE_WAL_PAYLOAD_CHUNKED_V1\0" || u64 LE payload length || payload up to |
| 32 | //! the chunk bytes)`: the chunk bytes are bound through the chunk digests in the table, |
| 33 | //! and recovery verifies every chunk against its digest before the frame digest. |
| 34 | //! * `seq`, `prev_frame_sha256` and the hash chain continue across v1 and v2 frames. |
| 35 | //! |
| 36 | //! Recovery applies a batch only when every frame in it validates (all or nothing). |
| 37 | //! The end of the log is the first all-zero batch header followed only by zeros. An |
| 38 | //! invalid batch is a torn tail only if no valid batch header follows it and the |
| 39 | //! sector that should hold its end reads back as zeros (see [`torn_evidence`]); the |
| 40 | //! space was zero before the write and the trailer has no zero byte, so a complete batch |
| 41 | //! never ends in zeros. Otherwise recovery fails closed with the specific refusal code. |
| 42 | //! Assumption (UNVERIFIED for this drive): a 512-byte sector write is atomic. |
| 43 | |
| 44 | use super::*; |
| 45 | use std::os::unix::fs::FileExt; |
| 46 | |
| 47 | /// WAL v2 file name inside the store root. |
| 48 | pub const WAL_V2_FILE: &str = "wal.v2.log"; |
| 49 | /// Frame and batch format version for WAL v2. |
| 50 | pub const WAL_V2_VERSION: u16 = 2; |
| 51 | /// Domain tag for the v2 frame chain digest. |
| 52 | pub const DOMAIN_WAL_FRAME_V2: &[u8] = b"SYNAPSE_WAL_FRAME_V2\0"; |
| 53 | /// Domain tag for the v2 payload digest. |
| 54 | pub const DOMAIN_WAL_PAYLOAD_V2: &[u8] = b"SYNAPSE_WAL_PAYLOAD_V2\0"; |
| 55 | /// Batch header magic. |
| 56 | pub const WAL_V2_BATCH_MAGIC: [u8; 4] = *b"SWB2"; |
| 57 | /// Batch header length. |
| 58 | pub const WAL_V2_BATCH_HEADER_LEN: usize = 64; |
| 59 | /// Batch alignment. |
| 60 | pub const WAL_V2_ALIGN: u64 = 4096; |
| 61 | /// Sector size used for torn-write evidence. |
| 62 | pub const WAL_V2_SECTOR: usize = 512; |
| 63 | /// Last 8 bytes of every batch body. No byte is zero, so the sector holding the end of |
| 64 | /// a batch is all zero only when that sector never reached the disk. |
| 65 | pub const WAL_V2_BATCH_TRAILER: [u8; 8] = *b"SWB2END!"; |
| 66 | |
| 67 | pub(crate) fn align_up(x: u64) -> u64 { |
| 68 | x.div_ceil(WAL_V2_ALIGN) * WAL_V2_ALIGN |
| 69 | } |
| 70 | |
| 71 | /// Frame flags bit: the payload carries content-defined chunks and chunk manifests (ADR |
| 72 | /// 0003 G2). The other flag bits still name the record codec. Binaries that predate G2 |
| 73 | /// refuse the bit (`WalFlagsNonZero`) instead of misreading the payload. |
| 74 | pub const WAL_FLAG_CHUNKED: u8 = 0x02; |
| 75 | /// Domain tag of the payload digest of a chunked payload. |
| 76 | pub const DOMAIN_WAL_PAYLOAD_CHUNKED_V1: &[u8] = b"SYNAPSE_WAL_PAYLOAD_CHUNKED_V1\0"; |
| 77 | |
| 78 | /// Codec and chunk flag declared by a v2 frame header flags byte. |
| 79 | pub(crate) fn parse_frame_flags(flags: u8) -> Option<(RecordCodec, bool)> { |
| 80 | let chunked = flags & WAL_FLAG_CHUNKED != 0; |
| 81 | RecordCodec::from_frame_flags(flags & !WAL_FLAG_CHUNKED).map(|c| (c, chunked)) |
| 82 | } |
| 83 | |
| 84 | /// A record encoded for WAL v2 before the critical section (payload, its digest, CRC). |
| 85 | #[derive(Debug, Clone)] |
| 86 | pub(crate) struct EncodedRecord { |
| 87 | pub kind: u8, |
| 88 | /// Frame header flags byte: the codec of the record metadata, plus |
| 89 | /// [`WAL_FLAG_CHUNKED`] when the payload carries chunk manifests. |
| 90 | pub flags: u8, |
| 91 | pub payload: Vec<u8>, |
| 92 | pub payload_sha256: [u8; 32], |
| 93 | pub payload_crc32c: u32, |
| 94 | /// Inline blobs: (digest, byte offset inside the payload, length). |
| 95 | pub inline: Vec<(BlobDigest, u32, u32)>, |
| 96 | /// Manifests of the chunked blobs this record stores (ADR 0003 G2). |
| 97 | pub manifests: Vec<ChunkManifest>, |
| 98 | /// Chunks carried by this record: (digest, byte offset inside the payload, length). |
| 99 | pub chunks: Vec<(ChunkDigest, u32, u32)>, |
| 100 | } |
| 101 | |
| 102 | pub(crate) fn payload_digest(payload: &[u8]) -> [u8; 32] { |
| 103 | let mut h = Sha256::new(); |
| 104 | h.update(DOMAIN_WAL_PAYLOAD_V2); |
| 105 | h.update(payload); |
| 106 | h.finalize().into() |
| 107 | } |
| 108 | |
| 109 | /// Payload digest of a chunked payload: the prefix before the chunk bytes, which holds |
| 110 | /// the chunk table (every chunk's `ChunkDigest` and length), is hashed; the chunk bytes |
| 111 | /// themselves are bound through their digests (verified on decode and on every read), |
| 112 | /// so dropping an already stored chunk never re-hashes the others. |
| 113 | pub(crate) fn chunked_payload_digest(payload: &[u8], prefix_len: usize) -> [u8; 32] { |
| 114 | let mut h = Sha256::new(); |
| 115 | h.update(DOMAIN_WAL_PAYLOAD_CHUNKED_V1); |
| 116 | h.update((payload.len() as u64).to_le_bytes()); |
| 117 | h.update(&payload[..prefix_len]); |
| 118 | h.finalize().into() |
| 119 | } |
| 120 | |
| 121 | fn too_large(what: &str) -> SynapseError { |
| 122 | SynapseError::new( |
| 123 | RefusalCode::QuotaPayloadTooLarge, |
| 124 | format!("{what} exceeds the WAL v2 32-bit length field"), |
| 125 | ) |
| 126 | } |
| 127 | |
| 128 | fn len32(n: usize, what: &str) -> SynapseResult<[u8; 4]> { |
| 129 | Ok(u32::try_from(n).map_err(|_| too_large(what))?.to_le_bytes()) |
| 130 | } |
| 131 | |
| 132 | /// Encode `record` with `blobs` stored inline (no chunks). |
| 133 | pub(crate) fn encode_record( |
| 134 | record: &WalRecord, |
| 135 | blobs: &[(BlobDigest, &[u8])], |
| 136 | codec: RecordCodec, |
| 137 | ) -> SynapseResult<EncodedRecord> { |
| 138 | let meta = codec::encode_record_with(record, codec)?; |
| 139 | encode_parts(record.kind_byte(), codec, &meta, blobs, &[], &[]) |
| 140 | } |
| 141 | |
| 142 | /// Encode a record whose metadata is `meta`: whole blobs inline, then (when `manifests` |
| 143 | /// is not empty, with [`WAL_FLAG_CHUNKED`]) the manifests, the chunk table, and the chunk |
| 144 | /// bytes. Layout of a chunked payload, little-endian: |
| 145 | /// `u32 meta_len | meta | u32 blob_count | (digest[32] | u32 len | bytes)* | |
| 146 | /// u32 manifest_count | (blob_digest[32] | u64 blob_len | u32 n | n x (chunk_digest[32] | |
| 147 | /// u32 len))* | u32 chunk_count | chunk_count x (chunk_digest[32] | u32 len) | |
| 148 | /// chunk bytes in table order`. |
| 149 | pub(crate) fn encode_parts( |
| 150 | kind: u8, |
| 151 | codec: RecordCodec, |
| 152 | meta: &[u8], |
| 153 | blobs: &[(BlobDigest, &[u8])], |
| 154 | manifests: &[ChunkManifest], |
| 155 | chunks: &[(ChunkDigest, &[u8])], |
| 156 | ) -> SynapseResult<EncodedRecord> { |
| 157 | let chunked = !manifests.is_empty(); |
| 158 | debug_assert!(chunked || chunks.is_empty(), "chunks without a manifest"); |
| 159 | let blob_bytes: usize = blobs.iter().map(|(_, b)| 36 + b.len()).sum(); |
| 160 | let manifest_bytes: usize = manifests.iter().map(|m| 44 + 36 * m.chunks.len()).sum(); |
| 161 | let chunk_bytes: usize = chunks.iter().map(|(_, b)| 36 + b.len()).sum(); |
| 162 | let mut payload = |
| 163 | Vec::with_capacity(16 + meta.len() + blob_bytes + manifest_bytes + chunk_bytes); |
| 164 | payload.extend_from_slice(&len32(meta.len(), "record metadata")?); |
| 165 | payload.extend_from_slice(meta); |
| 166 | payload.extend_from_slice(&len32(blobs.len(), "blob count")?); |
| 167 | let mut inline = Vec::with_capacity(blobs.len()); |
| 168 | for (digest, bytes) in blobs { |
| 169 | payload.extend_from_slice(&digest.0); |
| 170 | payload.extend_from_slice(&len32(bytes.len(), "blob")?); |
| 171 | let off = u32::try_from(payload.len()).map_err(|_| too_large("payload"))?; |
| 172 | payload.extend_from_slice(bytes); |
| 173 | inline.push((*digest, off, bytes.len() as u32)); |
| 174 | } |
| 175 | let mut placed_chunks = Vec::with_capacity(chunks.len()); |
| 176 | let prefix_len = if chunked { |
| 177 | payload.extend_from_slice(&len32(manifests.len(), "manifest count")?); |
| 178 | for m in manifests { |
| 179 | payload.extend_from_slice(&m.blob.0); |
| 180 | payload.extend_from_slice(&m.len.to_le_bytes()); |
| 181 | payload.extend_from_slice(&len32(m.chunks.len(), "manifest length")?); |
| 182 | for (d, l) in &m.chunks { |
| 183 | payload.extend_from_slice(&d.0); |
| 184 | payload.extend_from_slice(&l.to_le_bytes()); |
| 185 | } |
| 186 | } |
| 187 | payload.extend_from_slice(&len32(chunks.len(), "chunk count")?); |
| 188 | for (d, b) in chunks { |
| 189 | payload.extend_from_slice(&d.0); |
| 190 | payload.extend_from_slice(&len32(b.len(), "chunk")?); |
| 191 | } |
| 192 | let prefix_len = payload.len(); |
| 193 | for (d, b) in chunks { |
| 194 | let off = u32::try_from(payload.len()).map_err(|_| too_large("payload"))?; |
| 195 | payload.extend_from_slice(b); |
| 196 | placed_chunks.push((*d, off, b.len() as u32)); |
| 197 | } |
| 198 | Some(prefix_len) |
| 199 | } else { |
| 200 | None |
| 201 | }; |
| 202 | u32::try_from(payload.len()).map_err(|_| too_large("payload"))?; |
| 203 | Ok(EncodedRecord { |
| 204 | kind, |
| 205 | flags: codec.frame_flags() | if chunked { WAL_FLAG_CHUNKED } else { 0 }, |
| 206 | payload_sha256: match prefix_len { |
| 207 | Some(p) => chunked_payload_digest(&payload, p), |
| 208 | None => payload_digest(&payload), |
| 209 | }, |
| 210 | payload_crc32c: crc32c(&payload), |
| 211 | payload, |
| 212 | inline, |
| 213 | manifests: manifests.to_vec(), |
| 214 | chunks: placed_chunks, |
| 215 | }) |
| 216 | } |
| 217 | |
| 218 | impl EncodedRecord { |
| 219 | /// Codec of the record metadata. |
| 220 | pub fn codec(&self) -> RecordCodec { |
| 221 | parse_frame_flags(self.flags) |
| 222 | .expect("encoded with a known codec") |
| 223 | .0 |
| 224 | } |
| 225 | |
| 226 | /// The same record with its metadata encoded as `codec`, keeping only the manifests |
| 227 | /// `keep_manifest` accepts and the chunks `keep_chunk` accepts. Used when a store |
| 228 | /// migrates between prepare and commit, and to drop chunks (or whole manifests) the |
| 229 | /// store already holds (ADR 0003 G2). |
| 230 | pub fn rebuild( |
| 231 | &self, |
| 232 | record: &WalRecord, |
| 233 | codec: RecordCodec, |
| 234 | keep_manifest: impl Fn(&ChunkManifest) -> bool, |
| 235 | keep_chunk: impl Fn(&ChunkDigest) -> bool, |
| 236 | ) -> SynapseResult<Self> { |
| 237 | let meta = codec::encode_record_with(record, codec)?; |
| 238 | let slice = |off: u32, len: u32| &self.payload[off as usize..(off + len) as usize]; |
| 239 | let blobs: Vec<(BlobDigest, &[u8])> = self |
| 240 | .inline |
| 241 | .iter() |
| 242 | .map(|&(d, o, l)| (d, slice(o, l))) |
| 243 | .collect(); |
| 244 | let manifests: Vec<ChunkManifest> = self |
| 245 | .manifests |
| 246 | .iter() |
| 247 | .filter(|m| keep_manifest(m)) |
| 248 | .cloned() |
| 249 | .collect(); |
| 250 | let referenced: BTreeSet<ChunkDigest> = manifests |
| 251 | .iter() |
| 252 | .flat_map(|m| m.chunks.iter().map(|(d, _)| *d)) |
| 253 | .collect(); |
| 254 | let chunks: Vec<(ChunkDigest, &[u8])> = self |
| 255 | .chunks |
| 256 | .iter() |
| 257 | .filter(|(d, _, _)| referenced.contains(d) && keep_chunk(d)) |
| 258 | .map(|&(d, o, l)| (d, slice(o, l))) |
| 259 | .collect(); |
| 260 | encode_parts(self.kind, codec, &meta, &blobs, &manifests, &chunks) |
| 261 | } |
| 262 | |
| 263 | /// The same record with its metadata re-encoded as `codec` (inline blobs, manifests, |
| 264 | /// and chunks kept). |
| 265 | pub fn recode(&self, record: &WalRecord, codec: RecordCodec) -> SynapseResult<Self> { |
| 266 | if self.codec() == codec { |
| 267 | return Ok(self.clone()); |
| 268 | } |
| 269 | self.rebuild(record, codec, |_| true, |_| true) |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | /// Decoded v2 payload. |
| 274 | pub(crate) struct DecodedPayload { |
| 275 | pub record: WalRecord, |
| 276 | /// Inline blobs: (digest, byte offset inside the payload, length). |
| 277 | pub inline: Vec<(BlobDigest, u32, u32)>, |
| 278 | /// Chunk manifests (chunked payloads only). |
| 279 | pub manifests: Vec<ChunkManifest>, |
| 280 | /// Chunks carried by the payload: (digest, byte offset inside the payload, length). |
| 281 | pub chunks: Vec<(ChunkDigest, u32, u32)>, |
| 282 | /// Length of the hashed prefix of a chunked payload (`None` for a plain one). |
| 283 | pub prefix_len: Option<usize>, |
| 284 | } |
| 285 | |
| 286 | fn corrupt(seq: WalSeq, what: &str) -> SynapseError { |
| 287 | SynapseError::new( |
| 288 | RefusalCode::WalCrcMismatch, |
| 289 | format!("corrupt WAL v2 payload at {seq}: {what}"), |
| 290 | ) |
| 291 | } |
| 292 | |
| 293 | /// Decode a v2 payload, verifying every inline blob digest and every chunk digest. A |
| 294 | /// chunked payload must list each carried chunk once, carry only chunks its manifests |
| 295 | /// name, and state manifests whose chunk lengths add up to the blob length. Manifest |
| 296 | /// chunks the payload does not carry must already be stored (the caller checks). |
| 297 | pub(crate) fn decode_payload( |
| 298 | seq: WalSeq, |
| 299 | payload: &[u8], |
| 300 | codec: RecordCodec, |
| 301 | chunked: bool, |
| 302 | cap: u64, |
| 303 | ) -> SynapseResult<DecodedPayload> { |
| 304 | let rd_u32 = |at: usize| -> SynapseResult<u32> { |
| 305 | payload |
| 306 | .get(at..at + 4) |
| 307 | .map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes"))) |
| 308 | .ok_or_else(|| corrupt(seq, "truncated length field")) |
| 309 | }; |
| 310 | let rd_digest = |at: usize, what: &str| -> SynapseResult<[u8; 32]> { |
| 311 | Ok(payload |
| 312 | .get(at..at + 32) |
| 313 | .ok_or_else(|| corrupt(seq, what))? |
| 314 | .try_into() |
| 315 | .expect("32 bytes")) |
| 316 | }; |
| 317 | let meta_len = rd_u32(0)? as usize; |
| 318 | let meta = payload |
| 319 | .get(4..4 + meta_len) |
| 320 | .ok_or_else(|| corrupt(seq, "truncated metadata"))?; |
| 321 | let record = match codec { |
| 322 | RecordCodec::JsonV1 => { |
| 323 | serde_json::from_slice(meta).map_err(|e| corrupt(seq, &format!("record JSON: {e}")))? |
| 324 | } |
| 325 | RecordCodec::BinaryV2 => codec::decode_record(meta, cap).map_err(|r| { |
| 326 | r.into_error( |
| 327 | RefusalCode::WalRecordMalformed, |
| 328 | &format!("binary WAL v2 record at {seq}"), |
| 329 | ) |
| 330 | })?, |
| 331 | }; |
| 332 | let mut at = 4 + meta_len; |
| 333 | let count = rd_u32(at)? as usize; |
| 334 | at += 4; |
| 335 | let mut inline = Vec::with_capacity(count.min(4096)); |
| 336 | for _ in 0..count { |
| 337 | let digest = BlobDigest(rd_digest(at, "truncated blob digest")?); |
| 338 | let len = rd_u32(at + 32)? as usize; |
| 339 | let start = at + 36; |
| 340 | let bytes = payload |
| 341 | .get(start..start + len) |
| 342 | .ok_or_else(|| corrupt(seq, "truncated blob bytes"))?; |
| 343 | if BlobDigest::compute(bytes) != digest { |
| 344 | return Err(SynapseError::new( |
| 345 | RefusalCode::BlobDigestMismatch, |
| 346 | format!("inline blob {digest} corrupt in WAL v2 frame {seq}"), |
| 347 | )); |
| 348 | } |
| 349 | inline.push((digest, start as u32, len as u32)); |
| 350 | at = start + len; |
| 351 | } |
| 352 | let mut manifests = Vec::new(); |
| 353 | let mut chunks = Vec::new(); |
| 354 | let mut prefix_len = None; |
| 355 | if chunked { |
| 356 | let malformed = |what: &str| { |
| 357 | SynapseError::new( |
| 358 | RefusalCode::WalRecordMalformed, |
| 359 | format!("chunked WAL v2 payload at {seq}: {what}"), |
| 360 | ) |
| 361 | }; |
| 362 | let m_count = rd_u32(at)? as usize; |
| 363 | at += 4; |
| 364 | if m_count == 0 { |
| 365 | return Err(malformed("chunk flag set without a manifest")); |
| 366 | } |
| 367 | let mut named = BTreeSet::new(); |
| 368 | for _ in 0..m_count { |
| 369 | let blob = BlobDigest(rd_digest(at, "truncated manifest")?); |
| 370 | let blob_len = u64::from_le_bytes( |
| 371 | payload |
| 372 | .get(at + 32..at + 40) |
| 373 | .ok_or_else(|| corrupt(seq, "truncated manifest length"))? |
| 374 | .try_into() |
| 375 | .expect("8 bytes"), |
| 376 | ); |
| 377 | let n = rd_u32(at + 40)? as usize; |
| 378 | at += 44; |
| 379 | if n == 0 || n > payload.len() / 36 + 1 { |
| 380 | return Err(malformed("manifest chunk count out of range")); |
| 381 | } |
| 382 | let mut list = Vec::with_capacity(n); |
| 383 | let mut total = 0u64; |
| 384 | for _ in 0..n { |
| 385 | let d = ChunkDigest(rd_digest(at, "truncated manifest entry")?); |
| 386 | let l = rd_u32(at + 32)?; |
| 387 | if l == 0 { |
| 388 | return Err(malformed("empty chunk in a manifest")); |
| 389 | } |
| 390 | total += u64::from(l); |
| 391 | named.insert(d); |
| 392 | list.push((d, l)); |
| 393 | at += 36; |
| 394 | } |
| 395 | if total != blob_len { |
| 396 | return Err(malformed( |
| 397 | "manifest chunk lengths do not add up to the blob", |
| 398 | )); |
| 399 | } |
| 400 | manifests.push(ChunkManifest { |
| 401 | blob, |
| 402 | len: blob_len, |
| 403 | chunks: list, |
| 404 | }); |
| 405 | } |
| 406 | let c_count = rd_u32(at)? as usize; |
| 407 | at += 4; |
| 408 | if c_count > payload.len() / 36 + 1 { |
| 409 | return Err(malformed("chunk count out of range")); |
| 410 | } |
| 411 | let mut table = Vec::with_capacity(c_count); |
| 412 | let mut carried = BTreeSet::new(); |
| 413 | for _ in 0..c_count { |
| 414 | let d = ChunkDigest(rd_digest(at, "truncated chunk table")?); |
| 415 | let l = rd_u32(at + 32)?; |
| 416 | if l == 0 || !carried.insert(d) || !named.contains(&d) { |
| 417 | return Err(malformed( |
| 418 | "chunk table entry empty, repeated, or named by no manifest", |
| 419 | )); |
| 420 | } |
| 421 | table.push((d, l)); |
| 422 | at += 36; |
| 423 | } |
| 424 | prefix_len = Some(at); |
| 425 | for (d, l) in table { |
| 426 | let bytes = payload |
| 427 | .get(at..at + l as usize) |
| 428 | .ok_or_else(|| corrupt(seq, "truncated chunk bytes"))?; |
| 429 | if ChunkDigest::compute(bytes) != d { |
| 430 | return Err(SynapseError::new( |
| 431 | RefusalCode::BlobDigestMismatch, |
| 432 | format!("chunk {d} corrupt in WAL v2 frame {seq}"), |
| 433 | )); |
| 434 | } |
| 435 | chunks.push((d, at as u32, l)); |
| 436 | at += l as usize; |
| 437 | } |
| 438 | } |
| 439 | if at != payload.len() { |
| 440 | return Err(corrupt( |
| 441 | seq, |
| 442 | "trailing bytes after the last inline blob or chunk", |
| 443 | )); |
| 444 | } |
| 445 | Ok(DecodedPayload { |
| 446 | record, |
| 447 | inline, |
| 448 | manifests, |
| 449 | chunks, |
| 450 | prefix_len, |
| 451 | }) |
| 452 | } |
| 453 | |
| 454 | /// Build the 88-byte v2 frame header and its chain digest. |
| 455 | pub(crate) fn frame_header( |
| 456 | seq: WalSeq, |
| 457 | prev_sha: [u8; 32], |
| 458 | kind: u8, |
| 459 | flags: u8, |
| 460 | payload_len: u32, |
| 461 | payload_crc32c: u32, |
| 462 | payload_sha256: &[u8; 32], |
| 463 | ) -> ([u8; WAL_HEADER_LEN], [u8; 32]) { |
| 464 | let mut h = [0u8; WAL_HEADER_LEN]; |
| 465 | h[0..4].copy_from_slice(&WAL_MAGIC); |
| 466 | h[4..6].copy_from_slice(&WAL_V2_VERSION.to_le_bytes()); |
| 467 | h[6] = kind; |
| 468 | h[7] = flags; |
| 469 | h[8..16].copy_from_slice(&seq.0.to_le_bytes()); |
| 470 | h[16..48].copy_from_slice(&prev_sha); |
| 471 | h[48..52].copy_from_slice(&payload_len.to_le_bytes()); |
| 472 | h[52..56].copy_from_slice(&payload_crc32c.to_le_bytes()); |
| 473 | let sha = frame_digest(&h[0..56], payload_sha256); |
| 474 | h[56..88].copy_from_slice(&sha); |
| 475 | (h, sha) |
| 476 | } |
| 477 | |
| 478 | pub(crate) fn frame_digest(header_prefix_56: &[u8], payload_sha256: &[u8; 32]) -> [u8; 32] { |
| 479 | let mut hasher = Sha256::new(); |
| 480 | hasher.update(DOMAIN_WAL_FRAME_V2); |
| 481 | hasher.update(header_prefix_56); |
| 482 | hasher.update(payload_sha256); |
| 483 | hasher.finalize().into() |
| 484 | } |
| 485 | |
| 486 | fn batch_header(record_count: u32, body_len: u64, first_seq: WalSeq) -> [u8; 64] { |
| 487 | let mut h = [0u8; WAL_V2_BATCH_HEADER_LEN]; |
| 488 | h[0..4].copy_from_slice(&WAL_V2_BATCH_MAGIC); |
| 489 | h[4..6].copy_from_slice(&WAL_V2_VERSION.to_le_bytes()); |
| 490 | h[8..12].copy_from_slice(&record_count.to_le_bytes()); |
| 491 | h[16..24].copy_from_slice(&body_len.to_le_bytes()); |
| 492 | h[24..32].copy_from_slice(&first_seq.0.to_le_bytes()); |
| 493 | let crc = crc32c(&h[0..60]); |
| 494 | h[60..64].copy_from_slice(&crc.to_le_bytes()); |
| 495 | h |
| 496 | } |
| 497 | |
| 498 | /// Parsed batch header (`None` when magic, version, reserved bytes or CRC are wrong). |
| 499 | pub(crate) fn parse_batch_header(h: &[u8]) -> Option<(u32, u64, WalSeq)> { |
| 500 | if h.len() < WAL_V2_BATCH_HEADER_LEN || h[0..4] != WAL_V2_BATCH_MAGIC { |
| 501 | return None; |
| 502 | } |
| 503 | if u16::from_le_bytes([h[4], h[5]]) != WAL_V2_VERSION { |
| 504 | return None; |
| 505 | } |
| 506 | let crc = u32::from_le_bytes(h[60..64].try_into().ok()?); |
| 507 | if crc != crc32c(&h[0..60]) { |
| 508 | return None; |
| 509 | } |
| 510 | if h[6..8] |
| 511 | .iter() |
| 512 | .chain(&h[12..16]) |
| 513 | .chain(&h[32..60]) |
| 514 | .any(|b| *b != 0) |
| 515 | { |
| 516 | return None; |
| 517 | } |
| 518 | let count = u32::from_le_bytes(h[8..12].try_into().ok()?); |
| 519 | let body = u64::from_le_bytes(h[16..24].try_into().ok()?); |
| 520 | let first = WalSeq(u64::from_le_bytes(h[24..32].try_into().ok()?)); |
| 521 | Some((count, body, first)) |
| 522 | } |
| 523 | |
| 524 | /// Frame-level faults applied to the first frame of the next batch. |
| 525 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 526 | pub(crate) enum FrameFault { |
| 527 | None, |
| 528 | CorruptCrc, |
| 529 | CorruptChain, |
| 530 | SequenceGap, |
| 531 | DuplicateSequence, |
| 532 | } |
| 533 | |
| 534 | /// Builds one batch buffer: header, frames, zero padding to 4 KiB. |
| 535 | pub(crate) struct BatchBuilder { |
| 536 | buf: Vec<u8>, |
| 537 | segment: u64, |
| 538 | base_offset: u64, |
| 539 | count: u32, |
| 540 | first_seq: Option<WalSeq>, |
| 541 | } |
| 542 | |
| 543 | /// Placement of one frame inside a batch. |
| 544 | pub(crate) struct PlacedFrame { |
| 545 | pub seq: WalSeq, |
| 546 | pub frame_sha256: [u8; 32], |
| 547 | /// Segment file holding the frame (ADR 0003 A2; segment 1 is `wal.v2.log`). |
| 548 | pub segment: u64, |
| 549 | /// Absolute offset of the frame payload inside its segment file. |
| 550 | pub payload_offset: u64, |
| 551 | } |
| 552 | |
| 553 | impl BatchBuilder { |
| 554 | pub fn new(segment: u64, base_offset: u64, capacity: usize) -> Self { |
| 555 | let mut buf = Vec::with_capacity(capacity + WAL_V2_ALIGN as usize); |
| 556 | buf.resize(WAL_V2_BATCH_HEADER_LEN, 0); |
| 557 | Self { |
| 558 | buf, |
| 559 | segment, |
| 560 | base_offset, |
| 561 | count: 0, |
| 562 | first_seq: None, |
| 563 | } |
| 564 | } |
| 565 | |
| 566 | /// Append one frame. `fault` alters only this frame (test hook). |
| 567 | pub fn push( |
| 568 | &mut self, |
| 569 | seq: WalSeq, |
| 570 | prev_sha: [u8; 32], |
| 571 | enc: &EncodedRecord, |
| 572 | fault: FrameFault, |
| 573 | ) -> PlacedFrame { |
| 574 | let seq_on_disk = match fault { |
| 575 | FrameFault::SequenceGap => seq.next(), |
| 576 | FrameFault::DuplicateSequence => WalSeq(seq.0.saturating_sub(1)), |
| 577 | _ => seq, |
| 578 | }; |
| 579 | let mut prev = prev_sha; |
| 580 | if fault == FrameFault::CorruptChain { |
| 581 | prev[0] ^= 0xff; |
| 582 | } |
| 583 | let mut crc = enc.payload_crc32c; |
| 584 | if fault == FrameFault::CorruptCrc { |
| 585 | crc ^= 0xdead_beef; |
| 586 | } |
| 587 | let (header, sha) = frame_header( |
| 588 | seq_on_disk, |
| 589 | prev, |
| 590 | enc.kind, |
| 591 | enc.flags, |
| 592 | enc.payload.len() as u32, |
| 593 | crc, |
| 594 | &enc.payload_sha256, |
| 595 | ); |
| 596 | if self.first_seq.is_none() { |
| 597 | self.first_seq = Some(seq_on_disk); |
| 598 | } |
| 599 | self.buf.extend_from_slice(&header); |
| 600 | let payload_offset = self.base_offset + self.buf.len() as u64; |
| 601 | self.buf.extend_from_slice(&enc.payload); |
| 602 | self.count += 1; |
| 603 | PlacedFrame { |
| 604 | seq, |
| 605 | frame_sha256: sha, |
| 606 | segment: self.segment, |
| 607 | payload_offset, |
| 608 | } |
| 609 | } |
| 610 | |
| 611 | /// Finish the batch: append the trailer, fill the header and pad to 4 KiB. |
| 612 | pub fn finish(mut self) -> Vec<u8> { |
| 613 | self.buf.extend_from_slice(&WAL_V2_BATCH_TRAILER); |
| 614 | let body_len = (self.buf.len() - WAL_V2_BATCH_HEADER_LEN) as u64; |
| 615 | let h = batch_header(self.count, body_len, self.first_seq.unwrap_or(WalSeq::ZERO)); |
| 616 | self.buf[0..WAL_V2_BATCH_HEADER_LEN].copy_from_slice(&h); |
| 617 | let padded = align_up(self.buf.len() as u64) as usize; |
| 618 | self.buf.resize(padded, 0); |
| 619 | self.buf |
| 620 | } |
| 621 | } |
| 622 | |
| 623 | /// I/O faults for one batch write (test hooks). |
| 624 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 625 | pub(crate) enum BatchIoFault { |
| 626 | None, |
| 627 | /// Write only the first `n` bytes, then return an error. |
| 628 | FailWrite { |
| 629 | bytes_written: usize, |
| 630 | }, |
| 631 | /// Write everything, then report an `fdatasync` failure. |
| 632 | FailSync, |
| 633 | /// As `FailSync`, and the rollback write also fails (store becomes poisoned). |
| 634 | FailSyncAndRollback, |
| 635 | /// Write the first `n` bytes, then exit the process with `code` (crash simulation). |
| 636 | CrashAfterBytes { |
| 637 | bytes_written: usize, |
| 638 | code: i32, |
| 639 | }, |
| 640 | /// Write everything without syncing, then exit the process with `code`. |
| 641 | CrashBeforeSync { |
| 642 | code: i32, |
| 643 | }, |
| 644 | /// Write and `fdatasync` everything, then exit the process with `code` before the |
| 645 | /// caller updates its index or acknowledges anything (payload durable, index not). |
| 646 | CrashAfterSync { |
| 647 | code: i32, |
| 648 | }, |
| 649 | /// Write and sync the first `n` bytes, then stop as if the process had died: no |
| 650 | /// rollback, and the store refuses further writes until reopened. |
| 651 | TornThenStop { |
| 652 | bytes_written: usize, |
| 653 | }, |
| 654 | } |
| 655 | |
| 656 | /// Outcome of a failed batch write. |
| 657 | #[derive(Debug, Clone)] |
| 658 | pub(crate) enum BatchFailure { |
| 659 | /// The batch bytes were overwritten with zeros and synced; the log is unchanged. |
| 660 | RolledBack(SynapseError), |
| 661 | /// Rollback failed too; the on-disk tail is unknown until the store is reopened. |
| 662 | Poisoned(SynapseError), |
| 663 | } |
| 664 | |
| 665 | /// The file a [`WalV2Writer`] writes: a segment file (A2) or a segment slot of a raw |
| 666 | /// block device (R1). |
| 667 | #[derive(Debug)] |
| 668 | pub(crate) enum SegFile { |
| 669 | Fs(File), |
| 670 | Block { |
| 671 | dev: std::sync::Arc<crate::blockdev::BlockDevice>, |
| 672 | id: u64, |
| 673 | }, |
| 674 | } |
| 675 | |
| 676 | impl SegFile { |
| 677 | fn write_all_at(&self, buf: &[u8], at: u64) -> std::io::Result<()> { |
| 678 | match self { |
| 679 | SegFile::Fs(f) => f.write_all_at(buf, at), |
| 680 | SegFile::Block { dev, id } => dev.write_segment(*id, at, buf), |
| 681 | } |
| 682 | } |
| 683 | |
| 684 | /// `fdatasync` (R1: of the whole device). |
| 685 | fn sync_data(&self) -> std::io::Result<()> { |
| 686 | match self { |
| 687 | SegFile::Fs(f) => f.sync_data(), |
| 688 | SegFile::Block { dev, .. } => dev.flush(), |
| 689 | } |
| 690 | } |
| 691 | |
| 692 | /// `fsync` data and size (R1: `fdatasync` of the device; a slot has a fixed size). |
| 693 | fn sync_all(&self) -> std::io::Result<()> { |
| 694 | match self { |
| 695 | SegFile::Fs(f) => f.sync_all(), |
| 696 | SegFile::Block { dev, .. } => dev.flush(), |
| 697 | } |
| 698 | } |
| 699 | } |
| 700 | |
| 701 | /// Writer for `wal.v2.log`. |
| 702 | #[derive(Debug)] |
| 703 | pub(crate) struct WalV2Writer { |
| 704 | file: SegFile, |
| 705 | pub write_offset: u64, |
| 706 | pub prewritten_end: u64, |
| 707 | chunk: u64, |
| 708 | /// Pre-writing ahead stops here (the segment size), unless a batch needs more. |
| 709 | prewrite_cap: u64, |
| 710 | } |
| 711 | |
| 712 | fn injected(msg: &str) -> std::io::Error { |
| 713 | std::io::Error::other(format!("injected fault: {msg}")) |
| 714 | } |
| 715 | |
| 716 | impl WalV2Writer { |
| 717 | /// Open (creating if needed) with the log ending at `write_offset` and every byte in |
| 718 | /// `write_offset..file_len` known to be zero. Pre-writes one chunk ahead. |
| 719 | pub fn open(path: &Path, write_offset: u64, chunk: u64) -> SynapseResult<Self> { |
| 720 | let existed = path.exists(); |
| 721 | let file = OpenOptions::new() |
| 722 | .create(true) |
| 723 | .truncate(false) |
| 724 | .read(true) |
| 725 | .write(true) |
| 726 | .open(path) |
| 727 | .map_err(io_err)?; |
| 728 | if !existed { |
| 729 | file.sync_all().map_err(io_err)?; |
| 730 | if let Some(parent) = path.parent() { |
| 731 | sync_dir(parent)?; |
| 732 | } |
| 733 | } |
| 734 | let len = file.metadata().map_err(io_err)?.len(); |
| 735 | let mut w = Self { |
| 736 | file: SegFile::Fs(file), |
| 737 | write_offset, |
| 738 | prewritten_end: len.max(write_offset), |
| 739 | chunk: chunk.max(WAL_V2_ALIGN), |
| 740 | prewrite_cap: u64::MAX, |
| 741 | }; |
| 742 | w.ensure_space(WAL_V2_ALIGN).map_err(io_err)?; |
| 743 | Ok(w) |
| 744 | } |
| 745 | |
| 746 | /// A writer over a newly created, empty segment file (nothing pre-written yet). |
| 747 | pub fn new_empty(file: File, chunk: u64, prewrite_cap: u64) -> Self { |
| 748 | Self { |
| 749 | file: SegFile::Fs(file), |
| 750 | write_offset: 0, |
| 751 | prewritten_end: 0, |
| 752 | chunk: chunk.max(WAL_V2_ALIGN), |
| 753 | prewrite_cap: prewrite_cap.max(WAL_V2_ALIGN), |
| 754 | } |
| 755 | } |
| 756 | |
| 757 | /// A writer over segment slot `id` of a raw block device (R1) with the log ending at |
| 758 | /// `write_offset`. The slot was zeroed and flushed when it was created, so the whole |
| 759 | /// slot counts as pre-written; a batch past its end is refused. |
| 760 | pub fn on_block( |
| 761 | dev: std::sync::Arc<crate::blockdev::BlockDevice>, |
| 762 | id: u64, |
| 763 | write_offset: u64, |
| 764 | segment_bytes: u64, |
| 765 | ) -> Self { |
| 766 | Self { |
| 767 | file: SegFile::Block { dev, id }, |
| 768 | write_offset, |
| 769 | prewritten_end: segment_bytes, |
| 770 | chunk: segment_bytes.max(WAL_V2_ALIGN), |
| 771 | prewrite_cap: segment_bytes, |
| 772 | } |
| 773 | } |
| 774 | |
| 775 | /// Stop pre-writing ahead past `cap` bytes (a batch that needs more still gets it). |
| 776 | pub fn set_prewrite_cap(&mut self, cap: u64) { |
| 777 | self.prewrite_cap = cap.max(WAL_V2_ALIGN); |
| 778 | } |
| 779 | |
| 780 | /// Zero-fill and `sync_all` ahead of the write position until `need` bytes fit. |
| 781 | pub fn ensure_space(&mut self, need: u64) -> std::io::Result<()> { |
| 782 | if self.write_offset + need <= self.prewritten_end { |
| 783 | return Ok(()); |
| 784 | } |
| 785 | if let SegFile::Block { id, .. } = &self.file { |
| 786 | return Err(std::io::Error::other(format!( |
| 787 | "a batch of {need} bytes at offset {} does not fit segment slot {id} of {} bytes", |
| 788 | self.write_offset, self.prewritten_end |
| 789 | ))); |
| 790 | } |
| 791 | let ahead = (self.prewritten_end + self.chunk).min(self.prewrite_cap); |
| 792 | let target = align_up((self.write_offset + need).max(ahead)); |
| 793 | let zeros = vec![0u8; 1 << 20]; |
| 794 | let mut at = self.prewritten_end; |
| 795 | while at < target { |
| 796 | let n = ((target - at) as usize).min(zeros.len()); |
| 797 | self.file.write_all_at(&zeros[..n], at)?; |
| 798 | at += n as u64; |
| 799 | } |
| 800 | self.file.sync_all()?; |
| 801 | self.prewritten_end = target; |
| 802 | Ok(()) |
| 803 | } |
| 804 | |
| 805 | /// Write one finished batch at the write position and make it durable with one |
| 806 | /// `fdatasync`. On failure the batch extent is zeroed and synced again (rollback). |
| 807 | pub fn write_batch(&mut self, buf: &[u8], fault: BatchIoFault) -> Result<(), BatchFailure> { |
| 808 | let at = self.write_offset; |
| 809 | let fail = |e: std::io::Error| SynapseError::new(RefusalCode::IoFailure, e.to_string()); |
| 810 | if let Err(e) = self.ensure_space(buf.len() as u64) { |
| 811 | // Nothing was written into the log extent; extension bytes are zeros. |
| 812 | return Err(BatchFailure::RolledBack(fail(e))); |
| 813 | } |
| 814 | let res: std::io::Result<()> = match fault { |
| 815 | BatchIoFault::None => self |
| 816 | .file |
| 817 | .write_all_at(buf, at) |
| 818 | .and_then(|_| self.file.sync_data()), |
| 819 | BatchIoFault::FailWrite { bytes_written } => self |
| 820 | .file |
| 821 | .write_all_at(&buf[..bytes_written.min(buf.len())], at) |
| 822 | .and_then(|_| Err(injected("batch write failed"))), |
| 823 | BatchIoFault::FailSync | BatchIoFault::FailSyncAndRollback => self |
| 824 | .file |
| 825 | .write_all_at(buf, at) |
| 826 | .and_then(|_| Err(injected("fdatasync failed"))), |
| 827 | BatchIoFault::CrashAfterBytes { |
| 828 | bytes_written, |
| 829 | code, |
| 830 | } => { |
| 831 | let _ = self |
| 832 | .file |
| 833 | .write_all_at(&buf[..bytes_written.min(buf.len())], at); |
| 834 | std::process::exit(code); |
| 835 | } |
| 836 | BatchIoFault::CrashBeforeSync { code } => { |
| 837 | let _ = self.file.write_all_at(buf, at); |
| 838 | std::process::exit(code); |
| 839 | } |
| 840 | BatchIoFault::CrashAfterSync { code } => { |
| 841 | let _ = self |
| 842 | .file |
| 843 | .write_all_at(buf, at) |
| 844 | .and_then(|_| self.file.sync_data()); |
| 845 | std::process::exit(code); |
| 846 | } |
| 847 | BatchIoFault::TornThenStop { bytes_written } => { |
| 848 | let n = bytes_written.min(buf.len().saturating_sub(1)); |
| 849 | self.file |
| 850 | .write_all_at(&buf[..n], at) |
| 851 | .and_then(|_| self.file.sync_data()) |
| 852 | .map_err(|e| BatchFailure::Poisoned(fail(e)))?; |
| 853 | return Err(BatchFailure::Poisoned(SynapseError::new( |
| 854 | RefusalCode::WalTornFrame, |
| 855 | format!("injected fault: torn WAL v2 batch write ({n} bytes)"), |
| 856 | ))); |
| 857 | } |
| 858 | }; |
| 859 | match res { |
| 860 | Ok(()) => { |
| 861 | self.write_offset = at + buf.len() as u64; |
| 862 | Ok(()) |
| 863 | } |
| 864 | Err(e) => { |
| 865 | let err = fail(e); |
| 866 | let zeros = vec![0u8; buf.len()]; |
| 867 | let rollback = if fault == BatchIoFault::FailSyncAndRollback { |
| 868 | Err(injected("rollback write failed")) |
| 869 | } else { |
| 870 | self.file |
| 871 | .write_all_at(&zeros, at) |
| 872 | .and_then(|_| self.file.sync_data()) |
| 873 | }; |
| 874 | match rollback { |
| 875 | Ok(()) => Err(BatchFailure::RolledBack(err)), |
| 876 | Err(re) => Err(BatchFailure::Poisoned(SynapseError::new( |
| 877 | RefusalCode::IoFailure, |
| 878 | format!( |
| 879 | "{}; rollback failed: {re}; the outcome is unknown (the batch may be durable): reopen, then retry with the same idempotency key", |
| 880 | err.message |
| 881 | ), |
| 882 | ))), |
| 883 | } |
| 884 | } |
| 885 | } |
| 886 | } |
| 887 | |
| 888 | pub fn sync(&self) -> SynapseResult<()> { |
| 889 | self.file.sync_data().map_err(io_err) |
| 890 | } |
| 891 | |
| 892 | /// `fsync` data and metadata (size) of the file. |
| 893 | pub fn sync_all(&self) -> SynapseResult<()> { |
| 894 | self.file.sync_all().map_err(io_err) |
| 895 | } |
| 896 | } |
| 897 | |
| 898 | /// A batch read back during recovery. |
| 899 | pub(crate) struct RecoveredFrame { |
| 900 | pub seq: WalSeq, |
| 901 | pub frame_sha256: [u8; 32], |
| 902 | pub codec: RecordCodec, |
| 903 | pub record: WalRecord, |
| 904 | /// Inline blobs: (digest, absolute file offset, length). |
| 905 | pub inline: Vec<(BlobDigest, u64, u32)>, |
| 906 | /// Chunk manifests (ADR 0003 G2). |
| 907 | pub manifests: Vec<ChunkManifest>, |
| 908 | /// Chunks carried by the frame: (digest, absolute file offset, length). |
| 909 | pub chunks: Vec<(ChunkDigest, u64, u32)>, |
| 910 | } |
| 911 | |
| 912 | /// Validate the batch at `off`; on success return its frames and the aligned next offset. |
| 913 | pub(crate) fn validate_batch( |
| 914 | buf: &[u8], |
| 915 | off: usize, |
| 916 | mut expected_seq: WalSeq, |
| 917 | mut prev_sha: [u8; 32], |
| 918 | cap: u64, |
| 919 | ) -> SynapseResult<(Vec<RecoveredFrame>, usize)> { |
| 920 | let torn = |what: &str| { |
| 921 | SynapseError::new( |
| 922 | RefusalCode::WalTornFrame, |
| 923 | format!("torn WAL v2 batch at byte offset {off}: {what}"), |
| 924 | ) |
| 925 | }; |
| 926 | let header = buf |
| 927 | .get(off..off + WAL_V2_BATCH_HEADER_LEN) |
| 928 | .ok_or_else(|| torn("batch header past end of file"))?; |
| 929 | let (count, body_len, first_seq) = parse_batch_header(header).ok_or_else(|| { |
| 930 | SynapseError::new( |
| 931 | RefusalCode::WalMagicInvalid, |
| 932 | format!("invalid WAL v2 batch header at byte offset {off}"), |
| 933 | ) |
| 934 | })?; |
| 935 | let body_start = off + WAL_V2_BATCH_HEADER_LEN; |
| 936 | let body_end = body_start |
| 937 | .checked_add(usize::try_from(body_len).map_err(|_| torn("body length overflow"))?) |
| 938 | .ok_or_else(|| torn("body length overflow"))?; |
| 939 | if body_end > buf.len() { |
| 940 | return Err(torn("batch body past end of file")); |
| 941 | } |
| 942 | if first_seq != expected_seq { |
| 943 | return Err(SynapseError::new( |
| 944 | RefusalCode::WalSequenceGap, |
| 945 | format!("WAL v2 batch at {off} starts at {first_seq}, expected {expected_seq}"), |
| 946 | )); |
| 947 | } |
| 948 | let mut frames = Vec::with_capacity(count as usize); |
| 949 | let mut at = body_start; |
| 950 | for _ in 0..count { |
| 951 | let h = buf |
| 952 | .get(at..at + WAL_HEADER_LEN) |
| 953 | .filter(|_| at + WAL_HEADER_LEN <= body_end) |
| 954 | .ok_or_else(|| torn("frame header past batch end"))?; |
| 955 | if h[0..4] != WAL_MAGIC { |
| 956 | return Err(SynapseError::new( |
| 957 | RefusalCode::WalMagicInvalid, |
| 958 | format!("invalid WAL magic at byte offset {at}"), |
| 959 | )); |
| 960 | } |
| 961 | let version = u16::from_le_bytes([h[4], h[5]]); |
| 962 | if version != WAL_V2_VERSION { |
| 963 | return Err(SynapseError::new( |
| 964 | RefusalCode::WalVersionUnsupported, |
| 965 | format!("frame version {version} inside a WAL v2 batch at offset {at}"), |
| 966 | )); |
| 967 | } |
| 968 | let (codec, chunked) = parse_frame_flags(h[7]).ok_or_else(|| { |
| 969 | SynapseError::new( |
| 970 | RefusalCode::WalFlagsNonZero, |
| 971 | format!("unknown WAL flags {} at offset {at}", h[7]), |
| 972 | ) |
| 973 | })?; |
| 974 | let seq = WalSeq(u64::from_le_bytes(h[8..16].try_into().expect("8"))); |
| 975 | let prev: [u8; 32] = h[16..48].try_into().expect("32"); |
| 976 | let payload_len = u32::from_le_bytes(h[48..52].try_into().expect("4")) as usize; |
| 977 | let crc = u32::from_le_bytes(h[52..56].try_into().expect("4")); |
| 978 | let stored_sha: [u8; 32] = h[56..88].try_into().expect("32"); |
| 979 | if payload_len as u64 > cap { |
| 980 | return Err(SynapseError::new( |
| 981 | RefusalCode::QuotaPayloadTooLarge, |
| 982 | format!("WAL v2 frame at offset {at} declares {payload_len} payload bytes, above the cap {cap}"), |
| 983 | )); |
| 984 | } |
| 985 | let p_start = at + WAL_HEADER_LEN; |
| 986 | let p_end = p_start + payload_len; |
| 987 | if p_end > body_end { |
| 988 | return Err(torn("frame payload past batch end")); |
| 989 | } |
| 990 | if seq != expected_seq { |
| 991 | return Err(SynapseError::new( |
| 992 | RefusalCode::WalSequenceGap, |
| 993 | format!( |
| 994 | "WAL sequence mismatch at offset {at}: expected {expected_seq}, found {seq}" |
| 995 | ), |
| 996 | )); |
| 997 | } |
| 998 | if prev != prev_sha { |
| 999 | return Err(SynapseError::new( |
| 1000 | RefusalCode::WalChainMismatch, |
| 1001 | format!("WAL prev_frame_sha256 mismatch at {seq}"), |
| 1002 | )); |
| 1003 | } |
| 1004 | let payload = &buf[p_start..p_end]; |
| 1005 | let actual_crc = crc32c(payload); |
| 1006 | if actual_crc != crc { |
| 1007 | return Err(SynapseError::new( |
| 1008 | RefusalCode::WalCrcMismatch, |
| 1009 | format!( |
| 1010 | "WAL payload CRC32C mismatch at {seq}: expected {crc:#x}, computed {actual_crc:#x}" |
| 1011 | ), |
| 1012 | )); |
| 1013 | } |
| 1014 | // A chunked payload's digest covers the prefix before its chunk bytes, so it is |
| 1015 | // decoded (every chunk digest verified) before the chain digest is checked. |
| 1016 | let decoded = if chunked { |
| 1017 | Some(decode_payload(seq, payload, codec, true, cap)?) |
| 1018 | } else { |
| 1019 | None |
| 1020 | }; |
| 1021 | let payload_sha = match decoded.as_ref().and_then(|d| d.prefix_len) { |
| 1022 | Some(p) => chunked_payload_digest(payload, p), |
| 1023 | None => payload_digest(payload), |
| 1024 | }; |
| 1025 | if frame_digest(&h[0..56], &payload_sha) != stored_sha { |
| 1026 | return Err(SynapseError::new( |
| 1027 | RefusalCode::WalChainMismatch, |
| 1028 | format!("WAL frame_sha256 mismatch at {seq}"), |
| 1029 | )); |
| 1030 | } |
| 1031 | let decoded = match decoded { |
| 1032 | Some(d) => d, |
| 1033 | None => decode_payload(seq, payload, codec, false, cap)?, |
| 1034 | }; |
| 1035 | if decoded.record.kind_byte() != h[6] { |
| 1036 | return Err(match codec { |
| 1037 | RecordCodec::JsonV1 => corrupt(seq, "record kind byte does not match payload"), |
| 1038 | RecordCodec::BinaryV2 => SynapseError::new( |
| 1039 | RefusalCode::WalRecordMalformed, |
| 1040 | format!("record kind byte does not match payload at {seq}"), |
| 1041 | ), |
| 1042 | }); |
| 1043 | } |
| 1044 | frames.push(RecoveredFrame { |
| 1045 | seq, |
| 1046 | frame_sha256: stored_sha, |
| 1047 | codec, |
| 1048 | record: decoded.record, |
| 1049 | inline: decoded |
| 1050 | .inline |
| 1051 | .into_iter() |
| 1052 | .map(|(d, o, l)| (d, (p_start + o as usize) as u64, l)) |
| 1053 | .collect(), |
| 1054 | manifests: decoded.manifests, |
| 1055 | chunks: decoded |
| 1056 | .chunks |
| 1057 | .into_iter() |
| 1058 | .map(|(d, o, l)| (d, (p_start + o as usize) as u64, l)) |
| 1059 | .collect(), |
| 1060 | }); |
| 1061 | expected_seq = seq.next(); |
| 1062 | prev_sha = stored_sha; |
| 1063 | at = p_end; |
| 1064 | } |
| 1065 | if at + WAL_V2_BATCH_TRAILER.len() != body_end { |
| 1066 | return Err(torn("batch body length does not match its frames")); |
| 1067 | } |
| 1068 | if buf[at..body_end] != WAL_V2_BATCH_TRAILER { |
| 1069 | return Err(torn("batch trailer missing or damaged")); |
| 1070 | } |
| 1071 | Ok((frames, align_up(body_end as u64) as usize)) |
| 1072 | } |
| 1073 | |
| 1074 | /// `prev_frame_sha256` stated by the first frame of the batch at `off` (zeros when the |
| 1075 | /// bytes are missing; validation then fails on its own). |
| 1076 | pub(crate) fn first_frame_prev(buf: &[u8], off: usize) -> [u8; 32] { |
| 1077 | let at = off + WAL_V2_BATCH_HEADER_LEN; |
| 1078 | buf.get(at + 16..at + 48) |
| 1079 | .and_then(|s| s.try_into().ok()) |
| 1080 | .unwrap_or([0u8; 32]) |
| 1081 | } |
| 1082 | |
| 1083 | /// True when any 4 KiB-aligned offset at or after `from` holds a valid batch header. |
| 1084 | pub(crate) fn valid_batch_after(buf: &[u8], from: usize) -> bool { |
| 1085 | let mut o = align_up(from as u64) as usize; |
| 1086 | while o + WAL_V2_BATCH_HEADER_LEN <= buf.len() { |
| 1087 | if parse_batch_header(&buf[o..o + WAL_V2_BATCH_HEADER_LEN]).is_some() { |
| 1088 | return true; |
| 1089 | } |
| 1090 | o += WAL_V2_ALIGN as usize; |
| 1091 | } |
| 1092 | false |
| 1093 | } |
| 1094 | |
| 1095 | /// Torn-write evidence for the batch at `off` (it is invalid, and no valid batch header |
| 1096 | /// follows it). Batches go into space that was zero and synced, one batch in flight at a |
| 1097 | /// time, and every batch ends with the non-zero [`WAL_V2_BATCH_TRAILER`]. So: |
| 1098 | /// |
| 1099 | /// * Readable header: torn only if the sector holding the end of the declared extent |
| 1100 | /// reads back all zero inside the extent (that sector never reached the disk; a |
| 1101 | /// complete batch never ends in zeros, however short that last part is), and every |
| 1102 | /// byte after the extent is zero (nothing was written after it). A batch that ends |
| 1103 | /// with its trailer but fails validation is corruption, never truncated, even when its |
| 1104 | /// content holds whole zero sectors. |
| 1105 | /// * Header past the end of the file, or a declared body past it: a short file, torn. |
| 1106 | /// * Unreadable header: torn only if the header's whole sector is zero (lost). |
| 1107 | /// |
| 1108 | /// Limitation: a torn write that lost a middle sector but persisted the last one is not |
| 1109 | /// recognised as torn; recovery then fails closed even under `TruncateTornTail`. |
| 1110 | pub(crate) fn torn_evidence(buf: &[u8], off: usize) -> bool { |
| 1111 | let Some(header) = buf.get(off..off + WAL_V2_BATCH_HEADER_LEN) else { |
| 1112 | return true; |
| 1113 | }; |
| 1114 | let Some((_, body, _)) = parse_batch_header(header) else { |
| 1115 | let sector_end = (off + WAL_V2_SECTOR).min(buf.len()); |
| 1116 | return buf[off..sector_end].iter().all(|b| *b == 0); |
| 1117 | }; |
| 1118 | let Some(end) = usize::try_from(body) |
| 1119 | .ok() |
| 1120 | .and_then(|b| (off + WAL_V2_BATCH_HEADER_LEN).checked_add(b)) |
| 1121 | else { |
| 1122 | return false; |
| 1123 | }; |
| 1124 | if end > buf.len() { |
| 1125 | // The declared body runs past the end of the file: a short (torn) tail. |
| 1126 | return true; |
| 1127 | } |
| 1128 | let last_sector = ((end - 1) / WAL_V2_SECTOR * WAL_V2_SECTOR).max(off); |
| 1129 | let lost_end = buf[last_sector..end].iter().all(|b| *b == 0); |
| 1130 | let nothing_after = buf[end..].iter().all(|b| *b == 0); |
| 1131 | lost_end && nothing_after |
| 1132 | } |