use std::sync::Arc;
use tensor_wasm_artifacts::{ArtifactStore, ContentHash, InMemoryArtifactStore};
#[test]
fn concurrent_same_payload_put_is_idempotent() {
let store = InMemoryArtifactStore::new([0x5C; 32]);
let payload = b"the very same bytes hammered from every thread at once";
let expected = ContentHash::of(payload);
const N: usize = 16;
let hashes: Vec<ContentHash> = std::thread::scope(|s| {
let handles: Vec<_> = (0..N)
.map(|_| s.spawn(|| store.put(payload).expect("concurrent put")))
.collect();
handles
.into_iter()
.map(|h| h.join().expect("thread join"))
.collect()
});
for h in &hashes {
assert_eq!(*h, expected, "all threads agree on the content hash");
}
let listed = store.list().expect("list");
assert_eq!(
listed.len(),
1,
"concurrent identical puts collapse to one entry"
);
assert_eq!(listed[0], expected);
assert_eq!(store.get(&expected).expect("get"), payload);
}
#[test]
fn concurrent_put_via_arc_shared_handle() {
let store: Arc<dyn ArtifactStore> = Arc::new(InMemoryArtifactStore::new([0x6D; 32]));
let payload = b"arc-shared concurrent payload";
let expected = ContentHash::of(payload);
const N: usize = 8;
let mut handles = Vec::new();
for _ in 0..N {
let s = Arc::clone(&store);
let p = payload.to_vec();
handles.push(std::thread::spawn(move || s.put(&p).expect("put")));
}
for h in handles {
assert_eq!(h.join().expect("join"), expected);
}
assert_eq!(store.list().expect("list").len(), 1);
assert_eq!(store.get(&expected).expect("get"), payload);
}