-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathqmdb_any_fixed_sync.rs
More file actions
290 lines (260 loc) · 9.48 KB
/
qmdb_any_fixed_sync.rs
File metadata and controls
290 lines (260 loc) · 9.48 KB
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
#![no_main]
use arbitrary::Arbitrary;
use commonware_cryptography::Sha256;
use commonware_runtime::{buffer::paged::CacheRef, deterministic, BufferPooler, Metrics, Runner};
use commonware_storage::{
journal::contiguous::fixed::Config as FConfig,
merkle::mmr::Family,
mmr::journaled::Config as MmrConfig,
qmdb::{
any::{
unordered::fixed::{Db, Operation as FixedOperation},
FixedConfig as Config,
},
sync,
},
translator::TwoCap,
};
use commonware_utils::{non_empty_range, sequence::FixedBytes, NZUsize, NZU16, NZU64};
use libfuzzer_sys::fuzz_target;
use std::{num::NonZeroU16, sync::Arc};
type Key = FixedBytes<32>;
type Value = FixedBytes<32>;
type FixedDb = Db<Family, deterministic::Context, Key, Value, Sha256, TwoCap>;
const MAX_OPERATIONS: usize = 50;
#[derive(Debug)]
enum Operation {
// Basic ops to build source state
Update { key: [u8; 32], value: [u8; 32] },
Delete { key: [u8; 32] },
Commit,
Prune,
// Sync scenarios
SyncFull { fetch_batch_size: u64 },
// Failure simulation
SimulateFailure,
}
impl<'a> Arbitrary<'a> for Operation {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
let choice: u8 = u.arbitrary()?;
match choice % 8 {
0 | 1 => {
let key = u.arbitrary()?;
let value = u.arbitrary()?;
Ok(Operation::Update { key, value })
}
2 => {
let key = u.arbitrary()?;
Ok(Operation::Delete { key })
}
3 => Ok(Operation::Commit),
4 => Ok(Operation::Prune),
5 => {
let fetch_batch_size = u.arbitrary()?;
Ok(Operation::SyncFull { fetch_batch_size })
}
6 => Ok(Operation::SimulateFailure {}),
7 => {
let key = u.arbitrary()?;
Ok(Operation::Delete { key })
}
_ => unreachable!(),
}
}
}
#[derive(Debug)]
struct FuzzInput {
ops: Vec<Operation>,
commit_counter: u64,
}
impl<'a> Arbitrary<'a> for FuzzInput {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
let num_ops = u.int_in_range(1..=MAX_OPERATIONS)?;
let ops = (0..num_ops)
.map(|_| Operation::arbitrary(u))
.collect::<Result<Vec<_>, _>>()?;
Ok(FuzzInput {
ops,
commit_counter: 0,
})
}
}
const PAGE_SIZE: NonZeroU16 = NZU16!(129);
fn test_config(test_name: &str, pooler: &impl BufferPooler) -> Config<TwoCap> {
let page_cache = CacheRef::from_pooler(pooler, PAGE_SIZE, NZUsize!(1));
Config {
merkle_config: MmrConfig {
journal_partition: format!("{test_name}-mmr"),
metadata_partition: format!("{test_name}-meta"),
items_per_blob: NZU64!(3),
write_buffer: NZUsize!(1024),
thread_pool: None,
page_cache: page_cache.clone(),
},
journal_config: FConfig {
partition: format!("{test_name}-log"),
items_per_blob: NZU64!(3),
write_buffer: NZUsize!(1024),
page_cache,
},
translator: TwoCap,
}
}
async fn test_sync<
R: sync::resolver::Resolver<
Family = Family,
Digest = commonware_cryptography::sha256::Digest,
Op = FixedOperation<Family, Key, Value>,
>,
>(
context: deterministic::Context,
resolver: R,
target: sync::Target<Family, commonware_cryptography::sha256::Digest>,
fetch_batch_size: u64,
test_name: &str,
sync_id: usize,
) -> bool {
let db_config = test_config(test_name, &context);
let expected_root = target.root;
let sync_config: sync::engine::Config<FixedDb, R> = sync::engine::Config {
context: context.with_label("sync").with_attribute("id", sync_id),
update_rx: None,
finish_rx: None,
reached_target_tx: None,
db_config,
fetch_batch_size: NZU64!((fetch_batch_size % 100) + 1),
target,
resolver,
apply_batch_size: 100,
max_outstanding_requests: 10,
max_retained_roots: 8,
};
if let Ok(synced) = sync::sync(sync_config).await {
let actual_root = synced.root();
assert_eq!(
actual_root, expected_root,
"Synced root must match target root"
);
synced.destroy().await.is_ok()
} else {
false
}
}
const TEST_NAME: &str = "qmdb-any-fixed-fuzz-test";
fn fuzz(mut input: FuzzInput) {
let runner = deterministic::Runner::default();
runner.start(|context| async move {
let cfg = test_config(TEST_NAME, &context);
let mut db = FixedDb::init(context.clone(), cfg)
.await
.expect("Failed to init source db");
let mut restarts = 0usize;
let mut sync_id = 0;
let mut pending_writes: Vec<(Key, Option<Value>)> = Vec::new();
for op in &input.ops {
match op {
Operation::Update { key, value } => {
pending_writes.push((Key::new(*key), Some(Value::new(*value))));
}
Operation::Delete { key } => {
pending_writes.push((Key::new(*key), None));
}
Operation::Commit => {
let mut commit_id = [0u8; 32];
if input.commit_counter == 0 {
assert!(db.get_metadata().await.unwrap().is_none());
} else {
commit_id[..8].copy_from_slice(&input.commit_counter.to_be_bytes());
assert_eq!(
db.get_metadata().await.unwrap().unwrap(),
FixedBytes::new(commit_id),
);
}
input.commit_counter += 1;
commit_id[..8].copy_from_slice(&input.commit_counter.to_be_bytes());
let mut batch = db.new_batch();
for (k, v) in pending_writes.drain(..) {
batch = batch.write(k, v);
}
let merkleized = batch
.merkleize(&db, Some(FixedBytes::new(commit_id)))
.await
.unwrap();
db.apply_batch(merkleized)
.await
.expect("Commit should not fail");
db.commit().await.expect("Commit should not fail");
}
Operation::Prune => {
db.prune(db.sync_boundary())
.await
.expect("Prune should not fail");
}
Operation::SyncFull { fetch_batch_size } => {
if db.bounds().await.end == 0 {
continue;
}
input.commit_counter += 1;
let mut commit_id = [0u8; 32];
commit_id[..8].copy_from_slice(&input.commit_counter.to_be_bytes());
let mut batch = db.new_batch();
for (k, v) in pending_writes.drain(..) {
batch = batch.write(k, v);
}
let merkleized = batch
.merkleize(&db, Some(FixedBytes::new(commit_id)))
.await
.unwrap();
db.apply_batch(merkleized)
.await
.expect("commit should not fail");
db.commit().await.expect("Commit should not fail");
let target = sync::Target {
root: db.root(),
range: non_empty_range!(db.sync_boundary(), db.bounds().await.end),
};
let wrapped_src = Arc::new(db);
let _result = test_sync(
context.clone(),
wrapped_src.clone(),
target,
*fetch_batch_size,
&format!("full_{sync_id}"),
sync_id,
)
.await;
db = Arc::try_unwrap(wrapped_src)
.unwrap_or_else(|_| panic!("Failed to unwrap src"));
sync_id += 1;
}
Operation::SimulateFailure => {
// Simulate unclean shutdown by dropping the db without committing
pending_writes.clear();
drop(db);
let cfg = test_config(TEST_NAME, &context);
db = FixedDb::init(
context
.with_label("db")
.with_attribute("instance", restarts),
cfg,
)
.await
.expect("Failed to init source db");
restarts += 1;
}
}
}
let mut batch = db.new_batch();
for (k, v) in pending_writes.drain(..) {
batch = batch.write(k, v);
}
let merkleized = batch.merkleize(&db, None).await.unwrap();
db.apply_batch(merkleized)
.await
.expect("commit should not fail");
db.destroy().await.expect("Destroy should not fail");
});
}
fuzz_target!(|input: FuzzInput| {
fuzz(input);
});