store-io 0.6.0

Durable storage I/O for Rust databases: evidence-based durability classes, unforgeable receipts, direct I/O, io_uring and IOCP.
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
//! The simple API end to end on the real file system of the machine running
//! the tests (NTFS on Windows, ext4/XFS on Linux).
//!
//! Where the device is refused (a virtual disk with unverifiable durability,
//! or a file system mounted `nobarrier` as on CI runners), the store is opened
//! with the documented labelled override, and the test asserts that every
//! receipt says so. Nothing here weakens the class decision.

#![cfg(any(windows, target_os = "linux", target_os = "macos"))]
// Test setup unwraps (a failure is the test failing) and ignores values a
// given test does not inspect.
#![allow(
    clippy::unwrap_used,
    clippy::expect_used,
    unused_results,
    unused_must_use
)]

use std::ops::ControlFlow;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU32, Ordering};

use store_io::{
    Directory, DurabilityClass, Error, ReceiptLabel, ScanItem, Store, StoreOptions, Trust,
};

struct TempDir(PathBuf);

impl TempDir {
    fn new(tag: &str) -> Self {
        static N: AtomicU32 = AtomicU32::new(0);
        // $STORE_IO_TEST_DIR when set (CI: loop-mounted ext4 and XFS);
        // else $HOME on Linux (/tmp may be tmpfs) and %TEMP% on Windows.
        let base = std::env::var_os("STORE_IO_TEST_DIR")
            .or_else(|| std::env::var_os("HOME").filter(|_| cfg!(target_os = "linux")))
            .map_or_else(std::env::temp_dir, PathBuf::from);
        let d = base.join(format!(
            ".store-io-native-{}-{}-{tag}",
            std::process::id(),
            N.fetch_add(1, Ordering::Relaxed)
        ));
        std::fs::create_dir_all(&d).unwrap();
        Self(d)
    }

    fn path(&self) -> &Path {
        &self.0
    }
}

impl Drop for TempDir {
    fn drop(&mut self) {
        let _cleanup = std::fs::remove_dir_all(&self.0);
    }
}

/// Options for this machine: default trust where the device is accepted,
/// the labelled override where it is refused. Returns whether the override
/// was needed.
fn options_for(dir: &Path) -> (StoreOptions, bool) {
    let probe = store_io::probe(dir).unwrap();
    let refused = !matches!(probe.decision.durable_open, store_io::DurableOpen::Allowed);
    let opts = StoreOptions {
        trust: Trust {
            override_refusal: refused,
            ..Trust::default()
        },
        ..StoreOptions::default()
    };
    (opts, refused)
}

