win-durable-ioring 0.4.0

A ring for Windows file I/O with durability scheduled into its work: writes are tagged with epochs, and durability through an epoch is requested and reported in the ring's own completion stream. The Windows driver for durable-ioring, built on windows-ioring-sys. No unsafe code.
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
// Copyright (c) 2026 Mike Grier
//! The consumer's durability provider (DI-3.2.6, DI-D-27, DI-D-44), against real files: what a
//! seal asks it, its answers from inside `make_durable` and from another thread, what its failure
//! and its silence are reported as, and what a panic in it does; and the routing provider in that
//! place (DI-12.2.4), composing two providers. Every entry is reported to the conformance oracle.

use std::panic::{self, AssertUnwindSafe};
use std::sync::{Arc, Mutex, mpsc};
use std::time::{Duration, Instant};

use windows_threadpool_sys::wait::ThreadpoolWait;

use super::pushes::{BOUND, GIVEN, Harness, Ring, temp};
use super::{
    FlushDomain, FlushRequest, Keeper, Kept, TargetSetup, TempFile, V, domain, file, keeper, setup,
};
use durable_ioring::DurabilityProvider;
use durable_ioring::DurableRing;
use durable_ioring::RoutingProvider;
use durable_ioring::backend::SubmissionData;
use durable_ioring::{
    DurabilityRequest, Entry, EpochState, Failed, FailureCause, IoTargetKey, OpId, OpKind,
    WriteOptions,
};

/// `ERROR_IO_DEVICE`, the error a failing provider reports.
const IO_DEVICE: i32 = 1117;

/// An instance over `temp`, as `GIVEN` in `domains`, with `provider`.
fn instance(
    temp: &TempFile,
    domains: &[&str],
    provider: Option<Box<dyn DurabilityProvider<V>>>,
) -> Harness {
    Harness::new(
        Ring::new(setup(
            vec![file(GIVEN.0, temp, domains)],
            Vec::new(),
            provider,
        ))
        .expect("build an instance with a provider")
        .0,
    )
}

/// The requests the provider has been handed so far, taken.
fn taken(kept: &Kept) -> Vec<FlushRequest<V>> {
    std::mem::take(&mut *kept.lock().expect("the requests"))
}

/// The only request the provider has been handed.
fn only(kept: &Kept) -> FlushRequest<V> {
    let mut requests = taken(kept);
    assert_eq!(requests.len(), 1, "{requests:?}");
    requests.remove(0)
}

fn succeed(request: FlushRequest<V>) {
    for part in request.domains {
        part.completion.succeed();
    }
}

fn expect_durable(harness: &mut Harness, id: u64) {
    match harness.next_entry() {
        Entry::Durable { through } => assert_eq!(through, harness.epoch(id)),
        other => panic!("expected Durable through {id}, got {other:?}"),
    }
}

fn next_failed(harness: &mut Harness) -> Failed<V> {
    match harness.next_entry() {
        Entry::Failed(failed) => failed,
        other => panic!("expected Failed, got {other:?}"),
    }
}

/// Pop for a while, requiring nothing.
fn nothing_for_a_while(harness: &mut Harness) {
    let started = Instant::now();
    while started.elapsed() < Duration::from_millis(50) {
        assert!(harness.ring.pop().expect("pop").is_none());
        std::thread::sleep(Duration::from_millis(1));
    }
}

/// A provider that answers every domain it is asked about with success, inside `make_durable`.
#[derive(Debug)]
struct Answers(Vec<FlushDomain>);

impl DurabilityProvider<V> for Answers {
    fn domains(&self) -> Vec<FlushDomain> {
        self.0.clone()
    }

    fn make_durable(&mut self, request: FlushRequest<V>) {
        succeed(request);
    }
}

/// A provider that panics when asked anything.
#[derive(Debug)]
struct Panics(Vec<FlushDomain>);

impl DurabilityProvider<V> for Panics {
    fn domains(&self) -> Vec<FlushDomain> {
        self.0.clone()
    }

    fn make_durable(&mut self, _: FlushRequest<V>) {
        panic!("the provider panics");
    }
}

#[test]
fn a_provider_answering_inside_make_durable_makes_the_seal_durable() {
    let temp = temp(&[0; 16]);
    let provider = Answers(vec![domain("log")]);
    let mut harness = instance(&temp, &["log"], Some(Box::new(provider)));
    harness.write(GIVEN, 0, b"log", 1, 1);
    harness.next();
    assert_eq!(harness.seal(1), DurabilityRequest::Submitted);
    expect_durable(&mut harness, 1);
    assert_eq!(harness.state(1), EpochState::Durable);
    harness.finish();
}

