seerdb 0.0.10

Research-grade storage engine with learned data structures
Documentation
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
// Corruption detection tests
// Tests checksum validation and corruption handling
// Critical for data integrity: detect and reject corrupted data

use seerdb::{DBOptions, RecoveryMode, DB};
use std::fs::{self, OpenOptions};
use std::io::{Seek, SeekFrom, Write};
use std::path::PathBuf;
use tempfile::TempDir;

// Helper to find first SSTable file (handles dynamic sequence numbers)
fn find_sstable(data_dir: &PathBuf) -> Option<PathBuf> {
    fs::read_dir(data_dir)
        .ok()?
        .filter_map(|e| e.ok())
        .find(|e| e.file_name().to_string_lossy().ends_with(".sst"))
        .map(|e| e.path())
}

#[test]
fn test_detect_corrupted_sstable() {
    let temp_dir = TempDir::new().unwrap();
    let data_dir = PathBuf::from(temp_dir.path());

    // Write and flush data
    {
        let db = DB::open(&data_dir).unwrap();

        for i in 0..100 {
            db.put(format!("key_{:03}", i).as_bytes(), b"value")
                .unwrap();
        }

        db.flush().unwrap();
    }

    // Corrupt the SSTable file
    let sstable_path = find_sstable(&data_dir).expect("No SSTable found");
    {
        let mut file = OpenOptions::new().write(true).open(&sstable_path).unwrap();

        // Corrupt data at offset 1000
        file.seek(SeekFrom::Start(1000)).unwrap();
        file.write_all(b"CORRUPTED_DATA_HERE").unwrap();
    }

    // Reopen - should detect corruption
    {
        // DB::open may detect corruption immediately (preferred)
        match DB::open(&data_dir) {
            Ok(db) => {
                // If open succeeded, attempt to read - may detect corruption here
                let result = db.get(b"key_050");

                match result {
                    Ok(_) => {
                        // Data read succeeded (corruption not detected yet)
                        // This is acceptable if corrupted block wasn't accessed
                    }
                    Err(_) => {
                        // Corruption detected during read - this is the desired behavior
                    }
                }
            }
            Err(_) => {
                // Corruption detected at open time - this is best!
                // Test passes as corruption was detected
            }
        }
    }
}

#[test]
fn test_sstable_validate_method() {
    // Test SSTable::validate() method for corruption detection
    let temp_dir = TempDir::new().unwrap();
    let data_dir = PathBuf::from(temp_dir.path());

    // Write and flush data
    {
        let db = DB::open(&data_dir).unwrap();

        for i in 0..100 {
            db.put(format!("key_{:03}", i).as_bytes(), &vec![b'v'; 100])
                .unwrap();
        }

        db.flush().unwrap();
    }

    // Test validate() on uncorrupted file
    {
        use seerdb::sstable::SSTable;

        let sstable_path = find_sstable(&data_dir).expect("No SSTable found");
        let mut sstable = SSTable::open(&sstable_path).unwrap();

        // Should succeed for valid SSTable
        let result = sstable.validate();
        assert!(
            result.is_ok(),
            "Validate should succeed for uncorrupted SSTable"
        );
    }

    // Corrupt the file
    let sstable_path = find_sstable(&data_dir).expect("No SSTable found");
    {
        let mut file = OpenOptions::new().write(true).open(&sstable_path).unwrap();

        file.seek(SeekFrom::Start(500)).unwrap();
        file.write_all(b"CORRUPTION").unwrap();
    }

    // Test corruption detection on corrupted file
    {
        use seerdb::sstable::SSTable;

        // Corruption should be detected either during open() or validate()
        // Both are acceptable - fail fast is actually better
        match SSTable::open(&sstable_path) {
            Err(_) => {
                // Corruption detected during open - excellent! (fail fast)
            }
            Ok(mut sstable) => {
                // Opened successfully, corruption should be detected by validate()
                let result = sstable.validate();
                match result {
                    Ok(_) => {
                        // Corruption not detected - this is a problem if checksums are implemented
                        // But acceptable if block checksums aren't fully implemented yet
                    }
                    Err(_) => {
                        // Corruption detected by validate - good!
                    }
                }
            }
        }
    }
}

