commonware-runtime 2026.7.0

Execute asynchronous tasks with a configurable scheduler.
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
use crate::{deterministic::Auditor, Error, Handle, IoBufs, IoBufsMut};
use std::sync::Arc;

#[derive(Clone)]
pub struct Storage<S: crate::Storage> {
    inner: S,
    auditor: Arc<Auditor>,
}

impl<S: crate::Storage> Storage<S> {
    pub const fn new(inner: S, auditor: Arc<Auditor>) -> Self {
        Self { inner, auditor }
    }

    /// Get a reference to the inner storage.
    pub const fn inner(&self) -> &S {
        &self.inner
    }
}

impl<S: crate::Storage> crate::Storage for Storage<S> {
    type Blob = Blob<S::Blob>;

    async fn open_versioned(
        &self,
        partition: &str,
        name: &[u8],
        versions: std::ops::RangeInclusive<u16>,
    ) -> Result<(Self::Blob, u64, u16), Error> {
        self.auditor.event(b"open", |hasher| {
            hasher.update(partition.as_bytes());
            hasher.update(name);
            hasher.update(versions.start().to_be_bytes());
            hasher.update(versions.end().to_be_bytes());
        });
        self.inner
            .open_versioned(partition, name, versions)
            .await
            .map(|(blob, len, blob_version)| {
                (
                    Blob {
                        auditor: self.auditor.clone(),
                        inner: blob,
                        partition: partition.into(),
                        name: name.to_vec(),
                    },
                    len,
                    blob_version,
                )
            })
    }

    async fn remove(&self, partition: &str, name: Option<&[u8]>) -> Result<(), Error> {
        self.auditor.event(b"remove", |hasher| {
            hasher.update(partition.as_bytes());
            match name {
                Some(name) => {
                    hasher.update([1]);
                    hasher.update(name);
                }
                None => hasher.update([0]),
            }
        });
        self.inner.remove(partition, name).await
    }

    async fn scan(&self, partition: &str) -> Result<Vec<Vec<u8>>, Error> {
        self.auditor.event(b"scan", |hasher| {
            hasher.update(partition.as_bytes());
        });
        self.inner.scan(partition).await
    }
}

#[derive(Clone)]
pub struct Blob<B: crate::Blob> {
    auditor: Arc<Auditor>,
    partition: String,
    name: Vec<u8>,
    inner: B,
}

impl<B: crate::Blob> crate::Blob for Blob<B> {
    async fn read_at(&self, offset: u64, len: usize) -> Result<IoBufsMut, Error> {
        self.auditor.event(b"read_at", |hasher| {
            hasher.update(self.partition.as_bytes());
            hasher.update(&self.name);
            hasher.update(offset.to_be_bytes());
            hasher.update(len.to_be_bytes());
        });
        self.inner.read_at(offset, len).await
    }

    async fn read_at_buf(
        &self,
        offset: u64,
        len: usize,
        bufs: impl Into<IoBufsMut> + Send,
    ) -> Result<IoBufsMut, Error> {
        let bufs = bufs.into();
        self.auditor.event(b"read_at_buf", |hasher| {
            hasher.update(self.partition.as_bytes());
            hasher.update(&self.name);
            hasher.update(offset.to_be_bytes());
            hasher.update(len.to_be_bytes());
        });
        self.inner.read_at_buf(offset, len, bufs).await
    }

    async fn write_at(&self, offset: u64, bufs: impl Into<IoBufs> + Send) -> Result<(), Error> {
        let bufs = bufs.into();
        self.auditor.event(b"write_at", |hasher| {
            hasher.update(self.partition.as_bytes());
            hasher.update(&self.name);
            hasher.update(offset.to_be_bytes());
            hasher.update_bufs(&bufs);
        });
        self.inner.write_at(offset, bufs).await
    }

    async fn write_at_sync(
        &self,
        offset: u64,
        bufs: impl Into<IoBufs> + Send,
    ) -> Result<(), Error> {
        let bufs = bufs.into();
        self.auditor.event(b"write_at_sync", |hasher| {
            hasher.update(self.partition.as_bytes());
            hasher.update(&self.name);
            hasher.update(offset.to_be_bytes());
            hasher.update_bufs(&bufs);
        });
        self.inner.write_at_sync(offset, bufs).await
    }

    async fn resize(&self, len: u64) -> Result<(), Error> {
        self.auditor.event(b"resize", |hasher| {
            hasher.update(self.partition.as_bytes());
            hasher.update(&self.name);
            hasher.update(len.to_be_bytes());
        });
        self.inner.resize(len).await
    }