#[test]
fn test_store_round_trip_on_the_real_file_system() {
    let t = TempDir::new("store");
    let (opts, overridden) = options_for(t.path());
    let path = t.path().join("orders");
    let store = Store::create(&path, opts.clone()).unwrap();
    let class = store.report().decision.class;
    // An unsafe store exists only through the explicit, labelled override.
    if class == DurabilityClass::Unsafe {
        assert!(overridden, "an unsafe store opened without the override");
    }

    let wal = store.provision_append_region("wal", 8 << 20).unwrap();
    let (pos, receipt) = wal.append_durable(b"order 1001").unwrap();
    assert_eq!(receipt.class(), class);
    assert_eq!(
        matches!(receipt.label(), ReceiptLabel::Overridden(_)),
        overridden
    );
    let mut batch = wal.batch();
    for i in 0..100u32 {
        batch
            .append(format!("order {}", 2000 + i).as_bytes())
            .unwrap();
    }
    let (bpos, _) = batch.commit().unwrap();
    let big: Vec<u8> = (0..3_000_000u32).map(|i| (i % 251) as u8).collect();
    let (big_pos, _) = wal.append_durable(&big).unwrap();

    let pages = store.provision_page_region("pages", 1 << 20).unwrap();
    let bs = pages.block_size() as usize;
    pages
        .write_durable(pages.pos(0).unwrap(), &vec![7u8; bs])
        .unwrap();
    let manifest = store.provision_slot("manifest").unwrap();
    manifest.commit(b"wal@0").unwrap();
    let mut reservation = store.reserve(2 << 20, 9).unwrap();
    reservation
        .provision_page_region("tenant9", 1 << 20)
        .unwrap();
    drop((reservation, batch, wal, pages, manifest, store));

    // Read-only recovery: scan finds every record; nothing changes.
    let ro = Store::open_readonly(&path).unwrap();
    let wal = ro.append_region("wal").unwrap();
    let mut first = vec![0u8; 10];
    wal.read(pos.offset(), &mut first).unwrap();
    assert_eq!(&first, b"order 1001");
    let mut seen = Vec::new();
    let summary = wal
        .scan(0, |item| {
            if let ScanItem::Data { offset, bytes } = item {
                seen.push((offset, bytes.len()));
            }
            ControlFlow::Continue(())
        })
        .unwrap();
    assert_eq!(summary.unreadable, 0);
    assert_eq!(summary.end, wal.len());
    let mut back = vec![0u8; big.len()];
    wal.read(big_pos.offset(), &mut back).unwrap();
    assert!(back == big, "large append round trip");
    let mut rec = vec![0u8; 10];
    wal.read(bpos.offset(), &mut rec).unwrap();
    assert_eq!(&rec, b"order 2000");
    assert!(matches!(wal.append(b"x"), Err(Error::NotWritten { .. })));
    drop((wal, ro));

    // Writable reopen: positions resume where the caller says.
    let store = Store::open_with(&path, opts).unwrap();
    assert_eq!(store.slot("manifest").unwrap().read().unwrap(), b"wal@0");
    let wal = store.append_region("wal").unwrap();
    assert!(matches!(wal.append(b"x"), Err(Error::NotWritten { .. })));
    let end = big_pos.offset() + big.len() as u64;
    wal.resume_at(end).unwrap();
    let (next, _) = wal.append_durable(b"after reopen").unwrap();
    assert!(next.offset() >= end);
    assert!(
        store
            .space()
            .tags
            .iter()
            .any(|t| t.tag == 9 && t.physical > 0)
    );
    // A second writable open of the same store is refused.
    assert!(matches!(Store::open(&path), Err(Error::Locked)));
}

#[test]
fn test_directory_replace_on_the_real_file_system() {
    let t = TempDir::new("dir");
    let (opts, _) = options_for(t.path());
    let dir = Directory::open_with(t.path().join("meta"), true, opts.trust).unwrap();
    for (i, len) in [0usize, 15, 4096, 10_000].into_iter().enumerate() {
        let data: Vec<u8> = (0..len).map(|j| (i + j) as u8).collect();
        dir.replace("CURRENT", &data).unwrap();
        assert_eq!(dir.read("CURRENT").unwrap(), data);
        // Ordinary tools see the exact bytes too.
        assert_eq!(
            std::fs::read(t.path().join("meta").join("CURRENT")).unwrap(),
            data
        );
    }
    dir.remove("CURRENT").unwrap();
    assert!(matches!(dir.read("CURRENT"), Err(Error::NotFound { .. })));
    assert!(dir.class().is_some());
}

