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::*;
6use crate::store::NameCache;
7
8/// Every checkpoint row is restored as a version born at ts 1.
9const RESTORED_XMIN: u64 = 1;
10
11/// Install a slice's checkpoint rows as each id's only version, inline,
12/// under one store lock. Before any write a slot holds at most an earlier
13/// row for the same id — overlapping legacy parts (ADR-0183) can hold an id
14/// twice — and the later row replaces it rather than stacking a second
15/// live version a delete would leave visible. One lock for the slice, not
16/// one per row: concurrent load workers would otherwise convoy on the
17/// store's lock and land slower than the serial load. The slice's rows are
18/// admitted whole before the first write: a slice with a committed write in
19/// it refuses without restoring a single row.
20fn restore_slice<Live>(map: &IdVec<Chain<Live>>, rows: Vec<(i64, Live)>) -> Result<()> {
21    let rows = rows
22        .into_iter()
23        .map(|(id, live)| (id, Chain::inline(RESTORED_XMIN, live)))
24        .collect();
25    map.install_batch(rows, |previous| match previous {
26        None | Some(Chain::Inline { .. }) => Ok(()),
27        Some(Chain::Spilled(_)) => Err(relate_core::Error::storage(
28            "checkpoint restore into a graph with committed writes",
29        )),
30    })
31}
32
33/// Checkpoint payload of `id`'s version visible at `ts`, measured by
34/// `bytes`; `None` when no version is visible.
35fn visible_checkpoint_bytes<Live>(
36    map: &IdVec<Chain<Live>>,
37    id: i64,
38    ts: u64,
39    bytes: impl FnOnce(&Live) -> Result<u64>,
40) -> Result<Option<u64>> {
41    let Some(vers) = map.get(&id) else {
42        return Ok(None);
43    };
44    visible_version(&vers, ts)
45        .map(|v| bytes(v.live))
46        .transpose()
47}
48
49impl Graph {
50    /// Node ids changed since the last `clear_checkpoint_dirty` (ADR-0022).
51    pub fn dirty_node_ids(&self) -> HashSet<NodeId> {
52        self.dirty_nodes.lock().unwrap().clone()
53    }
54
55    /// Relationship ids changed since the last `clear_checkpoint_dirty`.
56    pub fn dirty_rel_ids(&self) -> HashSet<RelId> {
57        self.dirty_rels.lock().unwrap().clone()
58    }
59
60    pub fn clear_checkpoint_dirty(&self) {
61        self.dirty_nodes.lock().unwrap().clear();
62        self.dirty_rels.lock().unwrap().clear();
63    }
64
65    /// Variable checkpoint payload of the node visible at `ts`: label bytes
66    /// plus tagged property JSON. The Parquet codec adds its Int64 column
67    /// width. Borrows compact properties; does not build the property map.
68    pub fn node_checkpoint_bytes(&self, id: NodeId, ts: u64) -> Result<Option<u64>> {
69        visible_checkpoint_bytes(&self.nodes, id, ts, |live| {
70            live.checkpoint_bytes(&self.interner)
71        })
72    }
73
74    /// Variable checkpoint payload of the relationship visible at `ts`:
75    /// type-name bytes plus tagged property JSON. The Parquet codec adds
76    /// its Int64 column width.
77    pub fn rel_checkpoint_bytes(&self, id: RelId, ts: u64) -> Result<Option<u64>> {
78        visible_checkpoint_bytes(&self.rels, id, ts, |live| {
79            live.checkpoint_bytes(&self.interner)
80        })
81    }
82
83    /// Restore a node from a checkpoint (visible at commit_ts). Loading an
84    /// id again replaces its row; the later row wins. Only valid in the
85    /// graph's restore phase, before any write and before
86    /// `Graph::finish_restore` closes it: either is `Error::Storage`. The
87    /// label index is built by `Graph::finish_restore` after the load.
88    pub fn load_checkpoint_node(&self, node: Node) -> Result<()> {
89        self.load_checkpoint_nodes(&[node])
90    }
91
92    /// Restore a relationship from a checkpoint. Loading an id again
93    /// replaces its row, endpoints and type included; the later row wins.
94    /// Only valid in the graph's restore phase, before any write and before
95    /// `Graph::finish_restore` closes it: either is `Error::Storage`.
96    /// Adjacency is built from the restored rows by `Graph::finish_restore`
97    /// after the load.
98    pub fn load_checkpoint_rel(&self, rel: Relationship) -> Result<()> {
99        self.load_checkpoint_rels(&[rel])
100    }
101
102    /// Install a slice of checkpoint nodes — one decoded batch, a
103    /// window-disjoint run of ids from one part. The installer validates
104    /// every row id in the slice, so a caller does not repeat the check;
105    /// the next-id bump, the catalog update and the store lock are one per
106    /// slice instead of one per row, so concurrent load workers install
107    /// without contending on a per-row lock.
108    pub fn load_checkpoint_nodes(&self, nodes: &[Node]) -> Result<()> {
109        self.begin_restoring()?;
110        let mut next = 0;
111        for node in nodes {
112            next = next.max(checked_persisted_id(node.id, "node")?);
113        }
114        self.next_node_id.fetch_max(next, Ordering::Relaxed);
115        self.catalog
116            .lock()
117            .unwrap()
118            .record_labels(nodes.iter().flat_map(|node| node.labels.iter().cloned()));
119        let mut names = NameCache::default();
120        let rows = nodes
121            .iter()
122            .map(|node| {
123                let live = LiveNode::from_parts_cached(
124                    &self.interner,
125                    &mut names,
126                    &node.labels,
127                    &node.properties,
128                );
129                (node.id, live)
130            })
131            .collect();
132        restore_slice(&self.nodes, rows)
133    }
134
135    /// Relationship sibling of [`Self::load_checkpoint_nodes`]: it
136    /// validates each row's id and both endpoints, and the later row wins
137    /// by id, endpoints and type included.
138    pub fn load_checkpoint_rels(&self, rels: &[Relationship]) -> Result<()> {
139        self.begin_restoring()?;
140        let mut next = 0;
141        for rel in rels {
142            next = next.max(checked_persisted_id(rel.id, "relationship")?);
143            checked_persisted_id(rel.start, "relationship start")?;
144            checked_persisted_id(rel.end, "relationship end")?;
145        }
146        self.next_rel_id.fetch_max(next, Ordering::Relaxed);
147        {
148            let mut catalog = self.catalog.lock().unwrap();
149            for rel in rels {
150                catalog.record_rel_type(rel.rel_type.clone());
151            }
152        }
153        let mut names = NameCache::default();
154        let rows = rels
155            .iter()
156            .map(|rel| {
157                let live = LiveRel::from_parts_cached(
158                    &self.interner,
159                    &mut names,
160                    rel.start,
161                    rel.end,
162                    &rel.rel_type,
163                    &rel.properties,
164                );
165                (rel.id, live)
166            })
167            .collect();
168        restore_slice(&self.rels, rows)
169    }
170
171    /// End a checkpoint load, after its last row: close the restore phase
172    /// first — "the load is over" is true from the first step of
173    /// finalization, so no slice is admitted while the tail runs — then
174    /// build adjacency (the build itself emits the durable shape, the
175    /// chunks at or above the seal floor straight into their folded form,
176    /// ADR-0608) and clear the dirty ids, which the checkpoint already
177    /// holds. Called once per load. The index rebuild is deliberately NOT
178    /// here: the open flow's single post-replay site runs it exactly once
179    /// per open, after the graph is final (snapshot plus replayed tail) — a
180    /// snapshot+tail reopen must not pay the whole-graph rebuild twice
181    /// (LABS-1112).
182    #[doc(hidden)]
183    pub fn finish_restore(&self) {
184        self.close_restoring();
185        self.rebuild_adj();
186        self.clear_checkpoint_dirty();
187    }
188
189    /// A checkpoint load's entry: take the graph's restore phase for a
190    /// slice. The phase is one latch — born open, closed once by
191    /// [`Self::close_restoring`] — so every later slice of the same load
192    /// takes the same open latch; a graph that left it is refused in
193    /// [`Self::check_restoring`].
194    fn begin_restoring(&self) -> Result<()> {
195        if self.in_write.load(Ordering::Acquire) {
196            return Err(relate_core::Error::storage(
197                "checkpoint restore while a write is open",
198            ));
199        }
200        self.check_restoring()
201    }
202
203    /// The latch's read half: refuse a load the graph no longer accepts —
204    /// the restore phase closed by `finish_restore` or a published commit.
205    /// The phase, never a slot's version-chain shape, is the evidence: a
206    /// committed single-version write leaves the `Inline` chain a restored
207    /// row itself holds, and shape cannot tell the two apart.
208    fn check_restoring(&self) -> Result<()> {
209        if !self.restoring.load(Ordering::Acquire) {
210            return Err(relate_core::Error::storage(
211                "checkpoint restore into a graph with committed writes",
212            ));
213        }
214        Ok(())
215    }
216
217    /// The latch's one transition: open -> closed, final. Every entry that
218    /// ends the restore phase — [`Self::finish_restore`], a published
219    /// commit, a redo apply — closes through here.
220    pub(super) fn close_restoring(&self) {
221        self.restoring.store(false, Ordering::Release);
222    }
223}