commonware-storage 2026.10.0

Persist and retrieve data from an abstract store.
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
//! Journal conformance tests

use crate::journal::{
    authenticated,
    contiguous::{fixed, variable},
    segmented::{fixed as segmented_fixed, glob, oversized, variable as segmented_variable},
};
use commonware_codec::{Buf, FixedSize, RangeCfg, Read, ReadExt, Write};
use commonware_conformance::conformance_tests;
use commonware_cryptography::Sha256;
use commonware_parallel::Sequential;
use commonware_runtime::{
    BufMut, Supervisor as _,
    buffer::paged::CacheRef,
    conformance::{StorageConformance, StorageWorkload},
};
use commonware_utils::{NZU16, NZU64, NZUsize};
use core::num::{NonZeroU16, NonZeroU64, NonZeroUsize};
use oversized::Record;
use rand::RngExt as _;

const WRITE_BUFFER: NonZeroUsize = NZUsize!(1024);
const REPLAY_BUFFER: NonZeroUsize = NZUsize!(1024);
const ITEMS_PER_BLOB: NonZeroU64 = NZU64!(4096);
const PAGE_SIZE: NonZeroU16 = NZU16!(1024);
const PAGE_CACHE_SIZE: NonZeroUsize = NZUsize!(10);

fn fill_variable_item<const COMPRESSED: bool>(
    context: &mut commonware_runtime::deterministic::Context,
    index: usize,
    item: &mut Vec<u8>,
) {
    // Alternate repeated patterns with random bytes to cover compressed and raw zstd blocks.
    if COMPRESSED && index.is_multiple_of(2) {
        item.resize(192, 0);
        for (offset, byte) in item.iter_mut().enumerate() {
            *byte = (offset % 16) as u8;
        }
    } else {
        let size = context.random_range(0..256);
        item.resize(size, 0);
        context.fill(item.as_mut_slice());
    }
}

fn authenticated_merkle_config(prefix: &str) -> crate::merkle::full::Config<Sequential> {
    crate::merkle::full::Config {
        journal_partition: format!("{prefix}-merkle-journal"),
        metadata_partition: format!("{prefix}-merkle-metadata"),
        items_per_blob: NZU64!(11),
        write_buffer: WRITE_BUFFER,
        replay_buffer: REPLAY_BUFFER,
        strategy: Sequential,
        page_cache: CacheRef::new(PAGE_SIZE, PAGE_CACHE_SIZE),
    }
}

fn authenticated_journal_config(prefix: &str) -> fixed::Config {
    fixed::Config {
        partition: format!("{prefix}-journal"),
        items_per_blob: NZU64!(11),
        page_cache: CacheRef::new(PAGE_SIZE, PAGE_CACHE_SIZE),
        write_buffer: WRITE_BUFFER,
        replay_buffer: REPLAY_BUFFER,
    }
}

async fn run_authenticated_journal<F>(
    mut context: commonware_runtime::deterministic::Context,
    seed: u64,
    prefix: &'static str,
) -> Result<(), authenticated::Error<F>>
where
    F: crate::merkle::Family,
{
    let prefix = format!("{prefix}-{seed}");
    let mut journal =
        authenticated::Journal::<F, _, fixed::Journal<_, u64>, Sha256, Sequential>::new(
            context.child("authenticated"),
            authenticated_merkle_config(&prefix),
            authenticated_journal_config(&prefix),
            |_| true,
            crate::merkle::Bagging::ForwardFold,
        )
        .await?;

    let items = context.random_range(16..96);
    for i in 0..items {
        let item = seed.wrapping_add(i as u64);
        (journal, _) = journal.append(&item).await?;
    }
    let journal = journal.sync().await?;

    if items > 32 {
        let (journal, _) = journal
            .prune(crate::merkle::Location::new(items as u64 / 3))
            .await?;
        journal.sync().await?;
    }

    Ok(())
}

struct ContiguousFixedWorkload;

impl StorageWorkload for ContiguousFixedWorkload {
    type Error = crate::journal::Error;

    async fn run(
        mut context: commonware_runtime::deterministic::Context,
        seed: u64,
    ) -> Result<(), Self::Error> {
        let config = fixed::Config {
            partition: format!("contiguous-fixed-conformance-{seed}"),
            items_per_blob: ITEMS_PER_BLOB,
            page_cache: CacheRef::new(PAGE_SIZE, PAGE_CACHE_SIZE),
            write_buffer: WRITE_BUFFER,
            replay_buffer: REPLAY_BUFFER,
        };
        let mut journal = fixed::Journal::<_, u64>::init(context.child("journal"), config).await?;

        let mut data_to_write =
            vec![0u64; context.random_range(0..(ITEMS_PER_BLOB.get() as usize) * 4)];
        context.fill(&mut data_to_write[..]);

        for item in data_to_write.iter() {
            (journal, _) = journal.append(item).await?;
        }
        journal.sync().await?;
        Ok(())
    }
}

