OXYGENHUB

Coverage / crates/hub/src/repos/cache.rs 84.9%

241 of 284 lines run, 57 of 73 functions · run #532 on main · run missed

1
//! Loaded states cached by their heads (hub spec §16.3). A state is a pure
2
//! function of its heads, so entries never go stale; the cache is only
3
//! bounded. Shared across threads because `oxy_core::state::State` is
4
//! `Send + Sync`.
5
6
use oxy_core::hash::ChangeHash;
7
use oxy_core::repo::Repo;
8
use oxy_core::state::{Snapshot, State};
9
use std::collections::HashMap;
10
use std::path::{Path, PathBuf};
11
use std::sync::{Arc, Mutex};
12
13
/// A state and its materialised snapshot.
14
pub struct Loaded {
15
    pub heads: Vec<ChangeHash>,
16
    pub state: State,
17
    pub snapshot: Snapshot,
18
}
19
20
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
21
struct Key {
22
    repo: [u8; 16],
23
    heads: Vec<ChangeHash>,
24
}
25
26
struct Entry {
27
    loaded: Arc<Loaded>,
28
    last_used: u64,
29
    /// Its estimated size in bytes (`weight`).
30
    weight: usize,
31
}
32
33
/// A loaded state's estimated size (oxygenhub#246): five bytes per byte of
34
/// text and 384 per line (each file's line graph), and a kilobyte per change.
35
/// Measured on 2026-10-17 against what loading a state really adds to the
36
/// process (`measures_a_real_state`): oxygen's states ~85 MiB, oxygenhub's
37
/// ~70 MiB, which this puts at 88 and 75. The older "text three times over"
38
/// said 18 and 28, so a cache that thought it held 2.5 GB held 6-8 GB.
39331×
fn weight(l: &Loaded) -> usize {
40331×
    let (mut text, mut lines) = (0usize, 0usize);
41830×
    for f in l.snapshot.files.values() {
42830×
        match &f.content {
43613×
            oxy_core::state::FileContent::Text { bytes, .. } => {
44613×
                text += bytes.len();
4565229×
                lines += bytes.iter().filter(|b| **b == b'\n').count() + 1;
46
            }
47217×
            _ => text += 64,
48
        }
49
    }
50331×
    text.saturating_mul(5).saturating_add(lines.saturating_mul(384)).saturating_add(l.state.len().saturating_mul(1024))
51331×
}
52
53
/// What the state cache may hold, in bytes: OXYHUB_STATE_CACHE_MB, else
54
/// 3 GiB. A count alone let a few large repositories' states grow the hub
55
/// to 17 GB.
56426×
pub fn budget() -> usize {
57426×
    std::env::var("OXYHUB_STATE_CACHE_MB").ok().and_then(|v| v.parse::<usize>().ok()).unwrap_or(3 * 1024).saturating_mul(1 << 20)
58426×
}
59
60
/// What the bookmark lists and a change's "in bookmarks" need of a state:
61
/// small, so many are kept, and computed without filling the state cache.
62
/// A repository with more bookmarks than the state cache holds otherwise
63
/// cycled through it on every such page, so nothing stayed cached
64
/// (metalgear's 128 bookmarks: 7.7 s per change page, and every page of
65
/// every repository slower after it).
66
pub struct Summary {
67
    pub changes: std::collections::HashSet<ChangeHash>,
68
    pub latest_ms: u64,
69
    pub conflicted: bool,
70
}
71
72
impl Summary {
73678×
    pub fn brief(&self) -> Brief {
74678×
        Brief { changes: self.changes.len(), latest_ms: self.latest_ms, conflicted: self.conflicted }
75678×
    }
76
}
77
78
/// What a bookmark list and the overview show of a state (#145): how many
79
/// changes, the latest, and whether it is conflicted. A pure function of
80
/// the heads, so it is kept on disk as well and a restart costs nothing:
81
/// metalgear's 162 bookmarks took ~31 s to summarise again after one.
82
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
83
pub struct Brief {
84
    pub changes: usize,
85
    pub latest_ms: u64,
86
    pub conflicted: bool,
87
}
88
89
/// Summaries kept; each is the state's change set, a few hundred kilobytes
90
/// for a long history.
91
const SUMMARIES: usize = 2048;
92
/// Most summaries computed at once when a page needs many.
93
const PARALLEL: usize = 4;
94
95
/// Summaries by heads, each with when it was last used, and the clock.
96
type Summaries = (HashMap<Key, (Arc<Summary>, u64)>, u64);
97
98
/// A bounded least-recently-used cache of loaded states.
99
pub struct StateCache {
100
    capacity: usize,
101
    /// Bytes of estimated state it may hold (`budget`).
102
    budget: usize,
103
    inner: Mutex<(HashMap<Key, Entry>, u64)>,
104
    summaries: Mutex<Summaries>,
105
    /// Where briefs are kept on disk, when anywhere.
106
    briefs: Option<PathBuf>,
107
}
108
109
impl StateCache {
110417×
    pub fn new(capacity: usize) -> StateCache {
111417×
        StateCache::with_budget(capacity, budget())
112417×
    }
113
114419×
    pub fn with_budget(capacity: usize, budget: usize) -> StateCache {
115419×
        StateCache {
116419×
            capacity: capacity.max(1),
117419×
            budget,
118419×
            inner: Mutex::new((HashMap::new(), 0)),
119419×
            summaries: Mutex::new((HashMap::new(), 0)),
120419×
            briefs: None,
121419×
        }
122419×
    }
123
124
    /// Keep briefs on disk under `dir`, one small file per state.
125414×
    pub fn with_briefs(mut self, dir: PathBuf) -> StateCache {
126414×
        self.briefs = Some(dir);
127414×
        self
128414×
    }
129
130333×
    fn brief_path(&self, key: &Key) -> Option<PathBuf> {
131333×
        let dir = self.briefs.as_ref()?;
132331×
        let mut h = blake3::Hasher::new();
133521×
        for c in &key.heads {
134521×
            h.update(&c.0);
135521×
        }
136331×
        Some(dir.join(hex::encode(key.repo)).join(h.finalize().to_hex().as_str()))
137333×
    }
138
139404×
    fn known_brief(&self, key: &Key) -> Option<Brief> {
140404×
        if let Some((s, _)) = self.summaries.lock().unwrap().0.get(key) {
141349×
            return Some(s.brief());
14255×
        }
14355×
        read_brief(&self.brief_path(key)?)
144404×
    }
145
146
    /// The brief of the state with these heads: from memory, from disk, or
147
    /// worked out and kept.
1482×
    pub fn brief(&self, repo: &Repo, heads: &[ChangeHash]) -> Result<Brief, oxy_core::repo::RepoError> {
1492×
        Ok(self.briefs(repo, &[heads.to_vec()])?[0])
1502×
    }
151
152
    /// The briefs of many states, those not yet known worked out a few at
153
    /// a time in parallel.
154333×
    pub fn briefs(&self, repo: &Repo, all: &[Vec<ChangeHash>]) -> Result<Vec<Brief>, oxy_core::repo::RepoError> {
155333×
        let id = repo.id()?;
156404×
        let mut out: Vec<Option<Brief>> = all.iter().map(|h| self.known_brief(&Key { repo: id, heads: sorted(h) })).collect();
157404×
        let missing: Vec<usize> = (0..all.len()).filter(|&i| out[i].is_none()).collect();
158333×
        if missing.is_empty() {
159311×
            return Ok(out.into_iter().map(|b| b.expect("known")).collect());
16050×
        }
16150×
        let next = Mutex::new(missing.iter());
16250×
        let found: Mutex<Vec<(usize, Result<Brief, oxy_core::repo::RepoError>)>> = Mutex::new(Vec::new());
16350×
        let threads = PARALLEL.min(missing.len()).min(std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1));
164
        // A `Repo` stays on its thread, so each worker opens its own.
16550×
        let root = repo.root().to_path_buf();
16650×
        std::thread::scope(|s| {
16750×
            for _ in 0..threads {
16854×
                s.spawn(|| {
16954×
                    let mine = Repo::open(&root);
170
                    loop {
171108×
                        let Some(&i) = next.lock().unwrap().next() else { break };
17254×
                        let b = match &mine {
17354×
                            Ok(r) => self.summary(r, &all[i]).map(|s| s.brief()),
1740×
                            Err(e) => Err(oxy_core::repo::RepoError::Msg(format!("open {}: {e}", root.display()))),
175
                        };
17654×
                        found.lock().unwrap().push((i, b));
177
                    }
17854×
                });
179
            }
18050×
        });
18154×
        for (i, b) in found.into_inner().unwrap() {
18254×
            out[i] = Some(b?);
183
        }
18490×
        Ok(out.into_iter().map(|b| b.expect("worked out")).collect())
185333×
    }
