| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Deltas (codec 3): an object compressed with zstd against the raw payload |
| 5 | //! of another object, its base. |
| 6 | //! |
| 7 | //! The base is given to zstd as a reference prefix: the frame is an ordinary |
| 8 | //! zstd frame whose matches may reach back into the base, so decoding it |
| 9 | //! needs the base and nothing else. The window covers the base and the |
| 10 | //! object together, and long-distance matching finds the parts they share |
| 11 | //! however far apart they are. |
| 12 | //! |
| 13 | //! Depth is always one: a base is stored whole, never as a delta itself. |
| 14 | //! When the object a writer names as similar is a delta, the delta is made |
| 15 | //! against that delta's own base instead. So each delta holds every change |
| 16 | //! since its base, and grows version after version until it is no longer |
| 17 | //! worth it; the next version is then stored whole and becomes the base of |
| 18 | //! the ones after it. |
| 19 | |
| 20 | use braid_format::{Kind, ObjectId}; |
| 21 | use zstd::zstd_safe::{CCtx, CParameter}; |
| 22 | |
| 23 | use crate::record::{self, Header, RAW_MAX, ZSTD_LEVEL}; |
| 24 | |
| 25 | /// A delta is kept only when it takes at most this fraction of the bytes of |
| 26 | /// the object stored on its own: one quarter. |
| 27 | /// |
| 28 | /// The fraction decides how often a version is stored whole again. Imports |
| 29 | /// of the histories of four public repositories, compared with the same |
| 30 | /// histories packed by `git gc --aggressive`, took 2.9 to 3.7 times git's |
| 31 | /// size keeping deltas up to a half, 2.6 to 3.3 times up to a third, 2.5 to |
| 32 | /// 3.1 times up to a quarter, and 2.6 to 3.1 times up to a sixth: past a |
| 33 | /// quarter, the extra versions stored whole cost more than the shorter |
| 34 | /// deltas save. |
| 35 | const KEEP_DENOMINATOR: usize = 4; |
| 36 | |
| 37 | /// Blobs smaller than this may be stored as deltas; larger ones are stored |
| 38 | /// in chunks instead. Trees and derived objects, such as the git map, may |
| 39 | /// be deltas whatever their size. Changesets never are: against their first |
| 40 | /// parent, imported histories gave no delta that made the cut, and one in |
| 41 | /// thousands at twice the fraction. |
| 42 | pub(crate) const BLOB_MAX: u64 = crate::chunks::CHUNKED_MIN; |
| 43 | |
| 44 | /// The largest window a delta may use: 128 MiB, the largest that zstd |
| 45 | /// decoders accept without being told to. |
| 46 | const MAX_WINDOW_LOG: u32 = 27; |
| 47 | |
| 48 | /// The smallest window zstd has. |
| 49 | const MIN_WINDOW_LOG: u32 = 10; |
| 50 | |
| 51 | /// Whether an object of `kind` and `len` bytes may be stored as a delta. |
| 52 | pub(crate) fn eligible(kind: Kind, len: usize) -> bool { |
| 53 | // Small payloads are stored raw: a base id costs more than it saves. |
| 54 | if len <= RAW_MAX { |
| 55 | return false; |
| 56 | } |
| 57 | match kind { |
| 58 | Kind::Tree | Kind::Derived => true, |
| 59 | Kind::Blob => (len as u64) < BLOB_MAX, |
| 60 | _ => false, |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | /// The window, as a power of two, that holds `len` bytes, if zstd allows it. |
| 65 | fn window_log(len: usize) -> Option<u32> { |
| 66 | let log = usize::BITS - len.saturating_sub(1).leading_zeros(); |
| 67 | (log <= MAX_WINDOW_LOG).then_some(log.max(MIN_WINDOW_LOG)) |
| 68 | } |
| 69 | |
| 70 | /// Compresses `payload` against `base`. `None` if the two do not fit in one |
| 71 | /// window or zstd fails; the caller then stores the payload on its own. |
| 72 | pub(crate) fn compress(payload: &[u8], base: &[u8]) -> Option<Vec<u8>> { |
| 73 | let window = window_log(base.len().checked_add(payload.len())?)?; |
| 74 | let mut context = CCtx::try_create()?; |
| 75 | context |
| 76 | .set_parameter(CParameter::CompressionLevel(ZSTD_LEVEL)) |
| 77 | .ok()?; |
| 78 | context.set_parameter(CParameter::WindowLog(window)).ok()?; |
| 79 | context |
| 80 | .set_parameter(CParameter::EnableLongDistanceMatching(true)) |
| 81 | .ok()?; |
| 82 | context.ref_prefix(base).ok()?; |
| 83 | let mut out = Vec::with_capacity(zstd::zstd_safe::compress_bound(payload.len())); |
| 84 | context.compress2(&mut out, payload).ok()?; |
| 85 | Some(out) |
| 86 | } |
| 87 | |
| 88 | /// Restores the payload of a delta record from its stored frame and the raw |
| 89 | /// payload of its base, and verifies that it hashes to the record's id. |
| 90 | pub(crate) fn decode(header: &Header, stored: &[u8], base: &[u8]) -> Result<Vec<u8>, &'static str> { |
| 91 | let mut decoder = |
| 92 | zstd::stream::read::Decoder::with_ref_prefix(stored, base).map_err(|_| "bad zstd data")?; |
| 93 | decoder |
| 94 | .window_log_max(MAX_WINDOW_LOG) |
| 95 | .map_err(|_| "bad zstd data")?; |
| 96 | let payload = record::read_capped(decoder, header.raw_len)?; |
| 97 | record::verify(header, &payload)?; |
| 98 | Ok(payload) |
| 99 | } |
| 100 | |
| 101 | /// The record for `payload` as a delta against `base`, if it is worth it: |
| 102 | /// the frame and the base id together must take at most a quarter of the |
| 103 | /// bytes of the payload stored on its own (`standalone_len`). |
| 104 | pub(crate) fn encode( |
| 105 | kind: Kind, |
| 106 | id: ObjectId, |
| 107 | payload: &[u8], |
| 108 | base_id: &ObjectId, |
| 109 | base: &[u8], |
| 110 | standalone_len: usize, |
| 111 | ) -> Option<record::Encoded> { |
| 112 | let frame = compress(payload, base)?; |
| 113 | let cost = frame.len() + record::REFERENCE_LEN; |
| 114 | if cost.saturating_mul(KEEP_DENOMINATOR) > standalone_len { |
| 115 | return None; |
| 116 | } |
| 117 | record::assemble( |
| 118 | kind, |
| 119 | id, |
| 120 | record::CODEC_DELTA, |
| 121 | payload.len() as u64, |
| 122 | Some(base_id), |
| 123 | &frame, |
| 124 | ) |
| 125 | .ok() |
| 126 | } |
| 127 | |
| 128 | #[cfg(test)] |
| 129 | mod tests { |
| 130 | use super::*; |
| 131 | use crate::record::{CODEC_DELTA, check, standalone}; |
| 132 | |
| 133 | /// Text that compresses only a little on its own, as source code does. |
| 134 | fn text(seed: u64, lines: usize) -> Vec<u8> { |
| 135 | let mut state = seed | 1; |
| 136 | let mut out = Vec::new(); |
| 137 | for i in 0..lines { |
| 138 | state ^= state << 13; |
| 139 | state ^= state >> 7; |
| 140 | state ^= state << 17; |
| 141 | out.extend_from_slice(format!("line {i}: value {state:016x}\n").as_bytes()); |
| 142 | } |
| 143 | out |
| 144 | } |
| 145 | |
| 146 | #[test] |
| 147 | fn a_small_edit_is_a_small_delta() { |
| 148 | let base = text(7, 2000); |
| 149 | let mut edited = base.clone(); |
| 150 | edited[30_000..30_010].copy_from_slice(b"EDITED...."); |
| 151 | edited.extend_from_slice(b"one more line\n"); |
| 152 | let id = ObjectId::hash(Kind::Blob, &edited); |
| 153 | let base_id = ObjectId::hash(Kind::Blob, &base); |
| 154 | let (_, alone) = standalone(&edited); |
| 155 | let encoded = encode(Kind::Blob, id, &edited, &base_id, &base, alone.len()).unwrap(); |
| 156 | assert_eq!(encoded.header.codec, CODEC_DELTA); |
| 157 | assert!( |
| 158 | (encoded.header.stored_len as usize) * 20 < alone.len(), |
| 159 | "{} against {}", |
| 160 | encoded.header.stored_len, |
| 161 | alone.len() |
| 162 | ); |
| 163 | let checked = check(&encoded.bytes).unwrap(); |
| 164 | assert_eq!(checked.reference, Some(base_id)); |
| 165 | assert_eq!( |
| 166 | decode(&checked.header, checked.stored, &base).unwrap(), |
| 167 | edited |
| 168 | ); |
| 169 | // Another base gives a wrong payload, which the id check catches. |
| 170 | assert!(decode(&checked.header, checked.stored, &text(8, 2000)).is_err()); |
| 171 | } |
| 172 | |
| 173 | #[test] |
| 174 | fn unrelated_content_is_not_worth_a_delta() { |
| 175 | let payload = text(1, 500); |
| 176 | let base = text(2, 500); |
| 177 | let id = ObjectId::hash(Kind::Blob, &payload); |
| 178 | let (_, alone) = standalone(&payload); |
| 179 | assert!( |
| 180 | encode( |
| 181 | Kind::Blob, |
| 182 | id, |
| 183 | &payload, |
| 184 | &ObjectId::hash(Kind::Blob, &base), |
| 185 | &base, |
| 186 | alone.len() |
| 187 | ) |
| 188 | .is_none() |
| 189 | ); |
| 190 | } |
| 191 | |
| 192 | #[test] |
| 193 | fn windows_cover_base_and_payload() { |
| 194 | assert_eq!(window_log(0), Some(MIN_WINDOW_LOG)); |
| 195 | assert_eq!(window_log(1024), Some(10)); |
| 196 | assert_eq!(window_log(1025), Some(11)); |
| 197 | assert_eq!(window_log(8 << 20), Some(23)); |
| 198 | assert_eq!(window_log(1 << 27), Some(27)); |
| 199 | assert_eq!(window_log((1 << 27) + 1), None); |
| 200 | } |
| 201 | |
| 202 | #[test] |
| 203 | fn who_may_be_a_delta() { |
| 204 | assert!(!eligible(Kind::Blob, RAW_MAX)); |
| 205 | assert!(eligible(Kind::Blob, RAW_MAX + 1)); |
| 206 | assert!(eligible(Kind::Blob, BLOB_MAX as usize - 1)); |
| 207 | assert!(!eligible(Kind::Blob, BLOB_MAX as usize)); |
| 208 | assert!(eligible(Kind::Tree, 10 << 20)); |
| 209 | assert!(!eligible(Kind::Changeset, 1000)); |
| 210 | assert!(eligible(Kind::Derived, 10 << 20)); |
| 211 | assert!(!eligible(Kind::ChunkList, 1000)); |
| 212 | } |
| 213 | } |