/// Releasing a region on the real file system gives its space back without
/// touching anything else: the regions on either side, the slots and the
/// table read back exactly, before and after a reopen, and a region
/// provisioned into the freed space works. On Windows the release trims in
/// place, so the container keeps its length and never becomes sparse (a
/// sparse file may allocate on overwrite, which would cost the store its
/// class).
#[test]
fn test_releasing_a_region_leaves_its_neighbours_and_the_metadata_intact() {
    let t = TempDir::new("release");
    let (opts, _overridden) = options_for(t.path());
    let path = t.path().join("columns");
    let store = Store::create(&path, opts.clone()).unwrap();
    let fill =
        |tag: u8, len: usize| -> Vec<u8> { (0..len).map(|i| tag ^ (i % 253) as u8).collect() };
    let size = 1u64 << 20;
    let names = ["left", "middle", "right"];
    for (i, name) in names.iter().enumerate() {
        let r = store.provision_page_region(name, size).unwrap();
        r.write_durable(r.pos(0).unwrap(), &fill(i as u8 + 1, size as usize))
            .unwrap();
    }
    let manifest = store.provision_slot("manifest").unwrap();
    manifest.commit(b"left,middle,right").unwrap();
    let container = path.join(store_io::CONTAINER);
    let len_before = std::fs::metadata(&container).unwrap().len();

    store.page_region("middle").unwrap().release().unwrap();

    let check = |s: &Store| {
        for (i, name) in names.iter().enumerate().filter(|(_, n)| **n != "middle") {
            let r = s.page_region(name).unwrap();
            let mut back = vec![0u8; size as usize];
            r.read(r.pos(0).unwrap(), &mut back).unwrap();
            assert!(back == fill(i as u8 + 1, size as usize), "{name} changed");
        }
        assert!(matches!(
            s.page_region("middle"),
            Err(Error::NotFound { .. })
        ));
        assert_eq!(
            s.slot("manifest").unwrap().read().unwrap(),
            b"left,middle,right"
        );
        assert!(s.unavailable_regions().is_empty());
    };
    check(&store);
    assert_eq!(std::fs::metadata(&container).unwrap().len(), len_before);
    #[cfg(windows)]
    {
        use std::os::windows::fs::MetadataExt;
        const FILE_ATTRIBUTE_SPARSE_FILE: u32 = 0x200;
        let attrs = std::fs::metadata(&container).unwrap().file_attributes();
        assert_eq!(
            attrs & FILE_ATTRIBUTE_SPARSE_FILE,
            0,
            "the container became sparse"
        );
    }
    drop((manifest, store));

    let store = Store::open_with(&path, opts).unwrap();
    check(&store);
    // The freed space is reused and reads back what was written.
    let again = store.provision_page_region("again", size).unwrap();
    let data = fill(9, size as usize);
    again.write_durable(again.pos(0).unwrap(), &data).unwrap();
    let mut back = vec![0u8; size as usize];
    again.read(again.pos(0).unwrap(), &mut back).unwrap();
    assert!(back == data, "the reused space did not read back");
    check(&store);
}

/// D-092: a read-only open works on a container the process may not write
/// (a read-only file, as on a read-only mount or a backup copy), and two
/// readers open it at once.
#[test]
fn test_a_write_protected_store_opens_read_only_for_two_readers() {
    let t = TempDir::new("ro");
    let (opts, _overridden) = options_for(t.path());
    let path = t.path().join("backup");
    let store = Store::create(&path, opts).unwrap();
    let wal = store.provision_append_region("wal", 1 << 20).unwrap();
    let (pos, _) = wal.append_durable(b"kept in the backup").unwrap();
    drop((wal, store));

    let container = path.join(store_io::CONTAINER);
    let set_read_only = |on: bool| {
        let mut perms = std::fs::metadata(&container).unwrap().permissions();
        #[allow(clippy::permissions_set_readonly_false)]
        perms.set_readonly(on);
        std::fs::set_permissions(&container, perms).unwrap();
    };
    set_read_only(true);
    let first = Store::open_readonly(&path);
    let second = Store::open_readonly(&path);
    // Writable opens need write rights (unless the tests run as root).
    let writable = Store::open(&path);
    set_read_only(false);
    let (first, second) = (first.unwrap(), second.unwrap());
    for s in [&first, &second] {
        let mut out = vec![0u8; 18];
        s.append_region("wal")
            .unwrap()
            .read(pos.offset(), &mut out)
            .unwrap();
        assert_eq!(out, b"kept in the backup");
    }
    if cfg!(windows) {
        assert!(writable.is_err(), "a writable open of a read-only file");
    }
}

/// The platform's coarse clock (`GetTickCount64`, `CLOCK_MONOTONIC_COARSE`)
/// advances with real time: `oldest_outstanding` ages depend on it.
#[test]
fn test_the_coarse_clock_advances_with_real_time() {
    use store_io_platform::Platform;
    let p = store_io::NativePlatform::new();
    let t0 = p.monotonic_ms();
    std::thread::sleep(std::time::Duration::from_millis(250));
    let t1 = p.monotonic_ms();
    // Coarse resolution is at most 16 ms; allow a generous margin.
    let moved = t1.wrapping_sub(t0);
    assert!(
        t1 >= t0 + 200,
        "the clock advanced only {moved} ms in 250 ms"
    );
    assert!(moved < 10_000, "the clock jumped {moved} ms in 250 ms");
}