#[test]
fn test_corrupted_wal_detection() {
    // Test WAL corruption detection during recovery
    let temp_dir = TempDir::new().unwrap();
    let data_dir = PathBuf::from(temp_dir.path());

    // Write data without flushing
    {
        let db = DB::open(&data_dir).unwrap();

        for i in 0..50 {
            db.put(format!("key_{:03}", i).as_bytes(), b"value")
                .unwrap();
        }

        // Don't flush - data only in WAL
    }

    // Corrupt WAL file header (magic number) - this MUST be detected
    let wal_path = data_dir.join("wal.log");
    {
        let mut file = OpenOptions::new().write(true).open(&wal_path).unwrap();

        // Corrupt the magic number at offset 0 (header validation will fail)
        file.seek(SeekFrom::Start(0)).unwrap();
        file.write_all(b"BAAD").unwrap();
    }

    // Reopen - MUST detect WAL corruption since header is invalid
    {
        let result = DB::open(&data_dir);

        // WAL header validation should fail
        assert!(
            result.is_err(),
            "DB::open should fail when WAL header is corrupted"
        );
    }
}

#[test]
fn test_truncated_sstable() {
    let temp_dir = TempDir::new().unwrap();
    let data_dir = PathBuf::from(temp_dir.path());

    // Write and flush data
    {
        let db = DB::open(&data_dir).unwrap();

        for i in 0..100 {
            db.put(format!("key_{:03}", i).as_bytes(), &vec![b'v'; 100])
                .unwrap();
        }

        db.flush().unwrap();
    }

    // Truncate SSTable file (simulate incomplete write)
    let sstable_path = find_sstable(&data_dir).expect("No SSTable found");
    {
        use std::fs;
        let metadata = fs::metadata(&sstable_path).unwrap();
        let original_size = metadata.len();

        let file = OpenOptions::new().write(true).open(&sstable_path).unwrap();

        // Truncate to half size
        file.set_len(original_size / 2).unwrap();
    }

    // Reopen - should detect truncation
    {
        let result = DB::open(&data_dir);

        match result {
            Ok(db) => {
                // Opened despite truncation
                // Try to read data - should fail or return partial data
                let readable_count = (0..100)
                    .filter(|i| match db.get(format!("key_{:03}", i).as_bytes()) {
                        Ok(Some(_)) => true,
                        _ => false,
                    })
                    .count();

                // Should not be able to read all keys from truncated file
                assert!(
                    readable_count < 100,
                    "Should not read all keys from truncated SSTable"
                );
            }
            Err(_) => {
                // Failed to open - acceptable if truncation detected during load
            }
        }
    }
}

#[test]
fn test_missing_footer() {
    let temp_dir = TempDir::new().unwrap();
    let data_dir = PathBuf::from(temp_dir.path());

    // Write and flush data
    {
        let db = DB::open(&data_dir).unwrap();

        db.put(b"key", b"value").unwrap();
        db.flush().unwrap();
    }

    // Truncate footer (last 40 bytes)
    let sstable_path = find_sstable(&data_dir).expect("No SSTable found");
    {
        use std::fs;
        let metadata = fs::metadata(&sstable_path).unwrap();
        let size = metadata.len();

        let file = OpenOptions::new().write(true).open(&sstable_path).unwrap();

        // Remove footer
        file.set_len(size - 40).unwrap();
    }

    // Reopen - should fail to load SSTable
    {
        let result = DB::open(&data_dir);

        // Should fail or skip corrupted SSTable
        match result {
            Ok(_) => {
                // Opened but SSTable should not be loadable
                // This is acceptable if corrupted file is skipped
            }
            Err(_) => {
                // Failed to open - expected if SSTable loading is strict
            }
        }
    }
}

