Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,9 @@ library cannot prove whether
the candidate committed, so the application must not replay it.

Large values can be written through `ByteWriter` and read with authenticated,
bounded `read_at` calls. Reference nodes form application-defined trees without
exposing storage paths. `history` returns a bounded cursor over an authenticated checkpoint and
bounded `read_at` calls. Each reader caches at most two storage chunks, up to
4 MiB; caller-held byte slices can keep evicted chunks alive. Reference nodes
form application-defined trees without exposing storage paths. `history` returns a bounded cursor over an authenticated checkpoint and
ordered commits, including transaction IDs and recorded results, for bindings
or consumers that rebuild application state. Each item includes process-local
publication proofs for its object references. The cursor returns one record at
Expand Down
37 changes: 24 additions & 13 deletions src/byte_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,15 @@ pub struct ByteWriter {
failed: bool,
}

/// An authenticated byte stream with one cached storage chunk.
/// An authenticated byte stream with at most two cached storage chunks.
#[derive(Debug)]
pub struct ByteReader {
log: Log,
view: View,
chunk_bytes: u64,
len: u64,
children: Vec<ObjectRef>,
cached: Option<(usize, Bytes)>,
cached: [Option<(usize, Bytes)>; 2],
}

impl Log {
Expand Down Expand Up @@ -112,7 +112,7 @@ impl Log {
chunk_bytes,
len,
children: node.children,
cached: None,
cached: [None, None],
})
}
}
Expand Down Expand Up @@ -195,7 +195,9 @@ impl ByteReader {

/// Reads at most `max_len` bytes from an offset, stopping at the next chunk boundary.
/// Zero-length requests and offsets at or beyond EOF return empty bytes.
/// Each storage read authenticates a complete chunk; consecutive reads reuse one cache.
/// Each storage read authenticates a complete chunk. The two most recently used
/// chunks are cached, using at most four MiB for the cache. Returned byte slices
/// can keep evicted chunks alive while the caller holds them.
///
/// # Errors
/// Returns an error for an expired view, corrupt chunk, or storage failure.
Expand All @@ -204,19 +206,28 @@ impl ByteReader {
return Ok(Bytes::new());
}
let index = usize::try_from(offset / self.chunk_bytes).map_err(|_| invalid())?;
if self
.cached
if self.cached[0]
.as_ref()
.is_none_or(|(cached, _)| *cached != index)
{
self.cached = None;
let bytes = self
.log
.read_object(&self.view, &self.children[index])
.await?;
self.cached = Some((index, bytes));
if self.cached[1]
.as_ref()
.is_some_and(|(cached, _)| *cached == index)
{
self.cached.swap(0, 1);
} else {
// Release the older chunk before reading, so a miss cannot
// temporarily retain three storage chunks.
self.cached[1] = None;
let bytes = self
.log
.read_object(&self.view, &self.children[index])
.await?;
self.cached[1] = self.cached[0].take();
self.cached[0] = Some((index, bytes));
}
}
let (_, bytes) = self.cached.as_ref().ok_or_else(invalid)?;
let (_, bytes) = self.cached[0].as_ref().ok_or_else(invalid)?;
let start = usize::try_from(offset % self.chunk_bytes).map_err(|_| invalid())?;
Ok(bytes.slice(start..start + max_len.min(bytes.len() - start)))
}
Expand Down
132 changes: 129 additions & 3 deletions src/byte_stream_tests.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::*;
use crate::sim::{FailurePhase, FaultStore, Operation};
use crate::sim::{Failure, FailurePhase, FaultStore, Operation};
use crate::{
CheckpointStatus, CollectionFinish, CollectionStart, CommitStatus, LogId, Options,
TransactionId, ValidatedBackend,
Expand Down Expand Up @@ -89,7 +89,7 @@ async fn geometry_capacity_and_tiny_limits() -> TestResult {
}

#[tokio::test]
async fn reads_are_short_authenticated_and_cache_one_chunk() -> TestResult {
async fn reads_are_short_authenticated_and_cache_two_chunks() -> TestResult {
let faults = FaultStore::new(InMemory::new());
let (log, view) = setup(Arc::new(faults.clone()), small()).await?;
let payload: Vec<u8> = (0_u8..251).cycle().take(400).collect();
Expand All @@ -114,7 +114,7 @@ async fn reads_are_short_authenticated_and_cache_one_chunk() -> TestResult {
assert_eq!(faults.metrics().operation(Operation::Get).requests, 1);
assert_eq!(reader.read_at(399, 100).await?.as_ref(), &payload[399..]);
assert_eq!(reader.read_at(0, 1).await?.as_ref(), &payload[..1]);
assert_eq!(faults.metrics().operation(Operation::Get).requests, 3);
assert_eq!(faults.metrics().operation(Operation::Get).requests, 2);
let mut actual = Vec::new();
while actual.len() < payload.len() {
actual.extend_from_slice(&reader.read_at(actual.len() as u64, 19).await?);
Expand Down Expand Up @@ -322,3 +322,129 @@ async fn offset_read_verifies_the_entire_chunk() -> TestResult {
));
Ok(())
}

#[tokio::test]
async fn seek_cache_is_lazy_bounded_and_evicts_the_oldest_chunk() -> TestResult {
let faults = FaultStore::new(InMemory::new());
let (log, view) = setup(
Arc::new(faults.clone()),
Options {
max_object_bytes: 512,
max_object_refs: 16,
..Options::default()
},
)
.await?;
let payload: Vec<u8> = (0_u8..251).cycle().take(1536).collect();
let mut writer = log.byte_writer(&view)?;
writer.write(&payload).await?;
let root = writer.finish().await?;
let mut reader = log.open_bytes(&view, root.reference()).await?;
faults.reset();
for (offset, requests) in [(0_usize, 1), (512, 2), (0, 2), (1024, 3), (0, 3), (512, 4)] {
assert_eq!(
reader.read_at(u64::try_from(offset)?, 1).await?.as_ref(),
&payload[offset..=offset]
);
assert_eq!(
faults.metrics().operation(Operation::Get).requests,
requests
);
assert!(
reader
.cached
.iter()
.flatten()
.map(|(_, bytes)| bytes.len())
.sum::<usize>()
<= 1024
);
}
// A rejected miss cannot populate the cache or refund its storage request.
for occurrence in 5..=7 {
faults.schedule(Failure {
operation: Operation::Get,
phase: FailurePhase::Before,
occurrence,
});
}
assert!(matches!(
reader.read_at(1024, 1).await,
Err(Error::Store(_))
));
assert_eq!(faults.metrics().operation(Operation::Get).requests, 7);
assert_eq!(reader.read_at(512, 1).await?.as_ref(), &payload[512..513]);
assert_eq!(faults.metrics().operation(Operation::Get).requests, 7);
assert_eq!(
reader.read_at(1024, 1).await?.as_ref(),
&payload[1024..1025]
);
assert_eq!(faults.metrics().operation(Operation::Get).requests, 8);
let mut pause = faults.pause_next_get(FailurePhase::After);
let mut read = Box::pin(reader.read_at(0, 1));
tokio::select! {
result = &mut read => return Err(format!("read did not pause: {result:?}").into()),
entered = pause.wait_until_entered() => assert!(entered),
}
drop(read);
assert!(!pause.release());
// Cancellation after eviction preserves the authenticated MRU chunk only.
let (index, bytes) = reader.cached[0].as_ref().ok_or("missing cached chunk")?;
assert_eq!(*index, 2);
assert_eq!(bytes.as_ref(), &payload[1024..1536]);
assert!(reader.cached[1].is_none());
assert_eq!(faults.metrics().operation(Operation::Get).requests, 9);
assert_eq!(
reader.read_at(1024, 1).await?.as_ref(),
&payload[1024..1025]
);
assert_eq!(faults.metrics().operation(Operation::Get).requests, 9);
assert_eq!(reader.read_at(0, 1).await?.as_ref(), &payload[..1]);
assert_eq!(faults.metrics().operation(Operation::Get).requests, 10);
Ok(())
}

#[tokio::test]
async fn large_stream_seeks_keep_sparse_reads_and_the_original_view() -> TestResult {
let faults = FaultStore::new(InMemory::new());
let (log, view) = setup(Arc::new(faults.clone()), Options::default()).await?;
let payload: Vec<u8> = (0_u8..251).cycle().take(2 * MAX_CHUNK_BYTES + 17).collect();
let mut writer = log.byte_writer(&view)?;
writer.write(&payload).await?;
let root = writer.finish().await?;
let mut reader = log.open_bytes(&view, root.reference()).await?;
faults.reset();
let held = reader.read_at(0, 1).await?;
assert_eq!(faults.metrics().operation(Operation::Get).requests, 1);
assert_eq!(
faults.metrics().operation(Operation::Get).downloaded_bytes,
MAX_CHUNK_BYTES as u64
);
let tail = (2 * MAX_CHUNK_BYTES) as u64;
assert_eq!(
reader.read_at(tail, usize::MAX).await?.as_ref(),
&payload[2 * MAX_CHUNK_BYTES..]
);
assert_eq!(
reader.read_at(MAX_CHUNK_BYTES as u64, 1).await?.as_ref(),
&payload[MAX_CHUNK_BYTES..=MAX_CHUNK_BYTES]
);
assert_eq!(held.as_ref(), &payload[..1]);
assert_eq!(faults.metrics().operation(Operation::Get).requests, 3);
assert!(
reader
.cached
.iter()
.flatten()
.map(|(_, bytes)| bytes.len())
.sum::<usize>()
<= 2 * MAX_CHUNK_BYTES
);
// Unpublished chunks are collectible; a later miss retains the original epoch.
collect(&log).await?;
assert!(matches!(
reader.read_at(0, 1).await,
Err(Error::ViewExpired)
));
Ok(())
}
Loading