Coverage Report

Created: 2026-02-14 06:35

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/wasefire-store-0.2.4/src/driver.rs
Line
Count
Source
1
// Copyright 2019 Google LLC
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//      http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
//! Store wrapper for testing.
16
//!
17
//! [`StoreDriver`] wraps a [`Store`] and compares its behavior with its associated [`StoreModel`].
18
19
use crate::format::{Format, Position};
20
#[cfg(feature = "std")]
21
use crate::StoreUpdate;
22
use crate::{
23
    BufferCorruptFunction, BufferOptions, BufferStorage, Nat, Store, StoreError, StoreHandle,
24
    StoreModel, StoreOperation, StoreResult,
25
};
26
27
/// Tracks the store behavior against its model and its storage.
28
#[derive(Clone)]
29
pub enum StoreDriver {
30
    /// When the store is running.
31
    On(StoreDriverOn),
32
33
    /// When the store is off.
34
    Off(StoreDriverOff),
35
}
36
37
/// Keeps a power-on store and its model in sync.
38
#[derive(Clone)]
39
pub struct StoreDriverOn {
40
    /// The store being tracked.
41
    store: Store<BufferStorage>,
42
43
    /// The model associated to the store.
44
    model: StoreModel,
45
}
46
47
/// Keeps a power-off store and its potential models in sync.
48
#[derive(Clone)]
49
pub struct StoreDriverOff {
50
    /// The storage of the store being tracked.
51
    storage: BufferStorage,
52
53
    /// The last valid model before power off.
54
    model: StoreModel,
55
56
    /// In case of interrupted operation, the invariant after completion.
57
    complete: Option<Complete>,
58
}
59
60
/// The invariant a store must satisfy if an interrupted operation completes.
61
#[derive(Clone)]
62
struct Complete {
63
    /// The model after the operation completes.
64
    model: StoreModel,
65
66
    /// The entries that should be deleted after the operation completes.
67
    deleted: Vec<StoreHandle>,
68
}
69
70
/// Specifies an interruption.
71
pub struct StoreInterruption<'a> {
72
    /// After how many storage operations the interruption should happen.
73
    pub delay: usize,
74
75
    /// How the interrupted operation should be corrupted.
76
    pub corrupt: BufferCorruptFunction<'a>,