/// Page batches of several writes and reads larger than one buffer run on
/// the parallel lanes (D-096): on the Linux synchronous tier through the
/// submit pool, on io_uring and on Windows (IOCP) in the kernel. Every byte
/// comes back as written, one-page batches stay on the caller's thread, and
/// the pool is reported where there is one.
#[test]
fn test_parallel_page_batches_and_large_reads_round_trip() {
    let t = TempDir::new("parallel");
    let (opts, _) = options_for(t.path());
    // A store opened through the simple API has a platform, and so a pool,
    // of its own: its size is this store's choice.
    let opts = StoreOptions {
        t3_pool_threads: 3,
        ..opts
    };
    let store = Store::create(t.path().join("pages"), opts).unwrap();
    let pages = store.provision_page_region("pages", 16 << 20).unwrap();
    let bs = pages.block_size() as usize;
    let page = |round: u8, i: usize| -> Vec<u8> {
        (0..bs)
            .map(|k| (k as u8) ^ (i as u8).wrapping_mul(31) ^ round)
            .collect()
    };
    // 48 blocks spread over the first 8 MiB (a batch stages each write in a
    // pool buffer: 64 per size class by default).
    let stride = (8 << 20) / 48 / bs * bs;
    let mut one = pages.batch();
    one.write(pages.pos(0).unwrap(), &page(0, 0)).unwrap();
    one.commit().unwrap();
    assert_eq!(
        store.submit_pool_threads(),
        None,
        "a one-write batch started the pool"
    );
    for round in 1..=3u8 {
        let mut batch = pages.batch();
        // Staged in reverse order: the batch sorts them.
        for i in (0..48).rev() {
            batch
                .write(pages.pos((i * stride) as u64).unwrap(), &page(round, i))
                .unwrap();
        }
        batch.commit().unwrap();
        let mut back = vec![0u8; 8 << 20];
        assert_eq!(
            pages.read(pages.pos(0).unwrap(), &mut back).unwrap(),
            back.len()
        );
        for i in 0..48 {
            let at = i * stride;
            assert!(
                back[at..at + bs] == page(round, i),
                "round {round}: block {i} differs"
            );
        }
    }
    // Only the Linux synchronous tier runs operations on a pool; io_uring
    // runs them in the kernel.
    if store.report().io.interface == store_io::IoInterface::Synchronous {
        assert_eq!(store.submit_pool_threads(), Some(3));
    } else {
        assert_eq!(store.submit_pool_threads(), None);
    }
    assert_eq!(store.oldest_outstanding(), None);
}