#[test]
fn a_request_a_drain_makes_is_made_at_a_pop() {
    // Sealed with its write in flight -- the engine held, so no drain completes the write first --
    // the seal's request is made as the write's completion is drained, off the consumer's thread,
    // and waits for a consumer call (DI-D-44). Here the only calls are pops.
    let temp = temp(&[0; 16]);
    let (provider, kept) = keeper(&["log"]);
    let mut harness = instance(&temp, &["log"], provider);
    let epoch = harness.epoch(1);
    let id = {
        let mut engine = harness.ring.engine();
        let id = engine
            .write(
                GIVEN,
                0,
                SubmissionData::Owned(b"log".to_vec()),
                epoch,
                1,
                WriteOptions::new(),
            )
            .expect("accepted");
        let (answer, _) = engine.make_durable_through(epoch).expect("seal");
        assert_eq!(answer, DurabilityRequest::Submitted);
        id
    };
    harness
        .oracle
        .pushed(id, OpKind::Write { epoch }, 3, 1)
        .expect("the oracle accepts the push");
    harness.oracle.sealed(epoch);
    assert!(
        taken(&kept).is_empty(),
        "the write was in flight at the seal"
    );

    harness.next();
    let started = Instant::now();
    let request = loop {
        if let Some(request) = taken(&kept).pop() {
            break request;
        }
        assert!(started.elapsed() < BOUND, "no pop made the drain's request");
        assert!(harness.ring.pop().expect("pop").is_none());
        std::thread::sleep(Duration::from_millis(1));
    };
    succeed(request);
    expect_durable(&mut harness, 1);
    harness.finish();
}

#[test]
fn a_request_names_each_domain_its_files_and_their_writes() {
    let temps = [temp(&[0; 16]), temp(&[0; 16]), temp(&[0; 16])];
    let files = vec![
        file(2, &temps[0], &["log"]),
        file(3, &temps[1], &["log"]),
        file(4, &temps[2], &["disk"]),
    ];
    let (provider, kept) = keeper(&["log"]);
    let ring = Ring::new(setup(files, Vec::new(), provider))
        .expect("build")
        .0;
    let mut harness = Harness::new(ring);
    let first = harness.write(IoTargetKey(2), 0, b"one", 1, 1);
    let other = harness.write(IoTargetKey(3), 0, b"two", 1, 2);
    let second = harness.write(IoTargetKey(2), 8, b"three", 1, 3);
    harness.write(IoTargetKey(4), 0, b"four", 1, 4);
    harness.next_n(4);
    assert_eq!(harness.seal(1), DurabilityRequest::Submitted);

    let request = only(&kept);
    assert_eq!(request.domains.len(), 1, "disk is the default's");
    let part = &request.domains[0];
    assert_eq!(part.domain.bytes(), b"log");
    let named: Vec<_> = part
        .files
        .iter()
        .map(|f| (f.key, f.writes.clone()))
        .collect();
    assert_eq!(
        named,
        [
            (IoTargetKey(2), vec![first, second]),
            (IoTargetKey(3), vec![other])
        ]
    );
    assert_eq!(harness.state(1), EpochState::Pending);

    succeed(request);
    expect_durable(&mut harness, 1);
    harness.finish();
}

#[test]
fn a_seal_touching_no_served_domain_asks_the_provider_nothing() {
    let temp = temp(&[0; 16]);
    let (provider, kept) = keeper(&["log"]);
    let mut harness = instance(&temp, &["disk"], provider);
    harness.write(GIVEN, 0, b"disk", 1, 1);
    harness.next();
    assert_eq!(harness.seal(1), DurabilityRequest::Submitted);
    expect_durable(&mut harness, 1);
    assert!(taken(&kept).is_empty());
    harness.finish();
}