#[test]
fn test_corrupted_block_header() {
    let temp_dir = TempDir::new().unwrap();
    let data_dir = PathBuf::from(temp_dir.path());

    // Write and flush data
    {
        let db = DB::open(&data_dir).unwrap();

        for i in 0..100 {
            db.put(format!("key_{:03}", i).as_bytes(), b"value")
                .unwrap();
        }

        db.flush().unwrap();
    }

    // Corrupt block header (early in file)
    let sstable_path = find_sstable(&data_dir).expect("No SSTable found");
    {
        let mut file = OpenOptions::new().write(true).open(&sstable_path).unwrap();

        // Corrupt header area (after file header)
        file.seek(SeekFrom::Start(50)).unwrap();
        file.write_all(&[0xFF; 20]).unwrap();
    }

    // Try to read - corruption may be detected at open or during reads
    {
        // DB::open may detect corruption immediately (preferred)
        match DB::open(&data_dir) {
            Ok(db) => {
                // If open succeeded, reads may fail
                for i in 0..100 {
                    let _ = db.get(format!("key_{:03}", i).as_bytes());
                    // Corruption may be detected here
                }
            }
            Err(_) => {
                // Corruption detected at open time - this is good!
                // Test passes as corruption was detected
            }
        }
    }
}

#[test]
fn test_wrong_magic_number() {
    let temp_dir = TempDir::new().unwrap();
    let data_dir = PathBuf::from(temp_dir.path());

    // Write and flush data
    {
        let db = DB::open(&data_dir).unwrap();

        db.put(b"key", b"value").unwrap();
        db.flush().unwrap();
    }

    // Corrupt magic number in header
    let sstable_path = find_sstable(&data_dir).expect("No SSTable found");
    {
        let mut file = OpenOptions::new().write(true).open(&sstable_path).unwrap();

        // Overwrite magic number (first 4 bytes)
        file.seek(SeekFrom::Start(0)).unwrap();
        file.write_all(&[0xDE, 0xAD, 0xBE, 0xEF]).unwrap();
    }

    // Reopen - should reject file with wrong magic
    {
        let result = DB::open(&data_dir);

        // Should fail or skip file with wrong magic
        // This should be caught by SSTable::open()
        match result {
            Ok(_) => {
                // May succeed if corrupted file is skipped during load
            }
            Err(_) => {
                // Failed - this is expected behavior
            }
        }
    }
}

// =============================================================================
// RecoveryMode tests
// =============================================================================

#[test]
fn test_recovery_mode_best_effort_skips_corrupted_wal_records() {
    // Test that BestEffort mode recovers valid records before corruption
    let temp_dir = TempDir::new().unwrap();
    let data_dir = PathBuf::from(temp_dir.path());

    // Write data and simulate crash (no graceful shutdown)
    {
        let db = DB::open(&data_dir).unwrap();

        // Write 50 records - these go to WAL
        for i in 0..50 {
            db.put(format!("key_{:03}", i).as_bytes(), b"value")
                .unwrap();
        }
        // Simulate crash: prevent Drop from running (which would flush to SSTable)
        // This leaves data only in WAL for recovery testing
        std::mem::forget(db);
    }

    // Corrupt a record in the middle of the WAL (not the header)
    let wal_path = data_dir.join("wal.log");
    {
        let metadata = fs::metadata(&wal_path).unwrap();
        let file_size = metadata.len();

        let mut file = OpenOptions::new().write(true).open(&wal_path).unwrap();

        // WAL header is 8 bytes, each record has crc(4)+len(4)+data
        // Corrupt around 1/3 into the records (after header)
        // This ensures some records are readable before corruption
        let corrupt_offset = 8 + (file_size - 8) / 3; // 8 = header size
        file.seek(SeekFrom::Start(corrupt_offset)).unwrap();
        file.write_all(b"XXCORRUPTEDXX").unwrap();
    }

    // Reopen with BestEffort - should recover records before corruption
    {
        let result = DBOptions::default()
            .recovery_mode(RecoveryMode::BestEffort)
            .open(&data_dir);

        assert!(
            result.is_ok(),
            "BestEffort mode should open despite WAL corruption"
        );

        let db = result.unwrap();

        // Count how many records were recovered
        let mut recovered = 0;
        for i in 0..50 {
            if db
                .get(format!("key_{:03}", i).as_bytes())
                .unwrap()
                .is_some()
            {
                recovered += 1;
            }
        }

        // Should recover some but not all (corruption prevents reading rest)
        assert!(
            recovered > 0 && recovered < 50,
            "Expected partial recovery, got {} of 50 records",
            recovered
        );
    }
}

