Skip to main content

relate_executor/graph/
restore.rs

1//! Checkpoint-facing graph API: restoring checkpoint rows into a graph
2//! being loaded, and the payload sizes and dirty ids a checkpoint reads.
3
4use super::id_vec::IdVec;
5use super::*;
6
7/// Every checkpoint row is restored as a version born at ts 1.
8const RESTORED_XMIN: u64 = 1;
9
10/// Install a checkpoint row as `id`'s only version, inline. Before any
11/// write a slot holds at most an earlier row for the same id — overlapping
12/// legacy parts (ADR-0183) can hold an id twice — and the later row replaces
13/// it rather than stacking a second live version a delete would leave visible.
14fn restore<Live>(map: &IdVec<Chain<Live>>, id: i64, live: Live) -> Result<()> {
15    match map.entry(id) {
16        super::id_vec::Entry::Vacant(mut slot) => {
17            slot.insert(Chain::inline(RESTORED_XMIN, live));
18        }
19        super::id_vec::Entry::Occupied(mut slot) => match slot.get_mut() {
20            prev @ Chain::Inline { .. } => *prev = Chain::inline(RESTORED_XMIN, live),
21            Chain::Spilled(_) => {
22                return Err(relate_core::Error::storage(
23                    "checkpoint restore into a graph with committed writes",
24                ))
25            }
26        },
27    }
28    Ok(())
29}
30
31/// Checkpoint payload of `id`'s version visible at `ts`, measured by
32/// `bytes`; `None` when no version is visible.
33fn visible_checkpoint_bytes<Live>(
34    map: &IdVec<Chain<Live>>,
35    id: i64,
36    ts: u64,
37    bytes: impl FnOnce(&Live) -> Result<u64>,
38) -> Result<Option<u64>> {
39    let Some(vers) = map.get(&id) else {
40        return Ok(None);
41    };
42    vers.visible_at(ts).map(|v| bytes(v.live)).transpose()
43}
44
45impl Graph {
46    /// Node ids changed since the last `clear_checkpoint_dirty` (ADR-0022).
47    pub fn dirty_node_ids(&self) -> HashSet<NodeId> {
48        self.dirty_nodes.lock().unwrap().clone()
49    }
50
51    /// Relationship ids changed since the last `clear_checkpoint_dirty`.
52    pub fn dirty_rel_ids(&self) -> HashSet<RelId> {
53        self.dirty_rels.lock().unwrap().clone()
54    }
55
56    pub fn clear_checkpoint_dirty(&self) {
57        self.dirty_nodes.lock().unwrap().clear();
58        self.dirty_rels.lock().unwrap().clear();
59    }
60
61    /// Variable checkpoint payload of the node visible at `ts`: label bytes
62    /// plus tagged property JSON. The Parquet codec adds its Int64 column
63    /// width. Borrows compact properties; does not build the property map.
64    pub fn node_checkpoint_bytes(&self, id: NodeId, ts: u64) -> Result<Option<u64>> {
65        visible_checkpoint_bytes(&self.nodes, id, ts, |live| {
66            live.checkpoint_bytes(&self.interner)
67        })
68    }
69
70    /// Variable checkpoint payload of the relationship visible at `ts`:
71    /// type-name bytes plus tagged property JSON. The Parquet codec adds
72    /// its Int64 column width.
73    pub fn rel_checkpoint_bytes(&self, id: RelId, ts: u64) -> Result<Option<u64>> {
74        visible_checkpoint_bytes(&self.rels, id, ts, |live| {
75            live.checkpoint_bytes(&self.interner)
76        })
77    }
78
79    /// Restore a node from a checkpoint (visible at commit_ts). Loading an
80    /// id again replaces its row; the later row wins. Only valid on a graph
81    /// being restored, before any write: an open write is `Error::Storage`.
82    /// The label index is built by `Graph::finish_restore` after the load.
83    pub fn load_checkpoint_node(&self, node: Node) -> Result<()> {
84        self.check_restoring()?;
85        let next = checked_persisted_id(node.id, "node")?;
86        self.next_node_id.fetch_max(next, Ordering::Relaxed);
87        self.catalog
88            .lock()
89            .unwrap()
90            .record_labels(node.labels.iter().cloned());
91        let live = LiveNode::from_parts(
92            &self.interner,
93            std::sync::Arc::unwrap_or_clone(node.labels),
94            std::sync::Arc::unwrap_or_clone(node.properties).into(),
95        );
96        restore(&self.nodes, node.id, live)
97    }
98
99    /// Restore a relationship from a checkpoint. Loading an id again
100    /// replaces its row, endpoints and type included; the later row wins.
101    /// Only valid on a graph being restored, before any write: an open
102    /// write is `Error::Storage`. Adjacency is built from the restored rows
103    /// by `Graph::finish_restore` after the load.
104    pub fn load_checkpoint_rel(&self, rel: Relationship) -> Result<()> {
105        self.check_restoring()?;
106        let next = checked_persisted_id(rel.id, "relationship")?;
107        checked_persisted_id(rel.start, "relationship start")?;
108        checked_persisted_id(rel.end, "relationship end")?;
109        self.next_rel_id.fetch_max(next, Ordering::Relaxed);
110        let live = LiveRel::from_parts(
111            &self.interner,
112            rel.start,
113            rel.end,
114            &rel.rel_type,
115            std::sync::Arc::unwrap_or_clone(rel.properties).into(),
116        );
117        self.catalog.lock().unwrap().record_rel_type(rel.rel_type);
118        restore(&self.rels, rel.id, live)
119    }
120
121    /// End a checkpoint load, after its last row: build adjacency — the
122    /// build itself emits the durable shape, the chunks at or above the
123    /// seal floor straight into their folded form (ADR-0608) — and clear
124    /// the dirty ids, which the checkpoint already holds. Called once per
125    /// load. The index rebuild is deliberately NOT here: the open flow's
126    /// single post-replay site runs it exactly once per open, after the
127    /// graph is final (snapshot plus replayed tail) — a snapshot+tail
128    /// reopen must not pay the whole-graph rebuild twice (LABS-1112).
129    #[doc(hidden)]
130    pub fn finish_restore(&self) {
131        self.rebuild_adj();
132        self.clear_checkpoint_dirty();
133    }
134
135    fn check_restoring(&self) -> Result<()> {
136        if self.in_write.load(Ordering::Acquire) {
137            return Err(relate_core::Error::storage(
138                "checkpoint restore while a write is open",
139            ));
140        }
141        Ok(())
142    }
143}