186
187
    /// The summary of the state with these heads: from the state cache when
188
    /// it holds the state, else loaded and dropped, the state cache left as
189
    /// it was.
190498×
    pub fn summary(&self, repo: &Repo, heads: &[ChangeHash]) -> Result<Arc<Summary>, oxy_core::repo::RepoError> {
191498×
        let sorted = sorted(heads);
192498×
        let key = Key { repo: repo.id()?, heads: sorted.clone() };
193
        {
194498×
            let mut guard = self.summaries.lock().unwrap();
195498×
            let (map, tick) = &mut *guard;
196498×
            *tick += 1;
197498×
            if let Some(e) = map.get_mut(&key) {
198217×
                e.1 = *tick;
199217×
                return Ok(e.0.clone());
200281×
            }
201
        }
202281×
        let held = self.inner.lock().unwrap().0.get(&key).map(|e| e.loaded.clone());
203281×
        let summary = Arc::new(match held {
20433×
            Some(l) => summarise(&l.state, &l.snapshot),
205
            None => {
206248×
                let state = repo.load_state(&sorted)?;
207245×
                let snapshot = state.materialize();
208245×
                summarise(&state, &snapshot)
209
            }
210
        });
211278×
        if let Some(path) = self.brief_path(&key) {
212277×
            write_brief(&path, summary.brief());
213277×
        }
214278×
        let mut guard = self.summaries.lock().unwrap();
215278×
        let (map, tick) = &mut *guard;
216278×
        if map.len() >= SUMMARIES {
2170×
            if let Some(oldest) = map.iter().min_by_key(|(_, e)| e.1).map(|(k, _)| k.clone()) {
2180×
                map.remove(&oldest);
2190×
            }
220278×
        }
221278×
        map.insert(key, (summary.clone(), *tick));
222278×
        Ok(summary)
223498×
    }
