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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2024-present, fjall-rs
// Copyright (c) 2026-present, Dmitry Prudnikov
use alloc::sync::Arc;
use core::fmt::Debug;
use core::sync::atomic::Ordering::{AcqRel, Acquire, Release};
use crate::SeqNo;
use portable_atomic::AtomicU64;
/// The maximum allowed sequence number value.
///
/// The MSB (`0x8000_0000_0000_0000`) is reserved for internal use by the
/// transaction layer, so all sequence numbers must be strictly less than
/// this boundary. Values returned by [`SequenceNumberGenerator::next`]
/// must be at most `MAX_SEQNO - 1` (`0x7FFF_FFFF_FFFF_FFFE`), leaving
/// room for `seqno + 1` operations used internally by the engine.
pub const MAX_SEQNO: SeqNo = 0x7FFF_FFFF_FFFF_FFFF;
/// Trait for custom sequence number generation.
///
/// Implementations must be thread-safe and provide atomic operations
/// for sequence number management.
///
/// # Invariants
///
/// Implementors **must** respect the following invariants, which are
/// relied upon by the storage engine (e.g., for MVCC and transactions):
///
/// - The most-significant bit (MSB) of a sequence number is reserved
/// for internal use by the transaction layer.
/// - All sequence numbers produced by this generator **must** therefore
/// be strictly less than `0x8000_0000_0000_0000`.
/// - Calls to [`SequenceNumberGenerator::next`] on a given generator
/// instance must return monotonically increasing values (each `next`
/// returns a value that is strictly greater than any value previously
/// returned by `next` on the same instance) until the reserved MSB
/// boundary is reached.
/// - In practice, this means `next`-generated sequence numbers are
/// unique for the lifetime of the generator (modulo wrap-around, which
/// must not occur within the reserved MSB range).
///
/// Implementors are also responsible for ensuring that [`Self::get`] does not
/// return values that violate these invariants, and that [`Self::set`] and
/// [`Self::fetch_max`] do not violate them (e.g., by setting the counter to a
/// value at or above `0x8000_0000_0000_0000`, or by moving the counter
/// backwards such that subsequent calls to [`Self::next`] would observe
/// non-monotonic sequence numbers).
///
/// The [`Self::set`] method is a special-case escape hatch intended for use
/// during initialization or recovery. It may move the counter forwards
/// or backwards and therefore **may** cause subsequent calls to
/// [`Self::next`] to observe non-monotonic sequence numbers. This is
/// permitted; callers are responsible for using [`Self::fetch_max`] (or other
/// application-level logic) after `set` if they need to reestablish any
/// monotonicity guarantees.
///
/// # Supertraits
///
/// `UnwindSafe + RefUnwindSafe` are required because generators may be
/// captured inside `catch_unwind` (e.g., during ingestion error recovery).
///
/// The default implementation is [`SequenceNumberCounter`], which uses
/// an `Arc<AtomicU64>` for lock-free atomic operations. It enforces the
/// MSB boundary in `new`, `set`, and `fetch_max` (via assert/clamp),
/// and panics in `next` if the counter reaches the reserved range.
pub trait SequenceNumberGenerator:
Send + Sync + Debug + core::panic::UnwindSafe + core::panic::RefUnwindSafe + 'static
{
/// Gets the next sequence number, atomically incrementing the counter.
///
/// This must:
/// - Return a value strictly greater than any value previously returned
/// by `next` on the same generator instance (monotonic increase).
/// - Never return a value greater than `MAX_SEQNO - 1`, leaving room
/// for internal `seqno + 1` operations that must remain strictly
/// less than [`MAX_SEQNO`].
#[must_use]
fn next(&self) -> SeqNo;
/// Gets the current sequence number without incrementing.
///
/// This should be consistent with the value that will be used as the
/// basis for the next call to [`Self::next`], and must not itself alter the
/// monotonicity guarantees.
#[must_use]
fn get(&self) -> SeqNo;
/// Sets the sequence number to the given value.
///
/// Implementations must ensure that `value` is strictly less than
/// `0x8000_0000_0000_0000` (the MSB is reserved).
///
/// This method is intended for direct overrides (e.g., during
/// initialization or recovery) and is **not** required to preserve
/// monotonicity with respect to values previously returned by
/// [`Self::next`]. In particular, calling `set` with a value lower than a
/// previously returned `next` value may cause subsequent calls to
/// [`Self::next`] to observe non-monotonic sequence numbers. This is
/// allowed; callers that need to advance the sequence number in a
/// monotonic fashion should prefer [`Self::fetch_max`] instead of `set`.
fn set(&self, value: SeqNo);
/// Atomically updates the sequence number to the maximum of
/// the current value and the given value.
///
/// The resulting stored value must:
/// - Remain strictly less than `0x8000_0000_0000_0000`.
/// - Preserve the monotonicity guarantees expected by [`Self::next`].
fn fetch_max(&self, value: SeqNo);
}
/// A shared, cloneable sequence number generator.
pub type SharedSequenceNumberGenerator = Arc<dyn SequenceNumberGenerator>;
/// Thread-safe sequence number generator
///
/// # Examples
///
/// ```
/// # use lsm_tree::{AbstractTree, Config, SequenceNumberCounter};
/// #
/// # let path = tempfile::tempdir()?;
///
/// let seqno = SequenceNumberCounter::default();
/// let visible_seqno = SequenceNumberCounter::default();
///
/// let tree = Config::new(path, seqno.clone(), visible_seqno.clone()).open()?;
///
/// // Do some inserts...
/// for k in [b"a", b"b", b"c"] {
/// let batch_seqno = seqno.next();
/// tree.insert(k, "abc", batch_seqno);
/// visible_seqno.fetch_max(batch_seqno + 1);
/// }
///
/// // Create a batch
/// let batch_seqno = seqno.next();
/// tree.remove("a".as_bytes(), batch_seqno);
/// tree.remove("b".as_bytes(), batch_seqno);
/// tree.remove("c".as_bytes(), batch_seqno);
/// visible_seqno.fetch_max(batch_seqno + 1);
/// #
/// # assert!(tree.is_empty(visible_seqno.get(), None)?);
/// # Ok::<(), lsm_tree::Error>(())
/// ```
#[derive(Clone, Default, Debug)]
pub struct SequenceNumberCounter(Arc<AtomicU64>);
impl SequenceNumberCounter {
/// Creates a new counter, setting it to some previous value.
///
/// # Panics
///
/// Panics if `prev > MAX_SEQNO` (reserved MSB range).
///
/// Note: `prev == MAX_SEQNO` is allowed but means the counter is
/// exhausted — any subsequent call to [`next()`](Self::next) will panic.
#[must_use]
pub fn new(prev: SeqNo) -> Self {
assert!(
prev <= MAX_SEQNO,
"Sequence number must not use the reserved MSB"
);
Self(Arc::new(AtomicU64::new(prev)))
}
/// Allocates and returns the next sequence number, atomically
/// incrementing the internal counter.
///
/// The returned value is the counter's value **before** the increment
/// (i.e., pre-increment / fetch-then-add semantics).
///
/// # Panics
///
/// Panics if the current value is already [`MAX_SEQNO`] (i.e., when
/// advancing past it would enter the reserved MSB range).
#[must_use]
pub fn next(&self) -> SeqNo {
<Self as SequenceNumberGenerator>::next(self)
}
/// Returns the current internal counter value without incrementing.
///
/// This is the value that the next call to [`next()`](Self::next) will
/// return (and then advance past).
#[must_use]
pub fn get(&self) -> SeqNo {
<Self as SequenceNumberGenerator>::get(self)
}
/// Sets the sequence number to the given value.
///
/// # Panics
///
/// Panics if `value > MAX_SEQNO` (reserved MSB range).
pub fn set(&self, value: SeqNo) {
<Self as SequenceNumberGenerator>::set(self, value);
}
/// Atomically updates the sequence number to the maximum of
/// the current value and the provided value.
pub fn fetch_max(&self, value: SeqNo) {
<Self as SequenceNumberGenerator>::fetch_max(self, value);
}
}
impl SequenceNumberGenerator for SequenceNumberCounter {
fn next(&self) -> SeqNo {
// We use fetch_update (CAS loop) instead of fetch_add to ensure the
// internal counter never enters the reserved MSB range. With fetch_add,
// a caught panic (via catch_unwind, which the trait requires via
// UnwindSafe) would leave the counter permanently stuck at an invalid
// value. fetch_update only stores the new value on success.
match self.0.fetch_update(AcqRel, Acquire, |current| {
if current >= MAX_SEQNO {
None
} else {
Some(current + 1)
}
}) {
Ok(seqno) => seqno,
Err(current) => panic!("Ran out of sequence numbers (current: {current})"),
}
}
fn get(&self) -> SeqNo {
self.0.load(Acquire)
}
fn set(&self, value: SeqNo) {
assert!(
value <= MAX_SEQNO,
"Sequence number must not use the reserved MSB"
);
self.0.store(value, Release);
}
fn fetch_max(&self, value: SeqNo) {
// Clamp to the maximum allowed sequence number to avoid storing
// a value in the reserved MSB range.
let clamped = value.min(MAX_SEQNO);
self.0.fetch_max(clamped, AcqRel);
}
}
// Orphan rules satisfied: SequenceNumberGenerator is a local trait,
// so Arc<dyn SequenceNumberGenerator> is covered by a local type parameter.
impl From<SequenceNumberCounter> for SharedSequenceNumberGenerator {
fn from(counter: SequenceNumberCounter) -> Self {
Arc::new(counter)
}
}
#[cfg(test)]
mod tests;