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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
// SPDX-License-Identifier: BUSL-1.1
//! Document-engine undo entry application logic.
//!
//! `apply_undo_document` handles document-engine undo entries. All methods
//! return `Err((entry_index, detail))` on fatal failure so the caller can
//! escalate to a typed `RollbackFailed` response.
use tracing::error;
use crate::data::executor::core_loop::CoreLoop;
use crate::engine::sparse::btree_versioned::VersionedIndexEntry;
use super::UndoEntry;
#[derive(Clone, Copy)]
pub(super) struct UndoDocumentContext<'a> {
pub database_id: u64,
pub tid: u64,
pub entry_index: usize,
pub collection: &'a str,
pub document_id: &'a str,
}
impl CoreLoop {
// ── Document ────────────────────────────────────────────────────────────
pub(super) fn apply_undo_document(
&mut self,
database_id: u64,
tid: u64,
entry_index: usize,
entry: UndoEntry,
) -> Result<(), (usize, String)> {
match entry {
UndoEntry::PutDocument {
collection,
document_id,
surrogate,
old_value,
bitemporal_sys_from_ms,
bitemporal_index_tuples,
secondary_index_added,
secondary_index_removed,
chain_hash_prior,
} => {
let ctx = UndoDocumentContext {
database_id,
tid,
entry_index,
collection: &collection,
document_id: &document_id,
};
if let Some(sys_from_ms) = bitemporal_sys_from_ms {
// Bitemporal op: never wrote the non-versioned table, so
// physically remove the appended version row (+ its index
// entries) instead of a plain put/delete. `versioned_get_current`
// recomputes from the remaining rows, so removing the newest
// version restores the prior one automatically.
self.undo_bitemporal_write(ctx, sys_from_ms, &bitemporal_index_tuples)?;
} else {
let result = if let Some(old) = old_value {
self.sparse
.put(database_id, tid, &collection, &document_id, &old)
.map(|_| ())
.map_err(|e| e.to_string())
} else {
self.sparse
.delete(database_id, tid, &collection, &document_id)
.map(|_| ())
.map_err(|e| e.to_string())
};
result.map_err(|e| {
error!(
core = self.core_id,
entry_index,
collection = %collection,
document_id = %document_id,
error = %e,
"transaction undo: document restore failed; shard state unknown"
);
(
entry_index,
format!("document restore on {collection}/{document_id}: {e}"),
)
})?;
}
// Reverse plain secondary-index mutations: undo the inserts and
// restore the stale entries this put removed. Empty on the
// bitemporal path (its index reversal happened in
// `undo_bitemporal_write` above), so this is a no-op there.
self.undo_secondary_index(ctx, &secondary_index_added, &secondary_index_removed)?;
// Revert inverted index: remove the postings this rolled-back
// put wrote. FATAL on failure — a rollback that leaves stale FTS
// postings behind is the same silent-partial-success corruption
// the primary-store restore guards against.
self.inverted
.remove_document(
database_id,
crate::types::TenantId::new(tid),
&collection,
surrogate,
)
.map_err(|e| {
error!(
core = self.core_id,
entry_index,
collection = %collection,
document_id = %document_id,
error = %e,
"transaction undo: FTS posting removal failed; shard state unknown"
);
(
entry_index,
format!("fts posting removal on {collection}/{document_id}: {e}"),
)
})?;
// Evict any cached copy of the reversed document. Always safe:
// a stale hit would otherwise resurrect a rolled-back put; the
// worst case here is a cache miss.
self.doc_cache
.invalidate(database_id, tid, &collection, &document_id);
self.undo_chain_hash(database_id, tid, &collection, chain_hash_prior);
Ok(())
}
UndoEntry::DeleteDocument {
collection,
document_id,
surrogate,
old_value,
bitemporal_sys_from_ms,
bitemporal_index_tuples,
secondary_index_tuples,
chain_hash_prior,
} => {
let ctx = UndoDocumentContext {
database_id,
tid,
entry_index,
collection: &collection,
document_id: &document_id,
};
if let Some(sys_from_ms) = bitemporal_sys_from_ms {
self.undo_bitemporal_write(ctx, sys_from_ms, &bitemporal_index_tuples)?;
} else {
self.sparse
.put(database_id, tid, &collection, &document_id, &old_value)
.map(|_| ())
.map_err(|e| {
error!(
core = self.core_id,
entry_index,
collection = %collection,
document_id = %document_id,
error = %e,
"transaction undo: document re-insert failed; shard state unknown"
);
(
entry_index,
format!("document re-insert on {collection}/{document_id}: {e}"),
)
})?;
}
// Restore the plain secondary-index entries the forward delete
// cascade removed. Empty on the bitemporal path (no plain
// INDEXES entries there), so this is a no-op for it.
self.undo_secondary_index(ctx, &[], &secondary_index_tuples)?;
// Re-index the restored document into the full-text inverted
// index. The forward delete cascade removed its postings
// unconditionally, so a rollback that restored the row but not
// its postings would leave it restored-but-unsearchable. FATAL
// on failure — a half-restored FTS index is corruption.
self.reindex_restored_document_fts(ctx, surrogate, &old_value)?;
// Evict any cached copy of the reversed document (see the
// PutDocument branch): reversing a delete restores the row, so a
// stale post-delete cache entry must not linger.
self.doc_cache
.invalidate(database_id, tid, &collection, &document_id);
self.undo_chain_hash(database_id, tid, &collection, chain_hash_prior);
Ok(())
}
_ => unreachable!("apply_undo_document called with non-document entry"),
}
}
/// Physically reverse a bitemporal versioned write inside a single
/// caller-owned redb write transaction: remove the version/tombstone row
/// appended at `sys_from_ms`, plus every versioned index entry written at
/// the same system time. redb is single-writer, so all removals share one
/// transaction.
fn undo_bitemporal_write(
&self,
ctx: UndoDocumentContext<'_>,
sys_from_ms: i64,
index_tuples: &[(String, String)],
) -> Result<(), (usize, String)> {
let UndoDocumentContext {
database_id,
tid,
entry_index,
collection,
document_id,
} = ctx;
let map_err = |stage: &str, e: String| {
error!(
core = self.core_id,
entry_index,
collection = %collection,
document_id = %document_id,
error = %e,
"transaction undo: bitemporal version removal failed; shard state unknown"
);
(
entry_index,
format!("bitemporal {stage} on {collection}/{document_id}: {e}"),
)
};
let txn = self
.sparse
.db()
.begin_write()
.map_err(|e| map_err("begin_write", e.to_string()))?;
self.sparse
.versioned_remove_in_txn(&txn, database_id, tid, collection, document_id, sys_from_ms)
.map_err(|e| map_err("version remove", e.to_string()))?;
for (field, value) in index_tuples {
self.sparse
.versioned_index_remove_in_txn(
&txn,
VersionedIndexEntry {
database_id,
tenant: tid,
coll: collection,
field,
value,
doc_id: document_id,
sys_from_ms,
},
)
.map_err(|e| map_err("index remove", e.to_string()))?;
}
txn.commit().map_err(|e| map_err("commit", e.to_string()))?;
Ok(())
}
/// Reverse plain (non-bitemporal) secondary-index mutations from a
/// rolled-back document write.
///
/// `to_remove` were INSERTED on the forward path → delete them; `to_restore`
/// were REMOVED on the forward path (stale UPDATE entries, or a DELETE's
/// cascade) → re-insert them. Fatal on failure like the primary-store
/// restore, so a partial index rollback surfaces as `RollbackFailed` rather
/// than silently diverging the secondary index from the primary store.
fn undo_secondary_index(
&self,
ctx: UndoDocumentContext<'_>,
to_remove: &[(String, String)],
to_restore: &[(String, String)],
) -> Result<(), (usize, String)> {
let UndoDocumentContext {
database_id,
tid,
entry_index,
collection,
document_id,
} = ctx;
let map_err = |stage: &str, e: String| {
error!(
core = self.core_id,
entry_index,
collection = %collection,
document_id = %document_id,
error = %e,
"transaction undo: secondary-index reversal failed; shard state unknown"
);
(
entry_index,
format!("secondary-index {stage} on {collection}/{document_id}: {e}"),
)
};
for (field, value) in to_remove {
self.sparse
.index_remove(database_id, tid, collection, field, value, document_id)
.map_err(|e| map_err("remove", e.to_string()))?;
}
for (field, value) in to_restore {
self.sparse
.index_put(database_id, tid, collection, field, value, document_id)
.map_err(|e| map_err("restore", e.to_string()))?;
}
Ok(())
}
/// Reverse a hash-chain mutation performed by a document write. `None` =
/// the op never touched the chain; `Some(None)` = remove the key (genesis
/// insert); `Some(Some(prev))` = restore the key to its pre-image.
fn undo_chain_hash(
&mut self,
database_id: u64,
tid: u64,
collection: &str,
chain_hash_prior: Option<Option<String>>,
) {
match chain_hash_prior {
None => {}
Some(None) => {
self.chain_hashes.remove(&(
crate::types::DatabaseId::new(database_id),
crate::types::TenantId::new(tid),
collection.to_string(),
));
}
Some(Some(prev)) => {
self.chain_hashes.insert(
(
crate::types::DatabaseId::new(database_id),
crate::types::TenantId::new(tid),
collection.to_string(),
),
prev,
);
}
}
}
}