STRA-338 size-fn: strata-control: write_archive_inner split into plan, file and publish stages (fn>30 1 -> 0)
This commit is contained in:
@@ -100,6 +100,8 @@ enum RegionRule {
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
mod archive_file;
|
||||
mod archive_plan;
|
||||
mod write_archive;
|
||||
#[allow(unused_imports)]
|
||||
pub use write_archive::*;
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
//! Write stage of the KAR writer: sections, directory and header of a planned archive.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::archive_plan::Plan;
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
fn io_error(error: std::io::Error) -> String {
|
||||
error.to_string()
|
||||
}
|
||||
|
||||
pub(super) fn write_archive_file(
|
||||
file: &mut File,
|
||||
plan: &mut Plan<'_>,
|
||||
source: &SourceIdentity<'_>,
|
||||
consume_files: bool,
|
||||
) -> Result<(), String> {
|
||||
write_sections(file, plan, consume_files)?;
|
||||
let directory = write_directory(file, plan)?;
|
||||
write_header(file, plan, source, &directory)
|
||||
}
|
||||
|
||||
fn write_sections(file: &mut File, plan: &mut Plan<'_>, consume_files: bool) -> Result<(), String> {
|
||||
file.set_len(plan.payload_offset).map_err(io_error)?;
|
||||
file.seek(SeekFrom::Start(plan.string_offset))
|
||||
.map_err(io_error)?;
|
||||
file.write_all(&plan.names).map_err(io_error)?;
|
||||
for entry in &mut plan.placed {
|
||||
entry.payload_crc32 = write_section(file, entry)?;
|
||||
if consume_files {
|
||||
let path = match &entry.tensor.data {
|
||||
TensorData::RawFile { path, .. } | TensorData::NestedFile { path, .. } => path,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
fs::remove_file(path).map_err(io_error)?;
|
||||
}
|
||||
}
|
||||
if file.metadata().map_err(io_error)?.len() != plan.archive_bytes {
|
||||
return Err("KAR writer produced the wrong archive length".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_directory(file: &mut File, plan: &Plan<'_>) -> Result<Vec<u8>, String> {
|
||||
let mut directory = vec![0u8; plan.directory_bytes as usize];
|
||||
let (records, remainder) = directory.as_chunks_mut::<192>();
|
||||
debug_assert!(remainder.is_empty());
|
||||
for (entry, record) in plan.placed.iter().zip(records) {
|
||||
write_record(record, entry)?;
|
||||
}
|
||||
file.seek(SeekFrom::Start(plan.directory_offset))
|
||||
.map_err(io_error)?;
|
||||
file.write_all(&directory).map_err(io_error)?;
|
||||
Ok(directory)
|
||||
}
|
||||
|
||||
fn write_header(
|
||||
file: &mut File,
|
||||
plan: &Plan<'_>,
|
||||
source: &SourceIdentity<'_>,
|
||||
directory: &[u8],
|
||||
) -> Result<(), String> {
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(&plan.names);
|
||||
digest.update(directory);
|
||||
let mut header = [0u8; 256];
|
||||
fill_geometry(&mut header, plan);
|
||||
fill_identity(&mut header, plan, source);
|
||||
header[160..192].copy_from_slice(&digest.finalize());
|
||||
let header_crc = kar::crc32(&header[..192]);
|
||||
put_u32(&mut header, 192, header_crc);
|
||||
file.seek(SeekFrom::Start(0)).map_err(io_error)?;
|
||||
file.write_all(&header).map_err(io_error)?;
|
||||
file.sync_all().map_err(io_error)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn fill_geometry(header: &mut [u8; 256], plan: &Plan<'_>) {
|
||||
let totals = &plan.totals;
|
||||
header[..8].copy_from_slice(b"KARCHIV2");
|
||||
put_u32(header, 8, 2);
|
||||
put_u32(header, 12, 0x0403_0201);
|
||||
put_u32(header, 16, 256);
|
||||
put_u32(header, 20, 192);
|
||||
put_u64(header, 24, plan.directory_offset);
|
||||
put_u32(header, 32, plan.placed.len() as u32);
|
||||
put_u64(header, 40, plan.string_offset);
|
||||
put_u64(header, 48, plan.names.len() as u64);
|
||||
put_u64(header, 56, plan.payload_offset);
|
||||
put_u64(header, 64, plan.archive_bytes);
|
||||
put_u64(header, 72, totals.elements);
|
||||
put_u64(header, 80, totals.payload_bits);
|
||||
}
|
||||
|
||||
fn fill_identity(header: &mut [u8; 256], plan: &Plan<'_>, source: &SourceIdentity<'_>) {
|
||||
let totals = &plan.totals;
|
||||
put_u64(header, 88, source.total_elements);
|
||||
header[96..104]
|
||||
.copy_from_slice(&(plan.archive_bytes as f64 * 8.0 / totals.elements as f64).to_le_bytes());
|
||||
header[104] = if totals.min_planes == u8::MAX {
|
||||
0
|
||||
} else {
|
||||
totals.min_planes
|
||||
};
|
||||
header[105] = totals.max_planes;
|
||||
header[106] = 1;
|
||||
put_u32(header, 108, plan.source_name);
|
||||
put_u32(header, 112, plan.source_arch);
|
||||
put_u32(header, 116, plan.builder_name);
|
||||
put_u64(header, 120, source.bytes);
|
||||
header[128..160].copy_from_slice(&source.digest);
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
//! Layout stage of the KAR writer: the string table, the placement of every
|
||||
//! section and the totals the header records.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
pub(super) struct Plan<'a> {
|
||||
pub(super) names: Vec<u8>,
|
||||
pub(super) source_name: u32,
|
||||
pub(super) source_arch: u32,
|
||||
pub(super) builder_name: u32,
|
||||
pub(super) directory_offset: u64,
|
||||
pub(super) directory_bytes: u64,
|
||||
pub(super) string_offset: u64,
|
||||
pub(super) payload_offset: u64,
|
||||
pub(super) archive_bytes: u64,
|
||||
pub(super) totals: Totals,
|
||||
pub(super) placed: Vec<Placed<'a>>,
|
||||
}
|
||||
|
||||
pub(super) struct Totals {
|
||||
pub(super) elements: u64,
|
||||
pub(super) payload_bits: u64,
|
||||
pub(super) min_planes: u8,
|
||||
pub(super) max_planes: u8,
|
||||
}
|
||||
|
||||
impl Totals {
|
||||
fn new() -> Self {
|
||||
Totals {
|
||||
elements: 0,
|
||||
payload_bits: 0,
|
||||
min_planes: u8::MAX,
|
||||
max_planes: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn absorb(
|
||||
&mut self,
|
||||
layout: &NestedLayout,
|
||||
planes_min: u8,
|
||||
planes_max: u8,
|
||||
) -> Result<(), String> {
|
||||
self.payload_bits = self
|
||||
.payload_bits
|
||||
.checked_add(layout.payload_bits)
|
||||
.ok_or("KAR payload bit count overflow")?;
|
||||
self.min_planes = self.min_planes.min(planes_min);
|
||||
self.max_planes = self.max_planes.max(planes_max);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct Strings {
|
||||
names: Vec<u8>,
|
||||
tensor_offsets: Vec<u32>,
|
||||
source_name: u32,
|
||||
source_arch: u32,
|
||||
builder_name: u32,
|
||||
}
|
||||
|
||||
struct Geometry {
|
||||
n_padded: u64,
|
||||
section_bytes: u64,
|
||||
scales_offset: u64,
|
||||
books_offset: u64,
|
||||
planes_offset: u64,
|
||||
plane_stride: u32,
|
||||
}
|
||||
|
||||
impl From<&NestedLayout> for Geometry {
|
||||
fn from(layout: &NestedLayout) -> Self {
|
||||
Geometry {
|
||||
n_padded: layout.n_padded,
|
||||
section_bytes: layout.section_bytes,
|
||||
scales_offset: layout.scales_offset,
|
||||
books_offset: layout.books_offset,
|
||||
planes_offset: layout.planes_offset,
|
||||
plane_stride: layout.plane_stride,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn plan<'a>(
|
||||
tensors: &'a [Tensor<'a>],
|
||||
source: &SourceIdentity<'_>,
|
||||
) -> Result<Plan<'a>, String> {
|
||||
let strings = build_strings(tensors, source)?;
|
||||
let directory_offset = 256u64;
|
||||
let directory_bytes = (tensors.len() as u64)
|
||||
.checked_mul(192)
|
||||
.ok_or("KAR directory overflow")?;
|
||||
let string_offset = round_up(directory_offset + directory_bytes, 64)?;
|
||||
let payload_offset = round_up(string_offset + strings.names.len() as u64, 256)?;
|
||||
let mut totals = Totals::new();
|
||||
let mut cursor = payload_offset;
|
||||
let mut placed = Vec::with_capacity(tensors.len());
|
||||
for (tensor, &name_offset) in tensors.iter().zip(&strings.tensor_offsets) {
|
||||
let entry = place(tensor, name_offset, cursor, &mut totals)?;
|
||||
cursor = cursor
|
||||
.checked_add(entry.section_bytes)
|
||||
.ok_or("KAR archive size overflow")?;
|
||||
placed.push(entry);
|
||||
}
|
||||
if totals.elements > source.total_elements {
|
||||
return Err("KAR tensors exceed source element count".into());
|
||||
}
|
||||
Ok(Plan {
|
||||
names: strings.names,
|
||||
source_name: strings.source_name,
|
||||
source_arch: strings.source_arch,
|
||||
builder_name: strings.builder_name,
|
||||
directory_offset,
|
||||
directory_bytes,
|
||||
string_offset,
|
||||
payload_offset,
|
||||
archive_bytes: cursor,
|
||||
totals,
|
||||
placed,
|
||||
})
|
||||
}
|
||||
|
||||
fn append_string(names: &mut Vec<u8>, value: &str) -> Result<u32, String> {
|
||||
let offset = u32::try_from(names.len()).map_err(|_| "KAR string table is too large")?;
|
||||
push_cstr(names, value)?;
|
||||
Ok(offset)
|
||||
}
|
||||
|
||||
fn build_strings(tensors: &[Tensor<'_>], source: &SourceIdentity<'_>) -> Result<Strings, String> {
|
||||
let mut names = Vec::new();
|
||||
let mut tensor_offsets = Vec::with_capacity(tensors.len());
|
||||
let mut unique = HashSet::new();
|
||||
for tensor in tensors {
|
||||
if tensor.name.is_empty() || !unique.insert(tensor.name) {
|
||||
return Err("KAR tensor names must be nonempty and unique".into());
|
||||
}
|
||||
tensor_offsets.push(append_string(&mut names, tensor.name)?);
|
||||
}
|
||||
let source_name = append_string(&mut names, source.name)?;
|
||||
let source_arch = append_string(&mut names, source.architecture)?;
|
||||
let builder_name = append_string(&mut names, source.builder)?;
|
||||
if names.len() > 64 * 1024 * 1024 {
|
||||
return Err("KAR string table exceeds inspector limit".into());
|
||||
}
|
||||
Ok(Strings {
|
||||
names,
|
||||
tensor_offsets,
|
||||
source_name,
|
||||
source_arch,
|
||||
builder_name,
|
||||
})
|
||||
}
|
||||
|
||||
fn place<'a>(
|
||||
tensor: &'a Tensor<'a>,
|
||||
name_offset: u32,
|
||||
cursor: u64,
|
||||
totals: &mut Totals,
|
||||
) -> Result<Placed<'a>, String> {
|
||||
let n_elements = validate_shape(tensor)?;
|
||||
totals.elements = totals
|
||||
.elements
|
||||
.checked_add(n_elements)
|
||||
.ok_or("KAR element count overflow")?;
|
||||
let geometry = geometry(tensor, n_elements, cursor, totals)?;
|
||||
Ok(Placed {
|
||||
tensor,
|
||||
name_offset,
|
||||
n_elements,
|
||||
n_padded: geometry.n_padded,
|
||||
section_offset: cursor,
|
||||
section_bytes: geometry.section_bytes,
|
||||
scales_offset: geometry.scales_offset,
|
||||
books_offset: geometry.books_offset,
|
||||
planes_offset: geometry.planes_offset,
|
||||
plane_stride: geometry.plane_stride,
|
||||
payload_crc32: 0,
|
||||
})
|
||||
}
|
||||
|
||||
fn geometry(
|
||||
tensor: &Tensor<'_>,
|
||||
n_elements: u64,
|
||||
cursor: u64,
|
||||
totals: &mut Totals,
|
||||
) -> Result<Geometry, String> {
|
||||
match &tensor.data {
|
||||
TensorData::Raw(raw) => {
|
||||
raw_geometry(tensor, n_elements, raw.len() as u64, "RAW byte count")
|
||||
}
|
||||
TensorData::RawFile { bytes, .. } => {
|
||||
raw_geometry(tensor, n_elements, *bytes, "RAW file byte count")
|
||||
}
|
||||
TensorData::Nested { .. } => nested_geometry(tensor, n_elements, cursor, totals),
|
||||
TensorData::NestedFile { .. } => nested_file_geometry(tensor, n_elements, cursor, totals),
|
||||
}
|
||||
}
|
||||
|
||||
fn raw_geometry(
|
||||
tensor: &Tensor<'_>,
|
||||
n_elements: u64,
|
||||
bytes: u64,
|
||||
what: &str,
|
||||
) -> Result<Geometry, String> {
|
||||
let width = if tensor.source_dtype == 0 { 4 } else { 2 };
|
||||
if bytes
|
||||
!= n_elements
|
||||
.checked_mul(width)
|
||||
.ok_or("KAR RAW byte count overflow")?
|
||||
{
|
||||
return Err(format!(
|
||||
"{}: {} differs from tensor shape",
|
||||
tensor.name, what
|
||||
));
|
||||
}
|
||||
Ok(Geometry {
|
||||
n_padded: n_elements,
|
||||
section_bytes: round_up(bytes, 256)?,
|
||||
scales_offset: 0,
|
||||
books_offset: 0,
|
||||
planes_offset: 0,
|
||||
plane_stride: 0,
|
||||
})
|
||||
}
|
||||
|
||||
fn nested_geometry(
|
||||
tensor: &Tensor<'_>,
|
||||
n_elements: u64,
|
||||
cursor: u64,
|
||||
totals: &mut Totals,
|
||||
) -> Result<Geometry, String> {
|
||||
let TensorData::Nested {
|
||||
group,
|
||||
nesting,
|
||||
planes_min,
|
||||
planes_max,
|
||||
scales,
|
||||
books,
|
||||
planes,
|
||||
} = &tensor.data
|
||||
else {
|
||||
unreachable!()
|
||||
};
|
||||
let levels = u8::try_from(planes.len()).map_err(|_| "too many KAR planes")?;
|
||||
let layout = nested_layout(
|
||||
cursor,
|
||||
n_elements,
|
||||
*group,
|
||||
*nesting,
|
||||
*planes_min,
|
||||
*planes_max,
|
||||
levels,
|
||||
)?;
|
||||
validate_nested_slices(tensor.name, &layout, *group, scales, books, planes)?;
|
||||
totals.absorb(&layout, *planes_min, *planes_max)?;
|
||||
Ok(Geometry::from(&layout))
|
||||
}
|
||||
|
||||
fn nested_file_geometry(
|
||||
tensor: &Tensor<'_>,
|
||||
n_elements: u64,
|
||||
cursor: u64,
|
||||
totals: &mut Totals,
|
||||
) -> Result<Geometry, String> {
|
||||
let TensorData::NestedFile {
|
||||
group,
|
||||
nesting,
|
||||
planes_min,
|
||||
planes_max,
|
||||
levels,
|
||||
bytes,
|
||||
..
|
||||
} = &tensor.data
|
||||
else {
|
||||
unreachable!()
|
||||
};
|
||||
let layout = nested_layout(
|
||||
cursor,
|
||||
n_elements,
|
||||
*group,
|
||||
*nesting,
|
||||
*planes_min,
|
||||
*planes_max,
|
||||
*levels,
|
||||
)?;
|
||||
if *bytes != layout.section_bytes {
|
||||
return Err(format!(
|
||||
"{}: nested file section size mismatch",
|
||||
tensor.name
|
||||
));
|
||||
}
|
||||
totals.absorb(&layout, *planes_min, *planes_max)?;
|
||||
Ok(Geometry::from(&layout))
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
//! Moved out of the parent module by STRA-338: fn write_archive_inner.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::archive_file::write_archive_file;
|
||||
#[allow(unused_imports)]
|
||||
use super::archive_plan::plan;
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
@@ -9,269 +13,65 @@ pub(super) fn write_archive_inner(
|
||||
tensors: &[Tensor<'_>],
|
||||
consume_files: bool,
|
||||
) -> Result<kar::Summary, String> {
|
||||
check_request(destination, source, tensors)?;
|
||||
let mut plan = plan(tensors, source)?;
|
||||
let temporary = temporary_path(destination)?;
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&temporary)
|
||||
.map_err(|error| error.to_string())?;
|
||||
let result = write_archive_file(&mut file, &mut plan, source, consume_files);
|
||||
drop(file);
|
||||
publish(&temporary, destination, result)
|
||||
}
|
||||
|
||||
fn check_request(
|
||||
destination: &Path,
|
||||
source: &SourceIdentity<'_>,
|
||||
tensors: &[Tensor<'_>],
|
||||
) -> Result<(), String> {
|
||||
if fs::symlink_metadata(destination).is_ok() || tensors.is_empty() || tensors.len() > 100_000 {
|
||||
return Err("KAR destination exists or tensor count is invalid".into());
|
||||
}
|
||||
if source.bytes == 0 || source.total_elements == 0 {
|
||||
return Err("KAR source identity needs nonzero bytes and elements".into());
|
||||
}
|
||||
let mut names = Vec::new();
|
||||
let mut name_offsets = Vec::with_capacity(tensors.len());
|
||||
let mut unique = HashSet::new();
|
||||
for tensor in tensors {
|
||||
if tensor.name.is_empty() || !unique.insert(tensor.name) {
|
||||
return Err("KAR tensor names must be nonempty and unique".into());
|
||||
}
|
||||
name_offsets.push(u32::try_from(names.len()).map_err(|_| "KAR string table is too large")?);
|
||||
push_cstr(&mut names, tensor.name)?;
|
||||
}
|
||||
let source_name = u32::try_from(names.len()).map_err(|_| "KAR string table is too large")?;
|
||||
push_cstr(&mut names, source.name)?;
|
||||
let source_arch = u32::try_from(names.len()).map_err(|_| "KAR string table is too large")?;
|
||||
push_cstr(&mut names, source.architecture)?;
|
||||
let builder_name = u32::try_from(names.len()).map_err(|_| "KAR string table is too large")?;
|
||||
push_cstr(&mut names, source.builder)?;
|
||||
if names.len() > 64 * 1024 * 1024 {
|
||||
return Err("KAR string table exceeds inspector limit".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
let directory_offset = 256u64;
|
||||
let directory_bytes = (tensors.len() as u64)
|
||||
.checked_mul(192)
|
||||
.ok_or("KAR directory overflow")?;
|
||||
let string_offset = round_up(directory_offset + directory_bytes, 64)?;
|
||||
let payload_offset = round_up(string_offset + names.len() as u64, 256)?;
|
||||
let mut cursor = payload_offset;
|
||||
let mut total_elements = 0u64;
|
||||
let mut payload_bits = 0u64;
|
||||
let mut min_planes = u8::MAX;
|
||||
let mut max_planes = 0u8;
|
||||
let mut placed = Vec::with_capacity(tensors.len());
|
||||
for (tensor, &name_offset) in tensors.iter().zip(&name_offsets) {
|
||||
let n_elements = validate_shape(tensor)?;
|
||||
total_elements = total_elements
|
||||
.checked_add(n_elements)
|
||||
.ok_or("KAR element count overflow")?;
|
||||
let (n_padded, section_bytes, scales_offset, books_offset, planes_offset, plane_stride) =
|
||||
match &tensor.data {
|
||||
TensorData::Raw(raw) => {
|
||||
let width = if tensor.source_dtype == 0 { 4 } else { 2 };
|
||||
if raw.len() as u64
|
||||
!= n_elements
|
||||
.checked_mul(width)
|
||||
.ok_or("KAR RAW byte count overflow")?
|
||||
{
|
||||
return Err(format!(
|
||||
"{}: RAW byte count differs from tensor shape",
|
||||
tensor.name
|
||||
));
|
||||
}
|
||||
(n_elements, round_up(raw.len() as u64, 256)?, 0, 0, 0, 0)
|
||||
}
|
||||
TensorData::RawFile { bytes, .. } => {
|
||||
let width = if tensor.source_dtype == 0 { 4 } else { 2 };
|
||||
if *bytes
|
||||
!= n_elements
|
||||
.checked_mul(width)
|
||||
.ok_or("KAR RAW byte count overflow")?
|
||||
{
|
||||
return Err(format!(
|
||||
"{}: RAW file byte count differs from tensor shape",
|
||||
tensor.name
|
||||
));
|
||||
}
|
||||
(n_elements, round_up(*bytes, 256)?, 0, 0, 0, 0)
|
||||
}
|
||||
TensorData::Nested {
|
||||
group,
|
||||
nesting,
|
||||
planes_min,
|
||||
planes_max,
|
||||
scales,
|
||||
books,
|
||||
planes,
|
||||
} => {
|
||||
let levels = u8::try_from(planes.len()).map_err(|_| "too many KAR planes")?;
|
||||
let layout = nested_layout(
|
||||
cursor,
|
||||
n_elements,
|
||||
*group,
|
||||
*nesting,
|
||||
*planes_min,
|
||||
*planes_max,
|
||||
levels,
|
||||
)?;
|
||||
validate_nested_slices(tensor.name, &layout, *group, scales, books, planes)?;
|
||||
payload_bits = payload_bits
|
||||
.checked_add(layout.payload_bits)
|
||||
.ok_or("KAR payload bit count overflow")?;
|
||||
min_planes = min_planes.min(*planes_min);
|
||||
max_planes = max_planes.max(*planes_max);
|
||||
(
|
||||
layout.n_padded,
|
||||
layout.section_bytes,
|
||||
layout.scales_offset,
|
||||
layout.books_offset,
|
||||
layout.planes_offset,
|
||||
layout.plane_stride,
|
||||
)
|
||||
}
|
||||
TensorData::NestedFile {
|
||||
group,
|
||||
nesting,
|
||||
planes_min,
|
||||
planes_max,
|
||||
levels,
|
||||
bytes,
|
||||
..
|
||||
} => {
|
||||
let layout = nested_layout(
|
||||
cursor,
|
||||
n_elements,
|
||||
*group,
|
||||
*nesting,
|
||||
*planes_min,
|
||||
*planes_max,
|
||||
*levels,
|
||||
)?;
|
||||
if *bytes != layout.section_bytes {
|
||||
return Err(format!(
|
||||
"{}: nested file section size mismatch",
|
||||
tensor.name
|
||||
));
|
||||
}
|
||||
payload_bits = payload_bits
|
||||
.checked_add(layout.payload_bits)
|
||||
.ok_or("KAR payload bit count overflow")?;
|
||||
min_planes = min_planes.min(*planes_min);
|
||||
max_planes = max_planes.max(*planes_max);
|
||||
(
|
||||
layout.n_padded,
|
||||
layout.section_bytes,
|
||||
layout.scales_offset,
|
||||
layout.books_offset,
|
||||
layout.planes_offset,
|
||||
layout.plane_stride,
|
||||
)
|
||||
}
|
||||
};
|
||||
placed.push(Placed {
|
||||
tensor,
|
||||
name_offset,
|
||||
n_elements,
|
||||
n_padded,
|
||||
section_offset: cursor,
|
||||
section_bytes,
|
||||
scales_offset,
|
||||
books_offset,
|
||||
planes_offset,
|
||||
plane_stride,
|
||||
payload_crc32: 0,
|
||||
});
|
||||
cursor = cursor
|
||||
.checked_add(section_bytes)
|
||||
.ok_or("KAR archive size overflow")?;
|
||||
}
|
||||
if total_elements > source.total_elements {
|
||||
return Err("KAR tensors exceed source element count".into());
|
||||
}
|
||||
let archive_bytes = cursor;
|
||||
let temporary = destination.with_file_name(format!(
|
||||
fn temporary_path(destination: &Path) -> Result<std::path::PathBuf, String> {
|
||||
Ok(destination.with_file_name(format!(
|
||||
"{}.part",
|
||||
destination
|
||||
.file_name()
|
||||
.ok_or("KAR destination has no filename")?
|
||||
.to_string_lossy()
|
||||
));
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&temporary)
|
||||
.map_err(|error| error.to_string())?;
|
||||
let result = (|| -> Result<(), String> {
|
||||
file.set_len(payload_offset)
|
||||
.map_err(|error| error.to_string())?;
|
||||
file.seek(SeekFrom::Start(string_offset))
|
||||
.map_err(|error| error.to_string())?;
|
||||
file.write_all(&names).map_err(|error| error.to_string())?;
|
||||
for entry in &mut placed {
|
||||
entry.payload_crc32 = write_section(&mut file, entry)?;
|
||||
if consume_files {
|
||||
let path = match &entry.tensor.data {
|
||||
TensorData::RawFile { path, .. } | TensorData::NestedFile { path, .. } => path,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
fs::remove_file(path).map_err(|error| error.to_string())?;
|
||||
}
|
||||
}
|
||||
if file.metadata().map_err(|error| error.to_string())?.len() != archive_bytes {
|
||||
return Err("KAR writer produced the wrong archive length".into());
|
||||
}
|
||||
let mut directory = vec![0u8; directory_bytes as usize];
|
||||
let (records, remainder) = directory.as_chunks_mut::<192>();
|
||||
debug_assert!(remainder.is_empty());
|
||||
for (entry, record) in placed.iter().zip(records) {
|
||||
write_record(record, entry)?;
|
||||
}
|
||||
file.seek(SeekFrom::Start(directory_offset))
|
||||
.map_err(|error| error.to_string())?;
|
||||
file.write_all(&directory)
|
||||
.map_err(|error| error.to_string())?;
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(&names);
|
||||
digest.update(&directory);
|
||||
let mut header = [0u8; 256];
|
||||
header[..8].copy_from_slice(b"KARCHIV2");
|
||||
put_u32(&mut header, 8, 2);
|
||||
put_u32(&mut header, 12, 0x0403_0201);
|
||||
put_u32(&mut header, 16, 256);
|
||||
put_u32(&mut header, 20, 192);
|
||||
put_u64(&mut header, 24, directory_offset);
|
||||
put_u32(&mut header, 32, tensors.len() as u32);
|
||||
put_u64(&mut header, 40, string_offset);
|
||||
put_u64(&mut header, 48, names.len() as u64);
|
||||
put_u64(&mut header, 56, payload_offset);
|
||||
put_u64(&mut header, 64, archive_bytes);
|
||||
put_u64(&mut header, 72, total_elements);
|
||||
put_u64(&mut header, 80, payload_bits);
|
||||
put_u64(&mut header, 88, source.total_elements);
|
||||
header[96..104]
|
||||
.copy_from_slice(&(archive_bytes as f64 * 8.0 / total_elements as f64).to_le_bytes());
|
||||
header[104] = if min_planes == u8::MAX { 0 } else { min_planes };
|
||||
header[105] = max_planes;
|
||||
header[106] = 1;
|
||||
put_u32(&mut header, 108, source_name);
|
||||
put_u32(&mut header, 112, source_arch);
|
||||
put_u32(&mut header, 116, builder_name);
|
||||
put_u64(&mut header, 120, source.bytes);
|
||||
header[128..160].copy_from_slice(&source.digest);
|
||||
header[160..192].copy_from_slice(&digest.finalize());
|
||||
let header_crc = kar::crc32(&header[..192]);
|
||||
put_u32(&mut header, 192, header_crc);
|
||||
file.seek(SeekFrom::Start(0))
|
||||
.map_err(|error| error.to_string())?;
|
||||
file.write_all(&header).map_err(|error| error.to_string())?;
|
||||
file.sync_all().map_err(|error| error.to_string())?;
|
||||
Ok(())
|
||||
})();
|
||||
drop(file);
|
||||
if let Err(error) = result {
|
||||
let _ = fs::remove_file(&temporary);
|
||||
)))
|
||||
}
|
||||
|
||||
fn publish(
|
||||
temporary: &Path,
|
||||
destination: &Path,
|
||||
written: Result<(), String>,
|
||||
) -> Result<kar::Summary, String> {
|
||||
if let Err(error) = written {
|
||||
let _ = fs::remove_file(temporary);
|
||||
return Err(error);
|
||||
}
|
||||
let summary = match kar::verify(&temporary) {
|
||||
let summary = match kar::verify(temporary) {
|
||||
Ok(summary) => summary,
|
||||
Err(error) => {
|
||||
let _ = fs::remove_file(&temporary);
|
||||
let _ = fs::remove_file(temporary);
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
// A hard link publishes a fully written archive atomically without replacing
|
||||
// an existing destination, even if another writer won the race after preflight.
|
||||
if let Err(error) = fs::hard_link(&temporary, destination) {
|
||||
let _ = fs::remove_file(&temporary);
|
||||
if let Err(error) = fs::hard_link(temporary, destination) {
|
||||
let _ = fs::remove_file(temporary);
|
||||
return Err(error.to_string());
|
||||
}
|
||||
fs::remove_file(&temporary).map_err(|error| error.to_string())?;
|
||||
fs::remove_file(temporary).map_err(|error| error.to_string())?;
|
||||
Ok(summary)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user