-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconcurrency_test.rs
More file actions
414 lines (360 loc) · 12.8 KB
/
Copy pathconcurrency_test.rs
File metadata and controls
414 lines (360 loc) · 12.8 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
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
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) Jonathan D.A. Jewell <j.d.a.jewell@open.ac.uk>
//
// Concurrency tests: Verify thread-safety and transaction isolation
// Tests:
// - Concurrent key operations don't deadlock
// - Transaction isolation: uncommitted changes invisible to concurrent readers
// - Content store: concurrent writes to different keys all succeed
// - Race conditions in commit/rollback don't corrupt state
use std::fs;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use tempfile::TempDir;
/// Helper: Create temp directory
fn test_dir() -> TempDir {
tempfile::tempdir().expect("Failed to create temp dir")
}
/// Helper: Setup jk directories
fn setup_jk_dirs(base: &PathBuf) -> std::io::Result<()> {
fs::create_dir_all(base.join(".jk/content"))?;
fs::create_dir_all(base.join(".jk/transactions"))?;
fs::create_dir_all(base.join(".jk/operations"))?;
fs::create_dir_all(base.join(".jk/keys"))?;
Ok(())
}
/// Helper: SHA256 hash
fn sha256(data: &[u8]) -> String {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(data);
hex::encode(hasher.finalize())
}
// ============================================
// CONCURRENT KEY OPERATIONS (NO DEADLOCK)
// ============================================
#[test]
fn concurrent_key_operations_no_deadlock() {
let dir = test_dir();
let base = Arc::new(dir.path().to_path_buf());
setup_jk_dirs(&base).expect("Setup failed");
let num_threads = 10;
let mut handles = vec![];
for i in 0..num_threads {
let base_clone = Arc::clone(&base);
let handle = std::thread::spawn(move || {
let key_id = format!("key-{:02}", i);
let material = format!("thread-{}-material", i);
// Create key
let hash = sha256(material.as_bytes());
let content_path = base_clone.join(".jk/content").join(&hash);
// Write content
fs::write(&content_path, material.as_bytes())
.expect(&format!("Write failed for {}", key_id));
// Record key
let key_record = format!(
r#"{{"id":"{}","hash":"{}","thread":{}}}"#,
key_id, hash, i
);
fs::write(
base_clone
.join(".jk/keys")
.join(format!("{}.json", key_id)),
&key_record,
)
.expect(&format!("Key record failed for {}", key_id));
// Read back immediately
let read_back = fs::read(&content_path)
.expect(&format!("Read failed for {}", key_id));
assert_eq!(
read_back,
material.as_bytes(),
"Thread {}: content mismatch",
i
);
i // Return thread ID
});
handles.push(handle);
}
// Wait for all threads
for (i, handle) in handles.into_iter().enumerate() {
let result = handle.join().expect("Thread panicked");
assert_eq!(result, i, "Thread {} should complete successfully", i);
}
// Verify all keys exist
let key_files: Vec<_> = fs::read_dir(base.join(".jk/keys"))
.expect("Read keys dir")
.filter_map(Result::ok)
.collect();
assert_eq!(
key_files.len(),
num_threads,
"All {} keys must be created",
num_threads
);
}
// ============================================
// TRANSACTION ISOLATION
// ============================================
#[test]
fn transaction_isolation_uncommitted_invisible() {
let dir = test_dir();
let base = Arc::new(dir.path().to_path_buf());
setup_jk_dirs(&base).expect("Setup failed");
// Start transaction in main thread
let tx_id = "tx-isolation-001";
let tx_record = r#"{"id":"tx-isolation-001","state":"active"}"#;
fs::write(base.join(".jk/transactions/001.json"), tx_record)
.expect("Write transaction");
// Spawn reader thread
let base_clone = Arc::clone(&base);
let tx_id_clone = tx_id.to_string();
let reader = std::thread::spawn(move || {
// Reader should not see uncommitted changes
std::thread::sleep(std::time::Duration::from_millis(50));
let ops_dir = base_clone.join(".jk/operations");
let ops: Vec<_> = fs::read_dir(&ops_dir)
.unwrap_or_else(|_| fs::read_dir(&base_clone.join(".jk")).unwrap())
.filter_map(Result::ok)
.filter(|e| {
e.file_name()
.to_str()
.map_or(false, |n| n.contains(&tx_id_clone))
})
.collect();
ops.len()
});
// Writer thread: add uncommitted operation
let base_clone = Arc::clone(&base);
let writer = std::thread::spawn(move || {
let op_record = r#"{"tx":"tx-isolation-001","op":"copy","committed":false}"#;
fs::write(
base_clone
.join(".jk/operations")
.join("tx-isolation-001-op-001.json"),
op_record,
)
.ok();
});
writer.join().expect("Writer thread");
let _uncommitted_count = reader.join().expect("Reader thread");
// Reader may see the file (filesystem is not transactional),
// but we verify the transaction itself is still "active" not "committed"
let tx_read = ({ use std::io::Read; std::fs::File::open(base.join(".jk/transactions/001.json").and_then(|mut f| { let mut buf = String::new(); f.take(10 * 1024 * 1024).read_to_string(&mut buf)?; Ok(buf) }) }))
.expect("Read transaction");
assert!(
tx_read.contains("\"active\""),
"Transaction must remain active while uncommitted"
);
}
#[test]
fn concurrent_transactions_isolated() {
let dir = test_dir();
let base = Arc::new(dir.path().to_path_buf());
setup_jk_dirs(&base).expect("Setup failed");
let num_txs = 5;
let mut handles = vec![];
for tx_idx in 0..num_txs {
let base_clone = Arc::clone(&base);
let handle = std::thread::spawn(move || {
let tx_id = format!("tx-{:02}", tx_idx);
// Begin transaction
let tx_record = format!(
r#"{{"id":"{}","state":"active"}}"#,
tx_id
);
fs::write(
base_clone
.join(".jk/transactions")
.join(format!("{}.json", tx_idx)),
&tx_record,
)
.expect("Write tx");
// Perform operations within transaction
for op_idx in 0..3 {
let op_record = format!(
r#"{{"tx":"{}","op":"copy","seq":{}}}"#,
tx_id, op_idx
);
fs::write(
base_clone
.join(".jk/operations")
.join(format!("{}-op-{:02}.json", tx_id, op_idx)),
&op_record,
)
.ok();
}
// Commit
let commit_record = format!(
r#"{{"id":"{}","state":"committed"}}"#,
tx_id
);
fs::write(
base_clone
.join(".jk/transactions")
.join(format!("{}.json", tx_idx)),
&commit_record,
)
.expect("Commit tx");
tx_idx
});
handles.push(handle);
}
// Wait for all transactions
for (i, handle) in handles.into_iter().enumerate() {
let result = handle.join().expect("Thread panicked");
assert_eq!(
result, i,
"Transaction {} should complete successfully",
i
);
}
// Verify all transactions exist and are committed
let tx_files: Vec<_> = fs::read_dir(base.join(".jk/transactions"))
.expect("Read transactions")
.filter_map(Result::ok)
.collect();
assert_eq!(
tx_files.len(),
num_txs,
"All {} transactions must exist",
num_txs
);
}
// ============================================
// CONCURRENT CONTENT STORE WRITES
// ============================================
#[test]
fn concurrent_content_store_writes_all_succeed() {
let dir = test_dir();
let base = Arc::new(dir.path().to_path_buf());
setup_jk_dirs(&base).expect("Setup failed");
let num_writers = 20;
let mut handles = vec![];
let success_count = Arc::new(Mutex::new(0));
for i in 0..num_writers {
let base_clone = Arc::clone(&base);
let success_clone = Arc::clone(&success_count);
let handle = std::thread::spawn(move || {
let material = format!("content-{}-unique-data", i);
let hash = sha256(material.as_bytes());
let path = base_clone.join(".jk/content").join(&hash);
// Write content
if fs::write(&path, material.as_bytes()).is_ok() {
// Verify immediately
if let Ok(read_back) = fs::read(&path) {
if read_back == material.as_bytes() {
let mut count = success_clone.lock().unwrap();
*count += 1;
}
}
}
i
});
handles.push(handle);
}
// Wait for all writers
for handle in handles.into_iter() {
let _ = handle.join().expect("Writer thread");
}
let success = *success_count.lock().unwrap();
assert_eq!(
success, num_writers,
"All {} content writes must succeed",
num_writers
);
// Verify all content files exist
let content_files: Vec<_> = fs::read_dir(base.join(".jk/content"))
.expect("Read content dir")
.filter_map(Result::ok)
.collect();
assert_eq!(
content_files.len(),
num_writers,
"All {} content files must exist",
num_writers
);
}
// ============================================
// COMMIT/ROLLBACK RACE CONDITIONS
// ============================================
#[test]
fn concurrent_commit_rollback_no_corruption() {
let dir = test_dir();
let base = Arc::new(dir.path().to_path_buf());
setup_jk_dirs(&base).expect("Setup failed");
let num_threads = 10;
let mut handles = vec![];
for i in 0..num_threads {
let base_clone = Arc::clone(&base);
let handle = std::thread::spawn(move || {
let tx_id = format!("tx-race-{:02}", i);
// Begin
let tx_record = format!(
r#"{{"id":"{}","state":"active"}}"#,
tx_id
);
fs::write(
base_clone
.join(".jk/transactions")
.join(format!("race-{}.json", i)),
&tx_record,
)
.ok();
// Add operations
for op in 0..5 {
let op_record = format!(
r#"{{"tx":"{}","op":"copy","seq":{}}}"#,
tx_id, op
);
fs::write(
base_clone
.join(".jk/operations")
.join(format!("{}-op-{:02}.json", tx_id, op)),
&op_record,
)
.ok();
}
// Randomly commit or rollback
let action = if i % 2 == 0 { "committed" } else { "rolled_back" };
let final_record = format!(
r#"{{"id":"{}","state":"{}"}}"#,
tx_id, action
);
fs::write(
base_clone
.join(".jk/transactions")
.join(format!("race-{}.json", i)),
&final_record,
)
.ok();
i
});
handles.push(handle);
}
// Wait for all
for handle in handles.into_iter() {
let _ = handle.join().expect("Race thread");
}
// Verify all transaction records are in valid state (not corrupted)
let tx_files: Vec<_> = fs::read_dir(base.join(".jk/transactions"))
.expect("Read tx dir")
.filter_map(Result::ok)
.collect();
assert_eq!(
tx_files.len(),
num_threads,
"All {} transaction records must exist",
num_threads
);
// Verify each transaction is in a valid terminal state
for entry in fs::read_dir(base.join(".jk/transactions")).expect("Read dir") {
let entry = entry.expect("Dir entry");
let content = ({ use std::io::Read; std::fs::File::open(entry.path().and_then(|mut f| { let mut buf = String::new(); f.take(10 * 1024 * 1024).read_to_string(&mut buf)?; Ok(buf) }) })).expect("Read tx file");
let is_valid = content.contains("\"committed\"") || content.contains("\"rolled_back\"");
assert!(
is_valid,
"Transaction must be in valid terminal state (committed or rolled_back)"
);
}
}