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