#[test]
fn an_answer_from_another_thread_sets_the_readiness_signal() {
    let temp = temp(&[0; 16]);
    let (provider, kept) = keeper(&["log"]);
    let mut harness = instance(&temp, &["log"], provider);
    harness.write(GIVEN, 0, b"log", 1, 1);
    harness.next();
    assert_eq!(harness.seal(1), DurabilityRequest::Submitted);
    let request = only(&kept);
    assert!(harness.ring.pop().expect("pop").is_none());

    let signal = harness.ring.readiness().expect("the readiness signal");
    signal.reset().expect("withdraw any stale signal");
    let (woken, wakes) = mpsc::channel();
    let woken = Mutex::new(woken);
    let wait = ThreadpoolWait::new(
        signal.into(),
        move |_| {
            if let Ok(woken) = woken.lock() {
                let _ = woken.send(());
            }
        },
        None,
    )
    .expect("a wait on the signal");
    wait.arm(None);
    std::thread::spawn(move || succeed(request))
        .join()
        .expect("the answering thread");
    let set = wakes.recv_timeout(BOUND);
    wait.stop_and_drain();
    set.expect("the answer made an entry poppable and set the signal");
    expect_durable(&mut harness, 1);
    harness.finish();
}

#[test]
fn a_file_both_answer_for_waits_for_the_provider_after_its_flush() {
    let temp = temp(&[0; 16]);
    let (provider, kept) = keeper(&["log"]);
    let mut harness = instance(&temp, &["log", "disk"], provider);
    harness.write(GIVEN, 0, b"both", 1, 1);
    harness.next();
    assert_eq!(harness.seal(1), DurabilityRequest::Submitted);
    let request = only(&kept);
    nothing_for_a_while(&mut harness);
    assert_eq!(harness.state(1), EpochState::Pending);
    succeed(request);
    expect_durable(&mut harness, 1);
    harness.finish();
}

#[test]
fn a_provider_failure_is_reported_with_its_domain_and_error_and_holds_the_seal() {
    let temp = temp(&[0; 16]);
    let (provider, kept) = keeper(&["log"]);
    let mut harness = instance(&temp, &["log"], provider);
    let write = harness.write(GIVEN, 0, b"log", 1, 1);
    harness.next();
    assert_eq!(harness.seal(1), DurabilityRequest::Submitted);
    let mut request = only(&kept);
    request
        .domains
        .remove(0)
        .completion
        .fail(std::io::Error::from_raw_os_error(IO_DEVICE));

    let failed = next_failed(&mut harness);
    match &failed.cause {
        FailureCause::Provider { domain, error } => {
            assert_eq!(domain.bytes(), b"log");
            assert_eq!(error.raw_os_error(), Some(IO_DEVICE));
        }
        other => panic!("expected a provider failure, got {other:?}"),
    }
    let suspects: Vec<_> = failed.suspect.writes().iter().map(|w| w.op).collect();
    assert_eq!(suspects, [write]);
    assert_eq!(harness.state(1), EpochState::Blocked(failed.id));
    assert!(harness.ring.pop().expect("pop").is_none(), "one answer");
    harness.finish();
}

#[test]
fn a_completion_dropped_unanswered_is_reported_as_abandoned() {
    let temp = temp(&[0; 16]);
    let (provider, kept) = keeper(&["log"]);
    let mut harness = instance(&temp, &["log"], provider);
    harness.write(GIVEN, 0, b"log", 1, 1);
    harness.next();
    assert_eq!(harness.seal(1), DurabilityRequest::Submitted);
    drop(only(&kept));

    let failed = next_failed(&mut harness);
    assert!(
        matches!(&failed.cause, FailureCause::ProviderAbandoned { domain } if domain.bytes() == b"log"),
        "{:?}",
        failed.cause
    );
    assert_eq!(harness.state(1), EpochState::Blocked(failed.id));
    harness.finish();
}

#[test]
fn a_panic_in_the_provider_reaches_the_consumers_call_and_abandons_what_it_dropped() {
    let temp = temp(&[0; 16]);
    let provider = Panics(vec![domain("log")]);
    let mut harness = instance(&temp, &["log"], Some(Box::new(provider)));
    harness.write(GIVEN, 0, b"log", 1, 1);
    harness.next();
    let at = harness.default.at(1);
    let sealing = panic::catch_unwind(AssertUnwindSafe(|| harness.ring.make_durable_through(at)));
    assert!(sealing.is_err(), "the provider's panic propagates");
    harness.oracle.sealed(harness.epoch(1));

    let failed = next_failed(&mut harness);
    assert!(
        matches!(&failed.cause, FailureCause::ProviderAbandoned { domain } if domain.bytes() == b"log"),
        "{:?}",
        failed.cause
    );
    assert_eq!(
        harness.seal(1),
        DurabilityRequest::AlreadySealed(EpochState::Blocked(failed.id)),
        "the instance is still usable"
    );
    harness.finish();
}