77
}
78
79
/// Possible ways a driver operation may fail.
80
#[derive(Debug)]
81
pub enum StoreInvariant {
82
    /// The store reached its lifetime.
83
    ///
84
    /// This is not simulated by the model. So the operation should be ignored.
85
    NoLifetime,
86
87
    /// The store returned an unexpected error.
88
    StoreError(StoreError),
89
90
    /// The store did not recover an interrupted operation.
91
    Interrupted {
92
        /// The reason why the store didn't rollback the operation.
93
        rollback: Box<StoreInvariant>,
94
95
        /// The reason why the store didn't complete the operation.
96
        complete: Box<StoreInvariant>,
97
    },
98
99
    /// The store returned a different result than the model.
100
    DifferentResult {
101
        /// The result of the store.
102
        store: StoreResult<()>,
103
104
        /// The result of the model.
105
        model: StoreResult<()>,
106
    },
107
108
    /// The store did not wipe an entry.
109
    NotWiped {
110
        /// The key of the entry that has not been wiped.
111
        key: usize,
112
113
        /// The value of the entry in the storage.
114
        value: Vec<u8>,
115
    },
116
117
    /// The store has an entry not present in the model.
118
    OnlyInStore {
119
        /// The key of the additional entry.
120
        key: usize,
121
    },
122
123
    /// The store has a different value than the model for an entry.
124
    DifferentValue {
125
        /// The key of the entry with a different value.
126
        key: usize,
127
128
        /// The value of the entry in the store.
129
        store: Box<[u8]>,
130
131
        /// The value of the entry in the model.
132
        model: Box<[u8]>,
133
    },
134
135
    /// The store is missing an entry from the model.
136
    OnlyInModel {
137
        /// The key of the missing entry.
138
        key: usize,
139
    },
140
141
    /// The store reports a different capacity than the model.
142
    DifferentCapacity {
143
        /// The capacity according to the store.
144
        store: usize,
145
146
        /// The capacity according to the model.
147
        model: usize,
148
    },
149
150
    /// The store failed to track the number of erase cycles correctly.
151
    DifferentErase {
152
        /// The first page in physical storage order with a wrong value.
153
        page: usize,
154
155
        /// How many times the page has been erased according to the store.
156
        store: usize,
157
158
        /// How many times the page has been erased according to the model.
159
        model: usize,
160
    },
161
162
    /// The store failed to track the number of word writes correctly.
163
    DifferentWrite {
164
        /// The first page in physical storage order with a wrong value.
165
        page: usize,
166
167
        /// The first word in the page with a wrong value.
168
        word: usize,
169
170
        /// How many times the word has been written according to the store.
171
        ///
172
        /// This value is exact only for the metadata of the page. For the content of the page, it
173
        /// is set to:
174
        /// - 0 if the word is after the tail. Such word should not have been written.
175
        /// - 1 if the word is before the tail. Such word may or may not have been written.
176
        store: usize,
177
178
        /// How many times the word has been written according to the model.
179
        ///
180
        /// This value is exact only for the metadata of the page. For the content of the page, it
181
        /// is set to:
182
        /// - 0 if the word was not written.
183
        /// - 1 if the word was written.
184
        model: usize,
185
    },
186
}
187
188
impl From<StoreError> for StoreInvariant {
189
0
    fn from(error: StoreError) -> StoreInvariant {
190
0
        StoreInvariant::StoreError(error)
191
0
    }
192
}
193
194
impl StoreDriver {
195
    /// Provides read-only access to the storage.
196
0
    pub fn storage(&self) -> &BufferStorage {
197
0
        match self {
198
0
            StoreDriver::On(x) => x.store().storage(),
199
0
            StoreDriver::Off(x) => x.storage(),
200
        }
201
0
    }
202
203
    /// Provides read-only access to the model.
204
0
    pub fn model(&self) -> &StoreModel {
205
0
        match self {
206
0
            StoreDriver::On(x) => x.model(),
207
0
            StoreDriver::Off(x) => x.model(),
208
        }
209
0
    }
210
211
    /// Extracts the power-on version of the driver.
212
0
    pub fn on(self) -> Option<StoreDriverOn> {
213
0
        match self {
214
0
            StoreDriver::On(x) => Some(x),
215
0
            StoreDriver::Off(_) => None,
216
        }
217
0
    }
218
219
    /// Powers on the store if not already on.
220
0
    pub fn power_on(self) -> Result<StoreDriverOn, StoreInvariant> {
221
0
        match self {
222
0
            StoreDriver::On(x) => Ok(x),
223
0
            StoreDriver::Off(x) => x.power_on(),
224
        }
225
0
    }
226
227
    /// Extracts the power-off version of the driver.
228
0
    pub fn off(self) -> Option<StoreDriverOff> {
229
0
        match self {
230
0
            StoreDriver::On(_) => None,
231
0
            StoreDriver::Off(x) => Some(x),
232
        }
233
0
    }
234
}
235
236
impl StoreDriverOff {
237
    /// Starts a simulation with a clean storage given its configuration.
238
0
    pub fn new(options: BufferOptions, num_pages: usize) -> StoreDriverOff {
239
0
        let storage = vec![0xff; num_pages * options.page_size].into_boxed_slice();
240
0
        let storage = BufferStorage::new(storage, options);
241
0
        StoreDriverOff::new_dirty(storage)
242
0
    }
243
244
    /// Starts a simulation from an existing storage.
245
0
    pub fn new_dirty(storage: BufferStorage) -> StoreDriverOff {
246
0
        let format = Format::new(&storage).unwrap();
247
0
        StoreDriverOff { storage, model: StoreModel::new(format), complete: None }
248
0
    }
249
250
    /// Provides read-only access to the storage.
251
0
    pub fn storage(&self) -> &BufferStorage {
252
0
        &self.storage
253
0
    }
254
255
    /// Provides mutable access to the storage.
256
0
    pub fn storage_mut(&mut self) -> &mut BufferStorage {
257
0
        &mut self.storage
258
0
    }
259
260
    /// Provides read-only access to the model.
261
0
    pub fn model(&self) -> &StoreModel {
262
0
        &self.model
263
0
    }
264
265
    /// Powers on the store without interruption.
266
    ///
267
    /// # Panics
268
    ///
269
    /// Panics if the store cannot be powered on.
270
0
    pub fn power_on(self) -> Result<StoreDriverOn, StoreInvariant> {
271
0
        Ok(self.partial_power_on(StoreInterruption::none()).map_err(|x| x.1)?.on().unwrap())
272
0
    }
273
274
    /// Powers on the store with a possible interruption.
275
0
    pub fn partial_power_on(
276
0
        mut self, interruption: StoreInterruption,
277
0
    ) -> Result<StoreDriver, (BufferStorage, StoreInvariant)> {
278
0
        self.storage.arm_interruption(interruption.delay);
279
0
        Ok(match Store::new(self.storage) {
280
0
            Ok(mut store) => {
281
0
                store.storage_mut().disarm_interruption();
282
0
                let mut error = None;
283
0
                if let Some(complete) = self.complete {
284
0
                    match StoreDriverOn::new(store, complete.model, &complete.deleted) {
285
0
                        Ok(driver) => return Ok(StoreDriver::On(driver)),
286
0
                        Err((e, x)) => {
287
0
                            error = Some(e);
288
0
                            store = x;
289
0
                        }
290
                    }
291
0
                };
292
0
                StoreDriver::On(StoreDriverOn::new(store, self.model, &[]).map_err(
293
0
                    |(rollback, store)| {
294
0
                        let storage = store.extract_storage();
295
0
                        match error {
296
0
                            None => (storage, rollback),
297
0
                            Some(complete) => {
298
0
                                let rollback = Box::new(rollback);
299
0
                                let complete = Box::new(complete);
300
0
                                (storage, StoreInvariant::Interrupted { rollback, complete })
301
                            }
302
                        }
303
0
                    },
304
0
                )?)
305
            }
306
0
            Err((StoreError::StorageError, mut storage)) => {
307
0
                storage.corrupt_operation(interruption.corrupt);
308
0
                StoreDriver::Off(StoreDriverOff { storage, ..self })
309
            }
310
0
            Err((error, mut storage)) => {
311
0
                storage.reset_interruption();
312
0
                return Err((storage, StoreInvariant::StoreError(error)));
313
            }
314
        })
315
0
    }
316
317
    /// Returns the number of storage operations to power on.
318
    ///
319
    /// Returns `None` if the store cannot power on successfully.
320
0
    pub fn count_operations(&self) -> Option<usize> {
321
0
        let initial_delay = usize::MAX;
322
0
        let mut storage = self.storage.clone();
323
0
        storage.arm_interruption(initial_delay);
324
0
        let mut store = Store::new(storage).ok()?;
325
0
        Some(initial_delay - store.storage_mut().disarm_interruption())
326
0
    }
327
}
328
329
impl StoreDriverOn {
330
    /// Provides read-only access to the store.
331
0
    pub fn store(&self) -> &Store<BufferStorage> {
332
0
        &self.store
333
0
    }
334
335
    /// Extracts the store.
336
0
    pub fn extract_store(self) -> Store<BufferStorage> {
337
0
        self.store
338
0
    }
339
340
    /// Provides mutable access to the store.
341
0
    pub fn store_mut(&mut self) -> &mut Store<BufferStorage> {
342
0
        &mut self.store
343
0
    }
344
345
    /// Provides read-only access to the model.
346
0
    pub fn model(&self) -> &StoreModel {
347
0
        &self.model
348
0
    }
349
350
    /// Applies a store operation to the store and model without interruption.
351
0
    pub fn apply(&mut self, operation: StoreOperation) -> Result<(), StoreInvariant> {
352
0
        let (deleted, store_result) = self.store.apply(&operation);
353
0
        let model_result = self.model.apply(operation);
354
0
        if store_result != model_result {
355
0
            return Err(StoreInvariant::DifferentResult {
356
0
                store: store_result,
357
0
                model: model_result,
358
0
            });
359
0
        }
360
0
        self.check_deleted(&deleted)?;
361
0
        Ok(())
362
0
    }
363
364
    /// Applies a store operation to the store and model with a possible interruption.
365
0
    pub fn partial_apply(
366
0
        mut self, operation: StoreOperation, interruption: StoreInterruption,
367
0
    ) -> Result<(Option<StoreError>, StoreDriver), (Store<BufferStorage>, StoreInvariant)> {
368
0
        self.store.storage_mut().arm_interruption(interruption.delay);
369
0
        let (deleted, store_result) = self.store.apply(&operation);
370
0
        Ok(match store_result {
371
0
            Err(StoreError::NoLifetime) => return Err((self.store, StoreInvariant::NoLifetime)),
372
            Ok(()) | Err(StoreError::NoCapacity) | Err(StoreError::InvalidArgument) => {
373
0
                self.store.storage_mut().disarm_interruption();
374
0
                let model_result = self.model.apply(operation);
375
0
                if store_result != model_result {
376
0
                    return Err((
377
0
                        self.store,
378
0
                        StoreInvariant::DifferentResult {
379
0
                            store: store_result,
380
0
                            model: model_result,
381
0
                        },
382
0
                    ));
383
0
                }
384
0
                if store_result.is_ok() {
385
0
                    if let Err(invariant) = self.check_deleted(&deleted) {
386
0
                        return Err((self.store, invariant));
387
0
                    }
388
0
                }
389
0
                (store_result.err(), StoreDriver::On(self))
390
            }
391
            Err(StoreError::StorageError) => {
392
0
                let mut driver = StoreDriverOff {
393
0
                    storage: self.store.extract_storage(),
394
0
                    model: self.model,
395
0
                    complete: None,
396
0
                };
397
0
                driver.storage.corrupt_operation(interruption.corrupt);
398
0
                let mut model = driver.model.clone();
399
0
                if model.apply(operation).is_ok() {
400
0
                    driver.complete = Some(Complete { model, deleted });
401
0
                }
402
0
                (None, StoreDriver::Off(driver))
403
            }
404
0
            Err(error) => return Err((self.store, StoreInvariant::StoreError(error))),
405
        })
406
0
    }
407
408
    /// Returns the number of storage operations to apply a store operation.
409
    ///
410
    /// Returns `None` if the store cannot apply the operation successfully.
411
0
    pub fn count_operations(&self, operation: &StoreOperation) -> Option<usize> {
412
0
        let initial_delay = usize::MAX;
413
0
        let mut store = self.store.clone();
414
0
        store.storage_mut().arm_interruption(initial_delay);
415
0
        store.apply(operation).1.ok()?;
416
0
        Some(initial_delay - store.storage_mut().disarm_interruption())
417
0
    }
418
419
    /// Powers off the store.
420
0
    pub fn power_off(self) -> StoreDriverOff {
421
0
        StoreDriverOff { storage: self.store.extract_storage(), model: self.model, complete: None }
422
0
    }
423
424
    /// Applies an insertion to the store and model without interruption.
425
    #[cfg(feature = "std")]
426
0
    pub fn insert(&mut self, key: usize, value: &[u8]) -> Result<(), StoreInvariant> {
427
0
        let value = value.to_vec();
428
0
        let updates = vec![StoreUpdate::Insert { key, value }];
429
0
        self.apply(StoreOperation::Transaction { updates })
430
0
    }
431
432
    /// Applies a deletion to the store and model without interruption.
433
    #[cfg(feature = "std")]
434
0
    pub fn remove(&mut self, key: usize) -> Result<(), StoreInvariant> {
435
0
        let updates = vec![StoreUpdate::Remove { key }];
436
0
        self.apply(StoreOperation::Transaction { updates })
437
0
    }
438
439
    /// Applies a clear operation to the store and model without interruption.
440
    #[cfg(feature = "std")]
441
0
    pub fn clear(&mut self, min_key: usize) -> Result<(), StoreInvariant> {
442
0
        self.apply(StoreOperation::Clear { min_key })
443
0
    }
444
445
    /// Checks that the store and model are in sync.
446
0
    pub fn check(&self) -> Result<(), StoreInvariant> {
447
0
        self.recover_check(&[])
448
0
    }
449
450
    /// Starts a simulation from a power-off store.
451
    ///
452
    /// Checks that the store and model are in sync and that the given deleted entries are wiped.
453
0
    fn new(
454
0
        store: Store<BufferStorage>, model: StoreModel, deleted: &[StoreHandle],
455
0
    ) -> Result<StoreDriverOn, (StoreInvariant, Store<BufferStorage>)> {
456
0
        let driver = StoreDriverOn { store, model };
457
0
        match driver.recover_check(deleted) {
458
0
            Ok(()) => Ok(driver),
459
0
            Err(error) => Err((error, driver.store)),
460
        }
461
0
    }
462
463
    /// Checks that the store and model are in sync and that the given entries are wiped.
464
0
    fn recover_check(&self, deleted: &[StoreHandle]) -> Result<(), StoreInvariant> {
465
0
        self.check_deleted(deleted)?;
466
0
        self.check_model()?;
467
0
        self.check_storage()?;
468
0
        Ok(())
469
0
    }
470
471
    /// Checks that the given entries are wiped from the storage.
472
0
    fn check_deleted(&self, deleted: &[StoreHandle]) -> Result<(), StoreInvariant> {
473
0
        for handle in deleted {
474
0
            let value = self.store.inspect_value(handle);
475
0
            if !value.iter().all(|&x| x == 0x00) {
476
0
                return Err(StoreInvariant::NotWiped { key: handle.get_key(), value });
477
0
            }
478
        }
479
0
        Ok(())
480
0
    }
481
482
    /// Checks that the store and model are in sync.
483
0
    fn check_model(&self) -> Result<(), StoreInvariant> {
484
0
        let mut model_content = self.model.content().clone();
485
0
        for handle in self.store.iter()? {
486
0
            let handle = handle?;
487
0
            let model_value = match model_content.remove(&handle.get_key()) {
488
0
                None => return Err(StoreInvariant::OnlyInStore { key: handle.get_key() }),
489
0
                Some(x) => x,
490
            };
491
0
            let store_value = handle.get_value(&self.store)?.into_boxed_slice();
492
0
            if store_value != model_value {
493
0
                return Err(StoreInvariant::DifferentValue {
494
0
                    key: handle.get_key(),
495
0
                    store: store_value,
496
0
                    model: model_value,
497
0
                });
498
0
            }
499
        }
500
0
        if let Some(&key) = model_content.keys().next() {
501
0
            return Err(StoreInvariant::OnlyInModel { key });
502
0
        }
503
0
        let store_capacity = self.store.capacity()?.remaining();
504
0
        let model_capacity = self.model.capacity().remaining();
505
0
        if store_capacity != model_capacity {
506
0
            return Err(StoreInvariant::DifferentCapacity {
507
0
                store: store_capacity,
508
0
                model: model_capacity,
509
0
            });
510
0
        }
511
0
        Ok(())
512
0
    }
513
514
    /// Checks that the store is tracking lifetime correctly.
515
0
    fn check_storage(&self) -> Result<(), StoreInvariant> {
516
0
        let format = self.model.format();
517
0
        let storage = self.store.storage();
518
0
        let num_words = format.page_size() / format.word_size();
519
0
        let head = self.store.head()?;
520
0
        let tail = self.store.tail()?;
521
0
        for page in 0 .. format.num_pages() {
522
            // Check the erase cycle of the page.
523
0
            let store_erase = head.cycle(format) + (page < head.page(format)) as Nat;
524
0
            let model_erase = storage.get_page_erases(page as usize);
525
0
            if store_erase as usize != model_erase {
526
0
                return Err(StoreInvariant::DifferentErase {
527
0
                    page: page as usize,
528
0
                    store: store_erase as usize,
529
0
                    model: model_erase,
530
0
                });
531
0
            }
532
0
            let page_pos = Position::new(format, store_erase, page, 0);
533
534
            // Check the init word of the page.
535
0
            let mut store_write = (page_pos < tail) as usize;
536
0
            if page == 0 && tail == Position::new(format, 0, 0, 0) {
537
0
                // When the store is initialized and nothing written yet, the first page is still
538
0
                // initialized.
539
0
                store_write = 1;
540
0
            }
541
0
            let model_write = storage.get_word_writes((page * num_words) as usize);
542
0
            if store_write != model_write {
543
0
                return Err(StoreInvariant::DifferentWrite {
544
0
                    page: page as usize,
545
0
                    word: 0,
546
0
                    store: store_write,
547
0
                    model: model_write,
548
0
                });
549
0
            }
550
551
            // Check the compact info of the page.
552
0
            let model_write = storage.get_word_writes((page * num_words + 1) as usize);
553
0
            let store_write = 0;
554
0
            if store_write != model_write {
555
0
                return Err(StoreInvariant::DifferentWrite {
556
0
                    page: page as usize,
557
0
                    word: 1,
558
0
                    store: store_write,
559
0
                    model: model_write,
560
0
                });
561
0
            }
562
563
            // Check the content of the page. We only check cases where the model says a word was
564
            // written while the store doesn't think it should be the case. This is because the
565
            // model doesn't count writes to the same value. Also we only check whether a word is
566
            // written and not how many times. This is because this is hard to rebuild in the store.
567
0
            for word in 2 .. num_words {
568
0
                let store_write = (page_pos + (word - 2) < tail) as usize;
569
0
                let model_write =
570
0
                    (storage.get_word_writes((page * num_words + word) as usize) > 0) as usize;
571
0
                if store_write < model_write {
572
0
                    return Err(StoreInvariant::DifferentWrite {
573
0
                        page: page as usize,
574
0
                        word: word as usize,
575
0
                        store: store_write,
576
0
                        model: model_write,
577
0
                    });
578
0
                }
579
            }
580
        }
581
0
        Ok(())
582
0
    }
583
}
584
585
impl<'a> StoreInterruption<'a> {
586
    /// Builds an interruption that never triggers.
587
0
    pub fn none() -> StoreInterruption<'a> {
588
0
        StoreInterruption { delay: usize::MAX, corrupt: Box::new(|_, _| {}) }
589
0
    }
590
591
    /// Builds an interruption without corruption.
592
0
    pub fn pure(delay: usize) -> StoreInterruption<'a> {
593
0
        StoreInterruption { delay, corrupt: Box::new(|_, _| {}) }
594
0
    }
595
}