224
225
    /// The state with these heads, loaded once per hub process.
2261631×
    pub fn load(&self, repo: &Repo, heads: &[ChangeHash]) -> Result<Arc<Loaded>, oxy_core::repo::RepoError> {
2271631×
        let mut sorted = heads.to_vec();
2281631×
        sorted.sort();
2291631×
        sorted.dedup();
2301631×
        let key = Key { repo: repo.id()?, heads: sorted.clone() };
231
        {
2321630×
            let mut guard = self.inner.lock().unwrap();
2331630×
            let (map, tick) = &mut *guard;
2341630×
            *tick += 1;
2351630×
            if let Some(e) = map.get_mut(&key) {
2361298×
                e.last_used = *tick;
2371298×
                return Ok(e.loaded.clone());
238332×
            }
239
        }
240332×
        let state = repo.load_state(&sorted)?;
241331×
        let snapshot = state.materialize();
242331×
        let loaded = Arc::new(Loaded { heads: sorted, state, snapshot });
243331×
        let w = weight(&loaded);
244331×
        let mut guard = self.inner.lock().unwrap();
245331×
        let (map, tick) = &mut *guard;
246
        // The oldest go until it fits by count and by size; the new one
247
        // stays even when it alone is over the budget.
248331×
        let budget = self.budget;
249331×
        let mut total: usize = map.values().map(|e| e.weight).sum::<usize>() + w;
250332×
        while !map.is_empty() && (map.len() >= self.capacity || total > budget) {
2511×
            let Some(oldest) = map.iter().min_by_key(|(_, e)| e.last_used).map(|(k, _)| k.clone()) else {
2520×
                break;
253
            };
2541×
            if let Some(e) = map.remove(&oldest) {
2551×
                total -= e.weight;
2561×
            }
257
        }
258331×
        map.insert(key, Entry { loaded: loaded.clone(), last_used: *tick, weight: w });
259331×
        Ok(loaded)
2601631×
    }
261
262
    /// What it holds: loaded states, their estimated bytes, and summaries.
2639×
    pub fn stats(&self) -> (usize, usize, usize) {
2649×
        let (entries, weight) = {
2659×
            let guard = self.inner.lock().unwrap();
2669×
            (guard.0.len(), guard.0.values().map(|e| e.weight).sum())
267
        };
2689×
        (entries, weight, self.summaries.lock().unwrap().0.len())
2699×
    }
270
2716×
    pub fn len(&self) -> usize {
2726×
        self.inner.lock().unwrap().0.len()
2736×
    }
274
2750×
    pub fn is_empty(&self) -> bool {
2760×
        self.len() == 0
2770×
    }
