relate_executor/graph/apply_redo.rs
1use super::*;
2
3impl Graph {
4 pub fn apply_redo(&self, ops: Vec<RedoOp>, commit_ts: u64) -> Result<()> {
5 self.apply_redo_inner(ops, commit_ts, false)
6 }
7
8 /// Replay historical WAL under the old admission policy, preserving unknown
9 /// enforcement as legacy rather than inventing a typed checkpoint image.
10 #[doc(hidden)]
11 pub fn apply_replayed_redo(&self, ops: Vec<RedoOp>, commit_ts: u64) -> Result<()> {
12 self.apply_redo_inner(ops, commit_ts, true)
13 }
14
15 pub(super) fn apply_redo_inner(
16 &self,
17 ops: Vec<RedoOp>,
18 commit_ts: u64,
19 legacy_replay: bool,
20 ) -> Result<()> {
21 self.validate_redo_group(std::iter::once((ops.as_slice(), commit_ts)), !legacy_replay)?;
22 let legacy_created = if legacy_replay {
23 ops.iter()
24 .any(|op| matches!(op, RedoOp::CreateConstraint { .. }))
25 } else {
26 false
27 };
28 self.in_write.store(true, Ordering::Release);
29 self.write_ts.store(commit_ts, Ordering::Release);
30 self.record_redo.store(false, Ordering::Release);
31 for op in ops {
32 match op {
33 RedoOp::CreateNode {
34 id,
35 labels,
36 properties,
37 } => {
38 // Move the typed fields in — the caller consumed the WAL
39 // borrow before apply, so no clone is needed (ADR-0078).
40 self.install_node(
41 id,
42 std::sync::Arc::unwrap_or_clone(labels),
43 std::sync::Arc::unwrap_or_clone(properties).into(),
44 )?;
45 }
46 RedoOp::CreateRel {
47 id,
48 start,
49 end,
50 rel_type,
51 properties,
52 } => {
53 self.install_rel(
54 id,
55 start,
56 end,
57 rel_type,
58 std::sync::Arc::unwrap_or_clone(properties).into(),
59 )?;
60 }
61 RedoOp::DeleteNode { id } => {
62 self.delete_node(id, true)?;
63 self.drop_pull_identity(PullKind::Node, id);
64 }
65 RedoOp::DeleteRel { id } => {
66 self.delete_rel(id);
67 self.drop_pull_identity(PullKind::Rel, id);
68 }
69 RedoOp::SetNodeProp { id, key, value } => {
70 self.set_property_node(id, &key, value);
71 }
72 RedoOp::RemoveNodeProp { id, key } => {
73 self.set_property_node(id, &key, Value::Null);
74 }
75 RedoOp::SetRelProp { id, key, value } => {
76 self.set_property_rel(id, &key, value);
77 }
78 RedoOp::RemoveRelProp { id, key } => {
79 self.set_property_rel(id, &key, Value::Null);
80 }
81 RedoOp::AddLabels { id, labels } => {
82 self.add_labels(id, &labels);
83 }
84 RedoOp::RemoveLabels { id, labels } => {
85 self.remove_labels(id, &labels);
86 }
87 RedoOp::CreateIndex {
88 name,
89 label,
90 property,
91 } => {
92 self.install_named_index(IndexDef {
93 name,
94 label,
95 property,
96 })?;
97 }
98 RedoOp::DropIndex { name } => {
99 self.catalog.lock().unwrap().drop_index(&name);
100 let removed = {
101 let mut theater = self.theater.lock().unwrap();
102 theater.index_options.remove(&name);
103 theater.index_details.remove(&name)
104 };
105 if let Some(detail) = removed {
106 self.drop_detail(&detail);
107 self.refresh_index_charge();
108 self.recompute_used();
109 }
110 }
111 RedoOp::CreateConstraint {
112 name,
113 relationship,
114 label,
115 properties,
116 kind,
117 property_type,
118 enforced_label,
119 } => {
120 let def = ConstraintDef {
121 name,
122 relationship,
123 label,
124 properties,
125 kind,
126 property_type,
127 enforced_label,
128 };
129 // ADR-0439: a uniqueness constraint backfills its
130 // committed tuple map from the live graph. The catalog
131 // validates the kind first (its vocabulary is closed), so
132 // the spec builds before the insert moves the def.
133 let spec = super::constraint_keys::spec_from_def(&self.interner, &def);
134 self.catalog.lock().unwrap().insert_constraint(def)?;
135 if let Some(spec) = spec {
136 self.constraint_keys_install(spec);
137 }
138 }
139 RedoOp::DropConstraint { name } => {
140 self.catalog.lock().unwrap().drop_constraint(&name);
141 self.theater
142 .lock()
143 .unwrap()
144 .derived_constraints
145 .remove(&name);
146 self.legacy_unenforced.lock().unwrap().remove(&name);
147 self.constraint_keys_drop(&name);
148 }
149 RedoOp::CatalogDerivedConstraint { constraint } => {
150 if let Some(enforced) = &constraint.enforced_label {
151 // An enforced label is always a node label (even on a
152 // relationship constraint, `sourceLabel`/`targetLabel`
153 // name the endpoint's label).
154 self.record_schema_names(false, std::iter::once(enforced.clone()));
155 }
156 if self
157 .catalog
158 .lock()
159 .unwrap()
160 .constraints
161 .get(&constraint.name)
162 .is_some_and(|def| matching_enforced_label(def, &constraint))
163 {
164 self.legacy_unenforced
165 .lock()
166 .unwrap()
167 .remove(&constraint.name);
168 }
169 self.theater
170 .lock()
171 .unwrap()
172 .derived_constraints
173 .insert(constraint.name.clone(), constraint);
174 // No install here: the load-bearing invariant is that
175 // no durable image carries a uniqueness kind in this
176 // record. Witness 1: its only production constructor
177 // (the CREATE CONSTRAINT push) is gated on
178 // `enforced_label`. Witness 2: the parser sets that
179 // field only on `nodeLabelExistence` /
180 // `sourceLabelExistence` / `targetLabelExistence`.
181 // Derived uniqueness reachable via `SetCurrentGraphType`
182 // is the theater half of `uniqueness_specs`;
183 // `rebuild_constraint_keys` covers it.
184 }
185 RedoOp::CatalogIndexDetail {
186 name,
187 detail,
188 options,
189 } => {
190 // Decode before mutating: a corrupted op is an error,
191 // never a silently dropped index detail/options entry.
192 let options = redo::props_from_json(&options)?;
193 // The typed detail is the only op that knows whether its
194 // labels are node labels or relationship types; the
195 // catalog's `CreateIndex` row is entity-kind-blind.
196 self.record_schema_names(detail.relationship, detail.labels.iter().cloned());
197 {
198 let mut theater = self.theater.lock().unwrap();
199 theater.index_details.insert(name.clone(), detail.clone());
200 theater.index_options.insert(name, options);
201 }
202 self.refresh_index_charge();
203 self.materialize_detail(&detail);
204 self.recompute_used();
205 }
206 RedoOp::PutDatabase {
207 name,
208 language,
209 composite,
210 } => {
211 // ADR-0276: the databases catalog is store-level,
212 // shared by every namespace graph; per the ADR-0116 §8
213 // invariants only the fixed namespaces are kept,
214 // replayed entries for other names are ignored.
215 self.databases().put_database(&name, language, composite);
216 }
217 RedoOp::DropDatabase { .. } => {
218 // ADR-0116 §1/§8: the fixed namespaces cannot be
219 // dropped, and the `Namespace`-keyed catalog can only
220 // ever hold them, so a legacy `DROP DATABASE` redo is
221 // a no-op.
222 }
223 RedoOp::PutGraphType { name, body } => {
224 self.theater.lock().unwrap().graph_types.insert(name, body);
225 }
226 RedoOp::SetCurrentGraphType { body } => {
227 let (previous, derived) = {
228 let mut theater = self.theater.lock().unwrap();
229 let previous = theater.derived_constraints.clone();
230 super::theater::set_current_graph_type(&mut theater, &body)?;
231 (previous, theater.derived_constraints.clone())
232 };
233 // A record written before a generated-name or derivation
234 // change installs rows under names this binary no longer
235 // derives. Re-keying them here is what keeps a replayed
236 // store's catalog equal to its re-derived index (a stale
237 // row would otherwise survive every purge and turn the
238 // next `ALTER CURRENT GRAPH TYPE` into a conflict). This
239 // record replaces the set wholesale — the statement's own
240 // purge already dropped every record it named — so a
241 // record the new derivation does not produce goes. Each
242 // half runs under its own lock: schema capture takes the
243 // catalog without waiting for the theater, so no path may
244 // hold both.
245 let migration = (!previous.is_empty() && previous != derived).then(|| {
246 super::derived_migration::plan_derived_migration(
247 &previous,
248 &derived,
249 super::derived_migration::UnmatchedRecords::Drop,
250 )
251 });
252 let installed = match &migration {
253 Some(migration) => {
254 migration.apply_to_theater(&mut self.theater.lock().unwrap());
255 migration.apply_to_catalog(&mut self.catalog.lock().unwrap())?
256 }
257 None => Vec::new(),
258 };
259 {
260 let catalog = self.catalog.lock().unwrap();
261 self.legacy_unenforced.lock().unwrap().retain(|name, _| {
262 !catalog.constraints.get(name).is_some_and(|def| {
263 derived.get(name).is_some_and(|constraint| {
264 matching_enforced_label(def, constraint)
265 })
266 })
267 });
268 }
269 if let Some(migration) = migration {
270 migration
271 .install_theater_details(&mut self.theater.lock().unwrap(), &installed);
272 self.refresh_index_charge();
273 self.recompute_used();
274 }
275 // ADR-0439: this arm is the constraint-key map's fourth
276 // rebuild trigger. The derived set was just replaced
277 // wholesale from the persisted body, and the per-op row
278 // stream does not mirror it in every reachable shape:
279 // a legacy replay record may carry `SetCurrentGraphType`
280 // alone, without the `CreateConstraint` rows a current
281 // statement emits first, and a current statement's
282 // `sync_derived_constraints` skips a derived constraint
283 // that is schema-equivalent to a surviving catalog one,
284 // so that derived name has no row either. Rebuild from
285 // the committed catalog + the re-derived set so the map
286 // still covers both.
287 self.rebuild_constraint_keys();
288 }
289 RedoOp::PullIdentityPut {
290 source,
291 kind,
292 remote_id,
293 local_id,
294 } => {
295 self.pull_identity_put(source, kind, remote_id, local_id);
296 }
297 RedoOp::OntologySet { .. } | RedoOp::OntologyDrop { .. } => {
298 // ADR-0120 §2/§3: store-level ops; they carry no graph
299 // mutation. The document lives with the store layer —
300 // no graph is derived from it (ADR-0229 §3) — so replay
301 // is a deliberate no-op here.
302 }
303 }
304 }
305 self.pending_redo.lock().unwrap().clear();
306 self.set_commit_ts(commit_ts);
307 self.in_write.store(false, Ordering::Release);
308 self.record_redo.store(true, Ordering::Release);
309 // ADR-0595: reclaim the label postings the removal sites
310 // suspected — here, the single-writer apply's tail, after every
311 // op of this commit is installed, so no concurrent `index_add`
312 // can race the removal. An empty candidate set is one horizon
313 // read.
314 self.drain_label_suspects();
315 if legacy_created {
316 self.mark_legacy_unenforced();
317 }
318 Ok(())
319 }
320}