| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! How much room a store takes for an imported history. |
| 5 | //! |
| 6 | //! Each test imports a whole history twice: into a store that gets no |
| 7 | //! hints, so that every object is stored whole, and into one that gets the |
| 8 | //! importer's hints, so that blobs and trees can be deltas against the same |
| 9 | //! path in the first parent. One test makes a small history on the spot; |
| 10 | //! the other clones a real public repository with the git command line, |
| 11 | //! packs it with `git gc --aggressive`, and prints the size of each store |
| 12 | //! as a ratio to git's packed objects. Both check that the deltas help and |
| 13 | //! that both stores are sound. |
| 14 | //! |
| 15 | //! The second one needs the network, so it does not run by default: |
| 16 | //! |
| 17 | //! ```text |
| 18 | //! cargo test --release -p elffuss-braid-repo --test storage_size -- --ignored --nocapture |
| 19 | //! ``` |
| 20 | //! |
| 21 | //! `BRAID_SIZE_REPO` names another repository to measure: a URL, or a path |
| 22 | //! to a local git repository. |
| 23 | |
| 24 | use std::fs; |
| 25 | use std::path::Path; |
| 26 | use std::process::Command; |
| 27 | |
| 28 | use braid_format::{Kind, ObjectId, Objects}; |
| 29 | use braid_git::{GitMap, ImportOptions, import}; |
| 30 | use braid_store::{Options, Store}; |
| 31 | |
| 32 | /// A small public repository of ordinary source code with a long history. |
| 33 | const DEFAULT_REPO: &str = "https://github.com/rust-lang/log.git"; |
| 34 | |
| 35 | /// The store without hints: [`Objects::put_similar`] falls back to |
| 36 | /// [`Objects::put`], so nothing becomes a delta. |
| 37 | struct NoHints<'a>(&'a Store); |
| 38 | |
| 39 | impl Objects for NoHints<'_> { |
| 40 | type Error = braid_store::Error; |
| 41 | |
| 42 | fn get(&self, id: &ObjectId) -> Result<Option<(Kind, Vec<u8>)>, Self::Error> { |
| 43 | self.0.get(id) |
| 44 | } |
| 45 | |
| 46 | fn put(&self, kind: Kind, payload: &[u8]) -> Result<ObjectId, Self::Error> { |
| 47 | self.0.put(kind, payload) |
| 48 | } |
| 49 | |
| 50 | fn contains(&self, id: &ObjectId) -> Result<bool, Self::Error> { |
| 51 | self.0.contains(id) |
| 52 | } |
| 53 | |
| 54 | fn stat(&self, id: &ObjectId) -> Result<Option<(Kind, u64)>, Self::Error> { |
| 55 | self.0.stat(id) |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | /// Bytes of every file below `dir`. |
| 60 | fn size_of(dir: &Path) -> u64 { |
| 61 | let mut total = 0; |
| 62 | for entry in fs::read_dir(dir).unwrap() { |
| 63 | let entry = entry.unwrap(); |
| 64 | let meta = entry.metadata().unwrap(); |
| 65 | if meta.is_dir() { |
| 66 | total += size_of(&entry.path()); |
| 67 | } else { |
| 68 | total += meta.len(); |
| 69 | } |
| 70 | } |
| 71 | total |
| 72 | } |
| 73 | |
| 74 | fn git(args: &[&str]) { |
| 75 | let status = Command::new("git") |
| 76 | .args(args) |
| 77 | .env("GIT_TERMINAL_PROMPT", "0") |
| 78 | .status() |
| 79 | .expect("run git"); |
| 80 | assert!(status.success(), "git {args:?} failed"); |
| 81 | } |
| 82 | |
| 83 | /// Runs git in `dir` with a fixed identity and date, ignoring the user's |
| 84 | /// configuration. |
| 85 | fn git_in(dir: &Path, args: &[&str]) { |
| 86 | let status = Command::new("git") |
| 87 | .current_dir(dir) |
| 88 | .args([ |
| 89 | "-c", |
| 90 | "init.defaultBranch=main", |
| 91 | "-c", |
| 92 | "commit.gpgSign=false", |
| 93 | ]) |
| 94 | .args(args) |
| 95 | .env("GIT_CONFIG_GLOBAL", "/dev/null") |
| 96 | .env("GIT_CONFIG_NOSYSTEM", "1") |
| 97 | .env("GIT_AUTHOR_NAME", "Ada") |
| 98 | .env("GIT_AUTHOR_EMAIL", "ada@example.org") |
| 99 | .env("GIT_COMMITTER_NAME", "Ada") |
| 100 | .env("GIT_COMMITTER_EMAIL", "ada@example.org") |
| 101 | .env("GIT_AUTHOR_DATE", "1700000000 +0100") |
| 102 | .env("GIT_COMMITTER_DATE", "1700000000 +0100") |
| 103 | .status() |
| 104 | .expect("run git"); |
| 105 | assert!(status.success(), "git {args:?} failed"); |
| 106 | } |
| 107 | |
| 108 | /// Source-like text: lines that compress only a little on their own. |
| 109 | fn text(seed: u64, lines: usize) -> String { |
| 110 | let mut state = seed | 1; |
| 111 | let mut out = String::new(); |
| 112 | for i in 0..lines { |
| 113 | state ^= state << 13; |
| 114 | state ^= state >> 7; |
| 115 | state ^= state << 17; |
| 116 | out.push_str(&format!("pub const C{i}: u64 = 0x{state:016x};\n")); |
| 117 | } |
| 118 | out |
| 119 | } |
| 120 | |
| 121 | /// A history made on the spot: a file edited a little in every commit, in a |
| 122 | /// directory with enough files to be split into several tree nodes. |
| 123 | #[test] |
| 124 | fn an_imported_history_keeps_versions_as_deltas() { |
| 125 | let tmp = tempfile::tempdir().unwrap(); |
| 126 | let work = tmp.path().join("work"); |
| 127 | fs::create_dir_all(work.join("src/many")).unwrap(); |
| 128 | git_in(&work, &["init", "-q"]); |
| 129 | for i in 0..1100 { |
| 130 | fs::write(work.join(format!("src/many/f{i:04}.txt")), format!("{i}\n")).unwrap(); |
| 131 | } |
| 132 | let mut lib = text(1, 2000); |
| 133 | for n in 0..12 { |
| 134 | let at = (n * 4099) % (lib.len() - 20); |
| 135 | lib.replace_range(at..at + 10, &format!("/*{n:06}*/")); |
| 136 | fs::write(work.join("src/lib.rs"), &lib).unwrap(); |
| 137 | fs::write( |
| 138 | work.join(format!("src/many/f{:04}.txt", n * 97)), |
| 139 | format!("v{n}\n"), |
| 140 | ) |
| 141 | .unwrap(); |
| 142 | git_in(&work, &["add", "-A"]); |
| 143 | git_in(&work, &["commit", "-q", "-m", &format!("change {n}")]); |
| 144 | } |
| 145 | |
| 146 | let whole = import_into(&work, &tmp.path().join("whole"), false); |
| 147 | let deltas = import_into(&work, &tmp.path().join("deltas"), true); |
| 148 | let whole_report = whole.fsck().unwrap(); |
| 149 | let report = deltas.fsck().unwrap(); |
| 150 | assert!(whole_report.is_clean(), "{:#?}", whole_report.problems); |
| 151 | assert!(report.is_clean(), "{:#?}", report.problems); |
| 152 | assert_eq!(whole_report.delta_records, 0); |
| 153 | // Eleven later versions of the file, and of most tree nodes on the path |
| 154 | // to the files that changed: a node may stay whole when a delta would |
| 155 | // not take a quarter of it or less. |
| 156 | assert!(report.delta_records >= 11 * 2, "{report:?}"); |
| 157 | assert_eq!(report.objects, whole_report.objects); |
| 158 | let stats = deltas.stats().unwrap(); |
| 159 | let delta = stats |
| 160 | .codecs |
| 161 | .iter() |
| 162 | .find(|c| c.codec == braid_store::Codec::Delta) |
| 163 | .unwrap(); |
| 164 | assert!(delta.stored_bytes * 50 < delta.raw_bytes, "{delta:?}"); |
| 165 | assert!(size_of(deltas.root()) < size_of(whole.root())); |
| 166 | } |
| 167 | |
| 168 | /// Importing again stores the git map, which grew by a few pairings, as a |
| 169 | /// delta against the map it grew from rather than whole again. |
| 170 | #[test] |
| 171 | fn a_git_map_is_stored_against_the_one_it_grew_from() { |
| 172 | let tmp = tempfile::tempdir().unwrap(); |
| 173 | let work = tmp.path().join("work"); |
| 174 | fs::create_dir_all(work.join("files")).unwrap(); |
| 175 | git_in(&work, &["init", "-q"]); |
| 176 | for i in 0..300 { |
| 177 | fs::write(work.join(format!("files/f{i:03}.txt")), format!("{i}\n")).unwrap(); |
| 178 | } |
| 179 | git_in(&work, &["add", "-A"]); |
| 180 | git_in(&work, &["commit", "-q", "-m", "first"]); |
| 181 | let repo = braid_repo::Repo::init(&tmp.path().join("braid")).unwrap(); |
| 182 | repo.git_import(&work, "tester").unwrap(); |
| 183 | |
| 184 | fs::write(work.join("files/f000.txt"), "changed\n").unwrap(); |
| 185 | git_in(&work, &["commit", "-q", "-a", "-m", "second"]); |
| 186 | repo.git_import(&work, "tester").unwrap(); |
| 187 | |
| 188 | let stats = repo.store().stats().unwrap(); |
| 189 | let maps = stats |
| 190 | .kinds |
| 191 | .iter() |
| 192 | .find(|k| k.kind == Kind::Derived) |
| 193 | .unwrap(); |
| 194 | assert_eq!(maps.objects, 2); |
| 195 | // Two maps of almost the same size: the second one takes little room. |
| 196 | assert!(maps.stored_bytes * 10 < maps.raw_bytes * 6, "{maps:?}"); |
| 197 | assert!(repo.store().fsck().unwrap().is_clean()); |
| 198 | } |
| 199 | |
| 200 | /// Imports every branch and tag of the git repository `git_dir` into a new |
| 201 | /// store at `dir`, with or without hints, and returns the store. |
| 202 | fn import_into(git_dir: &Path, dir: &Path, hints: bool) -> Store { |
| 203 | let store = Store::init(dir, Options::default()).unwrap(); |
| 204 | let mut map = GitMap::new(); |
| 205 | let options = ImportOptions::default(); |
| 206 | let report = if hints { |
| 207 | import(git_dir, &store, &mut map, &options) |
| 208 | } else { |
| 209 | import(git_dir, &NoHints(&store), &mut map, &options) |
| 210 | } |
| 211 | .unwrap_or_else(|err| panic!("import: {err}")); |
| 212 | assert!(report.commits > 0, "{report:?}"); |
| 213 | // The map is part of what an import keeps, as `braid git import` does. |
| 214 | store.put(Kind::Derived, &map.to_bytes()).unwrap(); |
| 215 | store.sync().unwrap(); |
| 216 | store |
| 217 | } |
| 218 | |
| 219 | #[test] |
| 220 | #[ignore = "clones a public repository; run with --ignored"] |
| 221 | fn size_of_a_real_history() { |
| 222 | let source = std::env::var("BRAID_SIZE_REPO").unwrap_or_else(|_| DEFAULT_REPO.to_owned()); |
| 223 | let tmp = tempfile::tempdir().unwrap(); |
| 224 | let bare = tmp.path().join("repo.git"); |
| 225 | let bare_text = bare.to_str().unwrap(); |
| 226 | git(&[ |
| 227 | "clone", |
| 228 | "--quiet", |
| 229 | "--bare", |
| 230 | "--no-local", |
| 231 | &source, |
| 232 | bare_text, |
| 233 | ]); |
| 234 | git(&[ |
| 235 | "-C", |
| 236 | bare_text, |
| 237 | "gc", |
| 238 | "--quiet", |
| 239 | "--aggressive", |
| 240 | "--prune=now", |
| 241 | ]); |
| 242 | let git_size = size_of(&bare.join("objects")); |
| 243 | |
| 244 | let whole = import_into(&bare, &tmp.path().join("whole"), false); |
| 245 | let deltas = import_into(&bare, &tmp.path().join("deltas"), true); |
| 246 | let whole_size = size_of(whole.root()); |
| 247 | let deltas_size = size_of(deltas.root()); |
| 248 | |
| 249 | let ratio = |a: u64, b: u64| a as f64 / b as f64; |
| 250 | let stats = deltas.stats().unwrap(); |
| 251 | let report = deltas.fsck().unwrap(); |
| 252 | eprintln!( |
| 253 | "braid / git gc --aggressive, without deltas: {:.2}", |
| 254 | ratio(whole_size, git_size) |
| 255 | ); |
| 256 | eprintln!( |
| 257 | "braid / git gc --aggressive, with deltas: {:.2}", |
| 258 | ratio(deltas_size, git_size) |
| 259 | ); |
| 260 | eprintln!( |
| 261 | "with deltas / without: {:.2}", |
| 262 | ratio(deltas_size, whole_size) |
| 263 | ); |
| 264 | eprintln!( |
| 265 | "objects stored as deltas: {} of {}", |
| 266 | report.delta_records, report.records |
| 267 | ); |
| 268 | for codec in &stats.codecs { |
| 269 | if codec.objects > 0 { |
| 270 | eprintln!( |
| 271 | " {}: {:.3} of the objects, {:.3} of the stored bytes", |
| 272 | codec.codec.name(), |
| 273 | ratio(codec.objects, stats.objects), |
| 274 | ratio(codec.stored_bytes, stats.stored_bytes) |
| 275 | ); |
| 276 | } |
| 277 | } |
| 278 | for kind in &stats.kinds { |
| 279 | if kind.objects > 0 { |
| 280 | eprintln!( |
| 281 | " {}: {:.3} of the objects, {:.3} of the stored bytes", |
| 282 | kind.kind.name(), |
| 283 | ratio(kind.objects, stats.objects), |
| 284 | ratio(kind.stored_bytes, stats.stored_bytes) |
| 285 | ); |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | assert!(report.is_clean(), "{:#?}", report.problems); |
| 290 | assert!(report.delta_records > 0, "{report:?}"); |
| 291 | assert!(whole.fsck().unwrap().is_clean()); |
| 292 | assert!(deltas_size < whole_size); |
| 293 | // Both stores hold the same objects. |
| 294 | assert_eq!(whole.stats().unwrap().objects, stats.objects); |
| 295 | } |