/// The engine-layer submitter end to end on the real file system (D-098):
/// its operations run on the submit pool on Linux and on IOCP on Windows.
/// Appends and page writes complete in any order, land exactly where
/// submission said, every ticket syncs, and reads through the submitter
/// return every byte.
#[test]
fn test_submitter_round_trips_on_the_real_file_system() {
    use store_io::submit::{Done, SubmitterConfig};
    let full = |e: &Error| {
        matches!(
            e,
            Error::NotWritten {
                cause: store_io::NotWrittenCause::QueueFull,
                ..
            }
        )
    };
    let t = TempDir::new("submitter");
    let (opts, _) = options_for(t.path());
    let store = Store::create(t.path().join("sub"), opts).unwrap();
    let wal = store.provision_append_region("wal", 16 << 20).unwrap();
    let pages = store.provision_page_region("pages", 16 << 20).unwrap();
    let bs = pages.block_size() as usize;
    let record = |i: u64, len: usize| -> Vec<u8> {
        (0..len)
            .map(|k| (k as u8).wrapping_mul(13) ^ (i as u8).wrapping_mul(29) ^ 0xA5)
            .collect()
    };
    let mut sub = store
        .submitter(SubmitterConfig::default().with_depth(32))
        .unwrap();
    let mut placed = Vec::new();
    let mut done = Vec::new();
    for i in 0..64u64 {
        let len = 1 + (i as usize * 1531) % (3 * bs);
        let mut buf = sub.take_buf(len).unwrap();
        buf.as_mut_slice().copy_from_slice(&record(i, len));
        let at = loop {
            match sub.append(&wal, buf, store_io::submit::WriteMode::Plain, i) {
                Ok(pos) => break pos.offset(),
                Err(r) => {
                    assert!(full(&r.error), "{:?}", r.error);
                    buf = r.buf.unwrap();
                    done.extend(sub.wait(1).unwrap());
                }
            }
        };
        placed.push((at, len));
        let mut page = sub.take_buf(bs).unwrap();
        page.as_mut_slice().copy_from_slice(&record(1000 + i, bs));
        let pos = pages.pos(i * 3 * bs as u64).unwrap();
        while let Err(r) = sub.write(
            &pages,
            pos,
            page,
            store_io::submit::WriteMode::Plain,
            1000 + i,
        ) {
            assert!(full(&r.error), "{:?}", r.error);
            page = r.buf.unwrap();
            done.extend(sub.wait(1).unwrap());
        }
    }
    while sub.in_flight() > 0 {
        done.extend(sub.wait(sub.in_flight()).unwrap());
    }
    done.extend(sub.reap());
    assert_eq!(done.len(), 128);
    let mut last = None;
    for c in done {
        let Ok(Done::Written(w)) = c.outcome else {
            panic!("operation {} failed: {:?}", c.tag, c.outcome);
        };
        if c.tag >= 1000 {
            assert_eq!(w.ticket.pos().offset(), (c.tag - 1000) * 3 * bs as u64);
            pages.sync_through(&w.ticket).unwrap();
        } else {
            assert_eq!(w.ticket.pos().offset(), placed[c.tag as usize].0);
            if c.tag == 63 {
                last = Some(w.ticket);
            }
        }
    }
    wal.sync_through(&last.unwrap()).unwrap();
    for (i, &(at, len)) in placed.iter().enumerate() {
        let buf = sub.take_buf(len.div_ceil(bs) * bs).unwrap();
        sub.read_append(&wal, at, buf, i as u64).unwrap();
        let buf = sub.take_buf(bs).unwrap();
        let pos = pages.pos(i as u64 * 3 * bs as u64).unwrap();
        sub.read_page(&pages, pos, buf, 1000 + i as u64).unwrap();
        for c in sub.wait(2).unwrap() {
            let Ok(Done::Read { len: n }) = c.outcome else {
                panic!("read {} failed: {:?}", c.tag, c.outcome);
            };
            let got = c.buf.unwrap();
            if c.tag >= 1000 {
                assert_eq!(n, bs);
                assert!(got.as_slice() == record(c.tag, bs), "page {i} differs");
            } else {
                assert!(
                    got.as_slice()[..len] == record(i as u64, len),
                    "append {i} differs"
                );
                assert!(got.as_slice()[len..].iter().all(|&b| b == 0));
            }
        }
    }
    assert_eq!(sub.in_flight(), 0);
    drop(sub);
    assert_eq!(store.oldest_outstanding(), None);
}

/// Durable submitter writes and barriers on the real file system: the flush
/// thread's wake reaches a submitter blocked in its queue (IOCP on Windows,
/// the submit pool on Linux), and every receipt covers its write.
#[test]
fn test_durable_submitter_writes_on_the_real_file_system() {
    use store_io::submit::{Done, SubmitterConfig, WriteMode};
    let t = TempDir::new("durable");
    let (opts, _) = options_for(t.path());
    let store = Store::create(t.path().join("d"), opts).unwrap();
    let wal = store.provision_append_region("wal", 8 << 20).unwrap();
    let pages = store.provision_page_region("pages", 8 << 20).unwrap();
    let bs = pages.block_size() as usize;
    let mut sub = store
        .submitter(SubmitterConfig::default().with_depth(128))
        .unwrap();
    let mut done = Vec::new();
    for i in 0..32u64 {
        let mut buf = sub.take_buf(300 + i as usize).unwrap();
        buf.as_mut_slice().fill(i as u8);
        sub.append(&wal, buf, WriteMode::Durable, i).unwrap();
        // Reads in flight alongside, so waits block in the queue.
        let buf = sub.take_buf(bs).unwrap();
        sub.read_page(&pages, pages.pos(0).unwrap(), buf, 1000 + i)
            .unwrap();
    }
    sub.barrier_all(5000).unwrap();
    while sub.in_flight() > 0 {
        done.extend(sub.wait(1).unwrap());
    }
    done.extend(sub.reap());
    assert_eq!(done.len(), 65);
    for c in done {
        match (c.tag, c.outcome) {
            (5000, Ok(Done::Flushed)) => {}
            (t, Ok(Done::Read { .. })) if t >= 1000 => {}
            (t, Ok(Done::Written(w))) if t < 32 => {
                assert!(w.receipt.unwrap().covers(&w.ticket), "write {t}");
            }
            (t, other) => panic!("operation {t}: {other:?}"),
        }
    }
    drop(sub);
    assert_eq!(store.oldest_outstanding(), None);
}

