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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2024-present, fjall-rs
// Copyright (c) 2026-present, Structured World Foundation
use crate::double_ended_peekable::{DoubleEndedPeekable, DoubleEndedPeekableExt};
use crate::merge_operator::MergeOperator;
use crate::range_tombstone::RangeTombstone;
use crate::{InternalValue, SeqNo, UserKey, UserValue, ValueType, comparator::SharedComparator};
use alloc::sync::Arc;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
/// Consumes a stream of KVs and emits a new stream according to MVCC and tombstone rules
///
/// This iterator is used for read operations.
pub struct MvccStream<I: DoubleEndedIterator<Item = crate::Result<InternalValue>>> {
inner: DoubleEndedPeekable<crate::Result<InternalValue>, I>,
merge_operator: Option<Arc<dyn MergeOperator>>,
comparator: SharedComparator,
/// Range tombstones with per-source visibility cutoffs. When set, merge
/// resolution skips entries suppressed by an RT (treats them as a
/// tombstone boundary). Each tuple is `(tombstone, cutoff_seqno)`.
range_tombstones: Vec<(RangeTombstone, SeqNo)>,
/// Reusable buffer for reverse-iteration merge resolution. Avoids
/// allocating a fresh `Vec` on every `next_back()` call.
key_entries_buf: Vec<InternalValue>,
}
impl<I: DoubleEndedIterator<Item = crate::Result<InternalValue>>> MvccStream<I> {
/// Initializes a new multi-version-aware iterator.
#[must_use]
pub fn new(iter: I, merge_operator: Option<Arc<dyn MergeOperator>>) -> Self {
Self::new_with_comparator(
iter,
merge_operator,
crate::comparator::default_comparator(),
)
}
/// Initializes a new multi-version-aware iterator with the given comparator.
#[must_use]
pub fn new_with_comparator(
iter: I,
merge_operator: Option<Arc<dyn MergeOperator>>,
comparator: SharedComparator,
) -> Self {
Self {
inner: iter.double_ended_peekable(),
merge_operator,
comparator,
range_tombstones: Vec::new(),
key_entries_buf: Vec::new(),
}
}
/// Installs range tombstones for merge-resolution awareness.
///
/// When set, operands or base values suppressed by a range tombstone are
/// treated as a deletion boundary (merge stops, base = None).
#[must_use]
pub fn with_range_tombstones(mut self, rts: Vec<(RangeTombstone, SeqNo)>) -> Self {
self.range_tombstones = rts;
self
}
/// Returns true if the entry is suppressed by any installed range tombstone.
fn is_rt_suppressed(&self, entry: &InternalValue) -> bool {
self.range_tombstones.iter().any(|(rt, cutoff)| {
rt.should_suppress_with(
&entry.key.user_key,
entry.key.seqno,
*cutoff,
self.comparator.as_ref(),
)
})
}
/// Collects all entries for the given key and applies the merge operator (forward).
fn resolve_merge_forward(
&mut self,
head: &InternalValue,
merge_op: &dyn MergeOperator,
) -> crate::Result<InternalValue> {
let user_key = &head.key.user_key;
let mut operands: Vec<UserValue> = vec![head.value.clone()];
let mut base_value: Option<UserValue> = None;
let mut found_base = false;
let mut saw_indirection_base = false;
// Collect remaining same-key entries
loop {
let Some(next) = self.inner.next_if(|kv| {
if let Ok(kv) = kv {
kv.key.user_key == *user_key
} else {
true
}
}) else {
break;
};
let next = next?;
// Range tombstone suppression: an RT-suppressed entry is logically
// deleted — treat it as a tombstone boundary (no base value).
if self.is_rt_suppressed(&next) {
found_base = true;
break;
}
match next.key.value_type {
ValueType::MergeOperand => {
operands.push(next.value);
}
ValueType::Value => {
base_value = Some(next.value);
found_base = true;
break;
}
ValueType::Indirection => {
// Indirection payloads are internal blob pointers and must not be
// used as a merge base user value. Remember that we saw an
// indirection base so we can skip merge resolution for this key.
found_base = true;
saw_indirection_base = true;
break;
}
ValueType::Tombstone | ValueType::WeakTombstone => {
// Tombstone kills base
found_base = true;
break;
}
}
}
// Drain any remaining same-key entries
if found_base {
self.drain_key_min(user_key)?;
}
// If the base would be an indirection, do not attempt to resolve the merge;
// just return the newest entry unchanged.
if saw_indirection_base {
return Ok(head.clone());
}
// Reverse to chronological order (ascending seqno)
operands.reverse();
let operand_refs: Vec<&[u8]> = operands.iter().map(AsRef::as_ref).collect();
let merged = merge_op.merge(user_key, base_value.as_deref(), &operand_refs)?;
Ok(InternalValue::from_components(
user_key.clone(),
merged,
head.key.seqno,
ValueType::Value,
))
}
/// Resolves buffered entries for reverse iteration merge.
/// `entries` are in ascending seqno order (oldest first, as collected by `next_back`).
fn resolve_merge_buffered(&self, entries: Vec<InternalValue>) -> crate::Result<InternalValue> {
let Some(merge_op) = &self.merge_operator else {
// No merge operator — return newest entry (last in ascending order)
return entries
.into_iter()
.last()
.ok_or(crate::Error::Unrecoverable);
};
// entries are in ascending seqno order (oldest→newest)
// The newest entry (last) has the highest seqno — that's our result seqno.
let newest = entries.last().ok_or(crate::Error::Unrecoverable)?;
let mut operands: Vec<UserValue> = Vec::new();
let mut base_value: Option<UserValue> = None;
let result_seqno = newest.key.seqno;
let result_key = newest.key.user_key.clone();
// Process in descending seqno order (newest first) to match forward merge semantics
let mut saw_indirection = false;
for entry in entries.iter().rev() {
// RT-suppressed entries are logically deleted — treat as tombstone.
if self.is_rt_suppressed(entry) {
break;
}
match entry.key.value_type {
ValueType::MergeOperand => {
operands.push(entry.value.clone());
}
ValueType::Value => {
base_value = Some(entry.value.clone());
break;
}
ValueType::Indirection => {
// Do not use indirection bytes as a merge base; stop scanning
// older versions.
saw_indirection = true;
break;
}
ValueType::Tombstone | ValueType::WeakTombstone => {
break;
}
}
}
// If the base is an indirection, return the newest entry unchanged.
if saw_indirection {
return entries
.into_iter()
.last()
.ok_or(crate::Error::Unrecoverable);
}
// Reverse operands to chronological order (ascending seqno)
operands.reverse();
let operand_refs: Vec<&[u8]> = operands.iter().map(AsRef::as_ref).collect();
let merged = merge_op.merge(&result_key, base_value.as_deref(), &operand_refs)?;
Ok(InternalValue::from_components(
result_key,
merged,
result_seqno,
ValueType::Value,
))
}
// Drains all entries for the given user key from the front of the iterator.
fn drain_key_min(&mut self, key: &UserKey) -> crate::Result<()> {
loop {
let Some(next) = self.inner.next_if(|kv| {
if let Ok(kv) = kv {
kv.key.user_key == key
} else {
true
}
}) else {
return Ok(());
};
next?;
}
}
}
impl<I> crate::reseek::Reseekable for MvccStream<I>
where
I: DoubleEndedIterator<Item = crate::Result<InternalValue>> + crate::reseek::Reseekable,
{
/// Clear the lookahead peek buffers and the reverse-merge scratch buffer,
/// then forward the reposition to the inner merger. The installed range
/// tombstones and merge operator are position-independent and stay as-is.
fn reseek(&mut self, ctx: &crate::reseek::ReseekCtx) {
self.inner.reset_front_peeked();
self.inner.reset_back_peeked();
self.key_entries_buf.clear();
self.inner.inner_mut().reseek(ctx);
}
}
impl<I: DoubleEndedIterator<Item = crate::Result<InternalValue>>> Iterator for MvccStream<I> {
type Item = crate::Result<InternalValue>;
fn next(&mut self) -> Option<Self::Item> {
let head = fail_iter!(self.inner.next()?);
if head.key.value_type.is_merge_operand() {
// Clone the Arc (not the operator) — resolve_merge_forward needs
// &mut self which conflicts with borrowing self.merge_operator.
if let Some(merge_op) = self.merge_operator.clone()
&& !self.is_rt_suppressed(&head)
{
let result = self.resolve_merge_forward(&head, merge_op.as_ref());
return Some(result);
}
}
// As long as items are the same key, ignore them
fail_iter!(self.drain_key_min(&head.key.user_key));
Some(Ok(head))
}
}
impl<I: DoubleEndedIterator<Item = crate::Result<InternalValue>>> DoubleEndedIterator
for MvccStream<I>
{
fn next_back(&mut self) -> Option<Self::Item> {
// When a merge operator is configured we must buffer ALL entries
// for a key (not just MergeOperands) because we only learn that
// merge is needed when we reach the newest entry (last in
// reverse order). The base Value/Tombstone seen first must be
// preserved for the merge function.
//
// NOTE: Lazy allocation (only buffer after seeing MergeOperand) is
// incorrect — reverse iteration visits the oldest (base) entry first,
// so deferring allocation until a MergeOperand is found would lose
// the base Value needed by the merge function.
let has_merge_op = self.merge_operator.is_some();
self.key_entries_buf.clear();
loop {
let tail = fail_iter!(self.inner.next_back()?);
let prev = match self.inner.peek_back() {
Some(Ok(prev)) => prev,
Some(Err(_)) => {
#[expect(
clippy::expect_used,
reason = "we just asserted, the peeked value is an error"
)]
return Some(Err(self
.inner
.next_back()
.expect("should exist")
.expect_err("should be error")));
}
None => {
// Last item — resolve merge only if newest entry is a MergeOperand
// and not RT-suppressed.
if has_merge_op
&& tail.key.value_type.is_merge_operand()
&& !self.is_rt_suppressed(&tail)
{
self.key_entries_buf.push(tail);
let entries = self.key_entries_buf.drain(..).collect();
return Some(self.resolve_merge_buffered(entries));
}
return Some(Ok(tail));
}
};
if prev.key.user_key < tail.key.user_key {
// `tail` is the newest entry for this key — boundary reached.
// Only merge if the newest entry is a MergeOperand.
if has_merge_op
&& tail.key.value_type.is_merge_operand()
&& !self.is_rt_suppressed(&tail)
{
self.key_entries_buf.push(tail);
let entries = core::mem::take(&mut self.key_entries_buf);
return Some(self.resolve_merge_buffered(entries));
}
return Some(Ok(tail));
}
// Same key — buffer entry when merge operator is configured.
// We must buffer ALL types (including Value/Tombstone) because
// we don't yet know if the newest entry will be a MergeOperand.
if has_merge_op {
self.key_entries_buf.push(tail);
}
// Without merge operator: skip older versions (loop continues)
}
}
}
#[cfg(test)]
#[allow(clippy::string_lit_as_bytes)]
#[allow(
clippy::unwrap_used,
clippy::indexing_slicing,
clippy::useless_vec,
reason = "test code"
)]
mod tests;