    async fn sync(&self) -> Result<(), Error> {
        self.auditor.event(b"sync", |hasher| {
            hasher.update(self.partition.as_bytes());
            hasher.update(&self.name);
        });
        self.inner.sync().await
    }

    async fn start_sync(&self) -> Handle<()> {
        self.auditor.event(b"start_sync", |hasher| {
            hasher.update(self.partition.as_bytes());
            hasher.update(&self.name);
        });
        self.inner.start_sync().await
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        deterministic::Auditor,
        storage::{
            audited::Storage as AuditedStorage, memory::Storage as MemStorage,
            tests::run_storage_tests,
        },
        telemetry::metrics::Registry,
        Blob as _, BufferPool, BufferPoolConfig, Error, Handle, IoBuf, IoBufs, IoBufsMut,
        Storage as _,
    };
    use commonware_utils::sync::Mutex;
    use std::sync::Arc;

    fn test_pool() -> BufferPool {
        let mut registry = Registry::default();
        BufferPool::new(BufferPoolConfig::for_storage(), &mut registry)
    }

    #[tokio::test]
    async fn test_audited_storage() {
        let inner = MemStorage::new(test_pool());
        let auditor = Arc::new(crate::deterministic::Auditor::default());
        let storage = AuditedStorage::new(inner, auditor.clone());

        run_storage_tests(storage).await;
    }

    #[tokio::test]
    async fn test_audited_storage_separates_partition_and_blob_names() {
        let auditor1 = Arc::new(Auditor::default());
        let storage1 = AuditedStorage::new(MemStorage::new(test_pool()), auditor1.clone());
        let auditor2 = Arc::new(Auditor::default());
        let storage2 = AuditedStorage::new(MemStorage::new(test_pool()), auditor2.clone());

        storage1.open("a", b"bc").await.unwrap();
        storage2.open("ab", b"c").await.unwrap();

        assert_ne!(auditor1.state(), auditor2.state());
    }

    #[tokio::test]
    async fn test_audited_start_sync() {
        // Two independent storages run the same sequence of operations.
        let auditor1 = Arc::new(Auditor::default());
        let storage1 = AuditedStorage::new(MemStorage::new(test_pool()), auditor1.clone());
        let auditor2 = Arc::new(Auditor::default());
        let storage2 = AuditedStorage::new(MemStorage::new(test_pool()), auditor2.clone());

        let (blob1, _) = storage1.open("partition", b"test_blob").await.unwrap();
        let (blob2, _) = storage2.open("partition", b"test_blob").await.unwrap();
        blob1.write_at(0, b"hello world").await.unwrap();
        blob2.write_at(0, b"hello world").await.unwrap();

        // `start_sync` must record an auditor event, so the state advances.
        let before = auditor1.state();
        blob1.start_sync().await.await.unwrap();
        assert_ne!(
            auditor1.state(),
            before,
            "start_sync must record an auditor event"
        );

        // The recorded event must be deterministic across independent runs.
        blob2.start_sync().await.await.unwrap();
        assert_eq!(
            auditor1.state(),
            auditor2.state(),
            "Hashes do not match after start_sync"
        );
    }