struct ContiguousVariableWorkload<const COMPRESSED: bool = false>;

impl<const COMPRESSED: bool> StorageWorkload for ContiguousVariableWorkload<COMPRESSED> {
    type Error = crate::journal::Error;

    async fn run(
        mut context: commonware_runtime::deterministic::Context,
        seed: u64,
    ) -> Result<(), Self::Error> {
        let config = variable::Config {
            partition: format!("contiguous-variable-conformance-{seed}"),
            items_per_section: ITEMS_PER_BLOB,
            page_cache: CacheRef::new(PAGE_SIZE, PAGE_CACHE_SIZE),
            write_buffer: WRITE_BUFFER,
            replay_buffer: REPLAY_BUFFER,
            compression: COMPRESSED.then_some(3),
            codec_config: (RangeCfg::new(0..256), ()),
        };
        let mut journal =
            variable::Journal::<_, Vec<u8>>::init(context.child("journal"), config).await?;

        let mut data_to_write =
            vec![Vec::new(); context.random_range(0..(ITEMS_PER_BLOB.get() as usize) * 4)];
        for (i, item) in data_to_write.iter_mut().enumerate() {
            fill_variable_item::<COMPRESSED>(&mut context, i, item);
        }

        for item in data_to_write {
            (journal, _) = journal.append(&item).await?;
        }
        journal.sync().await?;
        Ok(())
    }
}

struct SegmentedFixedWorkload;

impl StorageWorkload for SegmentedFixedWorkload {
    type Error = crate::journal::Error;

    async fn run(
        mut context: commonware_runtime::deterministic::Context,
        seed: u64,
    ) -> Result<(), Self::Error> {
        let config = segmented_fixed::Config {
            partition: format!("segmented-fixed-conformance-{seed}"),
            page_cache: CacheRef::new(PAGE_SIZE, PAGE_CACHE_SIZE),
            write_buffer: WRITE_BUFFER,
        };
        let mut journal =
            segmented_fixed::Journal::<_, u64>::init(context.child("journal"), config).await?;

        let items_count = context.random_range(0..(ITEMS_PER_BLOB.get() as usize) * 4);
        let mut data_to_write = vec![0u64; items_count];
        context.fill(&mut data_to_write[..]);

        for (i, item) in data_to_write.iter().enumerate() {
            let section = (i % 3) as u64;
            (journal, _) = journal.append(section, item).await?;
        }

        journal.sync([0, 1, 2]).await?;
        Ok(())
    }
}

struct SegmentedGlobWorkload<const COMPRESSED: bool = false>;

impl<const COMPRESSED: bool> StorageWorkload for SegmentedGlobWorkload<COMPRESSED> {
    type Error = crate::journal::Error;

    async fn run(
        mut context: commonware_runtime::deterministic::Context,
        seed: u64,
    ) -> Result<(), Self::Error> {
        let config = glob::Config {
            partition: format!("segmented-glob-conformance-{seed}"),
            compression: COMPRESSED.then_some(3),
            codec_config: (RangeCfg::new(0..256), ()),
            write_buffer: WRITE_BUFFER,
        };
        let mut journal = glob::Glob::<_, Vec<u8>>::init(context.child("journal"), config).await?;

        let items_count = context.random_range(0..(ITEMS_PER_BLOB.get() as usize) * 4);
        let mut data_to_write = vec![Vec::new(); items_count];
        for (i, item) in data_to_write.iter_mut().enumerate() {
            fill_variable_item::<COMPRESSED>(&mut context, i, item);
        }

        for (i, item) in data_to_write.iter().enumerate() {
            let section = (i % 3) as u64;
            (journal, _, _) = journal.append(section, item).await?;
        }

        journal.sync([0, 1, 2]).await?;
        Ok(())
    }
}

struct SegmentedVariableWorkload<const COMPRESSED: bool = false>;

impl<const COMPRESSED: bool> StorageWorkload for SegmentedVariableWorkload<COMPRESSED> {
    type Error = crate::journal::Error;

    async fn run(
        mut context: commonware_runtime::deterministic::Context,
        seed: u64,
    ) -> Result<(), Self::Error> {
        let config = segmented_variable::Config {
            partition: format!("segmented-variable-conformance-{seed}"),
            page_cache: CacheRef::new(PAGE_SIZE, PAGE_CACHE_SIZE),
            write_buffer: WRITE_BUFFER,
            compression: COMPRESSED.then_some(3),
            codec_config: (RangeCfg::new(0..256), ()),
        };
        let mut journal =
            segmented_variable::Journal::<_, Vec<u8>>::init(context.child("journal"), config)
                .await?;

        let items_count = context.random_range(0..(ITEMS_PER_BLOB.get() as usize) * 4);
        let mut data_to_write = vec![Vec::new(); items_count];
        for (i, item) in data_to_write.iter_mut().enumerate() {
            fill_variable_item::<COMPRESSED>(&mut context, i, item);
        }

        for (i, item) in data_to_write.iter().enumerate() {
            let section = (i % 3) as u64;
            (journal, _, _) = journal.append(section, item).await?;
        }

        journal.sync([0, 1, 2]).await?;
        Ok(())
    }
}