/// A 4 MiB durable append from one buffer on the real file system: one OS
/// write (D-101), read back byte for byte.
#[test]
fn test_a_4_mib_submitter_append_on_the_real_file_system() {
    use store_io::submit::{Done, SubmitterConfig, WriteMode};
    let t = TempDir::new("large");
    let (opts, _) = options_for(t.path());
    let store = Store::create(t.path().join("l"), opts).unwrap();
    let wal = store.provision_append_region("wal", 16 << 20).unwrap();
    let mut sub = store.submitter(SubmitterConfig::default()).unwrap();
    let len = sub.max_buf();
    assert_eq!(len, 4 << 20);
    let bytes: Vec<u8> = (0..len).map(|k| (k as u8) ^ (k >> 13) as u8).collect();
    let mut buf = sub.take_buf(len).unwrap();
    buf.as_mut_slice().copy_from_slice(&bytes);
    let at = sub
        .append(&wal, buf, WriteMode::Durable, 1)
        .unwrap()
        .offset();
    let c = sub.wait(1).unwrap().next().unwrap();
    let Ok(Done::Written(w)) = c.outcome else {
        panic!("{:?}", c.outcome)
    };
    assert!(w.receipt.unwrap().covers(&w.ticket));
    let buf = sub.take_buf(len).unwrap();
    sub.read_append(&wal, at, buf, 2).unwrap();
    let c = sub.wait(1).unwrap().next().unwrap();
    assert!(
        c.buf.unwrap().as_slice() == bytes,
        "4 MiB read back differs"
    );
}

/// The store reports the kernel interface its I/O uses and why (D-082).
/// On Linux, `Auto` takes io_uring exactly when an explicit `Uring` choice
/// is accepted, `Sync` is always honoured, and a store written on one tier
/// reads back on the other.
#[test]
fn test_the_io_tier_is_chosen_and_reported() {
    use store_io::{IoInterface, LinuxTier, Op};
    let t = TempDir::new("tier");
    let (opts, _) = options_for(t.path());
    // Two lanes: on io_uring each ring holds two descriptors (a store's
    // parallel lanes and submitters; its lone-operation lanes are inline,
    // D-104), and tests running beside this one could otherwise exhaust the
    // process's limit and make `Auto` fall back (correctly, but not what is
    // checked here).
    let at = |tier| StoreOptions {
        linux_tier: tier,
        queues: 2,
        ..opts.clone()
    };
    let path = t.path().join("tiers");
    let store = Store::create(&path, at(LinuxTier::Sync)).unwrap();
    let io = store.report().io.clone();
    let line = format!("io               {} ({})", io.interface, io.reason);
    assert!(store.report().to_string().contains(&line));
    let wal = store.provision_append_region("wal", 1 << 20).unwrap();
    let ticket = wal.append(b"written on one tier").unwrap();
    wal.sync_through(&ticket).unwrap();
    drop((wal, store));
    if cfg!(windows) {
        assert_eq!(io.interface, IoInterface::Iocp);
        return;
    }
    // macOS has one path, whatever the tier asks.
    if cfg!(target_os = "macos") {
        assert_eq!(io.interface, IoInterface::Synchronous);
        return;
    }
    assert_eq!(
        (io.interface, io.reason.as_str()),
        (IoInterface::Synchronous, "chosen")
    );
    let auto = Store::open_with(&path, at(LinuxTier::Auto)).unwrap();
    // A submitter's queue is a ring on the io_uring tier: the live path then
    // counts it (the report is as of the open, before any ring exists).
    let sub = auto
        .submitter(store_io::submit::SubmitterConfig::default())
        .unwrap();
    let auto_io = auto.io_path();
    drop(sub);
    let wal = auto.append_region("wal").unwrap();
    let mut back = vec![0u8; 19];
    wal.read(ticket.pos().offset(), &mut back).unwrap();
    assert_eq!(back, b"written on one tier");
    drop((wal, auto));
    let ro = Store::open_readonly_with(&path, at(LinuxTier::Sync)).unwrap();
    assert_eq!(ro.report().io.interface, IoInterface::Synchronous);
    drop(ro);
    match Store::open_with(&path, at(LinuxTier::Uring)) {
        Ok(s) => {
            assert_eq!(s.report().io.interface, IoInterface::IoUring);
            assert_eq!(auto_io.interface, IoInterface::IoUring);
            assert!(auto_io.reason.starts_with("auto"), "{auto_io:?}");
            assert!(!auto_io.reason.contains("synchronous"), "{auto_io:?}");
        }
        Err(Error::Io { op: Op::Queue, .. }) => {
            assert!(
                std::env::var_os("STORE_IO_EXPECT_URING").is_none(),
                "io_uring refused where STORE_IO_EXPECT_URING says it works"
            );
            assert_eq!(auto_io.interface, IoInterface::Synchronous);
            assert!(auto_io.reason.contains("io_uring refused"), "{auto_io:?}");
        }
        Err(e) => panic!("{e}"),
    }
}