// The routing provider as the instance's provider (DI-12.2.4, DI-D-81, DI-D-83): two providers
// composed by a router, the log's and the disk's, each a keeper the test answers for.

const LOG: IoTargetKey = IoTargetKey(2);
const DISK: IoTargetKey = IoTargetKey(3);

/// A keeper serving `domains`, by itself, so a router can register it.
fn kept_by(domains: &[&str]) -> (Keeper, Kept) {
    let kept = Arc::new(Mutex::new(Vec::new()));
    let keeper = Keeper {
        domains: domains.iter().map(|name| domain(name)).collect(),
        kept: Arc::clone(&kept),
    };
    (keeper, kept)
}

/// An instance over `files`, whose provider is a router over a keeper serving `log` and one serving
/// `disk`, in that order; and what each keeps.
fn routed(files: Vec<TargetSetup>) -> (Harness, Kept, Kept) {
    let (log, log_kept) = kept_by(&["log"]);
    let (disk, disk_kept) = kept_by(&["disk"]);
    let router = RoutingProvider::builder()
        .register(log)
        .register(disk)
        .build()
        .expect("no domain twice");
    let ring = Ring::new(setup(files, Vec::new(), Some(Box::new(router))))
        .expect("build an instance with a router")
        .0;
    (Harness::new(ring), log_kept, disk_kept)
}

/// The files `requested` names, each with its writes.
fn named(request: &FlushRequest<V>) -> Vec<(String, IoTargetKey, Vec<OpId>)> {
    request
        .domains
        .iter()
        .flat_map(|part| {
            let name = String::from_utf8_lossy(part.domain.bytes()).into_owned();
            part.files
                .iter()
                .map(move |file| (name.clone(), file.key, file.writes.clone()))
        })
        .collect()
}

#[test]
fn a_seal_touching_both_routed_providers_asks_each_once_for_its_own_domain() {
    let temps = [temp(&[0; 16]), temp(&[0; 16])];
    let (mut harness, log_kept, disk_kept) = routed(vec![
        file(LOG.0, &temps[0], &["log"]),
        file(DISK.0, &temps[1], &["disk"]),
    ]);
    let log_write = harness.write(LOG, 0, b"log", 1, 1);
    let disk_write = harness.write(DISK, 0, b"disk", 1, 2);
    harness.next_n(2);
    assert_eq!(harness.seal(1), DurabilityRequest::Submitted);

    let log = only(&log_kept);
    let disk = only(&disk_kept);
    assert_eq!(named(&log), [("log".to_owned(), LOG, vec![log_write])]);
    assert_eq!(named(&disk), [("disk".to_owned(), DISK, vec![disk_write])]);

    succeed(log);
    nothing_for_a_while(&mut harness);
    assert_eq!(
        harness.state(1),
        EpochState::Pending,
        "the disk has not answered"
    );
    succeed(disk);
    expect_durable(&mut harness, 1);
    harness.finish();
}

#[test]
fn a_file_whose_domains_span_routed_providers_is_durable_only_when_every_one_succeeds() {
    // Its write is in each provider's call: the router merges nothing across providers, so a
    // file whose coupled domains are split between them costs each a flush (DI-2.12 point 1).
    let temp = temp(&[0; 16]);
    let (mut harness, log_kept, disk_kept) = routed(vec![file(GIVEN.0, &temp, &["log", "disk"])]);
    let write = harness.write(GIVEN, 0, b"both", 1, 1);
    harness.next();
    assert_eq!(harness.seal(1), DurabilityRequest::Submitted);

    let log = only(&log_kept);
    let disk = only(&disk_kept);
    assert_eq!(named(&log), [("log".to_owned(), GIVEN, vec![write])]);
    assert_eq!(named(&disk), [("disk".to_owned(), GIVEN, vec![write])]);

    succeed(disk);
    nothing_for_a_while(&mut harness);
    assert_eq!(
        harness.state(1),
        EpochState::Pending,
        "the log has not answered"
    );
    succeed(log);
    expect_durable(&mut harness, 1);
    harness.finish();
}

