Merge remote-tracking branch 'pr/1607' into wave-4
# Conflicts: # crates/victory-pipeline/src/cache.rs
This commit is contained in:
@ -1,7 +1,9 @@
|
||||
use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, OnceLock, Weak};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
@ -26,6 +28,51 @@ impl CacheKey {
|
||||
}
|
||||
}
|
||||
|
||||
// Only in-flight keys occupy the registry. A hit never takes this lock.
|
||||
type Gate = Mutex<()>;
|
||||
type Gates = HashMap<PathBuf, Weak<Gate>>;
|
||||
|
||||
fn gates() -> &'static Mutex<Gates> {
|
||||
static GATES: OnceLock<Mutex<Gates>> = OnceLock::new();
|
||||
GATES.get_or_init(Mutex::default)
|
||||
}
|
||||
|
||||
/// A lease keeps the per-output gate alive while the caller is working or
|
||||
/// waiting. The registry lock is never held during conversion or file I/O.
|
||||
struct Flight {
|
||||
path: PathBuf,
|
||||
gate: Option<Arc<Gate>>,
|
||||
}
|
||||
|
||||
impl Flight {
|
||||
fn acquire(path: &Path) -> Self {
|
||||
let mut entries = gates().lock().unwrap_or_else(|e| e.into_inner());
|
||||
let gate = entries.get(path).and_then(Weak::upgrade).unwrap_or_else(|| {
|
||||
let gate = Arc::new(Mutex::new(()));
|
||||
entries.insert(path.to_owned(), Arc::downgrade(&gate));
|
||||
gate
|
||||
});
|
||||
Self { path: path.to_owned(), gate: Some(gate) }
|
||||
}
|
||||
|
||||
fn lock(&self) -> std::sync::MutexGuard<'_, ()> {
|
||||
self.gate.as_ref().expect("live lease").lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Flight {
|
||||
fn drop(&mut self) {
|
||||
// Drop the strong reference while the registry is locked. Otherwise
|
||||
// two simultaneous final drops could both observe another owner and
|
||||
// leave a dead entry behind.
|
||||
let mut entries = gates().lock().unwrap_or_else(|e| e.into_inner());
|
||||
drop(self.gate.take());
|
||||
if entries.get(&self.path).is_some_and(|gate| gate.strong_count() == 0) {
|
||||
entries.remove(&self.path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Content-addressed store under the user's cache directory.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Cache {
|
||||
@ -54,6 +101,17 @@ impl Cache {
|
||||
tracing::trace!(converter = converter.id(), key = %key.to_hex(), "cache hit");
|
||||
return Ok(path);
|
||||
}
|
||||
// Hash-identical misses in the same cache share one conversion.
|
||||
// Canonicalize the existing root so independent Cache instances and
|
||||
// root aliases converge, without changing the returned path.
|
||||
let gate_path = std::fs::canonicalize(&self.root)?
|
||||
.join(path.strip_prefix(&self.root).expect("cache key is under root"));
|
||||
let flight = Flight::acquire(&gate_path);
|
||||
let _guard = flight.lock();
|
||||
// A preceding converter may have published while we were waiting.
|
||||
if path.is_file() {
|
||||
return Ok(path);
|
||||
}
|
||||
Self::publish(&path, converter, input)?;
|
||||
Ok(path)
|
||||
}
|
||||
@ -167,6 +225,89 @@ mod tests {
|
||||
assert_eq!(conv.runs.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_identical_misses_share_one_conversion() {
|
||||
struct SlowUpper(AtomicUsize);
|
||||
impl Converter for SlowUpper {
|
||||
fn id(&self) -> &'static str { "test.slow-upper" }
|
||||
fn version(&self) -> u32 { 1 }
|
||||
fn convert(&self, input: &[u8]) -> Result<Vec<u8>> {
|
||||
self.0.fetch_add(1, Ordering::Relaxed);
|
||||
std::thread::sleep(std::time::Duration::from_millis(40));
|
||||
Ok(input.to_ascii_uppercase())
|
||||
}
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("cache");
|
||||
let cache = Cache::open(&root).unwrap();
|
||||
let converter = SlowUpper(AtomicUsize::new(0));
|
||||
let input = vec![b'a'; 1 << 20];
|
||||
const WORKERS: usize = 32;
|
||||
let start = std::sync::Barrier::new(WORKERS);
|
||||
std::thread::scope(|scope| {
|
||||
let workers: Vec<_> = (0..WORKERS).map(|_| {
|
||||
let cache = Cache::open(&root).unwrap();
|
||||
let (start, converter, input) = (&start, &converter, &input);
|
||||
scope.spawn(move || {
|
||||
start.wait();
|
||||
cache.get_or_convert(converter, input).unwrap()
|
||||
})
|
||||
}).collect();
|
||||
let expected = cache.path_for(&CacheKey::new(&converter, &input));
|
||||
for worker in workers {
|
||||
assert_eq!(worker.join().unwrap(), expected);
|
||||
}
|
||||
assert_eq!(std::fs::read(&expected).unwrap(), vec![b'A'; input.len()]);
|
||||
let gate_path = std::fs::canonicalize(&root).unwrap().join(expected.strip_prefix(&root).unwrap());
|
||||
assert!(!gates().lock().unwrap().contains_key(&gate_path));
|
||||
});
|
||||
assert_eq!(converter.0.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn independent_keys_do_not_share_a_gate_and_registry_drains() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let a = tmp.path().join("a");
|
||||
let b = tmp.path().join("b");
|
||||
let first = Flight::acquire(&a);
|
||||
let same = Flight::acquire(&a);
|
||||
let other = Flight::acquire(&b);
|
||||
assert!(Arc::ptr_eq(first.gate.as_ref().unwrap(), same.gate.as_ref().unwrap()));
|
||||
assert!(!Arc::ptr_eq(first.gate.as_ref().unwrap(), other.gate.as_ref().unwrap()));
|
||||
let held = first.lock();
|
||||
assert!(other.gate.as_ref().unwrap().try_lock().is_ok());
|
||||
assert!(same.gate.as_ref().unwrap().try_lock().is_err());
|
||||
drop(held);
|
||||
drop(first);
|
||||
drop(same);
|
||||
drop(other);
|
||||
let entries = gates().lock().unwrap();
|
||||
assert!(!entries.contains_key(&a));
|
||||
assert!(!entries.contains_key(&b));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_conversion_releases_gate_for_retry() {
|
||||
struct Retry(AtomicUsize);
|
||||
impl Converter for Retry {
|
||||
fn id(&self) -> &'static str { "test.retry" }
|
||||
fn version(&self) -> u32 { 1 }
|
||||
fn convert(&self, input: &[u8]) -> Result<Vec<u8>> {
|
||||
if self.0.fetch_add(1, Ordering::Relaxed) == 0 {
|
||||
anyhow::bail!("first conversion failed");
|
||||
}
|
||||
Ok(input.to_vec())
|
||||
}
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let cache = Cache::open(tmp.path().join("cache")).unwrap();
|
||||
let converter = Retry(AtomicUsize::new(0));
|
||||
assert!(cache.get_or_convert(&converter, b"retry").is_err());
|
||||
let path = cache.get_or_convert(&converter, b"retry").unwrap();
|
||||
assert_eq!(std::fs::read(path).unwrap(), b"retry");
|
||||
assert_eq!(converter.0.load(Ordering::Relaxed), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_publication_removes_the_staging_file() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
Reference in New Issue
Block a user