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
44 changes: 26 additions & 18 deletions selene/src/composite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
use crate::store::TierStore;

use std::{
collections::{BinaryHeap, HashMap, HashSet},
collections::{HashMap, HashSet},
path::PathBuf,
sync::Arc,
time::{Duration, Instant},
Expand Down Expand Up @@ -82,6 +82,7 @@ struct Inbound {
/// Read jobs whose replies are awaited.
reads: usize,
disk_started: Option<Instant>,
used_disk: bool,
disk_bytes: u64,
error: Option<Error>,
/// The upload from memory slots has been handed to the memory store.
Expand Down Expand Up @@ -804,22 +805,17 @@ impl CompositeStore {
}

fn waiting_spills(&self) -> Vec<PrefixKey> {
let mut waiting = BinaryHeap::with_capacity(MAX_SPILLS + 1);
for (key, parked) in &self.parked {
if !parked.writing
&& let Some(node) = self.memory.index().node(key)
{
waiting.push((node.accessed(), *key));
if waiting.len() > MAX_SPILLS {
waiting.pop();
}
}
}
waiting
.into_sorted_vec()
.into_iter()
.map(|(_, key)| key)
.collect()
let mut waiting: Vec<(u64, PrefixKey)> = self
.parked
.iter()
.filter_map(|(key, parked)| {
(!parked.writing)
.then(|| self.memory.index().node(key).map(|node| (node.accessed(), *key)))
.flatten()
})
.collect();
waiting.sort_unstable_by_key(|&(accessed, _)| accessed);
waiting.into_iter().map(|(_, key)| key).collect()
}

/// Write cold parked records until their slots can cover the demand.
Expand Down Expand Up @@ -952,6 +948,7 @@ impl CompositeStore {
match self.start_read(fetch, key, tail_pages, bucket, row) {
Ok(()) => {
inbound.disk_started.get_or_insert_with(Instant::now);
inbound.used_disk = true;
inbound.nodes[index].state = NodeState::Reading;
inbound.reads += 1;
self.disk_inbound_rate.started();
Expand Down Expand Up @@ -1156,7 +1153,7 @@ impl CompositeStore {
}
self.disk.reused(key);
self.stats.fetched += 1;
let tier = if inbound.disk_started.is_some() {
let tier = if inbound.used_disk {
crate::Tier::Nvme
} else {
crate::Tier::Dram
Expand Down Expand Up @@ -1275,6 +1272,16 @@ impl HostStore for CompositeStore {
}
let short = self.memory.shortfall(needed);
if short > 0 && short > self.spillable_slots() {
if let Some(parent) = &parent
&& (self.outbound.contains_key(parent) || self.unwritten_ancestor(parent).is_some())
{
let root = self.unwritten_ancestor(parent).unwrap_or(*parent);
if self.parked.get(&root).is_some_and(|p| !p.writing) {
let _ = self.spill(root);
}
self.stats.store_skipped += 1;
return Ok(StoreOutcome::Retry(StoreReason::Inflight));
}
let result = self.disk.store(checkpoint);
match &result {
Ok(outcome) if *outcome != StoreOutcome::Queued => self.stats.store_skipped += 1,
Expand Down Expand Up @@ -1393,6 +1400,7 @@ impl HostStore for CompositeStore {
disk_pinned: Vec::new(),
reads: 0,
disk_started: None,
used_disk: false,
disk_bytes: 0,
error: None,
uploading: false,
Expand Down
89 changes: 60 additions & 29 deletions selene/src/disk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1165,10 +1165,12 @@ impl Worker {
self.faults.checkpoint("before_rename");
fs::rename(temporary, path)
.map_err(|e| io_failure(format!("rename record {}", path.display()), e))?;
#[cfg(not(windows))]
if sync {
File::open(path.parent().unwrap())
.and_then(|f| f.sync_all())
.map_err(|e| io_failure("sync record directory", e))?;
if let Err(error) = File::open(path.parent().unwrap()).and_then(|f| f.sync_all()) {
let _ = fs::remove_file(path);
return Err(io_failure("sync record directory", error));
}
}
#[cfg(any(test, feature = "test-support"))]
self.faults.checkpoint("after_rename");
Expand Down Expand Up @@ -1525,14 +1527,17 @@ fn direct_open_failure(action: &str, path: &Path, error: io::Error) -> Error {
#[cfg(target_os = "linux")]
fn preallocate(file: &File, length: u64) -> io::Result<()> {
use std::os::fd::AsRawFd;
// SAFETY: The descriptor is open for the call.
if unsafe { libc::fallocate(file.as_raw_fd(), 0, 0, length as libc::off_t) } == 0 {
return Ok(());
}
let error = io::Error::last_os_error();
match error.raw_os_error() {
Some(libc::EOPNOTSUPP | libc::ENOSYS) => Ok(()),
_ => Err(error),
loop {
// SAFETY: The descriptor is open for the call.
if unsafe { libc::fallocate(file.as_raw_fd(), 0, 0, length as libc::off_t) } == 0 {
return Ok(());
}
let error = io::Error::last_os_error();
match error.raw_os_error() {
Some(libc::EINTR) => continue,
Some(libc::EOPNOTSUPP | libc::ENOSYS) => return Ok(()),
_ => return Err(error),
}
}
}

Expand Down Expand Up @@ -1684,13 +1689,22 @@ impl Ring {
index: 0,
done: 0,
};
let mut retries = std::collections::VecDeque::new();
let mut pending = chunks.next();
let mut moved = 0u64;
let mut failure: Option<Error> = None;
loop {
while failure.is_none() {
let Some(chunk) = pending else { break };
let Some(slot) = self.free.pop() else { break };
let Some(chunk) = retries.pop_front().or_else(|| pending.take()) else {
break;
};
if pending.is_none() {
pending = chunks.next();
}
let Some(slot) = self.free.pop() else {
retries.push_front(chunk);
break;
};
let entry = if write {
opcode::Write::new(fd, chunk.address as *const u8, chunk.length)
.offset(chunk.offset)
Expand Down Expand Up @@ -1721,9 +1735,10 @@ impl Ring {
{
self.submitted_chunks += 1;
}
pending = chunks.next();
}
if self.free.len() == RING_DEPTH && (pending.is_none() || failure.is_some()) {
if self.free.len() == RING_DEPTH
&& ((retries.is_empty() && pending.is_none()) || failure.is_some())
{
break;
}
match self.ring.submit_and_wait(1) {
Expand All @@ -1736,7 +1751,11 @@ impl Ring {
let chunk = self.slots[slot];
self.free.push(slot);
let result = completion.result();
if result < 0 {
if result == -libc::EINTR {
if failure.is_none() {
retries.push_back(chunk);
}
} else if result < 0 {
failure.get_or_insert_with(|| {
io_failure(
format!(
Expand All @@ -1746,19 +1765,30 @@ impl Ring {
io::Error::from_raw_os_error(-result),
)
});
} else if (result as u64)
< required_end.map_or(u64::from(chunk.length), |end| {
} else {
let done = result as u64;
let needed = required_end.map_or(u64::from(chunk.length), |end| {
end.saturating_sub(chunk.offset).min(chunk.length.into())
})
{
failure.get_or_insert_with(|| {
invalid(format!(
"short direct {verb} of {result} bytes at file offset {}; {} were requested",
chunk.offset, chunk.length
))
});
} else {
moved += result as u64;
if done >= needed {
moved += done;
} else if done > 0 && done.is_multiple_of(BLOCK_BYTES) {
moved += done;
if failure.is_none() {
retries.push_back(Chunk {
offset: chunk.offset + done,
address: chunk.address + done as usize,
length: chunk.length - result as u32,
});
}
} else {
failure.get_or_insert_with(|| {
invalid(format!(
"short direct {verb} of {result} bytes at file offset {}; {} were requested",
chunk.offset, chunk.length
))
});
}
}
}
}
Expand Down Expand Up @@ -3702,15 +3732,16 @@ mod tests {
assert_eq!(opened, committed_zero);
writer.close(JobId(11)).unwrap();

// File truncated after a valid header retries the header block and fails reading checksums.
// File truncated after a valid header retries the block-aligned remainder to confirm
// EOF, then falls back to reading the header block and fails reading checksums (4 chunks).
let truncated = directory.join("truncated.ckpt");
fs::write(&truncated, committed_multi.encode().unwrap()).unwrap();
writer.ring.submitted_chunks = 0;
let err = writer
.open(JobId(12), truncated, multi_header)
.unwrap_err();
assert!(err.to_string().contains("short direct read"), "{err}");
assert_eq!(writer.ring.submitted_chunks, 3);
assert_eq!(writer.ring.submitted_chunks, 4);

drop(writer);
fs::remove_dir_all(directory).unwrap();
Expand Down
38 changes: 30 additions & 8 deletions selene/src/disk_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2088,6 +2088,8 @@ struct Reclaim {
/// The compacted record, for a truncate; `None` for an unlink.
key: Option<PrefixKey>,
bytes: u64,
/// Set if the compacted record was subsequently unlinked before truncate finished.
unlinked: bool,
}

pub struct DiskStore {
Expand Down Expand Up @@ -2153,10 +2155,13 @@ impl DiskStore {
let receive_profiles = transport.codec_receive_profiles();
let can_read = |record: &Scanned| match &record.header.packed {
None => true,
Some(layout) => layout
.required_profiles(record.row)
.iter()
.all(|p| receive_profiles.iter().any(|r| r.as_slice() == p.as_slice())),
Some(layout) => {
!receive_profiles.is_empty()
&& layout
.required_profiles(record.row)
.iter()
.all(|p| receive_profiles.iter().any(|r| r.as_slice() == p.as_slice()))
}
};
let scanned = if scanned.iter().any(|record| !can_read(record)) {
let mut kept = Vec::with_capacity(scanned.len());
Expand Down Expand Up @@ -2403,7 +2408,7 @@ impl DiskStore {
fn reclaim_inputs(&mut self) {
let pressure = self.budget.as_ref().map_or(0, |b| b.checkpoint_pressure());
if pressure != 0 {
let _ = self.make_room(pressure);
let _ = self.make_room_inner(pressure, false);
}
}

Expand Down Expand Up @@ -2894,6 +2899,10 @@ impl DiskStore {
/// evictable remains, and false before evicting anything when `bytes`
/// alone exceed the limit.
fn make_room(&mut self, bytes: u64) -> Result<bool> {
self.make_room_inner(bytes, true)
}

fn make_room_inner(&mut self, bytes: u64, request_input_reclaim: bool) -> Result<bool> {
if bytes > self.limit {
return Ok(false);
}
Expand Down Expand Up @@ -2928,7 +2937,9 @@ impl DiskStore {
self.compact(&key)?;
}
None => {
if let Some(budget) = &self.budget {
if request_input_reclaim
&& let Some(budget) = &self.budget
{
budget.request_input_reclaim(bytes);
}
return Ok(false);
Expand Down Expand Up @@ -3064,12 +3075,18 @@ impl DiskStore {
if node.location.bytes == 0 {
return Ok(());
}
for pending in self.maintenance.values_mut() {
if pending.key == Some(node.key) {
pending.unlinked = true;
}
}
let id = self.next_job();
self.maintenance.insert(
id,
Reclaim {
key: None,
bytes: node.location.bytes,
unlinked: false,
},
);
self.sync_budget();
Expand Down Expand Up @@ -3116,6 +3133,7 @@ impl DiskStore {
Reclaim {
key: Some(*key),
bytes: freed,
unlinked: false,
},
);
self.sync_budget();
Expand Down Expand Up @@ -3295,8 +3313,12 @@ impl DiskStore {
let Some(reclaim) = self.maintenance.remove(&id) else {
return;
};
let Reclaim { key, bytes } = reclaim;
if result.is_ok() {
let Reclaim {
key,
bytes,
unlinked,
} = reclaim;
if result.is_ok() || unlinked {
self.sync_budget();
return;
}
Expand Down
23 changes: 19 additions & 4 deletions selene/src/geometry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,11 @@ impl CacheGeometry {
"cache geometry requires nonempty planes and capacities",
));
}
if padded_bytes(self.row.unit_bytes).is_none()
|| self.planes.iter().any(|p| padded_bytes(p.unit_bytes).is_none())
{
return Err(invalid("cache geometry plane padded byte length overflow"));
}
Ok(())
}
}
Expand Down Expand Up @@ -162,10 +167,14 @@ impl Layout {
return Err(invalid("ranks disagree on page token count"));
}
let mut plane_offsets = Vec::with_capacity(rank.planes.len());
let mut offset = 0;
let mut offset = 0u64;
for plane in &rank.planes {
plane_offsets.push(offset);
offset += plane.padded_bytes();
let padded = padded_bytes(plane.unit_bytes)
.ok_or_else(|| invalid("plane padded byte length overflow"))?;
offset = offset
.checked_add(padded)
.ok_or_else(|| invalid("rank page byte length overflow"))?;
}
ranks.push(RankLayout {
page_offset: page_record_bytes,
Expand All @@ -174,8 +183,14 @@ impl Layout {
row_bytes: rank.row.unit_bytes,
row_offset: row_record_bytes,
});
page_record_bytes += offset;
row_record_bytes += rank.row_record_bytes();
page_record_bytes = page_record_bytes
.checked_add(offset)
.ok_or_else(|| invalid("page record byte length overflow"))?;
let rank_row = padded_bytes(rank.row.unit_bytes)
.ok_or_else(|| invalid("row padded byte length overflow"))?;
row_record_bytes = row_record_bytes
.checked_add(rank_row)
.ok_or_else(|| invalid("row record byte length overflow"))?;
}
Ok(Self {
page_tokens: first.page_tokens,
Expand Down
Loading
Loading