278
}
279
280902×
fn sorted(heads: &[ChangeHash]) -> Vec<ChangeHash> {
281902×
    let mut v = heads.to_vec();
282902×
    v.sort();
283902×
    v.dedup();
284902×
    v
285902×
}
286
287
/// A brief on disk: `changes latest_ms conflicted`.
28854×
fn read_brief(path: &Path) -> Option<Brief> {
28954×
    let text = std::fs::read_to_string(path).ok()?;
2901×
    let mut f = text.split_whitespace();
2911×
    Some(Brief { changes: f.next()?.parse().ok()?, latest_ms: f.next()?.parse().ok()?, conflicted: f.next()? == "1" })
29254×
}
293
294
/// Kept when it can be; a brief that is not kept is only worked out again.
295277×
fn write_brief(path: &Path, b: Brief) {
296277×
    let Some(dir) = path.parent() else { return };
297277×
    if std::fs::create_dir_all(dir).is_err() {
2980×
        return;
299277×
    }
300277×
    let tmp = path.with_extension(format!("tmp{}", std::process::id()));
301277×
    if std::fs::write(&tmp, format!("{} {} {}", b.changes, b.latest_ms, u8::from(b.conflicted))).is_ok() {
302277×
        std::fs::rename(&tmp, path).ok();
303277×
    }
304277×
}
305
306278×
fn summarise(state: &State, snapshot: &Snapshot) -> Summary {
307
    Summary {
308278×
        changes: state.changes().map(|(h, _)| *h).collect(),
309278×
        latest_ms: state.changes().map(|(_, m)| m.hlc.wall_ms).max().unwrap_or(0),
310278×
        conflicted: snapshot.is_conflicted(),
311
    }
312278×
}
313
314
#[cfg(test)]
315
mod tests {
316
    use super::*;
317
318
    /// What a loaded state really costs against `weight` (oxygenhub#246):
319
    /// `OXYHUB_MEASURE_REPO=path cargo test -p oxygenhub --lib
320
    /// measures_a_real_state -- --ignored --nocapture`.
321
    #[test]
322
    #[ignore]
3230×
    fn measures_a_real_state() {
3240×
        fn rss_kib() -> usize {
3250×
            let s = std::fs::read_to_string("/proc/self/status").unwrap();
3260×
            s.lines().find(|l| l.starts_with("VmRSS:")).and_then(|l| l.split_whitespace().nth(1)).unwrap().parse().unwrap()
3270×
        }
3280×
        let path = std::env::var("OXYHUB_MEASURE_REPO").expect("OXYHUB_MEASURE_REPO");
3290×
        let repo = Repo::open(std::path::Path::new(&path)).unwrap();
3300×
        let view = repo.view().unwrap();
331
        // Kept alive, so each load's memory is new, not reused.
3320×
        let cache = StateCache::with_budget(64, usize::MAX);
3330×
        let mut held = Vec::new();
3340×
        for bookmark in view.bookmarks.keys().take(6).cloned().collect::<Vec<_>>() {
3350×
            let heads = repo.heads_of(&view, &bookmark).unwrap();
3360×
            let before = rss_kib();
3370×
            let loaded = cache.load(&repo, &heads).unwrap();
3380×
            let after = rss_kib();
3390×
            let files = loaded.snapshot.files.len();
3400×
            let (mut text, mut lines) = (0usize, 0usize);
3410×
            for f in loaded.snapshot.files.values() {
3420×
                if let oxy_core::state::FileContent::Text { bytes, .. } = &f.content {
3430×
                    text += bytes.len();
3440×
                    lines += bytes.iter().filter(|b| **b == b'\n').count();
3450×
                }
346
            }
3470×
            println!(
348
                "{bookmark}: {} changes, {files} files, {} KiB text, {lines} lines: weight {} MiB, resident +{} MiB",
3490×
                loaded.state.len(),
3500×
                text >> 10,
3510×
                weight(&loaded) >> 20,
3520×
                (after.saturating_sub(before)) >> 10
353
            );
3540×
            held.push(loaded);
355
        }
3560×
    }
357
358
    #[test]
3591×
    fn caches_by_heads_and_evicts_the_oldest() {
3601×
        let dir = tempfile::tempdir().unwrap();
3611×
        let repo = Repo::init_bare(dir.path()).unwrap();
3621×
        let cache = StateCache::new(2);
3631×
        let a = cache.load(&repo, &[]).unwrap();
3641×
        let b = cache.load(&repo, &[]).unwrap();
3651×
        assert!(Arc::ptr_eq(&a, &b), "same heads, same entry");
3661×
        assert_eq!(cache.len(), 1);
3671×
        let h1 = oxy_core::hash::ObjectRef([1; 32]);
3681×
        let h2 = oxy_core::hash::ObjectRef([2; 32]);
369
        // Unknown heads fail to load and are not cached.
3701×
        assert!(cache.load(&repo, &[h1]).is_err());
3711×
        assert_eq!(cache.len(), 1);
3721×
        let _ = (h2, dir);
3731×
    }
374
375
    #[test]
3761×
    fn summaries_leave_the_state_cache_alone() {
3771×
        let dir = tempfile::tempdir().unwrap();
3781×
        let repo = Repo::init_bare(dir.path()).unwrap();
3791×
        let cache = StateCache::new(2);
3801×
        let a = cache.summary(&repo, &[]).unwrap();
3811×
        assert_eq!(cache.len(), 0, "a summary does not fill the state cache");
3821×
        assert!(Arc::ptr_eq(&a, &cache.summary(&repo, &[]).unwrap()), "kept");
3831×
        assert!(a.changes.is_empty() && !a.conflicted);
3841×
        assert!(cache.summary(&repo, &[oxy_core::hash::ObjectRef([3; 32])]).is_err());
3851×
    }
386
387
    #[test]
3881×
    fn a_size_budget_evicts_the_oldest_and_keeps_the_newest() {
3891×
        let dir = tempfile::tempdir().unwrap();
3901×
        let repo = Repo::init(dir.path()).unwrap();
3911×
        std::fs::write(dir.path().join("a.txt"), "a\n".repeat(1000)).unwrap();
3921×
        let one = repo.commit("one", &[]).unwrap();
3931×
        std::fs::write(dir.path().join("b.txt"), "b\n".repeat(1000)).unwrap();
3941×
        let two = repo.commit("two", &[]).unwrap();
395
        // Room for nothing: each load stays, the one before goes.
3961×
        let cache = StateCache::with_budget(64, 0);
3971×
        cache.load(&repo, &[one]).unwrap();
3981×
        assert_eq!(cache.len(), 1, "kept though over the budget");
3991×
        cache.load(&repo, &[two]).unwrap();
4001×
        assert_eq!(cache.len(), 1, "the older one went");
401
        // Room for plenty: both stay.
4021×
        let roomy = StateCache::with_budget(64, 1 << 30);
4031×
        roomy.load(&repo, &[one]).unwrap();
4041×
        roomy.load(&repo, &[two]).unwrap();
4051×
        assert_eq!(roomy.len(), 2);
4061×
    }
407
408
    #[test]
4091×
    fn briefs_are_worked_out_in_parallel_and_survive_a_restart() {
4101×
        let dir = tempfile::tempdir().unwrap();
4111×
        let repo = Repo::init(dir.path()).unwrap();
4121×
        std::fs::write(dir.path().join("a.txt"), "a\n").unwrap();
4131×
        let one = repo.commit("one", &[]).unwrap();
4141×
        std::fs::write(dir.path().join("b.txt"), "b\n").unwrap();
4151×
        let two = repo.commit("two", &[]).unwrap();
4161×
        let kept = tempfile::tempdir().unwrap();
4171×
        let cache = StateCache::new(8).with_briefs(kept.path().to_path_buf());
4181×
        let got = cache.briefs(&repo, &[vec![one], vec![one, two], vec![]]).unwrap();
4191×
        assert_eq!(got.iter().map(|b| b.changes).collect::<Vec<_>>(), vec![1, 2, 0]);
4201×
        assert!(got[1].latest_ms >= got[0].latest_ms && !got[1].conflicted);
421
        // A new cache (a restarted hub) reads them back without loading a
422
        // state: a repository that no longer has the changes still answers.
4231×
        let gone = tempfile::tempdir().unwrap();
4241×
        let empty = Repo::init(gone.path()).unwrap();
4251×
        let empty_id = empty.id().unwrap();
4261×
        for f in std::fs::read_dir(kept.path()).unwrap() {
4271×
            let f = f.unwrap().path();
4281×
            std::fs::rename(&f, kept.path().join(hex::encode(empty_id))).unwrap();
4291×
        }
4301×
        let restarted = StateCache::new(8).with_briefs(kept.path().to_path_buf());
4311×
        assert_eq!(restarted.brief(&empty, &[two, one]).unwrap(), got[1], "from disk, whatever the heads' order");
4321×
        assert!(StateCache::new(8).brief(&empty, &[one, two]).is_err(), "without the disk it would have to load");
433
        // Unknown heads are an error, not a guess.
4341×
        assert!(cache.briefs(&repo, &[vec![one], vec![oxy_core::hash::ObjectRef([9; 32])]]).is_err());
435
        // A bare repository, as the hub keeps them, works across threads too.
4361×
        let bare_dir = tempfile::tempdir().unwrap();
4371×
        let bare = Repo::init_bare(bare_dir.path()).unwrap();
4381×
        assert_eq!(cache.briefs(&bare, &[vec![], vec![]]).unwrap().len(), 2);
4391×
    }
440
}