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