/// A store with `register_file` (D-078, Linux io_uring): a submitter's
/// writes and reads round-trip, and the live path says what its ring
/// registered; with it off, the same round trip registers nothing.
#[cfg(target_os = "linux")]
#[test]
fn test_a_registered_file_round_trips_and_is_reported() {
    use store_io::LinuxTier;
    use store_io::submit::{Done, SubmitterConfig, WriteMode};
    let t = TempDir::new("registered");
    let (opts, _) = options_for(t.path());
    for on in [true, false] {
        let opts = StoreOptions {
            linux_tier: LinuxTier::Uring,
            register_file: on,
            ..opts.clone()
        };
        let store = match Store::create(t.path().join(format!("s-{on}")), opts) {
            Ok(s) => s,
            Err(e) => {
                assert!(
                    std::env::var_os("STORE_IO_EXPECT_URING").is_none(),
                    "io_uring refused ({e}) where STORE_IO_EXPECT_URING says it works"
                );
                return;
            }
        };
        let pages = store.provision_page_region("p", 1 << 20).unwrap();
        let mut sub = store
            .submitter(SubmitterConfig::default().with_depth(4))
            .unwrap();
        let path = store.io_path();
        if on {
            assert!(
                path.reason.contains("asked on 1 ring(s)")
                    && path.reason.contains("a direct descriptor on 1"),
                "{path:?}"
            );
        } else {
            assert!(!path.reason.contains("registration"), "{path:?}");
        }
        let mut buf = sub.take_buf(4096).unwrap();
        buf.as_mut_slice().fill(0x6B);
        sub.write(&pages, pages.pos(8192).unwrap(), buf, WriteMode::Plain, 1)
            .map_err(|r| r.error)
            .unwrap();
        for c in sub.wait(1).unwrap() {
            assert!(matches!(c.outcome, Ok(Done::Written(_))));
        }
        let buf = sub.take_buf(4096).unwrap();
        sub.read_page(&pages, pages.pos(8192).unwrap(), buf, 2)
            .map_err(|r| r.error)
            .unwrap();
        let c = sub.wait(1).unwrap().next().unwrap();
        assert!(matches!(c.outcome, Ok(Done::Read { len: 4096 })));
        assert!(c.buf.unwrap().as_slice().iter().all(|&b| b == 0x6B));
        let mut out = vec![0u8; 4096];
        pages.read(pages.pos(8192).unwrap(), &mut out).unwrap();
        assert!(
            out.iter().all(|&b| b == 0x6B),
            "the blocking read disagrees ({on})"
        );
    }
}

