test: cover STRA-8 I/O failure closures
Linux / verify (pull_request) Successful in 2m8s
Linux / changed-scope-coverage (pull_request) Skipped
Linux / keyless-cuda (pull_request) Skipped
Linux / hosted-cuda-package (pull_request) Skipped
Linux / linux-cli-container (pull_request) Successful in 1m50s
Linux / linux-static-cli (pull_request) Successful in 5m35s
Linux / release-cli (pull_request) Skipped

This commit is contained in:
Pavlo Ratushnyi
2026-10-07 03:49:04 +02:00
parent 4cb41467dd
commit 3253c8fc36
3 changed files with 649 additions and 62 deletions
+43
View File
@@ -563,6 +563,49 @@ mod tests {
assert!(!path.exists());
}
fn assert_slice_reader_destination_error(root: &Path, calibration: &kar_codec::Calibration) {
let path = root.join("slice-occupied.section");
fs::write(&path, b"keep existing bytes").unwrap();
let bytes = vec![0u8; 128];
let mut source = Cursor::new(bytes.as_slice());
let request = section_request(&path, calibration);
let result = encode_section_with_set_len(&mut source, &request, File::set_len);
assert!(result.is_err());
assert_eq!(fs::read(path).unwrap(), b"keep existing bytes");
}
fn assert_slice_reader_set_len_error(root: &Path, calibration: &kar_codec::Calibration) {
let path = root.join("slice-cannot-size.section");
let bytes = vec![0u8; 128];
let mut source = Cursor::new(bytes.as_slice());
let request = section_request(&path, calibration);
assert!(encode_section_with_set_len(&mut source, &request, reject_section_size).is_err());
assert!(!path.exists());
}
fn section_request<'a>(
destination: &'a Path,
calibration: &'a kar_codec::Calibration,
) -> SectionRequest<'a> {
SectionRequest {
absolute_offset: 0,
source_kind: 0,
source_bytes: 128,
elements: 32,
calibration,
destination,
}
}
#[test]
fn borrowed_slice_reader_preserves_destination_and_cleans_sizing_failure() {
let root = test_dir("slice-reader-errors");
let calibration = test_calibration();
assert_slice_reader_destination_error(&root, &calibration);
assert_slice_reader_set_len_error(&root, &calibration);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn section_encoder_accepts_borrowed_and_file_readers() {
let root = test_dir("reader-types");
+381 -33
View File
@@ -286,8 +286,21 @@ pub(crate) fn canonical_archive_destination(destination: &Path) -> Result<PathBu
#[cfg(unix)]
fn validate_private_archive_parent(parent: &Path) -> Result<(), String> {
let uid = unsafe { libc::geteuid() };
validate_private_archive_parent_with(parent, uid, archive_symlink_metadata)
}
fn archive_symlink_metadata(path: &Path) -> io::Result<fs::Metadata> {
fs::symlink_metadata(path)
}
#[cfg(unix)]
fn validate_private_archive_parent_with(
parent: &Path,
uid: u32,
metadata: fn(&Path) -> io::Result<fs::Metadata>,
) -> Result<(), String> {
for directory in parent.ancestors().collect::<Vec<_>>().into_iter().rev() {
let metadata = fs::symlink_metadata(directory).map_err(|error| error.to_string())?;
let metadata = metadata(directory).map_err(|error| error.to_string())?;
// The caller passes a canonicalized parent, so every ancestor is a directory.
if !archive_parent_owner_allowed(metadata.uid(), uid) {
return Err("KAR parent is not owned by the service or root".into());
@@ -374,11 +387,23 @@ fn archive_temp_metadata_matches(
}
fn remove_archive_temp_locked(path: &Path, file: &File) -> Result<(), String> {
remove_archive_temp_locked_with(path, file, archive_remove_file)
}
fn archive_remove_file(path: &Path) -> io::Result<()> {
fs::remove_file(path)
}
fn remove_archive_temp_locked_with(
path: &Path,
file: &File,
remove: fn(&Path) -> io::Result<()>,
) -> Result<(), String> {
let path = private_archive_destination(path)?;
if !archive_temp_path_matches(&path, file) {
return Ok(());
}
fs::remove_file(path).map_err(|error| error.to_string())
remove(&path).map_err(|error| error.to_string())
}
fn archive_temp_options() -> OpenOptions {
@@ -397,16 +422,43 @@ fn archive_temp_path(destination: &Path, slot: u8) -> PathBuf {
}
fn reap_stale_archive_temps(destination: &Path) -> Result<(), String> {
reap_stale_archive_temps_with(destination, archive_read_dir)
}
fn archive_read_dir(path: &Path) -> io::Result<fs::ReadDir> {
fs::read_dir(path)
}
#[cfg(unix)]
fn reap_stale_archive_temps_with(
destination: &Path,
read_directory: fn(&Path) -> io::Result<fs::ReadDir>,
) -> Result<(), String> {
let destination = private_archive_destination(destination)?;
#[cfg(unix)]
{
let parent = destination.parent().unwrap_or_else(|| Path::new("."));
for entry in fs::read_dir(parent).map_err(|error| error.to_string())? {
reap_archive_temp_entry(&destination, entry.map_err(|error| error.to_string())?)?;
}
let parent = destination
.parent()
.expect("canonical archive destination always has a parent");
let entries = read_directory(parent).map_err(|error| error.to_string())?;
reap_archive_temp_entries(&destination, entries)
}
#[cfg(not(unix))]
fn reap_stale_archive_temps_with(
destination: &Path,
_read_directory: fn(&Path) -> io::Result<fs::ReadDir>,
) -> Result<(), String> {
let _ = private_archive_destination(destination)?;
Ok(())
}
#[cfg(unix)]
fn reap_archive_temp_entries(
destination: &Path,
entries: impl IntoIterator<Item = io::Result<fs::DirEntry>>,
) -> Result<(), String> {
for entry in entries {
reap_archive_temp_entry(destination, entry.map_err(|error| error.to_string())?)?;
}
#[cfg(not(unix))]
let _ = &destination;
Ok(())
}
@@ -514,6 +566,7 @@ fn unlink_if_same_archive_temp(
#[cfg(unix)]
#[derive(Clone, Copy)]
struct ArchiveTempPathOps {
opened_metadata: fn(&File) -> io::Result<fs::Metadata>,
metadata: fn(&Path) -> io::Result<fs::Metadata>,
remove: fn(&Path) -> io::Result<()>,
}
@@ -522,6 +575,7 @@ struct ArchiveTempPathOps {
impl ArchiveTempPathOps {
fn system() -> Self {
Self {
opened_metadata: File::metadata,
metadata: archive_temp_symlink_metadata,
remove: archive_temp_remove_file,
}
@@ -547,7 +601,7 @@ fn unlink_if_same_archive_temp_with(
operations: ArchiveTempPathOps,
) -> Result<(), String> {
let (path, destination) = private_archive_pair(path, destination)?;
let opened = file.metadata().map_err(|error| error.to_string())?;
let opened = (operations.opened_metadata)(file).map_err(|error| error.to_string())?;
let current = match (operations.metadata)(&path) {
Ok(meta) => meta,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
@@ -1332,6 +1386,14 @@ fn verify_nested_spool(
fn verify_nested_spool_reader<R: Read + Seek>(
file: &mut R,
plan: &NestedSectionPlan<'_>,
) -> Result<SectionSummary, String> {
verify_nested_spool_reader_with_seek(file, plan, Seek::seek)
}
fn verify_nested_spool_reader_with_seek<R: Read + Seek>(
file: &mut R,
plan: &NestedSectionPlan<'_>,
seek: fn(&mut R, SeekFrom) -> io::Result<u64>,
) -> Result<SectionSummary, String> {
validate_nested_file(
file,
@@ -1342,8 +1404,7 @@ fn verify_nested_spool_reader<R: Read + Seek>(
levels: plan.levels,
},
)?;
file.seek(SeekFrom::Start(0))
.map_err(|error| error.to_string())?;
seek(file, SeekFrom::Start(0)).map_err(|error| error.to_string())?;
let digest = hash_reader(file)?;
Ok(SectionSummary {
bytes: plan.layout.section_bytes,
@@ -1765,6 +1826,15 @@ fn copy_nested_file_from<R: Read + Seek>(
state: &mut SectionWriteState<'_>,
request: NestedFileCopy<'_, '_, '_>,
source: &mut R,
) -> Result<(), String> {
copy_nested_file_from_with_seek(state, request, source, Seek::seek)
}
fn copy_nested_file_from_with_seek<R: Read + Seek>(
state: &mut SectionWriteState<'_>,
request: NestedFileCopy<'_, '_, '_>,
source: &mut R,
seek: fn(&mut R, SeekFrom) -> io::Result<u64>,
) -> Result<(), String> {
validate_nested_file(
source,
@@ -1775,7 +1845,7 @@ fn copy_nested_file_from<R: Read + Seek>(
levels: request.levels,
},
)?;
seek_source_offset(source, request.offset).map_err(|error| error.to_string())?;
seek(source, SeekFrom::Start(request.offset)).map_err(|error| error.to_string())?;
let actual = copy_region(state, source, request.bytes)?;
if actual.as_slice() != request.digest {
return Err(format!(
@@ -1787,20 +1857,48 @@ fn copy_nested_file_from<R: Read + Seek>(
}
fn open_source_region(path: &Path, offset: u64, bytes: u64, label: &str) -> Result<File, String> {
let mut source = File::open(path).map_err(|error| error.to_string())?;
open_source_region_with(path, offset, bytes, label, SourceRegionOps::system())
}
struct SourceRegionOps {
open: fn(&Path) -> io::Result<File>,
metadata: fn(&File) -> io::Result<fs::Metadata>,
seek: fn(&mut File, SeekFrom) -> io::Result<u64>,
}
impl SourceRegionOps {
fn system() -> Self {
Self {
open: open_archive_source_file,
metadata: File::metadata,
seek: Seek::seek,
}
}
}
fn open_archive_source_file(path: &Path) -> io::Result<File> {
File::open(path)
}
fn open_source_region_with(
path: &Path,
offset: u64,
bytes: u64,
label: &str,
operations: SourceRegionOps,
) -> Result<File, String> {
let mut source = (operations.open)(path).map_err(|error| error.to_string())?;
let end = offset.checked_add(bytes);
let source_len = source.metadata().map_err(|error| error.to_string())?.len();
let source_len = (operations.metadata)(&source)
.map_err(|error| error.to_string())?
.len();
if end.is_none_or(|end| end > source_len) {
return Err(format!("{label} source file is truncated"));
}
seek_source_offset(&mut source, offset).map_err(|error| error.to_string())?;
(operations.seek)(&mut source, SeekFrom::Start(offset)).map_err(|error| error.to_string())?;
Ok(source)
}
fn seek_source_offset(source: &mut impl Seek, offset: u64) -> io::Result<()> {
source.seek(SeekFrom::Start(offset)).map(|_| ())
}
fn copy_region<R: Read>(
state: &mut SectionWriteState<'_>,
source: &mut R,
@@ -2000,16 +2098,23 @@ fn check_file_region(
bytes: u64,
rule: RegionRule,
) -> Result<(), String> {
source
.seek(SeekFrom::Start(offset))
.map_err(|error| error.to_string())?;
check_file_region_with(source, offset, bytes, rule, Seek::seek, Read::read_exact)
}
fn check_file_region_with<R: Read + Seek>(
source: &mut R,
offset: u64,
bytes: u64,
rule: RegionRule,
seek: fn(&mut R, SeekFrom) -> io::Result<u64>,
read_exact: fn(&mut R, &mut [u8]) -> io::Result<()>,
) -> Result<(), String> {
seek(source, SeekFrom::Start(offset)).map_err(|error| error.to_string())?;
let mut remaining = bytes;
let mut buffer = [0u8; 64 * 1024];
while remaining > 0 {
let count = remaining.min(buffer.len() as u64) as usize;
source
.read_exact(&mut buffer[..count])
.map_err(|error| error.to_string())?;
read_exact(source, &mut buffer[..count]).map_err(|error| error.to_string())?;
validate_region_chunk(&buffer[..count], rule)?;
remaining -= count as u64;
}
@@ -2226,6 +2331,8 @@ mod tests {
inner: std::io::Cursor<Vec<u8>>,
fail_seek_at: Option<usize>,
seeks: usize,
fail_read_at: Option<usize>,
reads: usize,
}
impl FaultReadSeek {
@@ -2234,12 +2341,18 @@ mod tests {
inner: std::io::Cursor::new(bytes),
fail_seek_at: None,
seeks: 0,
fail_read_at: None,
reads: 0,
}
}
}
impl Read for FaultReadSeek {
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
self.reads += 1;
if self.fail_read_at == Some(self.reads) {
return Err(io::ErrorKind::Other.into());
}
self.inner.read(buffer)
}
}
@@ -2440,6 +2553,14 @@ mod tests {
fs::remove_dir_all(root).unwrap();
}
#[cfg(unix)]
#[test]
fn private_archive_parent_propagates_metadata_errors() {
let root = test_dir("private-parent-metadata-error");
assert!(validate_private_archive_parent_with(&root, 0, denied_temp_metadata).is_err());
fs::remove_dir_all(root).unwrap();
}
#[cfg(unix)]
#[test]
fn archive_parent_owner_policy_accepts_root_and_service_only() {
@@ -2709,11 +2830,21 @@ mod tests {
let root = test_dir("temp-unlink-io-errors");
let destination = root.join("archive.kar");
assert_temp_unlink_metadata_error(&destination);
assert_temp_unlink_opened_metadata_error(&destination);
assert_temp_unlink_remove_error(&destination);
assert_locked_temp_remove_error(&destination);
assert!(archive_temp_path(&destination, 0).exists());
fs::remove_dir_all(root).unwrap();
}
#[cfg(unix)]
fn assert_locked_temp_remove_error(destination: &Path) {
let (path, file, _) = locked_archive_temp(destination);
assert!(remove_archive_temp_locked_with(&path, &file, denied_temp_remove).is_err());
assert!(path.exists());
drop(file);
}
#[cfg(unix)]
fn locked_archive_temp(destination: &Path) -> (PathBuf, File, fs::Metadata) {
let path = archive_temp_path(destination, 0);
@@ -2738,6 +2869,7 @@ mod tests {
&before,
&file,
ArchiveTempPathOps {
opened_metadata: File::metadata,
metadata: denied_temp_metadata,
remove: archive_temp_remove_file
},
@@ -2747,6 +2879,21 @@ mod tests {
drop(file);
}
#[cfg(unix)]
fn assert_temp_unlink_opened_metadata_error(destination: &Path) {
let (path, file, before) = locked_archive_temp(destination);
let operations = ArchiveTempPathOps {
opened_metadata: denied_opened_metadata,
metadata: archive_temp_symlink_metadata,
remove: archive_temp_remove_file,
};
assert!(
unlink_if_same_archive_temp_with(&path, destination, &before, &file, operations)
.is_err()
);
drop(file);
}
#[cfg(unix)]
fn assert_temp_unlink_remove_error(destination: &Path) {
let (path, file, before) = locked_archive_temp(destination);
@@ -2757,6 +2904,7 @@ mod tests {
&before,
&file,
ArchiveTempPathOps {
opened_metadata: File::metadata,
metadata: archive_temp_symlink_metadata,
remove: denied_temp_remove
},
@@ -2771,6 +2919,11 @@ mod tests {
Err(io::ErrorKind::PermissionDenied.into())
}
#[cfg(unix)]
fn denied_opened_metadata(_: &File) -> io::Result<fs::Metadata> {
Err(io::ErrorKind::PermissionDenied.into())
}
#[cfg(unix)]
fn denied_temp_remove(_: &Path) -> io::Result<()> {
Err(io::ErrorKind::PermissionDenied.into())
@@ -3255,6 +3408,22 @@ mod tests {
assert!(create_archive_temp(&missing).is_err());
}
#[cfg(unix)]
#[test]
fn stale_archive_reaper_reports_directory_and_entry_errors() {
let root = test_dir("stale-reaper-errors");
let destination = root.join("archive.kar");
assert!(reap_stale_archive_temps_with(&destination, denied_directory_read).is_err());
let entries = std::iter::once(Err(io::ErrorKind::PermissionDenied.into()));
assert!(reap_archive_temp_entries(&destination, entries).is_err());
fs::remove_dir_all(root).unwrap();
}
#[cfg(unix)]
fn denied_directory_read(_: &Path) -> io::Result<fs::ReadDir> {
Err(io::ErrorKind::PermissionDenied.into())
}
#[test]
fn source_region_and_hash_reader_fail_on_short_or_unreadable_inputs() {
let root = test_dir("source-region-errors");
@@ -3267,6 +3436,53 @@ mod tests {
fs::remove_dir_all(root).unwrap();
}
#[cfg(unix)]
#[test]
fn source_region_propagates_metadata_and_seek_errors() {
let root = test_dir("source-region-ops");
let path = root.join("source.bin");
fs::write(&path, [0u8; 4]).unwrap();
assert!(
open_source_region_with(
&path,
0,
1,
"test",
SourceRegionOps {
metadata: denied_opened_metadata,
..SourceRegionOps::system()
}
)
.is_err()
);
assert!(
open_source_region_with(
&path,
0,
1,
"test",
SourceRegionOps {
seek: reject_seek::<File>,
..SourceRegionOps::system()
}
)
.is_err()
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn read_faults_propagate_through_hash_and_region_copy() {
let mut hashing = FaultReadSeek::new(vec![1]);
hashing.fail_read_at = Some(1);
assert!(hash_reader(&mut hashing).is_err());
let mut source = FaultReadSeek::new(vec![1]);
source.fail_read_at = Some(1);
let mut output = FaultArchiveOutput::default();
let mut state = SectionWriteState::new(&mut output);
assert!(copy_region(&mut state, &mut source, 1).is_err());
}
#[test]
fn oversized_section_padding_is_rejected() {
let root = test_dir("padding-overflow");
@@ -3394,6 +3610,50 @@ mod tests {
assert!(check_file_region(&mut source, 0, 0, RegionRule::ZeroPadding).is_err());
}
#[test]
fn file_backed_region_check_propagates_seek_and_read_errors() {
let root = test_dir("region-file-errors");
let path = root.join("region.bin");
fs::write(&path, [0u8; 4]).unwrap();
assert_file_region_seek_error(&path);
assert_file_region_read_error(&path);
fs::remove_dir_all(root).unwrap();
}
fn assert_file_region_seek_error(path: &Path) {
let mut source = File::open(path).unwrap();
assert!(
check_file_region_with(
&mut source,
0,
0,
RegionRule::ZeroPadding,
reject_seek::<File>,
Read::read_exact
)
.is_err()
);
}
fn assert_file_region_read_error(path: &Path) {
let mut source = File::open(path).unwrap();
assert!(
check_file_region_with(
&mut source,
0,
1,
RegionRule::ZeroPadding,
Seek::seek,
reject_read::<File>
)
.is_err()
);
}
fn reject_read<R: Read>(_: &mut R, _: &mut [u8]) -> io::Result<()> {
Err(io::ErrorKind::Other.into())
}
#[test]
fn nested_spool_and_copy_propagate_post_validation_seek_failures() {
let input = reference_input();
@@ -3408,6 +3668,41 @@ mod tests {
fs::remove_dir_all(root).unwrap();
}
#[test]
fn file_backed_nested_readers_propagate_post_validation_seek_errors() {
let root = test_dir("nested-file-seek-errors");
let input = reference_input();
let tensors = reference_tensors(&input);
let plan = NestedSectionPlan::new(&tensors[1]).unwrap();
let spool = root.join("nested.spool");
write_nested_section(&spool, &tensors[1]).unwrap();
assert_file_spool_verify_seek_error(&spool, &plan);
assert_file_spool_copy_seek_error(&spool, &plan);
fs::remove_dir_all(root).unwrap();
}
fn assert_file_spool_verify_seek_error(path: &Path, plan: &NestedSectionPlan<'_>) {
let mut file = File::open(path).unwrap();
assert!(
verify_nested_spool_reader_with_seek(&mut file, plan, reject_seek::<File>).is_err()
);
}
fn assert_file_spool_copy_seek_error(path: &Path, plan: &NestedSectionPlan<'_>) {
let mut source = File::open(path).unwrap();
let mut output = FaultArchiveOutput::default();
let mut state = SectionWriteState::new(&mut output);
let request = nested_file_copy(path, plan, &[0; 32]);
assert!(
copy_nested_file_from_with_seek(&mut state, request, &mut source, reject_seek::<File>)
.is_err()
);
}
fn reject_seek<R: Seek>(_: &mut R, _: SeekFrom) -> io::Result<u64> {
Err(io::ErrorKind::Other.into())
}
fn verify_nested_spool_seek_paths(
bytes: &[u8],
plan: &NestedSectionPlan<'_>,
@@ -3624,14 +3919,16 @@ mod tests {
let tensors = reference_tensors(&input);
let mut plan = ArchivePlan::build(&source, &tensors).unwrap();
let root = test_dir("archive-plan-file-errors");
for operation in [
ArchiveOutputOperation::SetLength,
ArchiveOutputOperation::Length,
ArchiveOutputOperation::Seek,
ArchiveOutputOperation::Write,
for (operation, call) in [
(ArchiveOutputOperation::SetLength, 1),
(ArchiveOutputOperation::Length, 1),
(ArchiveOutputOperation::Seek, 1),
(ArchiveOutputOperation::Seek, 2),
(ArchiveOutputOperation::Write, 1),
(ArchiveOutputOperation::Write, 2),
] {
let mut output = File::create(root.join("archive.part")).unwrap();
fail_archive_output_at(operation, 1);
fail_archive_output_at(operation, call);
assert!(plan.write(&mut output, &source, &tensors, false).is_err());
}
fs::remove_dir_all(root).unwrap();
@@ -3740,6 +4037,33 @@ mod tests {
assert_eq!(output.archive_len().unwrap(), plan.layout.section_bytes);
}
#[test]
fn file_backed_nested_spool_cleans_length_and_sync_failures() {
let root = test_dir("nested-spool-file-errors");
let input = reference_input();
let tensors = reference_tensors(&input);
let plan = NestedSectionPlan::new(&tensors[1]).unwrap();
for (name, operation) in [
("length", ArchiveOutputOperation::Length),
("sync", ArchiveOutputOperation::Sync),
] {
assert_file_nested_spool_failure(&root, name, operation, &plan);
}
fs::remove_dir_all(root).unwrap();
}
fn assert_file_nested_spool_failure(
root: &Path,
name: &str,
operation: ArchiveOutputOperation,
plan: &NestedSectionPlan<'_>,
) {
let path = root.join(format!("{name}.spool"));
fail_archive_output_at(operation, 1);
assert!(write_nested_spool(&path, plan).is_err());
assert!(!path.exists());
}
#[test]
fn payload_writer_propagates_archive_length_metadata_error() {
let input = reference_input();
@@ -4036,6 +4360,30 @@ mod tests {
fs::remove_dir_all(root).unwrap();
}
#[cfg(unix)]
#[test]
fn archive_temp_name_parser_handles_non_utf8_and_invalid_destination() {
use std::os::unix::ffi::OsStrExt;
let destination = Path::new("/");
assert!(archive_temp_path(destination, 0).file_name().is_some());
assert!(!is_archive_temp_name(
destination,
std::ffi::OsStr::new("other")
));
assert!(!is_archive_temp_name(
destination,
std::ffi::OsStr::from_bytes(&[0xff])
));
}
#[test]
fn archive_temp_removal_reports_a_missing_staging_file() {
let root = test_dir("remove-missing-temp");
assert!(remove_archive_temp(&root.join("missing.part")).is_err());
fs::remove_dir_all(root).unwrap();
}
#[cfg(unix)]
#[test]
fn failed_writer_cleanup_holds_lock_across_reaper_and_slot_reuse() {
+225 -29
View File
@@ -437,11 +437,23 @@ fn prepare_shard_tensors(
fn prepare_one_shard(
request: ShardedShardRequest<'_>,
state: &mut ShardedPrepareState,
) -> Result<(), String> {
prepare_one_shard_with_open(request, state, open_shard_file)
}
fn open_shard_file(path: &Path) -> std::io::Result<File> {
File::open(path)
}
fn prepare_one_shard_with_open(
request: ShardedShardRequest<'_>,
state: &mut ShardedPrepareState,
open: fn(&Path) -> std::io::Result<File>,
) -> Result<(), String> {
let path = request.source_dir.join(&request.shard.name);
let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?;
check_shard_index(&index, request.shard, &mut state.architecture)?;
let mut source = File::open(&path).map_err(|error| error.to_string())?;
let mut source = open(&path).map_err(|error| error.to_string())?;
prepare_shard_records(&request, &index, &mut source, state)?;
verify_prepared_shard(&path, request.shard, &source)
}
@@ -596,9 +608,17 @@ fn verify_prepared_shard(
shard: &derived_mixed::ShardIdentity,
source: &File,
) -> Result<(), String> {
if source.metadata().map_err(|error| error.to_string())?.len() != shard.gguf_bytes
|| hash_file(path)? != shard.gguf_sha256
{
verify_shard_file_metadata(path, shard, source, File::metadata)
}
fn verify_shard_file_metadata(
path: &Path,
shard: &derived_mixed::ShardIdentity,
source: &File,
metadata: fn(&File) -> std::io::Result<fs::Metadata>,
) -> Result<(), String> {
let length = metadata(source).map_err(|error| error.to_string())?.len();
if length != shard.gguf_bytes || hash_file(path)? != shard.gguf_sha256 {
return Err(format!(
"{}: GGUF shard changed during preparation",
shard.name
@@ -1020,7 +1040,7 @@ impl<'a> StreamPreparation<'a> {
}
fn prepare_shard(&mut self, shard: &derived_mixed::ShardIdentity) -> Result<(), String> {
self.prepare_shard_with_open(shard, |path| File::open(path))
self.prepare_shard_with_open(shard, open_shard_file)
}
fn prepare_shard_with_open(
@@ -1138,15 +1158,7 @@ impl<'a> StreamPreparation<'a> {
path: &Path,
source: &File,
) -> Result<(), String> {
if source.metadata().map_err(|error| error.to_string())?.len() != shard.gguf_bytes
|| hash_file(path)? != shard.gguf_sha256
{
return Err(format!(
"{}: GGUF shard changed during preparation",
shard.name
));
}
Ok(())
verify_shard_file_metadata(path, shard, source, File::metadata)
}
fn publish(self) -> Result<PreviewSummary, String> {
@@ -1408,6 +1420,7 @@ fn streamed_builder(request: &StreamPrepareRequest<'_>) -> String {
}
}
#[derive(Clone, Copy)]
struct RawF32Spool<'a> {
absolute: u64,
source_kind: u32,
@@ -1432,25 +1445,32 @@ fn spool_raw_f32_with_sync<R: Read + Seek>(
.create_new(true)
.open(request.path)
.map_err(|error| error.to_string())?;
let result = (|| {
let mut writer = BufWriter::new(file);
let digests = write_raw_f32_chunks(
reader,
request.absolute,
request.source_kind,
request.source_bytes,
&mut writer,
)?;
writer.flush().map_err(|error| error.to_string())?;
sync(writer.get_ref()).map_err(|error| error.to_string())?;
Ok(digests)
})();
let mut writer = BufWriter::new(file);
let result = write_raw_f32_spool(reader, request, &mut writer, sync);
if result.is_err() {
let _ = fs::remove_file(request.path);
}
result
}
fn write_raw_f32_spool<R: Read + Seek>(
reader: &mut R,
request: RawF32Spool<'_>,
writer: &mut BufWriter<File>,
sync: fn(&File) -> std::io::Result<()>,
) -> Result<([u8; 32], [u8; 32], u64), String> {
let digests = write_raw_f32_chunks(
reader,
request.absolute,
request.source_kind,
request.source_bytes,
writer,
)?;
writer.flush().map_err(|error| error.to_string())?;
sync(writer.get_ref()).map_err(|error| error.to_string())?;
Ok(digests)
}
fn write_raw_f32_chunks<R: Read + Seek, W: Write>(
reader: &mut R,
absolute: u64,
@@ -1753,9 +1773,18 @@ fn verify_single_source_unchanged(
request: &SingleSourcePrepare<'_>,
index: &gguf::TensorIndex,
identity: &SingleSourceIdentity,
) -> Result<(), String> {
verify_single_source_with_metadata(request, index, identity, File::metadata)
}
fn verify_single_source_with_metadata(
request: &SingleSourcePrepare<'_>,
index: &gguf::TensorIndex,
identity: &SingleSourceIdentity,
metadata: fn(&File) -> std::io::Result<fs::Metadata>,
) -> Result<(), String> {
let source = File::open(request.source_path).map_err(|error| error.to_string())?;
if source.metadata().map_err(|error| error.to_string())?.len() != index.summary.file_size
if metadata(&source).map_err(|error| error.to_string())?.len() != index.summary.file_size
|| hash_file(request.source_path)? != identity.original_digest
{
return Err("GGUF source changed during F32 preparation".into());
@@ -2473,9 +2502,17 @@ fn write_provenance_contents_with_sync(
fn write_provenance_json<W: Write>(
writer: &mut W,
value: &serde_json::Value,
) -> Result<(), String> {
write_provenance_json_with_newline(writer, value, Write::write_all)
}
fn write_provenance_json_with_newline<W: Write>(
writer: &mut W,
value: &serde_json::Value,
write_newline: fn(&mut W, &[u8]) -> std::io::Result<()>,
) -> Result<(), String> {
serde_json::to_writer_pretty(&mut *writer, value).map_err(|error| error.to_string())?;
writer.write_all(b"\n").map_err(|error| error.to_string())
write_newline(writer, b"\n").map_err(|error| error.to_string())
}
fn hash_file(path: &Path) -> Result<[u8; 32], String> {
@@ -2956,6 +2993,30 @@ mod tests {
assert_changed_size_source_rejected(&request, &index, &identity);
}
#[test]
fn single_source_preparation_and_recheck_report_missing_source() {
let fixture = overlay_fixture();
let existing = fixture.directory.join("indexed-source.gguf");
let bytes = two_tensor_f32_gguf();
fs::write(&existing, &bytes).unwrap();
let index = gguf::tensor_index(&existing).unwrap();
let identity = single_source_identity_for(&existing, &index, &bytes);
let missing = fixture.directory.join("missing-source.gguf");
let request = single_source_request(&missing);
let staging = StagingDir(PathBuf::new());
assert!(prepare_single_source_tensors(&request, &index, &identity, &staging).is_err());
assert!(verify_single_source_unchanged(&request, &index, &identity).is_err());
}
fn single_source_request(source_path: &Path) -> SingleSourcePrepare<'_> {
SingleSourcePrepare {
source_path,
destination: Path::new("unused.kar"),
levels: 2,
kind: PreviewKind::F32,
}
}
#[test]
fn single_tensor_read_rejects_source_truncated_after_indexing() {
let fixture = overlay_fixture();
@@ -2994,6 +3055,49 @@ mod tests {
assert!(verify_prepared_shard(&path, &shard, &source).is_err());
}
#[test]
fn shard_verification_propagates_source_metadata_error() {
let fixture = overlay_fixture();
let path = fixture.directory.join("metadata-error.gguf");
fs::write(&path, b"valid indexed bytes").unwrap();
let source = File::open(&path).unwrap();
let shard = derived_mixed::ShardIdentity {
name: "metadata-error.gguf".into(),
gguf_sha256: hash_file(&path).unwrap(),
gguf_bytes: fs::metadata(&path).unwrap().len(),
tensor_count: 1,
};
assert!(verify_shard_file_metadata(&path, &shard, &source, reject_file_metadata).is_err());
}
#[test]
fn single_source_recheck_propagates_metadata_error() {
let fixture = overlay_fixture();
let path = fixture.directory.join("source-metadata-error.gguf");
fs::write(&path, b"source").unwrap();
let request = single_source_request(&path);
let identity = SingleSourceIdentity {
architecture: "fixture".into(),
source_name: "source.gguf".into(),
original_digest: [0; 32],
source_bytes: 6,
derived: None,
};
assert!(
verify_single_source_with_metadata(
&request,
&empty_tensor_index(),
&identity,
reject_file_metadata
)
.is_err()
);
}
fn reject_file_metadata(_: &File) -> std::io::Result<fs::Metadata> {
Err(std::io::ErrorKind::PermissionDenied.into())
}
#[test]
fn shard_index_rejects_architecture_count_and_size_drift() {
let fixture = overlay_fixture();
@@ -3215,6 +3319,14 @@ mod tests {
assert_oversized_single_source_rejected(&fixture.directory);
}
#[test]
fn single_source_index_reports_malformed_gguf() {
let path = preview_test_path("malformed-index", "gguf");
fs::write(&path, b"not a GGUF").unwrap();
assert!(load_single_source_index(&path).is_err());
fs::remove_file(path).unwrap();
}
#[test]
fn single_source_index_rejects_tensor_count_above_limit() {
let path = preview_test_path("too-many-tensors", "gguf");
@@ -3439,6 +3551,39 @@ mod tests {
assert!(result.is_err());
}
#[cfg(unix)]
#[test]
fn file_backed_raw_spool_reports_write_and_flush_errors() {
assert_raw_file_write_error();
assert_raw_file_flush_error();
}
#[cfg(unix)]
fn assert_raw_file_write_error() {
let Ok(file) = fs::OpenOptions::new().write(true).open("/dev/full") else {
return;
};
let mut writer = BufWriter::with_capacity(0, file);
let mut reader = std::io::Cursor::new(2.5f32.to_le_bytes());
assert!(write_raw_f32_chunks(&mut reader, 0, 0, 4, &mut writer).is_err());
}
#[cfg(unix)]
fn assert_raw_file_flush_error() {
let Ok(file) = fs::OpenOptions::new().write(true).open("/dev/full") else {
return;
};
let mut writer = BufWriter::new(file);
let mut reader = std::io::Cursor::new(2.5f32.to_le_bytes());
let request = RawF32Spool {
absolute: 0,
source_kind: 0,
source_bytes: 4,
path: Path::new("unused.raw"),
};
assert!(write_raw_f32_spool(&mut reader, request, &mut writer, File::sync_all).is_err());
}
fn reject_spool_sync(_: &File) -> std::io::Result<()> {
Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied))
}
@@ -3944,6 +4089,24 @@ mod tests {
assert_post_index_open_error(&mut preparation, &shard);
}
#[test]
fn legacy_shard_preparation_returns_source_open_error_after_indexing() {
let fixture = overlay_fixture();
let identity =
derived_mixed::fingerprint_shards(&fixture.manifest, &fixture.directory).unwrap();
let shard = &identity.shards[0];
let staging = StagingDir::create(&fixture.directory.join("legacy-open-error.kar")).unwrap();
let request = ShardedShardRequest {
identity: &identity,
shard,
source_dir: &fixture.directory,
staging: &staging,
levels: 2,
};
let mut state = ShardedPrepareState::new(identity.tensors.len());
assert!(prepare_one_shard_with_open(request, &mut state, reject_source_open).is_err());
}
fn assert_post_index_open_error(
preparation: &mut StreamPreparation<'_>,
shard: &derived_mixed::ShardIdentity,
@@ -3957,6 +4120,10 @@ mod tests {
);
}
fn reject_source_open(_: &Path) -> std::io::Result<File> {
Err(std::io::ErrorKind::PermissionDenied.into())
}
#[test]
fn streamed_staging_refuses_existing_directory_and_root_destination() {
let fixture = overlay_fixture();
@@ -4024,6 +4191,35 @@ mod tests {
assert!(write_provenance_json(&mut LimitedProvenanceWriter(size), &value).is_err());
}
#[test]
fn file_backed_provenance_writer_reports_json_and_newline_errors() {
let value = serde_json::json!({"source":"fixture"});
assert_file_provenance_newline_error(&value);
assert_file_provenance_json_error(&value);
}
fn assert_file_provenance_newline_error(value: &serde_json::Value) {
let root = overlay_fixture();
let path = root.directory.join("newline-error.json");
let mut file = File::create(&path).unwrap();
assert!(
write_provenance_json_with_newline(&mut file, value, reject_newline::<File>).is_err()
);
assert!(!fs::read(path).unwrap().ends_with(b"\n"));
}
fn reject_newline<W: Write>(_: &mut W, _: &[u8]) -> std::io::Result<()> {
Err(std::io::ErrorKind::PermissionDenied.into())
}
#[cfg(unix)]
fn assert_file_provenance_json_error(value: &serde_json::Value) {
let Ok(mut file) = fs::OpenOptions::new().write(true).open("/dev/full") else {
return;
};
assert!(write_provenance_json(&mut file, value).is_err());
}
fn reject_provenance_sync(_: &File) -> std::io::Result<()> {
Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied))
}