    #[tokio::test]
    async fn test_audited_storage_combined() {
        // Initialize the first storage and auditor
        let inner1 = MemStorage::new(test_pool());
        let auditor1 = Arc::new(Auditor::default());
        let storage1 = AuditedStorage::new(inner1, auditor1.clone());

        // Initialize the second storage and auditor
        let inner2 = MemStorage::new(test_pool());
        let auditor2 = Arc::new(Auditor::default());
        let storage2 = AuditedStorage::new(inner2, auditor2.clone());

        // Perform a sequence of operations on both storages simultaneously
        let (blob1, _) = storage1.open("partition", b"test_blob").await.unwrap();
        let (blob2, _) = storage2.open("partition", b"test_blob").await.unwrap();

        // Write data to the blobs
        blob1.write_at(0, b"hello world").await.unwrap();
        blob2.write_at(0, b"hello world").await.unwrap();
        assert_eq!(
            auditor1.state(),
            auditor2.state(),
            "Hashes do not match after write"
        );

        // Read data from the blobs
        let read = blob1.read_at(0, 11).await.unwrap();
        assert_eq!(
            read.coalesce(),
            b"hello world",
            "Blob1 content does not match"
        );
        let read = blob2.read_at(0, 11).await.unwrap();
        assert_eq!(
            read.coalesce(),
            b"hello world",
            "Blob2 content does not match"
        );
        assert_eq!(
            auditor1.state(),
            auditor2.state(),
            "Hashes do not match after read"
        );

        // Resize the blobs
        blob1.resize(5).await.unwrap();
        blob2.resize(5).await.unwrap();
        assert_eq!(
            auditor1.state(),
            auditor2.state(),
            "Hashes do not match after resize"
        );

        // Sync the blobs
        blob1.sync().await.unwrap();
        blob2.sync().await.unwrap();
        assert_eq!(
            auditor1.state(),
            auditor2.state(),
            "Hashes do not match after sync"
        );

        // Drop the blobs
        drop(blob1);
        drop(blob2);

        assert_eq!(
            auditor1.state(),
            auditor2.state(),
            "Hashes do not match after drop"
        );

        // Remove the blobs
        storage1
            .remove("partition", Some(b"test_blob"))
            .await
            .unwrap();
        storage2
            .remove("partition", Some(b"test_blob"))
            .await
            .unwrap();
        assert_eq!(
            auditor1.state(),
            auditor2.state(),
            "Hashes do not match after remove"
        );

        // Scan the partitions
        let blobs1 = storage1.scan("partition").await.unwrap();
        let blobs2 = storage2.scan("partition").await.unwrap();
        assert!(
            blobs1.is_empty(),
            "Partition1 should be empty after blob removal"
        );
        assert!(
            blobs2.is_empty(),
            "Partition2 should be empty after blob removal"
        );
        assert_eq!(
            auditor1.state(),
            auditor2.state(),
            "Hashes do not match after scan"
        );
    }

    #[derive(Clone)]
    struct RecordingBlob {
        write_chunk_counts: Arc<Mutex<Vec<usize>>>,
        sync_write_chunk_counts: Arc<Mutex<Vec<usize>>>,
    }

    impl crate::Blob for RecordingBlob {
        async fn read_at(&self, _offset: u64, _len: usize) -> Result<IoBufsMut, Error> {
            unreachable!("not used in test");
        }

        async fn read_at_buf(
            &self,
            _offset: u64,
            _len: usize,
            _bufs: impl Into<IoBufsMut> + Send,
        ) -> Result<IoBufsMut, Error> {
            unreachable!("not used in test");
        }

        async fn write_at(
            &self,
            _offset: u64,
            bufs: impl Into<IoBufs> + Send,
        ) -> Result<(), Error> {
            self.write_chunk_counts
                .lock()
                .push(bufs.into().chunk_count());
            Ok(())
        }

        async fn write_at_sync(
            &self,
            _offset: u64,
            bufs: impl Into<IoBufs> + Send,
        ) -> Result<(), Error> {
            self.sync_write_chunk_counts
                .lock()
                .push(bufs.into().chunk_count());
            Ok(())
        }

        async fn resize(&self, _len: u64) -> Result<(), Error> {
            Ok(())
        }

        async fn sync(&self) -> Result<(), Error> {
            Ok(())
        }

        async fn start_sync(&self) -> Handle<()> {
            Handle::ready(self.sync().await)
        }
    }

    #[tokio::test]
    async fn test_audited_blob_writes_preserve_chunking() {
        let write_chunk_counts = Arc::new(Mutex::new(Vec::new()));
        let sync_write_chunk_counts = Arc::new(Mutex::new(Vec::new()));
        let blob = super::Blob {
            auditor: Arc::new(crate::deterministic::Auditor::default()),
            partition: "partition".into(),
            name: b"blob".to_vec(),
            inner: RecordingBlob {
                write_chunk_counts: write_chunk_counts.clone(),
                sync_write_chunk_counts: sync_write_chunk_counts.clone(),
            },
        };

        blob.write_at(
            0,
            IoBufs::from(vec![
                IoBuf::from(b"a".to_vec()),
                IoBuf::from(b"b".to_vec()),
                IoBuf::from(b"c".to_vec()),
                IoBuf::from(b"d".to_vec()),
            ]),
        )
        .await
        .unwrap();

        assert_eq!(*write_chunk_counts.lock(), vec![4]);
        assert!(sync_write_chunk_counts.lock().is_empty());

        blob.write_at_sync(
            0,
            IoBufs::from(vec![
                IoBuf::from(b"a".to_vec()),
                IoBuf::from(b"b".to_vec()),
                IoBuf::from(b"c".to_vec()),
                IoBuf::from(b"d".to_vec()),
            ]),
        )
        .await
        .unwrap();

        assert_eq!(*write_chunk_counts.lock(), vec![4]);
        assert_eq!(*sync_write_chunk_counts.lock(), vec![4]);
    }
}