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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! WAL-proven, bounded checkpoint changes to rows in a published disk generation.
use super::*;
use reddb_engine::storage::segment_key_lookup::SegmentKeyLookup;
use super::secondary_index::{SecondaryIndexProjector, SECONDARY_KEY_BYTES_MAX};
use reddb_engine::storage::collection_read::{EncodedRecord, PagedCollection};
fn posting(
projector: &dyn SecondaryIndexProjector,
entity: &UnifiedEntity,
) -> Result<Option<Vec<u8>>, StoreError> {
let mut key = [0; SECONDARY_KEY_BYTES_MAX];
let Some(length) = projector.project(entity, &mut key)? else {
return Ok(None);
};
let bytes = key.get(..length).ok_or_else(|| {
StoreError::Serialization("secondary key exceeds its bounded buffer".into())
})?;
let mut posting = Vec::with_capacity(length + 8);
posting.extend_from_slice(bytes);
posting.extend_from_slice(&entity.id.raw().to_be_bytes());
Ok(Some(posting))
}
fn classified_row(entity: &UnifiedEntity) -> bool {
matches!(&entity.data, EntityData::Row(row)
if row.named.is_some() || row.schema.is_some() || row.columns.is_empty())
&& entity.branch_version().is_none()
}
/// What a checkpoint publishes for a changed row, as
/// `apply_sparse_checkpoint_tree` decides it. The postings of the row must be
/// those of that image.
#[derive(Clone, Copy, PartialEq, Eq)]
enum PublishedImage {
/// The row as it is.
Row,
/// The row without the mark of a delete whose transaction is still open.
WithoutPendingDelete,
/// Nothing new: the version is written by a transaction still open, and
/// is revisited by the next checkpoint.
Deferred,
}
fn key_posting(row: &UnifiedEntity) -> Option<Vec<u8>> {
let key = SegmentKeyLookup::key(row)?;
let fingerprint = reddb_file::native_key_index::fingerprint(key);
Some(reddb_file::native_key_index::encode_candidate(&fingerprint, row.id.raw()).to_vec())
}
type PostingChange<'a> = (&'a Arc<BTree>, Option<Vec<u8>>, Option<Vec<u8>>);
#[derive(Default)]
struct PostingPlan<'a> {
changes: Vec<PostingChange<'a>>,
payload_bytes: usize,
}
impl<'a> PostingPlan<'a> {
fn add(
&mut self,
tree: &'a Arc<BTree>,
before: Option<Vec<u8>>,
after: Option<Vec<u8>>,
) -> Result<bool, StoreError> {
if before == after {
return Ok(true);
}
if self.changes.len() >= super::checkpoint_delta::POSTING_CHANGES_MAX {
return Ok(super::checkpoint_delta::refused(
"more than 65536 index entries changed",
));
}
self.payload_bytes = self
.payload_bytes
.saturating_add(before.as_ref().map_or(0, Vec::capacity))
.saturating_add(after.as_ref().map_or(0, Vec::capacity));
self.changes.reserve(1);
let retained = self
.changes
.capacity()
.saturating_mul(std::mem::size_of::<PostingChange>())
.saturating_add(self.payload_bytes);
if retained > 8 * 1024 * 1024 {
return Ok(super::checkpoint_delta::refused(
"the changed index entries exceed 8 MiB",
));
}
self.changes.push((tree, before, after));
Ok(true)
}
/// The trees the plan changes, each once.
fn trees(&self) -> Vec<&'a Arc<BTree>> {
let mut trees: Vec<&'a Arc<BTree>> = Vec::new();
for (tree, _, _) in &self.changes {
if !trees.iter().any(|known| Arc::ptr_eq(known, tree)) {
trees.push(tree);
}
}
trees
}
/// Whether every entry to remove is in its tree and every entry to add is
/// not. Asked per tree in key order, so a leaf answers for its
/// neighbours: one descent per entry was a quarter of a delta's time.
fn matches_its_trees(&self) -> Result<bool, StoreError> {
for tree in self.trees() {
let mut expected: Vec<(&[u8], bool)> = Vec::new();
for (owner, before, after) in &self.changes {
if Arc::ptr_eq(owner, tree) {
expected.extend(before.as_deref().map(|key| (key, true)));
expected.extend(after.as_deref().map(|key| (key, false)));
}
}
expected.sort_unstable();
let mut probe = tree.sorted_probe();
for (key, present) in expected {
let found = probe
.contains(key)
.map_err(|e| StoreError::Io(std::io::Error::other(e.to_string())))?;
if found != present {
return Ok(super::checkpoint_delta::refused(
"an index entry does not match its row",
));
}
}
}
Ok(true)
}
/// Add and remove the planned entries, each tree's additions in one
/// sorted pass instead of a descent and a leaf write for every entry.
fn apply(self) -> Result<(), StoreError> {
let failed = |e: BTreeError| StoreError::Io(std::io::Error::other(e.to_string()));
for tree in self.trees() {
let mut added: Vec<(Vec<u8>, Vec<u8>)> = Vec::new();
let mut removed: Vec<&[u8]> = Vec::new();
for (owner, before, after) in &self.changes {
if Arc::ptr_eq(owner, tree) {
added.extend(after.iter().map(|key| (key.clone(), Vec::new())));
removed.extend(before.as_deref());
}
}
added.sort_unstable();
tree.insert_sorted(&added).map_err(failed)?;
removed.sort_unstable();
for key in removed {
if !tree.delete(key).map_err(failed)? {
return Err(StoreError::Serialization(
"validated index posting disappeared".into(),
));
}
}
}
Ok(())
}
}
impl UnifiedStore {
pub(super) fn sparse_cold_row_tree(
&self,
collection: &str,
manager: &Arc<SegmentManager>,
tree: &Arc<BTree>,
previous: &CheckpointVersion,
current: &mut CheckpointVersion,
) -> Result<Option<Arc<BTree>>, StoreError> {
// Postings are reconciled against the image this checkpoint publishes
// for each row: a version of a transaction still open is deferred and
// a delete it has not committed is left out, as the data tree does.
// The rows the previous checkpoint deferred are revisited here; only an
// unknown set of them (more than the bounded list) needs the copy.
let Some(deferred) = previous.deferred_rows.as_ref() else {
return super::checkpoint_delta::declined(
"the previous checkpoint deferred more rows than it lists",
);
};
if self.commit.is_none() || self.ownership_active_epoch.load(Ordering::Acquire) == 0 {
return super::checkpoint_delta::declined("no ownership epoch");
}
// A checkpoint that deferred rows leaves the changed rows resident
// (its base is not installed again until nothing is deferred). The
// delta then covers what changed since that checkpoint's segments
// and the rows it deferred: every row whose image can differ.
if previous.pending_vault != current.pending_vault {
return super::checkpoint_delta::declined("the vault rows changed");
}
let keys = self.key_indices.read();
let Some(keys) = keys.get(collection) else {
return super::checkpoint_delta::declined("the collection has no published key index");
};
if !keys.source.ptr_eq(&Arc::downgrade(tree)) {
return super::checkpoint_delta::declined(
"the key index was built from another data tree",
);
}
let specs = self.secondary_index_specs.read();
let specs = specs.get(collection);
// Include internal visibility/count projections, not just declared SQL
// indexes. Every published tree needs its exact deterministic projector.
// Missing/new definitions and pinned generations retain replacement.
if keys.secondary.len() != specs.map_or(0, |s| s.len())
|| keys.secondary.iter().any(|(name, index)| {
specs
.and_then(|s| s.get(name))
.is_none_or(|spec| spec.identity != index.identity)
})
{
// A projection built in the background is declared before it is
// published, and its build reads the data tree a delta would change.
let building = specs.is_some_and(|specs| {
specs
.iter()
.any(|(name, spec)| spec.deferred && !keys.secondary.contains_key(name))
});
return super::checkpoint_delta::declined(if building {
"an index of the collection is still being built"
} else {
"the published indexes are not the declared ones"
});
}
if !super::checkpoint_delta::readers_leave(|| {
keys.secondary.iter().any(|(_, index)| {
Arc::strong_count(&index.tree) != 1 || index.tree.has_retirement_readers()
})
}) {
return super::checkpoint_delta::declined("a reader holds an index tree");
}
let Some(ids) = manager.checkpoint_mutations_since(&previous.segments) else {
return super::checkpoint_delta::declined(
"the mutation journal no longer reaches the previous checkpoint",
);
};
let root_before = tree.root_page_id();
manager
.try_with_unshared_backing_source_delta(
root_before,
crate::storage::unified::segment::CHECKPOINT_MUTATIONS_MAX,
|source, removed| {
let mut changed_xid_high_water_mark = 0;
let result = (|| {
// The store and the sole backing source are the only tree owners.
// Owned cursors can outlive their source: check their separate pin.
if Arc::strong_count(tree) != 2 || tree.has_retirement_readers() {
return super::checkpoint_delta::declined(
"a reader holds the data tree",
);
}
let exclusive_keys = keys.indexed
&& Arc::strong_count(&keys.tree) == 2
&& !keys.tree.has_retirement_readers()
&& PagedCollection::with_key_index(
Arc::clone(tree),
Arc::clone(&keys.tree),
)
.shares_trees_with(source);
let ids: std::collections::BTreeSet<_> = ids
.iter()
.chain(removed)
.chain(deferred.iter())
.copied()
.collect();
// Bound projection work separately from retained memory. Visibility
// and equality keys are usually much shorter than the codec maximum.
let posting_count = ids.len().saturating_mul(keys.secondary.len());
let max_changes =
crate::storage::unified::segment::CHECKPOINT_MUTATIONS_MAX;
if ids.len() > max_changes
|| posting_count > super::checkpoint_delta::POSTING_CHANGES_MAX
{
return super::checkpoint_delta::declined(
"more than 8192 changed rows, or 65536 index entries",
);
}
let mut data_deletes = Vec::new();
let mut postings = PostingPlan::default();
// `ids` ascend, and so do their keys: one leaf answers
// for the rows that follow it.
let mut published = tree.sorted_probe();
for id in &ids {
let mut after_key = None;
let mut image = PublishedImage::Row;
let eligible = manager.get_with(*id, |entity| {
changed_xid_high_water_mark =
changed_xid_high_water_mark.max(entity.max_transaction_id());
if !classified_row(entity) || current.pending_vault.contains(id) {
return false;
}
if current.excluded_xids.contains(&entity.xmin) {
image = PublishedImage::Deferred;
} else if entity.xmax != 0
&& current.excluded_xids.contains(&entity.xmax)
{
image = PublishedImage::WithoutPendingDelete;
let mut published = entity.clone();
published.xmax = 0;
after_key = key_posting(&published);
} else {
after_key = key_posting(entity);
}
true
});
let deleting = removed.contains(id);
if eligible != (if deleting { None } else { Some(true) }) {
return super::checkpoint_delta::declined(
"a changed row is in the vault or not a classified table row",
);
}
// Keep the old image only while comparing this row's projections.
let limit = 1024 * 1024;
let old = match published.get(&id.raw().to_be_bytes(), limit) {
Ok(Some(bytes)) => {
let record = EncodedRecord { id: *id, bytes };
match record.decode_with_budget(self.format_version(), limit) {
Ok((entity, _)) if classified_row(&entity) => Some(entity),
Ok(_) | Err(StoreError::ReadLimitExceeded { .. }) => {
return super::checkpoint_delta::declined(
"a published row is unclassified or over 1 MiB",
)
}
Err(error) => return Err(error),
}
}
Ok(None) => None,
Err(BTreeError::ReadLimitExceeded { .. }) => {
return super::checkpoint_delta::declined(
"a published row is over 1 MiB",
)
}
Err(error) => {
return Err(StoreError::Io(std::io::Error::other(
error.to_string(),
)))
}
};
if deleting && old.is_some() {
data_deletes.push(*id);
}
let before_key = old.as_ref().and_then(key_posting);
if image == PublishedImage::Deferred {
// The published image of the row stays as it is.
after_key = before_key.clone();
}
if before_key != after_key
&& (!exclusive_keys
|| !postings.add(&keys.tree, before_key, after_key)?)
{
return super::checkpoint_delta::declined(
"the key index is shared with a reader",
);
}
if let Some(specs) = specs {
for (name, index) in &keys.secondary {
let projector = specs[name].projector.as_ref();
let before = old
.as_ref()
.map(|row| posting(projector, row))
.transpose()?
.flatten();
let after = match image {
_ if deleting => None,
PublishedImage::Deferred => before.clone(),
PublishedImage::WithoutPendingDelete => manager
.get_with(*id, |row| {
let mut published = row.clone();
published.xmax = 0;
posting(projector, &published)
})
.ok_or(StoreError::EntityNotFound(*id))??,
PublishedImage::Row => manager
.get_with(*id, |row| posting(projector, row))
.ok_or(StoreError::EntityNotFound(*id))??,
};
if !postings.add(&index.tree, before, after)? {
return super::checkpoint_delta::declined(
"an index refused the change",
);
}
}
}
}
drop(published);
if !postings.matches_its_trees()? {
return super::checkpoint_delta::declined(
"an index entry does not match its row",
);
}
let applied = self.apply_sparse_checkpoint_tree(
collection, manager, tree, previous, current, removed,
)?;
if applied.is_some() {
// Data and projections share the active page-undo epoch;
// their roots publish together in the existing catalog fence.
for id in data_deletes {
if !tree.delete(&id.raw().to_be_bytes()).map_err(|e| {
StoreError::Io(std::io::Error::other(e.to_string()))
})? {
return Err(StoreError::Serialization(
"validated physical row disappeared".into(),
));
}
}
postings.apply()?;
}
Ok(applied)
})();
let published = if result.as_ref().is_ok_and(Option::is_some) {
let root = tree.root_page_id();
// Carry the changed headers into the existing upper bound
// even when an in-place update retains the same root page.
// Publish the exact count without recounting old payloads.
if let Some(summary) = self.recovery_xid_summary.write().as_mut() {
if summary.roots.get(collection) == Some(&root_before) {
summary.high_water_mark =
summary.high_water_mark.max(changed_xid_high_water_mark);
summary.roots.insert(collection.to_owned(), root);
}
}
Some((root, manager.count() as u64))
} else {
None
};
(result, published)
},
)
.unwrap_or_else(|| {
super::checkpoint_delta::declined(manager.backing_delta_refusal(
root_before,
crate::storage::unified::segment::CHECKPOINT_MUTATIONS_MAX,
))
})
}
}