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
//! 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()
}
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() >= crate::storage::unified::segment::CHECKPOINT_MUTATIONS_MAX {
return Ok(false);
}
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 > 1024 * 1024 {
return Ok(false);
}
for (key, expected) in [(before.as_ref(), true), (after.as_ref(), false)] {
if let Some(key) = key {
let found = tree
.get(key)
.map_err(|e| StoreError::Io(std::io::Error::other(e.to_string())))?;
if found.is_some() != expected {
return Ok(false);
}
}
}
self.changes.push((tree, before, after));
Ok(true)
}
}
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> {
// An unpublished/normalized row can have a different set of postings.
// Only reconcile the projections of complete, committed row images.
if self.commit.is_none()
|| self.ownership_active_epoch.load(Ordering::Acquire) == 0
|| !previous.segments.is_empty()
|| previous.pending_vault != current.pending_vault
|| previous.has_unprojected_rows
|| previous
.deferred_rows
.as_ref()
.is_none_or(|ids| !ids.is_empty())
{
return Ok(None);
}
let keys = self.key_indices.read();
let Some(keys) = keys.get(collection) else {
return Ok(None);
};
if !keys.source.ptr_eq(&Arc::downgrade(tree)) {
return Ok(None);
}
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
|| Arc::strong_count(&index.tree) != 1
|| index.tree.has_retirement_readers()
})
})
{
return Ok(None);
}
let Some(ids) = manager.checkpoint_mutations_since(&previous.segments) else {
return Ok(None);
};
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 Ok(None);
}
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).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 > max_changes {
return Ok(None);
}
let mut data_deletes = Vec::new();
let mut postings = PostingPlan::default();
for id in &ids {
let mut after_key = None;
let eligible = manager.get_with(*id, |entity| {
changed_xid_high_water_mark =
changed_xid_high_water_mark.max(entity.max_transaction_id());
after_key = key_posting(entity);
classified_row(entity)
&& !current.excluded_xids.contains(&entity.xmin)
&& (entity.xmax == 0
|| !current.excluded_xids.contains(&entity.xmax))
&& !current.pending_vault.contains(id)
});
let deleting = removed.contains(id);
if eligible != (if deleting { None } else { Some(true) }) {
return Ok(None);
}
// Keep the old image only while comparing this row's projections.
let limit = 1024 * 1024;
let old = match tree.get_with_budget(&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 Ok(None)
}
Err(error) => return Err(error),
}
}
Ok(None) => None,
Err(BTreeError::ReadLimitExceeded { .. }) => return Ok(None),
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 before_key != after_key
&& (!exclusive_keys
|| !postings.add(&keys.tree, before_key, after_key)?)
{
return Ok(None);
}
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 = if deleting {
None
} else {
manager
.get_with(*id, |row| posting(projector, row))
.ok_or(StoreError::EntityNotFound(*id))??
};
if !postings.add(&index.tree, before, after)? {
return Ok(None);
}
}
}
}
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(),
));
}
}
for (index, before, after) in postings.changes {
if let Some(key) = after {
index.insert(&key, &[]).map_err(|e| {
StoreError::Io(std::io::Error::other(e.to_string()))
})?;
}
if let Some(key) = before {
let removed = index.delete(&key).map_err(|e| {
StoreError::Io(std::io::Error::other(e.to_string()))
})?;
if !removed {
return Err(StoreError::Serialization(
"validated index posting disappeared".into(),
));
}
}
}
}
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(Ok(None))
}
}