#[test]
fn one_routed_provider_failing_fails_only_the_files_in_its_domains() {
    let temps = [temp(&[0; 16]), temp(&[0; 16])];
    let (mut harness, log_kept, disk_kept) = routed(vec![
        file(LOG.0, &temps[0], &["log"]),
        file(DISK.0, &temps[1], &["disk"]),
    ]);
    let log_write = harness.write(LOG, 0, b"log", 1, 1);
    harness.write(DISK, 0, b"disk", 1, 2);
    harness.next_n(2);
    assert_eq!(harness.seal(1), DurabilityRequest::Submitted);

    succeed(only(&disk_kept));
    let mut log = only(&log_kept);
    log.domains
        .remove(0)
        .completion
        .fail(std::io::Error::from_raw_os_error(IO_DEVICE));

    let failed = next_failed(&mut harness);
    match &failed.cause {
        FailureCause::Provider { domain, error } => {
            assert_eq!(domain.bytes(), b"log");
            assert_eq!(error.raw_os_error(), Some(IO_DEVICE));
        }
        other => panic!("expected the log provider's failure, got {other:?}"),
    }
    let suspects: Vec<_> = failed.suspect.writes().iter().map(|w| w.op).collect();
    assert_eq!(
        suspects,
        [log_write],
        "the disk's file is not in the log's domain"
    );
    assert_eq!(harness.state(1), EpochState::Blocked(failed.id));
    harness.finish();
}

#[test]
fn a_file_whose_domains_span_routed_providers_fails_when_either_fails() {
    let temp = temp(&[0; 16]);
    let (mut harness, log_kept, disk_kept) = routed(vec![file(GIVEN.0, &temp, &["log", "disk"])]);
    let write = harness.write(GIVEN, 0, b"both", 1, 1);
    harness.next();
    assert_eq!(harness.seal(1), DurabilityRequest::Submitted);

    succeed(only(&log_kept));
    let mut disk = only(&disk_kept);
    disk.domains
        .remove(0)
        .completion
        .fail(std::io::Error::from_raw_os_error(IO_DEVICE));

    let failed = next_failed(&mut harness);
    assert!(
        matches!(&failed.cause, FailureCause::Provider { domain, .. } if domain.bytes() == b"disk"),
        "{:?}",
        failed.cause
    );
    let suspects: Vec<_> = failed.suspect.writes().iter().map(|w| w.op).collect();
    assert_eq!(suspects, [write]);
    assert_eq!(harness.state(1), EpochState::Blocked(failed.id));
    harness.finish();
}

#[test]
fn a_domain_no_routed_provider_serves_is_the_defaults() {
    let temp = temp(&[0; 16]);
    let (mut harness, log_kept, disk_kept) = routed(vec![file(GIVEN.0, &temp, &["other"])]);
    harness.write(GIVEN, 0, b"other", 1, 1);
    harness.next();
    assert_eq!(harness.seal(1), DurabilityRequest::Submitted);
    expect_durable(&mut harness, 1);
    assert!(taken(&log_kept).is_empty());
    assert!(taken(&disk_kept).is_empty());
    harness.finish();
}

#[test]
fn a_panic_in_a_routed_provider_abandons_its_domains_and_those_not_yet_handed_on() {
    let temps = [temp(&[0; 16]), temp(&[0; 16])];
    let (disk, disk_kept) = kept_by(&["disk"]);
    let router = RoutingProvider::builder()
        .register(Panics(vec![domain("log")]))
        .register(disk)
        .build()
        .expect("no domain twice");
    let ring = Ring::new(setup(
        vec![
            file(LOG.0, &temps[0], &["log"]),
            file(DISK.0, &temps[1], &["disk"]),
        ],
        Vec::new(),
        Some(Box::new(router)),
    ))
    .expect("build an instance with a router")
    .0;
    let mut harness = Harness::new(ring);
    harness.write(LOG, 0, b"log", 1, 1);
    harness.write(DISK, 0, b"disk", 1, 2);
    harness.next_n(2);
    let at = harness.default.at(1);
    let sealing = panic::catch_unwind(AssertUnwindSafe(|| harness.ring.make_durable_through(at)));
    assert!(
        sealing.is_err(),
        "the provider's panic propagates through the router"
    );
    harness.oracle.sealed(harness.epoch(1));
    assert!(taken(&disk_kept).is_empty(), "the disk was never called");

    let mut abandoned = Vec::new();
    for _ in 0..2 {
        match next_failed(&mut harness).cause {
            FailureCause::ProviderAbandoned { domain } => abandoned.push(domain),
            other => panic!("expected an abandoned domain, got {other:?}"),
        }
    }
    abandoned.sort_by(|a, b| a.bytes().cmp(b.bytes()));
    assert_eq!(abandoned, [domain("disk"), domain("log")]);
    harness.finish();
}