/// Test entry for SegmentedOversized conformance.
#[derive(Clone)]
struct TestEntry {
    id: u64,
    value_offset: u64,
    value_size: u32,
}

impl Write for TestEntry {
    fn write(&self, buf: &mut impl BufMut) {
        self.id.write(buf);
        self.value_offset.write(buf);
        self.value_size.write(buf);
    }
}

impl Read for TestEntry {
    type Cfg = ();

    fn read_cfg(buf: &mut impl Buf, _: &Self::Cfg) -> Result<Self, commonware_codec::Error> {
        let id = u64::read(buf)?;
        let value_offset = u64::read(buf)?;
        let value_size = u32::read(buf)?;
        Ok(Self {
            id,
            value_offset,
            value_size,
        })
    }
}

impl FixedSize for TestEntry {
    const SIZE: usize = u64::SIZE + u64::SIZE + u32::SIZE;
}

impl Record for TestEntry {
    fn value_location(&self) -> (u64, u32) {
        (self.value_offset, self.value_size)
    }

    fn with_location(mut self, offset: u64, size: u32) -> Self {
        self.value_offset = offset;
        self.value_size = size;
        self
    }
}

struct SegmentedOversizedWorkload<const COMPRESSED: bool = false>;

impl<const COMPRESSED: bool> StorageWorkload for SegmentedOversizedWorkload<COMPRESSED> {
    type Error = crate::journal::Error;

    async fn run(
        mut context: commonware_runtime::deterministic::Context,
        seed: u64,
    ) -> Result<(), Self::Error> {
        let config = oversized::Config {
            index_partition: format!("segmented-oversized-index-conformance-{seed}"),
            value_partition: format!("segmented-oversized-value-conformance-{seed}"),
            index_page_cache: CacheRef::new(PAGE_SIZE, PAGE_CACHE_SIZE),
            index_write_buffer: WRITE_BUFFER,
            value_write_buffer: WRITE_BUFFER,
            replay_buffer: REPLAY_BUFFER,
            compression: COMPRESSED.then_some(3),
            codec_config: (RangeCfg::new(0..256), ()),
        };
        let mut journal =
            oversized::Oversized::<_, TestEntry, Vec<u8>>::init(context.child("journal"), config)
                .await?;

        let items_count = context.random_range(0..(ITEMS_PER_BLOB.get() as usize) * 4);
        let mut data_to_write = vec![Vec::new(); items_count];
        for (i, item) in data_to_write.iter_mut().enumerate() {
            fill_variable_item::<COMPRESSED>(&mut context, i, item);
        }

        for (i, item) in data_to_write.iter().enumerate() {
            let section = (i % 3) as u64;
            let entry = TestEntry {
                id: i as u64,
                value_offset: 0,
                value_size: 0,
            };
            (journal, _, _, _) = journal.append(section, entry, item).await?;
        }

        journal.sync([0, 1, 2]).await?;
        Ok(())
    }
}

struct AuthenticatedMmrWorkload;

impl StorageWorkload for AuthenticatedMmrWorkload {
    type Error = authenticated::Error<crate::mmr::Family>;

    async fn run(
        context: commonware_runtime::deterministic::Context,
        seed: u64,
    ) -> Result<(), Self::Error> {
        run_authenticated_journal::<crate::mmr::Family>(
            context,
            seed,
            "authenticated-mmr-conformance",
        )
        .await
    }
}

struct AuthenticatedMmbWorkload;

impl StorageWorkload for AuthenticatedMmbWorkload {
    type Error = authenticated::Error<crate::mmb::Family>;

    async fn run(
        context: commonware_runtime::deterministic::Context,
        seed: u64,
    ) -> Result<(), Self::Error> {
        run_authenticated_journal::<crate::mmb::Family>(
            context,
            seed,
            "authenticated-mmb-conformance",
        )
        .await
    }
}

conformance_tests! {
    StorageConformance<ContiguousFixedWorkload> => 512,
    StorageConformance<ContiguousVariableWorkload> => 512,
    StorageConformance<ContiguousVariableWorkload<true>> => 512,
    StorageConformance<SegmentedFixedWorkload> => 512,
    StorageConformance<SegmentedGlobWorkload> => 512,
    StorageConformance<SegmentedGlobWorkload<true>> => 512,
    StorageConformance<SegmentedVariableWorkload> => 512,
    StorageConformance<SegmentedVariableWorkload<true>> => 512,
    StorageConformance<SegmentedOversizedWorkload> => 512,
    StorageConformance<SegmentedOversizedWorkload<true>> => 512,
    StorageConformance<AuthenticatedMmrWorkload> => 256,
    StorageConformance<AuthenticatedMmbWorkload> => 256,
}