/// Flushes in flight on the real file system (D-124): eight writers append
/// durably with four flushes allowed; every receipt covers its append and
/// every append reads back after a reopen. Linux (4.16 and later) runs the
/// four when the store needs flushes; Windows, which cannot yet be shown to
/// keep flush failures per handle, runs one.
#[test]
fn test_flushes_in_flight_on_the_real_file_system() {
    let t = TempDir::new("flushes");
    let (mut opts, _) = options_for(t.path());
    opts.flushes_in_flight = 4;
    let store = Store::create(t.path().join("f"), opts.clone()).unwrap();
    let ran = store.report().flushes_in_flight;
    if cfg!(windows) {
        assert_eq!(ran, 1);
    } else {
        assert!(ran == 1 || ran == 4, "{ran}");
    }
    let wal = store.provision_append_region("wal", 8 << 20).unwrap();
    let acked = std::sync::Mutex::new(Vec::new());
    std::thread::scope(|scope| {
        for w in 0..8u8 {
            let (wal, acked) = (&wal, &acked);
            scope.spawn(move || {
                for i in 0..50u8 {
                    let data = vec![w.wrapping_mul(31).wrapping_add(i); 700];
                    let (pos, receipt) = wal.append_durable(&data).unwrap();
                    assert!(receipt.durable_through() >= pos.offset() + data.len() as u64);
                    acked.lock().unwrap().push((pos.offset(), data));
                }
            });
        }
    });
    // Linux 4.16 and later keep flush failures per handle.
    let per_handle = std::fs::read_to_string("/proc/sys/kernel/osrelease").is_ok_and(|r| {
        let mut v = r
            .trim()
            .split(|c: char| !c.is_ascii_digit())
            .map(|x| x.parse::<u32>().unwrap_or(0));
        (v.next().unwrap_or(0), v.next().unwrap_or(0)) >= (4, 16)
    });
    if store.domain_stats().flushes > 0 && per_handle {
        assert_eq!(
            ran, 4,
            "flushes were needed and the kernel keeps errors per handle"
        );
    }
    drop((wal, store));
    let store = Store::open_with(t.path().join("f"), opts).unwrap();
    let wal = store.append_region("wal").unwrap();
    for (at, data) in acked.into_inner().unwrap() {
        let mut out = vec![0u8; data.len()];
        assert_eq!(wal.read(at, &mut out).unwrap(), data.len());
        assert!(out == data, "append at {at}");
    }
}

/// Concurrent probes of one directory each use a file of their own: none
/// removes or reuses another's.
#[test]
fn test_concurrent_probes_of_one_directory() {
    let t = TempDir::new("probes");
    std::thread::scope(|scope| {
        for _ in 0..4 {
            let dir = t.path();
            scope.spawn(move || {
                for _ in 0..8 {
                    store_io::probe(dir).unwrap();
                }
            });
        }
    });
}

/// A directory's replace takes the real lock on the real file system: held
/// by another handle (another process would hold it the same way), the
/// replace fails `Locked` and leaves the object as it was.
#[test]
fn test_a_directory_replace_takes_the_lock_on_the_real_file_system() {
    use store_io_platform::{FileMode, FileName, Platform};
    let t = TempDir::new("dirlock");
    let (opts, _) = options_for(t.path());
    let d = Directory::open_with(t.path(), true, opts.trust).unwrap();
    d.replace("m", b"old").unwrap();
    let p = store_io::NativePlatform::new();
    let dir = p.open_dir(t.path(), false).unwrap();
    let lock_file = p
        .open_file(
            &dir,
            &FileName::new(".sio-lock").unwrap(),
            FileMode::ReadWrite,
        )
        .unwrap();
    let held = p.lock_exclusive(&lock_file).unwrap();
    let r = d.replace("m", b"new");
    assert!(matches!(r, Err(Error::Locked)), "{r:?}");
    assert_eq!(d.read("m").unwrap(), b"old");
    drop(held);
    d.replace("m", b"new").unwrap();
    assert_eq!(d.read("m").unwrap(), b"new");
}

/// A directory's largest object is set through the facade's handle too
/// (independent review F-5): its default, and a smaller limit refusing a
/// larger replace and leaving the object as it was.
#[test]
fn test_a_directory_s_largest_object_is_set_through_the_facade() {
    let t = TempDir::new("dirmax");
    let (opts, _) = options_for(t.path());
    assert_eq!(Directory::DEFAULT_MAX_OBJECT, 16 << 20);
    let d = Directory::open_with(t.path(), true, opts.trust)
        .unwrap()
        .with_max_object(4096);
    assert_eq!(d.max_object(), 4096);
    d.replace("m", &[1u8; 4096]).unwrap();
    let r = d.replace("m", &[2u8; 4097]);
    assert!(
        matches!(
            r,
            Err(Error::NotWritten {
                cause: store_io_core::error::NotWrittenCause::TooLarge,
                ..
            })
        ),
        "{r:?}"
    );
    assert_eq!(d.read("m").unwrap(), vec![1u8; 4096]);
}