#[test]
fn test_recovery_mode_strict_fails_on_corrupted_wal() {
    // Test that Strict mode fails on any WAL corruption
    let temp_dir = TempDir::new().unwrap();
    let data_dir = PathBuf::from(temp_dir.path());

    // Write data and simulate crash (no graceful shutdown)
    {
        let db = DB::open(&data_dir).unwrap();

        for i in 0..50 {
            db.put(format!("key_{:03}", i).as_bytes(), b"value")
                .unwrap();
        }
        // Simulate crash: prevent Drop from running (which would flush to SSTable)
        std::mem::forget(db);
    }

    // Corrupt a record (not the header, but record data)
    let wal_path = data_dir.join("wal.log");
    {
        let metadata = fs::metadata(&wal_path).unwrap();
        let file_size = metadata.len();

        let mut file = OpenOptions::new().write(true).open(&wal_path).unwrap();

        // Corrupt around 1/3 into the records (after header)
        let corrupt_offset = 8 + (file_size - 8) / 3;
        file.seek(SeekFrom::Start(corrupt_offset)).unwrap();
        file.write_all(b"XXCORRUPTEDXX").unwrap();
    }

    // Reopen with Strict mode - should fail on corruption
    {
        let result = DBOptions::default()
            .recovery_mode(RecoveryMode::Strict)
            .open(&data_dir);

        // Should fail on corruption
        match result {
            Ok(_) => panic!("Strict mode should fail when WAL has corruption"),
            Err(err) => {
                // Error should mention WAL corruption
                let err_str = err.to_string().to_lowercase();
                assert!(
                    err_str.contains("wal")
                        || err_str.contains("corruption")
                        || err_str.contains("checksum"),
                    "Error should indicate WAL corruption: {}",
                    err
                );
            }
        }
    }
}

#[test]
fn test_recovery_mode_best_effort_is_default() {
    // Verify that BestEffort is the default recovery mode
    let opts = DBOptions::default();
    assert_eq!(
        opts.recovery_mode,
        RecoveryMode::BestEffort,
        "Default recovery mode should be BestEffort"
    );
}

#[test]
fn test_recovery_mode_strict_succeeds_on_clean_wal() {
    // Test that Strict mode works fine when WAL is not corrupted
    let temp_dir = TempDir::new().unwrap();
    let data_dir = PathBuf::from(temp_dir.path());

    // Write data and simulate crash (no graceful shutdown)
    {
        let db = DB::open(&data_dir).unwrap();

        for i in 0..50 {
            db.put(format!("key_{:03}", i).as_bytes(), b"value")
                .unwrap();
        }
        // Simulate crash: prevent Drop from running (which would flush to SSTable)
        std::mem::forget(db);
    }

    // Reopen with Strict mode - should succeed with clean WAL
    {
        let result = DBOptions::default()
            .recovery_mode(RecoveryMode::Strict)
            .open(&data_dir);

        assert!(result.is_ok(), "Strict mode should succeed on clean WAL");

        let db = result.unwrap();

        // All records should be recovered
        for i in 0..50 {
            let value = db.get(format!("key_{:03}", i).as_bytes()).unwrap();
            assert!(value.is_some(), "Record {} should be recovered", i);
        }
    }
}