Introduce session persistence and artifact caching
This change implements a robust session management system allowing users to persist distance calculation samples and parameters across invocations. It includes concurrency-safe directory locking, deterministic parameter encoding, artifact integrity checks, and caching mechanisms to skip resampling when valid data is available.
This commit is contained in:
1 parent
a8bcf5ffac
commit
7861e886e7
15 files changed
+746
-59
No files matched your search
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "obiksession"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
obisys = { path = "../obisys", default-features = false }
|
||||
memmap2 = "0.9.11"
|
||||
xxhash-rust = { version = "0.8.18", features = ["xxh3"] }
|
||||
tracing = "0.1"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
@@ -0,0 +1,19 @@
|
||||
//! Domain-agnostic session persistence: a named directory that survives
|
||||
//! across separate CLI invocations, holding an opaque parameter blob (used
|
||||
//! to detect stale/mismatched reuse) plus a checksummed cache of named
|
||||
//! binary artifacts.
|
||||
//!
|
||||
//! Deliberately knows nothing about what the parameters or artifacts
|
||||
//! *mean* — no k-mer/genome/tally concept anywhere in this crate. A
|
||||
//! caller (e.g. `obikphylo`, for its `--session` support around
|
||||
//! `PairwiseTally`/`PartitionDispersion`/`SnpAlignment`) serializes its own
|
||||
//! parameter struct and artifacts to bytes however it likes (`rkyv`,
|
||||
//! `bincode`, ...) and hands raw `&[u8]` to this crate; [`Session`] only
|
||||
//! deals in byte blobs, directory lifecycle, and locking. Same split
|
||||
//! already used elsewhere in this project between a generic mechanism
|
||||
//! crate and the domain crate that plugs into it (`obisys`/`obikindex`,
|
||||
//! `obicompactvec`/`obikindexer`).
|
||||
|
||||
mod session;
|
||||
|
||||
pub use session::{ParamsConflict, Session, SessionOutcome};
|
||||
@@ -0,0 +1,249 @@
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use memmap2::Mmap;
|
||||
use obisys::DirLock;
|
||||
|
||||
const PARAMS_FILE: &str = "params.bin";
|
||||
const ARTIFACTS_DIR: &str = "artifacts";
|
||||
const CHECKSUM_EXT: &str = "xxh3";
|
||||
|
||||
/// Whether [`Session::open`] found a fresh (just-created, or just-reset by
|
||||
/// `force`) directory or reused one whose saved parameters matched the
|
||||
/// requested ones exactly.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SessionOutcome {
|
||||
/// New directory, or an existing one reset because its saved
|
||||
/// parameters didn't match and `force: true` was passed. No cached
|
||||
/// artifact in it can be trusted — there either isn't one yet, or the
|
||||
/// ones that were there have just been deleted.
|
||||
Created,
|
||||
/// Existing directory whose saved parameters matched byte-for-byte.
|
||||
/// Every artifact already cached under it was produced under these
|
||||
/// same parameters and is safe to [`Session::restore`].
|
||||
Reused,
|
||||
}
|
||||
|
||||
/// Returned by [`Session::open`] when the directory already holds a
|
||||
/// parameter blob that doesn't match the one just requested, and `force`
|
||||
/// wasn't set. This crate has no idea what the bytes mean, so it can't
|
||||
/// produce a useful diagnostic on its own — the caller, who serialized
|
||||
/// both, is expected to deserialize `saved`/`requested` itself and report
|
||||
/// exactly which field(s) differ before deciding whether to error out,
|
||||
/// point at a different directory, or retry [`Session::open`] with
|
||||
/// `force: true`.
|
||||
#[derive(Debug)]
|
||||
pub struct ParamsConflict {
|
||||
pub saved: Vec<u8>,
|
||||
pub requested: Vec<u8>,
|
||||
}
|
||||
|
||||
/// An open session directory: exclusively locked (via [`obisys::DirLock`])
|
||||
/// for as long as this value lives, so no other `obiksession`-using
|
||||
/// process can read a half-written artifact or reset the directory out
|
||||
/// from under this one.
|
||||
#[derive(Debug)]
|
||||
pub struct Session {
|
||||
dir: PathBuf,
|
||||
outcome: SessionOutcome,
|
||||
_lock: DirLock,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Open (or create, or reset) a session directory — see
|
||||
/// [`SessionOutcome`]/[`ParamsConflict`] for the three possible
|
||||
/// outcomes. Blocks until the directory's lock is free (see
|
||||
/// [`obisys::DirLock::acquire`]) — a second process pointed at the
|
||||
/// same session directory waits rather than racing it.
|
||||
pub fn open(dir: &Path, params: &[u8], force: bool) -> io::Result<Result<Session, ParamsConflict>> {
|
||||
let lock = DirLock::acquire(dir)?;
|
||||
let params_path = dir.join(PARAMS_FILE);
|
||||
|
||||
let saved = read_checked(¶ms_path)?;
|
||||
match saved {
|
||||
Some(saved) if saved == params => Ok(Ok(Session {
|
||||
dir: dir.to_path_buf(),
|
||||
outcome: SessionOutcome::Reused,
|
||||
_lock: lock,
|
||||
})),
|
||||
Some(saved) if !force => Ok(Err(ParamsConflict { saved, requested: params.to_vec() })),
|
||||
_ => {
|
||||
// No saved params yet, or a mismatch with `force: true`:
|
||||
// start clean. Any artifact cached under different params
|
||||
// is stale by construction — deleting the whole
|
||||
// `artifacts/` directory is simpler and safer than trying
|
||||
// to figure out which entries are still valid.
|
||||
let artifacts_dir = dir.join(ARTIFACTS_DIR);
|
||||
if artifacts_dir.exists() {
|
||||
fs::remove_dir_all(&artifacts_dir)?;
|
||||
}
|
||||
fs::create_dir_all(&artifacts_dir)?;
|
||||
write_checked(¶ms_path, params)?;
|
||||
Ok(Ok(Session {
|
||||
dir: dir.to_path_buf(),
|
||||
outcome: SessionOutcome::Created,
|
||||
_lock: lock,
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn dir(&self) -> &Path {
|
||||
&self.dir
|
||||
}
|
||||
|
||||
pub fn outcome(&self) -> SessionOutcome {
|
||||
self.outcome
|
||||
}
|
||||
|
||||
fn artifact_path(&self, name: &str) -> PathBuf {
|
||||
self.dir.join(ARTIFACTS_DIR).join(name)
|
||||
}
|
||||
|
||||
/// Restore a previously [`store`](Self::store)d artifact, `mmap`ed
|
||||
/// read-only for zero-copy access by the caller (e.g. `rkyv::access`
|
||||
/// straight over the returned bytes).
|
||||
///
|
||||
/// `Ok(None)` if `name` isn't cached yet, *or* if its checksum doesn't
|
||||
/// match what was recorded at [`store`](Self::store) time — treated
|
||||
/// the same as "not cached" rather than an error, so a partial dump
|
||||
/// left behind by a killed process just triggers a recompute on the
|
||||
/// next run instead of a hard failure.
|
||||
pub fn restore(&self, name: &str) -> io::Result<Option<Mmap>> {
|
||||
verify_mmap(&self.artifact_path(name))
|
||||
}
|
||||
|
||||
/// Store `bytes` under `name`, plus a checksum sidecar, atomically:
|
||||
/// both are written to a temporary file and renamed into place, so a
|
||||
/// crash mid-write can never leave a corrupt file that a later
|
||||
/// [`restore`](Self::restore) mistakes for valid (the checksum file is
|
||||
/// only ever renamed into place *after* the data file's rename
|
||||
/// succeeds, so the two can't disagree about which write completed).
|
||||
pub fn store(&self, name: &str, bytes: &[u8]) -> io::Result<()> {
|
||||
write_checked(&self.artifact_path(name), bytes)
|
||||
}
|
||||
}
|
||||
|
||||
fn checksum_path_for(path: &Path) -> PathBuf {
|
||||
let mut os_str = path.as_os_str().to_owned();
|
||||
os_str.push(".");
|
||||
os_str.push(CHECKSUM_EXT);
|
||||
PathBuf::from(os_str)
|
||||
}
|
||||
|
||||
/// `mmap` `path` and verify it against its checksum sidecar. `Ok(None)`
|
||||
/// when `path` doesn't exist, its checksum sidecar doesn't exist/parse, or
|
||||
/// the checksum doesn't match — every case here means "nothing usable is
|
||||
/// cached," never an error the caller has to handle specially.
|
||||
fn verify_mmap(path: &Path) -> io::Result<Option<Mmap>> {
|
||||
if !path.exists() {
|
||||
return Ok(None);
|
||||
}
|
||||
let Ok(expected_str) = fs::read_to_string(checksum_path_for(path)) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Ok(expected) = expected_str.trim().parse::<u64>() else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let file = fs::File::open(path)?;
|
||||
// SAFETY: the file is only ever written by `write_checked` (atomic
|
||||
// temp-then-rename) and this whole directory is held under this
|
||||
// process's exclusive `DirLock` for the `Session`'s entire lifetime —
|
||||
// no other process can be concurrently modifying it underneath this
|
||||
// mapping.
|
||||
let mmap = unsafe { Mmap::map(&file)? };
|
||||
let actual = xxhash_rust::xxh3::xxh3_64(&mmap[..]);
|
||||
if actual != expected {
|
||||
tracing::warn!(
|
||||
path = %path.display(),
|
||||
"session artifact failed checksum verification — treating as absent"
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(mmap))
|
||||
}
|
||||
|
||||
fn read_checked(path: &Path) -> io::Result<Option<Vec<u8>>> {
|
||||
Ok(verify_mmap(path)?.map(|mmap| mmap[..].to_vec()))
|
||||
}
|
||||
|
||||
fn write_checked(path: &Path, bytes: &[u8]) -> io::Result<()> {
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
let tmp = path.with_extension("tmp");
|
||||
fs::write(&tmp, bytes)?;
|
||||
fs::rename(&tmp, path)?;
|
||||
|
||||
let checksum = xxhash_rust::xxh3::xxh3_64(bytes);
|
||||
let checksum_path = checksum_path_for(path);
|
||||
let checksum_tmp = checksum_path.with_extension("tmp");
|
||||
fs::write(&checksum_tmp, checksum.to_string())?;
|
||||
fs::rename(&checksum_tmp, checksum_path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn fresh_directory_is_created() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path().join("session");
|
||||
let session = Session::open(&dir, b"params-v1", false).unwrap().unwrap();
|
||||
assert_eq!(session.outcome(), SessionOutcome::Created);
|
||||
assert!(session.restore("missing").unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matching_params_reuse_and_restore_artifact() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path().join("session");
|
||||
{
|
||||
let session = Session::open(&dir, b"params-v1", false).unwrap().unwrap();
|
||||
session.store("tally", b"some serialized bytes").unwrap();
|
||||
}
|
||||
let session = Session::open(&dir, b"params-v1", false).unwrap().unwrap();
|
||||
assert_eq!(session.outcome(), SessionOutcome::Reused);
|
||||
let restored = session.restore("tally").unwrap().unwrap();
|
||||
assert_eq!(&restored[..], b"some serialized bytes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mismatched_params_without_force_conflicts() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path().join("session");
|
||||
Session::open(&dir, b"params-v1", false).unwrap().unwrap();
|
||||
let conflict = Session::open(&dir, b"params-v2", false).unwrap().unwrap_err();
|
||||
assert_eq!(conflict.saved, b"params-v1");
|
||||
assert_eq!(conflict.requested, b"params-v2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mismatched_params_with_force_resets_artifacts() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path().join("session");
|
||||
{
|
||||
let session = Session::open(&dir, b"params-v1", false).unwrap().unwrap();
|
||||
session.store("tally", b"old data").unwrap();
|
||||
}
|
||||
let session = Session::open(&dir, b"params-v2", true).unwrap().unwrap();
|
||||
assert_eq!(session.outcome(), SessionOutcome::Created);
|
||||
assert!(session.restore("tally").unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupted_artifact_is_treated_as_absent() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path().join("session");
|
||||
let session = Session::open(&dir, b"params-v1", false).unwrap().unwrap();
|
||||
session.store("tally", b"good data").unwrap();
|
||||
// Corrupt the data file after the fact without touching the
|
||||
// checksum sidecar — simulates a partial/garbled write.
|
||||
std::fs::write(dir.join("artifacts").join("tally"), b"corrupted!").unwrap();
|
||||
assert!(session.restore("tally").unwrap().is_none());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user