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
//! Concurrency-under-mutation tests.
//!
//! These tests verify that concurrent readers (`get`, `scan`) work
//! correctly while the engine is actively flushing frozen memtables
//! or running compaction. The engine uses an `Arc<RwLock<EngineInner>>`
//! so readers and writers contend on the same lock. These tests prove
//! that readers always see a consistent snapshot and never observe
//! partial state.
//!
//! ## See also
//! - [`tests_hardening`] — concurrent reads during writes
//! - [`tests_stress`] — heavy mixed CRUD under load
#[cfg(test)]
#[allow(non_snake_case)]
mod tests {
use crate::engine::Engine;
use crate::engine::tests::helpers::*;
use std::sync::Arc;
use std::thread;
use tempfile::TempDir;
// ================================================================
// 1. Concurrent reads during flush
// ================================================================
/// # Scenario
/// Spawn reader threads doing `get()` while the main thread flushes
/// frozen memtables to SSTables.
///
/// # Expected behavior
/// All reader threads see consistent data — either the pre-flush or
/// post-flush state — and never encounter errors or missing keys.
#[test]
fn memtable_sstable__concurrent_gets_during_flush() {
init_tracing();
let tmp = TempDir::new().unwrap();
let path = tmp.path();
let engine = Arc::new(Engine::open(path, small_buffer_config()).unwrap());
// Write enough data to create frozen memtables.
for i in 0..50u32 {
engine
.put(
format!("key_{i:04}").into_bytes(),
format!("val_{i:04}").into_bytes(),
)
.unwrap();
}
// Spawn reader threads.
let mut handles = Vec::new();
for _ in 0..4 {
let eng = Arc::clone(&engine);
handles.push(thread::spawn(move || {
for i in 0..50u32 {
let key = format!("key_{i:04}").into_bytes();
// get() should never error — it may return Some or None
// depending on flush timing, but must not panic/error.
let _ = eng.get(key).expect("get must not error during flush");
}
}));
}
// Flush while readers are running.
engine.flush_all_frozen().unwrap();
for h in handles {
h.join().expect("reader thread panicked");
}
// After flush, all keys must be readable.
for i in 0..50u32 {
let val = engine
.get(format!("key_{i:04}").into_bytes())
.unwrap()
.expect("key must exist after flush");
assert_eq!(val, format!("val_{i:04}").into_bytes());
}
}
// ================================================================
// 2. Concurrent scans during flush
// ================================================================
/// # Scenario
/// Spawn reader threads doing `scan()` while the main thread flushes.
///
/// # Expected behavior
/// Scans complete without errors and return sorted, consistent results.
#[test]
fn memtable_sstable__concurrent_scans_during_flush() {
init_tracing();
let tmp = TempDir::new().unwrap();
let path = tmp.path();
let engine = Arc::new(Engine::open(path, small_buffer_config()).unwrap());
for i in 0..50u32 {
engine
.put(
format!("key_{i:04}").into_bytes(),
format!("val_{i:04}").into_bytes(),
)
.unwrap();
}
let mut handles = Vec::new();
for _ in 0..4 {
let eng = Arc::clone(&engine);
handles.push(thread::spawn(move || {
for _ in 0..5 {
let results: Vec<_> = eng
.scan(b"key_", b"key_\xff")
.expect("scan must not error during flush")
.collect();
// Must be sorted.
for w in results.windows(2) {
assert!(w[0].0 <= w[1].0, "scan results must be sorted");
}
}
}));
}
engine.flush_all_frozen().unwrap();
for h in handles {
h.join().expect("reader thread panicked");
}
}
// ================================================================
// 3. Concurrent reads during minor compaction
// ================================================================
/// # Scenario
/// Build enough SSTables to trigger minor compaction, then run
/// compaction while reader threads are doing `get()`.
///
/// # Expected behavior
/// All readers see consistent data. No errors, no missing keys.
#[test]
fn memtable_sstable__concurrent_gets_during_minor_compaction() {
init_tracing();
let tmp = TempDir::new().unwrap();
let path = tmp.path();
// Use config that triggers compaction with min_threshold=4.
let engine = Arc::new(engine_with_multi_sstables(path, 200, "key"));
let mut handles = Vec::new();
for _ in 0..4 {
let eng = Arc::clone(&engine);
handles.push(thread::spawn(move || {
for i in 0..200u32 {
let key = format!("key_{i:04}").into_bytes();
let _ = eng.get(key).expect("get must not error during compaction");
}
}));
}
// Run compaction while readers contend.
let _ = engine.minor_compact();
for h in handles {
h.join().expect("reader thread panicked");
}
// All data must remain consistent.
for i in 0..200u32 {
let key = format!("key_{i:04}").into_bytes();
assert!(
engine.get(key).unwrap().is_some(),
"key_{i:04} must be readable after compaction"
);
}
}
// ================================================================
// 4. Concurrent reads during major compaction
// ================================================================
/// # Scenario
/// Run major compaction while reader threads scan.
///
/// # Expected behavior
/// Scan results remain consistent and sorted.
#[test]
fn memtable_sstable__concurrent_scans_during_major_compaction() {
init_tracing();
let tmp = TempDir::new().unwrap();
let path = tmp.path();
let engine = Arc::new(engine_with_multi_sstables(path, 200, "key"));
let mut handles = Vec::new();
for _ in 0..4 {
let eng = Arc::clone(&engine);
handles.push(thread::spawn(move || {
let results: Vec<_> = eng
.scan(b"key_", b"key_\xff")
.expect("scan must not error during compaction")
.collect();
for w in results.windows(2) {
assert!(w[0].0 <= w[1].0, "scan must be sorted");
}
assert!(!results.is_empty(), "scan should return data");
}));
}
let _ = engine.major_compact();
for h in handles {
h.join().expect("reader thread panicked");
}
}
// ================================================================
// 5. Concurrent writes during flush
// ================================================================
/// # Scenario
/// Multiple writer threads compete for the write lock while
/// flush is also running.
///
/// # Expected behavior
/// No deadlocks, no data loss. All written keys present afterwards.
#[test]
fn memtable_sstable__concurrent_writes_during_flush() {
init_tracing();
let tmp = TempDir::new().unwrap();
let path = tmp.path();
let engine = Arc::new(Engine::open(path, small_buffer_config()).unwrap());
// Pre-populate.
for i in 0..20u32 {
engine
.put(
format!("pre_{i:04}").into_bytes(),
format!("val_{i:04}").into_bytes(),
)
.unwrap();
}
let mut handles = Vec::new();
for t in 0..4u32 {
let eng = Arc::clone(&engine);
handles.push(thread::spawn(move || {
for i in 0..10u32 {
eng.put(
format!("t{t}_k{i}").into_bytes(),
format!("t{t}_v{i}").into_bytes(),
)
.unwrap();
}
}));
}
// Flush concurrently with writes.
engine.flush_all_frozen().unwrap();
for h in handles {
h.join().expect("writer thread panicked");
}
// Final flush to capture remaining.
engine.flush_all_frozen().unwrap();
// All pre-populated keys.
for i in 0..20u32 {
assert!(
engine
.get(format!("pre_{i:04}").into_bytes())
.unwrap()
.is_some(),
"pre_{i:04} should exist"
);
}
// All thread-written keys.
for t in 0..4u32 {
for i in 0..10u32 {
assert!(
engine
.get(format!("t{t}_k{i}").into_bytes())
.unwrap()
.is_some(),
"t{t}_k{i} should exist"
);
}
}
}
// ================================================================
// 6. Concurrent compaction attempts serialize correctly
// ================================================================
/// # Scenario
/// Two threads both call `minor_compact()` simultaneously.
/// One gets the lock first and compacts; the second should either
/// compact any remaining buckets or return `Ok(false)`.
///
/// # Expected behavior
/// No panics, no data corruption. Data remains consistent.
#[test]
fn memtable_sstable__concurrent_compaction_attempts() {
init_tracing();
let tmp = TempDir::new().unwrap();
let path = tmp.path();
let engine = Arc::new(engine_with_multi_sstables(path, 200, "key"));
let eng1 = Arc::clone(&engine);
let eng2 = Arc::clone(&engine);
let h1 = thread::spawn(move || eng1.minor_compact());
let h2 = thread::spawn(move || eng2.minor_compact());
let r1 = h1.join().expect("compaction thread 1 panicked");
let r2 = h2.join().expect("compaction thread 2 panicked");
// Both should succeed (possibly one returns false).
assert!(r1.is_ok(), "compaction 1 should not error");
assert!(r2.is_ok(), "compaction 2 should not error");
// Data integrity.
for i in 0..200u32 {
let key = format!("key_{i:04}").into_bytes();
assert!(
engine.get(key).unwrap().is_some(),
"key_{i:04} must be readable"
);
}
}
}