OXYGENHUB

Coverage / crates/oxy-core/src/repo/checkpoint.rs 92.4%

159 of 172 lines run, 18 of 30 functions · run #275 on carry-identical · run missed

1
//! Checkpoints (spec §11): a serialized state kept per bookmark so loading
2
//! a state costs the changes since the checkpoint rather than all of them.
3
//!
4
//! The newest checkpoint of each bookmark is pointed at by
5
//! `.oxy/checkpoints/<bookmark>`; older ones become unreachable and are
6
//! garbage collected. A checkpoint applies to a requested head set when all
7
//! of its heads lie in that set's closure, which the loader establishes while
8
//! walking from the requested heads and stopping at checkpoint members.
9
10
use super::*;
11
use crate::objects::Checkpoint;
12
13
impl Repo {
142513×
    fn checkpoint_pointer(&self, bookmark: &str) -> PathBuf {
152513×
        self.oxy.join("checkpoints").join(name_file(bookmark))
162513×
    }
17
18
    /// The newest checkpoint recorded for a bookmark.
192502×
    pub fn latest_checkpoint(&self, bookmark: &str) -> Result<Option<(ObjectRef, Checkpoint)>> {
202502×
        match fs::read_to_string(self.checkpoint_pointer(bookmark)) {
2159×
            Ok(h) => {
2259×
                let r = ObjectRef::from_hex(h.trim())
2359×
                    .ok_or_else(|| RepoError::Msg("corrupt checkpoint pointer".into()))?;
2459×
                match self.store.get_typed(&r, ObjectType::Checkpoint) {
2559×
                    Ok(bytes) => Ok(Some((r, Checkpoint::decode(&bytes)?))),
260×
                    Err(StoreError::NotFound(_)) => Ok(None),
270×
                    Err(e) => Err(e.into()),
28
                }
29
            }
302443×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
310×
            Err(e) => Err(e.into()),
32
        }
332502×
    }
34
35
    /// Every checkpoint pointer, for garbage collection roots.
3691×
    pub(crate) fn checkpoint_refs(&self) -> Result<Vec<ObjectRef>> {
3791×
        let dir = self.oxy.join("checkpoints");
3891×
        let mut out = Vec::new();
3991×
        if let Ok(rd) = fs::read_dir(&dir) {
4011×
            for e in rd.flatten() {
4111×
                if let Ok(h) = fs::read_to_string(e.path()) {
4211×
                    if let Some(r) = ObjectRef::from_hex(h.trim()) {
4311×
                        out.push(r);
4411×
                    }
450×
                }
46
            }
4780×
        }
4891×
        Ok(out)
4991×
    }
50
51
    /// Write a checkpoint of `state` (whose heads are `heads`) for `bookmark`.
529×
    pub(crate) fn write_checkpoint(
539×
        &self,
549×
        bookmark: &str,
559×
        state: &State,
569×
        heads: &[ChangeHash],
579×
    ) -> Result<(ObjectRef, usize)> {
589×
        let batch = self.store.begin_batch()?;
599×
        let (blob, payload_len) = self.store_checkpoint_payload(state)?;
609×
        let cp = Checkpoint {
619×
            heads: StateObject::new(heads.to_vec()).heads,
629×
            count: state.len() as u64,
639×
            payload: blob,
649×
        };
659×
        let r = self.store.put(ObjectType::Checkpoint, &cp.encode())?;
669×
        batch.finish()?;
679×
        fs::create_dir_all(self.oxy.join("checkpoints"))?;
689×
        write_atomic(&self.checkpoint_pointer(bookmark), r.to_hex().as_bytes())?;
699×
        Ok((r, payload_len))
709×
    }
71
72
    /// Store `state` as a version 2 payload (spec §11): the graphs of large
73
    /// files as blobs of their own, shared with earlier checkpoints when
74
    /// unchanged, and the index naming them. Returns the index blob and its size.
759×
    pub(crate) fn store_checkpoint_payload(&self, state: &State) -> Result<(ObjectRef, usize)> {
769×
        let graphs = state.checkpoint_file_graphs();
7739×
        for (_, enc) in &graphs {
7839×
            if enc.len() >= crate::state::INLINE_GRAPH_LIMIT {
793×
                self.store_blob(enc)?;
8036×
            }
81
        }
829×
        let index = state.checkpoint_index(&graphs, Repo::blob_ref);
839×
        Ok((self.store_blob(&index)?, index.len()))
849×
    }
85
86
    /// The graph blobs a checkpoint's payload names (none for version 1).
877×
    pub(crate) fn checkpoint_graph_blobs(&self, cp: &Checkpoint) -> Result<Vec<ObjectRef>> {
887×
        let payload = self.read_blob(&cp.payload)?;
897×
        Ok(State::checkpoint_graph_refs(&payload)?)
907×
    }
91
92
    /// Decode a checkpoint's payload, reading its graph blobs from the store.
9319×
    pub(crate) fn state_from_checkpoint(&self, payload: &[u8]) -> Result<State> {
9419×
        Ok(State::from_checkpoint(payload, |refs| {
954×
            self.read_blobs(refs).map_err(|e| {
962×
                crate::objects::ObjectError::Schema(format!("checkpoint graph blobs: {e}"))
972×
            })
984×
        })?)
9919×
    }
100
101
    /// Checkpoint the current bookmark's state now.
1026×
    pub fn checkpoint(&self) -> Result<(ObjectRef, usize, usize)> {
1036×
        let heads = self.bookmark_heads()?;
1046×
        let state = self.load_state_full(&heads)?;
1056×
        let (r, bytes) = self.write_checkpoint(&self.config.bookmark, &state, &heads)?;
1066×
        Ok((r, state.len(), bytes))
1076×
    }
108
109
    /// Point `bookmark` at an already stored checkpoint (a shallow clone's base).
1102×
    pub(crate) fn install_checkpoint(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
1112×
        Checkpoint::decode(&self.store.get_typed(r, ObjectType::Checkpoint)?)?;
1122×
        fs::create_dir_all(self.oxy.join("checkpoints"))?;
1132×
        write_atomic(&self.checkpoint_pointer(bookmark), r.to_hex().as_bytes())
1142×
    }
115
116
    /// A bundle holding a checkpoint of exactly `heads` with its payload
117
    /// (spec §16.1 `checkpoint`); the current bookmark checkpoint is reused
118
    /// when it matches, otherwise one is made and, when `heads` are the
119
    /// bookmark's, kept.
1202×
    pub fn checkpoint_bundle_for(&self, heads: &[ChangeHash]) -> Result<Bundle> {
1212×
        let wanted = StateObject::new(heads.to_vec()).heads;
1222×
        let bookmark = self.config.bookmark.clone();
1232×
        let current = self.bookmark_heads()?;
1242×
        let r = match self.latest_checkpoint(&bookmark)? {
1251×
            Some((r, cp)) if cp.heads == wanted => r,
126
            _ => {
1271×
                let state = self.load_state(&wanted)?;
1281×
                if current == wanted {
1291×
                    self.write_checkpoint(&bookmark, &state, &wanted)?.0
130
                } else {
1310×
                    let (blob, _) = self.store_checkpoint_payload(&state)?;
1320×
                    let cp = Checkpoint {
1330×
                        heads: wanted.clone(),
1340×
                        count: state.len() as u64,
1350×
                        payload: blob,
1360×
                    };
1370×
                    self.store.put(ObjectType::Checkpoint, &cp.encode())?
138
                }
139
            }
140
        };
1412×
        let cp = Checkpoint::decode(&self.store.get_typed(&r, ObjectType::Checkpoint)?)?;
1422×
        let mut bundle = Bundle::default();
1432×
        for c in Blob::decode(&self.store.get_typed(&cp.payload, ObjectType::Blob)?)?.chunks {
1442×
            bundle.objects.push(self.store.get(&c)?);
145
        }
1462×
        bundle.objects.push(self.store.get(&cp.payload)?);
1472×
        for g in self.checkpoint_graph_blobs(&cp)? {
1481×
            for c in Blob::decode(&self.store.get_typed(&g, ObjectType::Blob)?)?.chunks {
1491×
                bundle.objects.push(self.store.get(&c)?);
150
            }
1511×
            bundle.objects.push(self.store.get(&g)?);
152
        }
1532×
        bundle.objects.push((ObjectType::Checkpoint, cp.encode()));
1542×
        Ok(bundle)
1552×
    }
156
157
    /// Load the state of `heads` using a checkpoint when one applies.
158200×
    pub(crate) fn load_state_checkpointed(&self, heads: &[ChangeHash]) -> Result<Option<State>> {
159200×
        self.load_state_checkpointed_as(heads, false)
160200×
    }
161
162
    /// As [`Repo::load_state_checkpointed`]; `history` builds no file graph.
1631856×
    pub(crate) fn load_state_checkpointed_as(
1641856×
        &self,
1651856×
        heads: &[ChangeHash],
1661856×
        history: bool,
1671856×
    ) -> Result<Option<State>> {
1681856×
        let mut bookmarks: Vec<String> = vec![self.config.bookmark.clone()];
1691856×
        if let Ok(rd) = fs::read_dir(self.oxy.join("checkpoints")) {
17043×
            for e in rd.flatten() {
17143×
                let name = file_name_to_name(&e.file_name().to_string_lossy());
17243×
                if !bookmarks.contains(&name) {
1730×
                    bookmarks.push(name);
17443×
                }
175
            }
1761813×
        }
1771856×
        for b in bookmarks {
1781856×
            let Some((_, cp)) = self.latest_checkpoint(&b)? else {
1791813×
                continue;
180
            };
18143×
            let payload = {
18243×
                let _t = crate::timing::phase("load: read checkpoint");
18343×
                self.read_blob(&cp.payload)?
184
            };
18542×
            let base = {
18643×
                let _t = crate::timing::phase("load: decode checkpoint");
18743×
                if history {
18833×
                    State::from_checkpoint_history(&payload)?
189
                } else {
19010×
                    self.state_from_checkpoint(&payload)?
191
                }
192
            };
19342×
            let cp_heads: BTreeSet<ChangeHash> = cp.heads.iter().copied().collect();
19442×
            let mut found: BTreeSet<ChangeHash> = BTreeSet::new();
19542×
            let mut delta: Vec<(ChangeHash, Change, Vec<crate::objects::TextRef>)> = Vec::new();
19642×
            let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
19742×
            let mut stack: Vec<ChangeHash> = heads.to_vec();
198185×
            while let Some(h) = stack.pop() {
199143×
                if !seen.insert(h) {
20021×
                    continue;
201122×
                }
202122×
                if base.contains(&h) {
20380×
                    if cp_heads.contains(&h) {
20439×
                        found.insert(h);
20541×
                    }
20680×
                    continue;
20742×
                }
208
                // For history, the skeleton: text is read only for the
209
                // graphs built later, and a state holding none can be
210
                // indexed (oxygen#93).
21142×
                let (c, texts) = if history {
21235×
                    self.store.get_change_lazy(&h)?
213
                } else {
2147×
                    (self.store.get_change(&h)?, Vec::new())
215
                };
21642×
                stack.extend(c.deps.iter().copied());
21742×
                delta.push((h, c, texts));
218
            }
21942×
            if found.len() != cp_heads.len() {
2204×
                continue;
22138×
            }
22238×
            let _t = crate::timing::phase("load: apply delta and validate");
22338×
            let mut state = base;
22438×
            for (h, c, texts) in delta {
22533×
                if history {
22626×
                    state.add_known(h, c, texts);
22726×
                } else {
2287×
                    state.add_unchecked(c);
2297×
                }
230
            }
23138×
            state.validate()?;
23238×
            return Ok(Some(state));
233
        }
2341817×
        Ok(None)
2351856×
    }
236
}