STRA-8: make streamed KAR publication recoverable
Linux / verify (pull_request) Successful in 2m54s
Linux / keyless-cuda (pull_request) Skipped
Linux / hosted-cuda-package (pull_request) Skipped
Linux / linux-cli-container (pull_request) Successful in 2m5s
Linux / linux-static-cli (pull_request) Successful in 5m34s
Linux / release-cli (pull_request) Skipped

This commit is contained in:
Pavlo Ratushnyi
2026-10-06 10:36:48 +02:00
parent d3e63a789e
commit 3bcfbfd856
8 changed files with 1772 additions and 614 deletions
+8 -6
View File
@@ -693,12 +693,14 @@ pub fn prepare(
let section_path = staging.0.join(format!("{:06}.section", prepared.len()));
let section = kar_stream_encode::encode_section(
&mut source,
location.absolute,
location.kind,
location.source_bytes,
elements,
&calibration,
&section_path,
&kar_stream_encode::SectionRequest {
absolute_offset: location.absolute,
source_kind: location.kind,
source_bytes: location.source_bytes,
elements,
calibration: &calibration,
destination: &section_path,
},
)?;
if section.source_digest != source_sha256 || section.derived_digest != f32_sha256 {
return Err(format!("{}: candidate source changed", candidate.name));
+243 -130
View File
@@ -19,15 +19,98 @@ pub struct SectionResult {
pub relative_l2: f64,
}
pub struct SectionRequest<'a> {
pub absolute_offset: u64,
pub source_kind: u32,
pub source_bytes: u64,
pub elements: u64,
pub calibration: &'a kar_codec::Calibration,
pub destination: &'a Path,
}
struct SectionLayout {
levels: usize,
words: u64,
books_start: u64,
planes_start: u64,
plane_stride: u64,
section_bytes: u64,
}
struct SectionEncoder<'a> {
path: std::path::PathBuf,
calibration: &'a kar_codec::Calibration,
scale_writer: BufWriter<File>,
plane_writers: Vec<BufWriter<File>>,
pending: [f32; 32],
filled: usize,
seen: u64,
groups: u64,
error_sum: f64,
reference_sum: f64,
}
pub fn encode_section<R: Read + Seek>(
reader: &mut R,
absolute_offset: u64,
source_kind: u32,
source_bytes: u64,
elements: u64,
calibration: &kar_codec::Calibration,
destination: &Path,
request: &SectionRequest<'_>,
) -> Result<SectionResult, String> {
let layout = SectionLayout::new(request.elements, request.calibration)?;
let section = OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.open(request.destination)
.map_err(|error| error.to_string())?;
let result = section
.set_len(layout.section_bytes)
.map_err(|error| error.to_string())
.and_then(|()| encode_section_contents(reader, request, &layout));
drop(section);
if result.is_err() {
let _ = fs::remove_file(request.destination);
}
result
}
impl SectionLayout {
fn new(elements: u64, calibration: &kar_codec::Calibration) -> Result<Self, String> {
validate_calibration(elements, calibration)?;
let levels = calibration.books.len();
let words = elements.div_ceil(32);
let scales_bytes = words.checked_mul(2).ok_or("KAR scales overflow")?;
let books_start = round_up(scales_bytes, 16)?;
let books_bytes = (1u64 << (levels + 2)) - 4;
let planes_start = round_up(
books_start
.checked_add(books_bytes)
.ok_or("KAR books overflow")?,
16,
)?;
let plane_stride = round_up(words.checked_mul(4).ok_or("KAR planes overflow")?, 16)?;
if plane_stride > u32::MAX as u64 {
return Err("KAR plane stride exceeds format limit".into());
}
let planes_bytes = plane_stride
.checked_mul(levels as u64)
.ok_or("KAR planes overflow")?;
let section_bytes = round_up(
planes_start
.checked_add(planes_bytes)
.ok_or("KAR section overflow")?,
256,
)?;
Ok(Self {
levels,
words,
books_start,
planes_start,
plane_stride,
section_bytes,
})
}
}
fn validate_calibration(elements: u64, calibration: &kar_codec::Calibration) -> Result<(), String> {
let levels = calibration.books.len();
if elements == 0
|| !(1..=8).contains(&levels)
@@ -46,138 +129,164 @@ pub fn encode_section<R: Read + Seek>(
{
return Err("invalid streamed KAR calibration".into());
}
let words = elements.div_ceil(32);
let scales_bytes = words.checked_mul(2).ok_or("KAR scales overflow")?;
let books_start = round_up(scales_bytes, 16)?;
let books_bytes = (1u64 << (levels + 2)) - 4;
let planes_start = round_up(
books_start
.checked_add(books_bytes)
.ok_or("KAR books overflow")?,
16,
Ok(())
}
fn encode_section_contents<R: Read + Seek>(
reader: &mut R,
request: &SectionRequest<'_>,
layout: &SectionLayout,
) -> Result<SectionResult, String> {
let (source_digest, derived_digest, relative_l2) =
encode_stream_values(reader, request, layout)?;
sync_file(request.destination)?;
let digest = hash_file(request.destination)?;
Ok(SectionResult {
bytes: layout.section_bytes,
digest,
source_digest,
derived_digest,
relative_l2,
})
}
fn encode_stream_values<R: Read + Seek>(
reader: &mut R,
request: &SectionRequest<'_>,
layout: &SectionLayout,
) -> Result<([u8; 32], [u8; 32], f64), String> {
let mut encoder = SectionEncoder::new(request.destination, request.calibration, layout)?;
let mut source_hash = Sha256::new();
let mut derived_hash = Sha256::new();
let decoded_bytes = gguf_f32_stream::visit(
reader,
request.absolute_offset,
request.source_kind,
request.source_bytes,
|raw, f32_bytes| {
source_hash.update(raw);
derived_hash.update(f32_bytes);
encoder.push(f32_bytes, request.elements)
},
)?;
let plane_stride = round_up(words.checked_mul(4).ok_or("KAR planes overflow")?, 16)?;
if plane_stride > u32::MAX as u64 {
return Err("KAR plane stride exceeds format limit".into());
}
let section_bytes = round_up(
planes_start
.checked_add(
plane_stride
.checked_mul(levels as u64)
.ok_or("KAR planes overflow")?,
)
.ok_or("KAR section overflow")?,
256,
)?;
let section = OpenOptions::new()
let relative_l2 = encoder.finish(request.elements, decoded_bytes, layout)?;
Ok((
source_hash.finalize().into(),
derived_hash.finalize().into(),
relative_l2,
))
}
fn sync_file(path: &Path) -> Result<(), String> {
OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.open(destination)
.map_err(|error| error.to_string())?;
let result = (|| -> Result<SectionResult, String> {
section
.set_len(section_bytes)
.map_err(|error| error.to_string())?;
let mut scale_writer = writer_at(destination, 0)?;
let mut plane_writers = (0..levels)
.map(|level| writer_at(destination, planes_start + level as u64 * plane_stride))
.open(path)
.and_then(|file| file.sync_all())
.map_err(|error| error.to_string())
}
impl<'a> SectionEncoder<'a> {
fn new(
path: &Path,
calibration: &'a kar_codec::Calibration,
layout: &SectionLayout,
) -> Result<Self, String> {
let scale_writer = writer_at(path, 0)?;
let plane_writers = (0..layout.levels)
.map(|level| {
writer_at(
path,
layout.planes_start + level as u64 * layout.plane_stride,
)
})
.collect::<Result<Vec<_>, _>>()?;
let mut pending = [0.0f32; 32];
let mut filled = 0usize;
let mut seen = 0u64;
let mut groups = 0u64;
let mut error_sum = 0.0f64;
let mut reference_sum = 0.0f64;
let mut source_hash = Sha256::new();
let mut derived_hash = Sha256::new();
let decoded_bytes = gguf_f32_stream::visit(
reader,
absolute_offset,
source_kind,
source_bytes,
|raw, f32_bytes| {
source_hash.update(raw);
derived_hash.update(f32_bytes);
for word in f32_bytes.as_chunks::<4>().0 {
if seen >= elements {
return Err("GGUF tensor decodes beyond its shape".into());
}
pending[filled] = f32::from_le_bytes(*word);
filled += 1;
seen += 1;
if filled == 32 {
write_group(
&pending,
calibration,
&mut scale_writer,
&mut plane_writers,
&mut error_sum,
&mut reference_sum,
)?;
filled = 0;
groups += 1;
}
}
Ok(())
},
Ok(Self {
path: path.to_path_buf(),
calibration,
scale_writer,
plane_writers,
pending: [0.0; 32],
filled: 0,
seen: 0,
groups: 0,
error_sum: 0.0,
reference_sum: 0.0,
})
}
fn push(&mut self, bytes: &[u8], elements: u64) -> Result<(), String> {
for word in bytes.as_chunks::<4>().0 {
if self.seen >= elements {
return Err("GGUF tensor decodes beyond its shape".into());
}
self.pending[self.filled] = f32::from_le_bytes(*word);
self.filled += 1;
self.seen += 1;
if self.filled == 32 {
self.write_pending(32)?;
}
}
Ok(())
}
fn write_pending(&mut self, count: usize) -> Result<(), String> {
write_group(
&self.pending[..count],
self.calibration,
&mut self.scale_writer,
&mut self.plane_writers,
&mut self.error_sum,
&mut self.reference_sum,
)?;
if seen != elements
self.filled = 0;
self.groups += 1;
Ok(())
}
fn finish(
&mut self,
elements: u64,
decoded_bytes: u64,
layout: &SectionLayout,
) -> Result<f64, String> {
if self.seen != elements
|| decoded_bytes != elements.checked_mul(4).ok_or("F32 size overflow")?
{
return Err("GGUF decoded tensor shape mismatch".into());
}
if filled != 0 {
write_group(
&pending[..filled],
calibration,
&mut scale_writer,
&mut plane_writers,
&mut error_sum,
&mut reference_sum,
)?;
groups += 1;
if self.filled != 0 {
self.write_pending(self.filled)?;
}
if groups != words {
if self.groups != layout.words {
return Err("KAR encoded group count mismatch".into());
}
scale_writer.flush().map_err(|error| error.to_string())?;
for writer in &mut plane_writers {
self.scale_writer
.flush()
.map_err(|error| error.to_string())?;
for writer in &mut self.plane_writers {
writer.flush().map_err(|error| error.to_string())?;
}
drop(scale_writer);
drop(plane_writers);
let mut book_writer = writer_at(destination, books_start)?;
for book in &calibration.books {
self.write_books(layout.books_start)?;
if self.reference_sum == 0.0 {
Ok(self.error_sum.sqrt())
} else {
Ok((self.error_sum / self.reference_sum).sqrt())
}
}
fn write_books(&self, offset: u64) -> Result<(), String> {
let mut writer = writer_at(&self.path, offset)?;
for book in &self.calibration.books {
for bits in book {
book_writer
writer
.write_all(&bits.to_le_bytes())
.map_err(|error| error.to_string())?;
}
}
book_writer.flush().map_err(|error| error.to_string())?;
drop(book_writer);
section.sync_all().map_err(|error| error.to_string())?;
let digest = hash_file(destination)?;
let relative_l2 = if reference_sum == 0.0 {
error_sum.sqrt()
} else {
(error_sum / reference_sum).sqrt()
};
Ok(SectionResult {
bytes: section_bytes,
digest,
source_digest: source_hash.finalize().into(),
derived_digest: derived_hash.finalize().into(),
relative_l2,
})
})();
drop(section);
if result.is_err() {
let _ = fs::remove_file(destination);
writer.flush().map_err(|error| error.to_string())?;
Ok(())
}
result
}
fn write_group(
@@ -316,12 +425,14 @@ mod tests {
let output = root.join("streamed.section");
let streamed = encode_section(
&mut Cursor::new(&source),
0,
0,
source.len() as u64,
weights.len() as u64,
&calibration,
&output,
&SectionRequest {
absolute_offset: 0,
source_kind: 0,
source_bytes: source.len() as u64,
elements: weights.len() as u64,
calibration: &calibration,
destination: &output,
},
)
.unwrap();
assert_eq!(fs::read(&output).unwrap(), fs::read(&reference).unwrap());
@@ -382,12 +493,14 @@ mod tests {
));
let result = encode_section(
&mut Cursor::new(&source),
0,
21,
source.len() as u64,
(257 * iq3_s::BLOCK_ELEMENTS) as u64,
&calibration,
&path,
&SectionRequest {
absolute_offset: 0,
source_kind: 21,
source_bytes: source.len() as u64,
elements: (257 * iq3_s::BLOCK_ELEMENTS) as u64,
calibration: &calibration,
destination: &path,
},
)
.unwrap();
assert_eq!(
+78 -12
View File
@@ -285,13 +285,7 @@ fn write_archive_inner(
return Err("KAR tensors exceed source element count".into());
}
let archive_bytes = cursor;
let temporary = destination.with_file_name(format!(
"{}.part",
destination
.file_name()
.ok_or("KAR destination has no filename")?
.to_string_lossy()
));
let temporary = archive_temporary_path(destination)?;
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
@@ -375,13 +369,32 @@ fn write_archive_inner(
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);
publish_verified_archive(&temporary, destination, summary, remove_archive_temp)
}
fn archive_temporary_path(destination: &Path) -> Result<std::path::PathBuf, String> {
let name = destination
.file_name()
.ok_or("KAR destination has no filename")?
.to_string_lossy();
Ok(destination.with_file_name(format!("{name}.part")))
}
fn remove_archive_temp(path: &Path) -> Result<(), String> {
fs::remove_file(path).map_err(|error| error.to_string())
}
fn publish_verified_archive(
temporary: &Path,
destination: &Path,
summary: kar::Summary,
cleanup: fn(&Path) -> Result<(), String>,
) -> Result<kar::Summary, String> {
if let Err(error) = fs::hard_link(temporary, destination) {
let _ = cleanup(temporary);
return Err(error.to_string());
}
fs::remove_file(&temporary).map_err(|error| error.to_string())?;
cleanup(temporary)?;
Ok(summary)
}
@@ -952,6 +965,59 @@ fn put_u64(bytes: &mut [u8], offset: usize, value: u64) {
mod tests {
use super::*;
fn fail_cleanup(_: &Path) -> Result<(), String> {
Err("injected temporary cleanup failure".into())
}
#[test]
fn post_publish_temporary_cleanup_error_keeps_archive_without_overwriting() {
let root = std::env::temp_dir().join(format!("strata-kar-publish-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
fs::create_dir(&root).unwrap();
let temporary = root.join("candidate.part");
let destination = root.join("archive.kar");
fs::write(&temporary, b"verified archive").unwrap();
let summary = kar::Summary {
archive_bytes: 16,
tensor_count: 1,
total_elements: 1,
source_total_elements: 1,
accounted_bpw: 128.0,
source_digest: [0; 32],
source_bytes: 4,
max_planes: 0,
};
assert!(publish_verified_archive(&temporary, &destination, summary, fail_cleanup).is_err());
assert_eq!(fs::read(&destination).unwrap(), b"verified archive");
assert!(temporary.exists());
let unrelated = root.join("unrelated.kar");
let competing = root.join("competing.part");
fs::write(&unrelated, b"do not replace").unwrap();
fs::write(&competing, b"other archive").unwrap();
let competing_summary = kar::Summary {
archive_bytes: 13,
tensor_count: 1,
total_elements: 1,
source_total_elements: 1,
accounted_bpw: 104.0,
source_digest: [0; 32],
source_bytes: 4,
max_planes: 0,
};
assert!(
publish_verified_archive(
&competing,
&unrelated,
competing_summary,
remove_archive_temp,
)
.is_err()
);
assert_eq!(fs::read(unrelated).unwrap(), b"do not replace");
fs::remove_dir_all(root).unwrap();
}
#[test]
fn streams_canonical_nested_section_and_rejects_corruption() {
let source = SourceIdentity {
+106 -39
View File
@@ -92,47 +92,114 @@ async fn ensure_sharded_streamed_with_policy(
levels: u8,
ple_part_elements: Option<u64>,
) -> Result<PreviewOutcome, Box<dyn Error>> {
if !(1..=8).contains(&levels) {
return Err("streamed sharded preparation requires 1..=8 KAR levels".into());
StreamedEnsureRequest {
manifest,
source_dir,
archive,
levels,
ple_part_elements,
}
.run()
.await
}
struct StreamedEnsureRequest<'a> {
manifest: &'a model::Manifest,
source_dir: &'a Path,
archive: &'a Path,
levels: u8,
ple_part_elements: Option<u64>,
}
impl StreamedEnsureRequest<'_> {
async fn run(self) -> Result<PreviewOutcome, Box<dyn Error>> {
self.validate()?;
preflight_existing_shards(self.manifest, self.source_dir, self.archive, self.levels)?;
model::fetch(self.manifest, self.source_dir).await?;
model::verify(self.manifest, self.source_dir).await?;
self.resolve_archive()
}
fn validate(&self) -> Result<(), Box<dyn Error>> {
if !(1..=8).contains(&self.levels) {
return Err("streamed sharded preparation requires 1..=8 KAR levels".into());
}
if let Some(limit) = self.ple_part_elements {
stream_parts::validate_ple_limit(limit)?;
}
Ok(())
}
fn resolve_archive(self) -> Result<PreviewOutcome, Box<dyn Error>> {
match fs::symlink_metadata(self.archive) {
Ok(metadata) => self.reuse_existing(metadata),
Err(error) if error.kind() == io::ErrorKind::NotFound => self.create_archive(),
Err(error) => Err(error.into()),
}
}
fn reuse_existing(&self, metadata: fs::Metadata) -> Result<PreviewOutcome, Box<dyn Error>> {
if !metadata.is_file() || metadata.file_type().is_symlink() {
return Err("existing KAR path must be a regular file".into());
}
let summary = if prepare_preview::has_pending_streamed_publication(self.archive)? {
prepare_preview::recover_sharded_streamed_provenance(
self.manifest,
self.source_dir,
self.archive,
self.levels,
self.ple_part_elements,
)?
.ok_or("KAR recovery intent disappeared before verification")?
} else {
self.verify_archive()?
};
Ok(PreviewOutcome::Reused(summary))
}
fn create_archive(&self) -> Result<PreviewOutcome, Box<dyn Error>> {
let created = if let Some(limit) = self.ple_part_elements {
prepare_preview::prepare_sharded_streamed_ple(
self.manifest,
self.source_dir,
self.archive,
self.levels,
limit,
)?
} else {
prepare_preview::prepare_sharded_streamed(
self.manifest,
self.source_dir,
self.archive,
self.levels,
)?
};
self.verify_archive()?;
Ok(PreviewOutcome::Created(created))
}
fn verify_archive(&self) -> Result<kar::Summary, String> {
verify_streamed_archive(
self.manifest,
self.source_dir,
self.archive,
self.levels,
self.ple_part_elements,
)
}
}
fn verify_streamed_archive(
manifest: &model::Manifest,
source_dir: &Path,
archive: &Path,
levels: u8,
ple_part_elements: Option<u64>,
) -> Result<kar::Summary, String> {
if let Some(limit) = ple_part_elements {
stream_parts::validate_ple_limit(limit)?;
}
preflight_existing_shards(manifest, source_dir, archive, levels)?;
model::fetch(manifest, source_dir).await?;
model::verify(manifest, source_dir).await?;
match fs::symlink_metadata(archive) {
Ok(metadata) => {
if !metadata.is_file() || metadata.file_type().is_symlink() {
return Err("existing KAR path must be a regular file".into());
}
let summary = if let Some(limit) = ple_part_elements {
prepare_preview::verify_sharded_streamed_ple(
manifest, source_dir, archive, levels, limit,
)?
} else {
prepare_preview::verify_sharded_streamed(manifest, source_dir, archive, levels)?
};
Ok(PreviewOutcome::Reused(summary))
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
let created = if let Some(limit) = ple_part_elements {
prepare_preview::prepare_sharded_streamed_ple(
manifest, source_dir, archive, levels, limit,
)?
} else {
prepare_preview::prepare_sharded_streamed(manifest, source_dir, archive, levels)?
};
if let Some(limit) = ple_part_elements {
prepare_preview::verify_sharded_streamed_ple(
manifest, source_dir, archive, levels, limit,
)?;
} else {
prepare_preview::verify_sharded_streamed(manifest, source_dir, archive, levels)?;
}
Ok(PreviewOutcome::Created(created))
}
Err(error) => Err(error.into()),
prepare_preview::verify_sharded_streamed_ple(manifest, source_dir, archive, levels, limit)
} else {
prepare_preview::verify_sharded_streamed(manifest, source_dir, archive, levels)
}
}
File diff suppressed because it is too large Load Diff
+254 -95
View File
@@ -171,7 +171,14 @@ pub(crate) fn plan_shards_with_limit(
source_dir: &Path,
max_part_elements: u64,
) -> Result<Vec<Vec<PartIdentity>>, String> {
plan_shards_with_limits(identity, source_dir, max_part_elements, None)
plan_shards_with_limits(
identity,
source_dir,
PlanLimits {
max_part_elements,
ple_part_elements: None,
},
)
}
pub fn plan_shards_with_ple_limit(
@@ -183,117 +190,269 @@ pub fn plan_shards_with_ple_limit(
plan_shards_with_limits(
identity,
source_dir,
MAX_PART_ELEMENTS,
Some(ple_part_elements),
PlanLimits {
max_part_elements: MAX_PART_ELEMENTS,
ple_part_elements: Some(ple_part_elements),
},
)
}
fn plan_shards_with_limits(
identity: &derived_mixed::ShardedIdentity,
source_dir: &Path,
limits: PlanLimits,
) -> Result<Vec<Vec<PartIdentity>>, String> {
ShardPlanner::new(identity, source_dir, limits).plan()
}
#[derive(Clone, Copy)]
struct PlanLimits {
max_part_elements: u64,
ple_part_elements: Option<u64>,
) -> Result<Vec<Vec<PartIdentity>>, String> {
let mut result = Vec::with_capacity(identity.tensors.len());
let mut names = HashSet::new();
let mut number = 0usize;
let mut saw_ple = false;
for shard in &identity.shards {
let path = source_dir.join(&shard.name);
}
struct ShardPlanner<'a> {
identity: &'a derived_mixed::ShardedIdentity,
source_dir: &'a Path,
limits: PlanLimits,
result: Vec<Vec<PartIdentity>>,
names: HashSet<String>,
number: usize,
saw_ple: bool,
}
struct ParentHashes {
source: Sha256,
f32: Sha256,
}
struct PartBuildContext<'a> {
index: &'a gguf::TensorIndex,
tensor: &'a gguf::TensorInfo,
original: &'a derived_mixed::TensorIdentity,
split: bool,
}
impl<'a> ShardPlanner<'a> {
fn new(
identity: &'a derived_mixed::ShardedIdentity,
source_dir: &'a Path,
limits: PlanLimits,
) -> Self {
Self {
identity,
source_dir,
limits,
result: Vec::with_capacity(identity.tensors.len()),
names: HashSet::new(),
number: 0,
saw_ple: false,
}
}
fn plan(mut self) -> Result<Vec<Vec<PartIdentity>>, String> {
for shard in &self.identity.shards {
self.plan_shard(shard)?;
}
if self.number != self.identity.tensors.len() {
return Err("GGUF tensor count differs from virtual source".into());
}
if self.limits.ple_part_elements.is_some() && !self.saw_ple {
return Err("PLE partition policy requires per_layer_token_embd.weight".into());
}
Ok(self.result)
}
fn plan_shard(&mut self, shard: &derived_mixed::ShardIdentity) -> Result<(), String> {
let path = self.source_dir.join(&shard.name);
let index = gguf::tensor_index(&path).map_err(|error| error.to_string())?;
if index.tensors.len() != shard.tensor_count {
return Err("GGUF shard changed during KAR part planning".into());
}
let mut source = File::open(&path).map_err(|error| error.to_string())?;
let mut source = File::open(path).map_err(|error| error.to_string())?;
for tensor in &index.tensors {
let original = identity
.tensors
.get(number)
.ok_or("GGUF tensor count differs from virtual source")?;
if original.name != tensor.name || original.source_kind != tensor.kind {
return Err("GGUF tensor differs from virtual source".into());
}
let part_limit = if tensor.name == PLE_TENSOR_NAME {
saw_ple = true;
ple_part_elements.unwrap_or(max_part_elements)
} else {
max_part_elements
};
let layouts = layout_with_limit(tensor, original.derived_offset, part_limit)?;
if tensor.name == PLE_TENSOR_NAME && ple_part_elements.is_some() && layouts.len() < 2 {
return Err("PLE part limit must split the PLE tensor".into());
}
let split = layouts.len() > 1;
let mut parent_source = Sha256::new();
let mut parent_f32 = Sha256::new();
let mut parts = Vec::with_capacity(layouts.len());
for part in layouts {
if !names.insert(part.name.clone()) {
return Err(format!("duplicate KAR part name: {}", part.name));
}
let (source_sha256, f32_sha256) = if split {
let absolute = index
.summary
.data_start
.checked_add(tensor.offset)
.and_then(|n| n.checked_add(part.source_byte_offset))
.ok_or("GGUF part offset overflow")?;
let mut source_hash = Sha256::new();
let mut f32_hash = Sha256::new();
let count = gguf_f32_stream::visit(
&mut source,
absolute,
tensor.kind,
part.source_bytes,
|raw, f32_bytes| {
source_hash.update(raw);
f32_hash.update(f32_bytes);
parent_source.update(raw);
parent_f32.update(f32_bytes);
Ok(())
},
)?;
if count != part.derived_bytes {
return Err("GGUF part derived byte count mismatch".into());
}
(source_hash.finalize().into(), f32_hash.finalize().into())
} else {
(original.source_sha256, original.f32_sha256)
};
parts.push(PartIdentity {
name: part.name,
parent_name: tensor.name.clone(),
parent_dimensions: tensor.dimensions.clone(),
dimensions: part.dimensions,
source_kind: tensor.kind,
source_byte_offset: part.source_byte_offset,
source_bytes: part.source_bytes,
source_sha256,
derived_offset: part.derived_offset,
derived_bytes: part.derived_bytes,
f32_sha256,
});
}
if split
&& (parent_source.finalize().as_slice() != original.source_sha256
|| parent_f32.finalize().as_slice() != original.f32_sha256)
{
return Err(format!(
"{}: KAR part hashes differ from source",
tensor.name
));
}
result.push(parts);
number += 1;
self.plan_tensor(&index, &mut source, tensor)?;
}
Ok(())
}
fn plan_tensor(
&mut self,
index: &gguf::TensorIndex,
source: &mut File,
tensor: &gguf::TensorInfo,
) -> Result<(), String> {
self.validate_original_tensor(tensor)?;
let derived_offset = self.identity.tensors[self.number].derived_offset;
let part_limit = self.part_limit(tensor);
let layouts = layout_with_limit(tensor, derived_offset, part_limit)?;
self.require_ple_split(tensor, &layouts)?;
let original = &self.identity.tensors[self.number];
let context = PartBuildContext {
index,
tensor,
original,
split: layouts.len() > 1,
};
let parts = self.build_parts(source, layouts, context)?;
self.register_parts(parts)
}
fn validate_original_tensor(&self, tensor: &gguf::TensorInfo) -> Result<(), String> {
let original = self
.identity
.tensors
.get(self.number)
.ok_or("GGUF tensor count differs from virtual source")?;
if original.name != tensor.name || original.source_kind != tensor.kind {
return Err("GGUF tensor differs from virtual source".into());
}
Ok(())
}
fn part_limit(&mut self, tensor: &gguf::TensorInfo) -> u64 {
if tensor.name == PLE_TENSOR_NAME {
self.saw_ple = true;
self.limits
.ple_part_elements
.unwrap_or(self.limits.max_part_elements)
} else {
self.limits.max_part_elements
}
}
if number != identity.tensors.len() {
return Err("GGUF tensor count differs from virtual source".into());
fn require_ple_split(
&self,
tensor: &gguf::TensorInfo,
layouts: &[Layout],
) -> Result<(), String> {
if tensor.name == PLE_TENSOR_NAME
&& self.limits.ple_part_elements.is_some()
&& layouts.len() < 2
{
return Err("PLE part limit must split the PLE tensor".into());
}
Ok(())
}
if ple_part_elements.is_some() && !saw_ple {
return Err("PLE partition policy requires per_layer_token_embd.weight".into());
fn build_parts(
&self,
source: &mut File,
layouts: Vec<Layout>,
context: PartBuildContext<'_>,
) -> Result<Vec<PartIdentity>, String> {
let mut hashes = ParentHashes {
source: Sha256::new(),
f32: Sha256::new(),
};
let mut parts = Vec::with_capacity(layouts.len());
for layout in layouts {
parts.push(self.build_part(source, &layout, &context, &mut hashes)?);
}
self.verify_parent_hashes(context.tensor, context.original, context.split, hashes)?;
Ok(parts)
}
Ok(result)
fn build_part(
&self,
source: &mut File,
layout: &Layout,
context: &PartBuildContext<'_>,
hashes: &mut ParentHashes,
) -> Result<PartIdentity, String> {
let tensor = context.tensor;
let (source_sha256, f32_sha256) = if context.split {
hash_layout(
source,
context.index.summary.data_start,
tensor,
layout,
hashes,
)?
} else {
(context.original.source_sha256, context.original.f32_sha256)
};
Ok(PartIdentity {
name: layout.name.clone(),
parent_name: tensor.name.clone(),
parent_dimensions: tensor.dimensions.clone(),
dimensions: layout.dimensions.clone(),
source_kind: tensor.kind,
source_byte_offset: layout.source_byte_offset,
source_bytes: layout.source_bytes,
source_sha256,
derived_offset: layout.derived_offset,
derived_bytes: layout.derived_bytes,
f32_sha256,
})
}
fn verify_parent_hashes(
&self,
tensor: &gguf::TensorInfo,
original: &derived_mixed::TensorIdentity,
split: bool,
hashes: ParentHashes,
) -> Result<(), String> {
if split
&& (hashes.source.finalize().as_slice() != original.source_sha256
|| hashes.f32.finalize().as_slice() != original.f32_sha256)
{
return Err(format!(
"{}: KAR part hashes differ from source",
tensor.name
));
}
Ok(())
}
fn register_parts(&mut self, parts: Vec<PartIdentity>) -> Result<(), String> {
for part in &parts {
if !self.names.insert(part.name.clone()) {
return Err(format!("duplicate KAR part name: {}", part.name));
}
}
self.result.push(parts);
self.number += 1;
Ok(())
}
}
fn hash_layout(
source: &mut File,
data_start: u64,
tensor: &gguf::TensorInfo,
layout: &Layout,
parent: &mut ParentHashes,
) -> Result<([u8; 32], [u8; 32]), String> {
let absolute = data_start
.checked_add(tensor.offset)
.and_then(|offset| offset.checked_add(layout.source_byte_offset))
.ok_or("GGUF part offset overflow")?;
let mut hashes = ParentHashes {
source: Sha256::new(),
f32: Sha256::new(),
};
let count = gguf_f32_stream::visit(
source,
absolute,
tensor.kind,
layout.source_bytes,
|raw, f32_bytes| {
hashes.source.update(raw);
hashes.f32.update(f32_bytes);
parent.source.update(raw);
parent.f32.update(f32_bytes);
Ok(())
},
)?;
if count != layout.derived_bytes {
return Err("GGUF part derived byte count mismatch".into());
}
Ok((
hashes.source.finalize().into(),
hashes.f32.finalize().into(),
))
}
#[cfg(test)]
+1
View File
@@ -139,6 +139,7 @@ The test toolchain was installed into ignored `artifacts/tool-venv/` for this ru
- Command: `strata-next model prepare-sharded-streamed qwen-iq3-s --source-dir /Users/para/.local/share/strata-next/qwen-iq3-s --output /Users/para/.local/share/strata-next/qwen-iq3-s-l2-v4.kar --levels 2`.
- The complete archive has **55,295,529,472 bytes** (51.49797487 GiB) across 1,225 KAR records; the two GGUF shards have 83,617,662,656 bytes. Archive/source ratio is 0.66129006, saving 28,322,133,184 bytes (33.87099%). Accounted rate is 2.500025 bits per derived F32 weight. Archive SHA-256 is `536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5`; derived F32 SHA-256 is `c89bfcea7b1c979ad2e9e64c59fcc3c03fc414b345c5f47f027ce0ba99015479`.
- The writer's full payload CRC verification passed before atomic publication, and a versioned provenance sidecar was written. The maximum tensor relative L2 error measured during encoding was 0.68008092. This is **not** a model-level quality result or permission to serve with KAR-2. No Linux GPU inference, GPU decode, or paired end-to-end throughput result exists yet.
- Archive publication keeps a source/policy-bound pending intent until the provenance sidecar is atomically linked. Deterministic fault tests cover destination hash failure, sidecar publication failure, provenance and pending-intent temporary cleanup failure, and archive temporary-link cleanup failure. Retry verifies source shards, KAR records and payload CRCs before recovering the matching sidecar; no existing archive or provenance file is replaced. This makes an interrupted publication recoverable, but does not change the archive's lossy quality status.
- A separate `model verify-sharded-streamed /Users/para/.local/share/strata-next/qwen-iq3-s-l2-v4.kar --manifest qwen-iq3-s --source-dir /Users/para/.local/share/strata-next/qwen-iq3-s --levels 2` run exited successfully. It recomputed the derived F32 source identity, checked both manifest shards, all 1,225 KAR source records and payload CRCs, the archive SHA-256, and the v4 provenance policy. The provenance sidecar SHA-256 is `3edceb512c386ea4552a3e5d3d49fbd841f7bd1b314aeba8b2a87ac811a8a6b5`. Temporary section files, old real-data slices, local header fixtures, and superseded local Docker images were removed; both verified GGUF shards, the final KAR, and its provenance remain outside Git.
## 2026-10-03 — outer block codec and selective precision probes
+14
View File
@@ -139,6 +139,20 @@ The CPU quality oracle can decode up to one million values from an arbitrary nes
`model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N` adds the opt-in fetch → source verify → streamed prepare → archive verify sequence. On rerun it only reuses an archive after fresh shard, payload, and provenance checks; a damaged archive or changed level fails closed. The measured level-2 real-model archive is 55,295,529,472 bytes (51.50 GiB); its model quality remains unmeasured. Use an external model volume or the Linux GPU host for preparation.
Streamed publication is retry-safe across the archive/provenance boundary. Before
the no-replace archive link, preparation publishes a `.pending.json` intent that
binds the verified source identity and exact partition/level policy. If hashing
the published archive or publishing its provenance sidecar fails, the archive
and intent are retained. A later `ensure-sharded-streamed` may recover only
when that intent matches the current pinned shards and policy and a fresh
independent archive verification succeeds; it then writes the sidecar with a
no-replace link. An archive without a matching intent is never adopted, and an
existing sidecar or archive is never overwritten. Temporary-link cleanup after
a successful archive or provenance publication can fail without invalidating
the atomically linked destination; any leftover `.part` file is not treated as
an archive or sidecar. Recovery proves artifact integrity only, not lossy model
quality or serving readiness.
`model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels 2 --ple-part-elements 100000000` selects an experimental v5 partition policy. Only `per_layer_token_embd.weight` gets the smaller limit; other tensors keep the v4 limit. The policy is encoded in the KAR builder string and provenance, and the matching verifier reconstructs every part from the pinned GGUF source. Reuse with another limit or the v4 command fails closed. For the target PLE dimensions, this limit plans 513 adjacent parts of at most 100 million elements, each aligned to complete GGUF rows and quantization blocks. This is a layout calculation, not a new measured archive size or GPU result. Overlay preparation and paired comparison now accept a single split PLE part in a v5 base; a synthetic fixture covers this path, while no full v5 model overlay has been produced. The existing v4 archive and its overlay remain the preserved comparison artifacts; producing a second full-model archive requires more free external storage than is currently available locally.
The streamed assembly now consumes private staged sections as it copies them into the archive, then independently verifies the finished archive before publication. This keeps peak preparation space close to the larger of staged sections or final archive, plus the source shards, rather than requiring both copies of the encoded payload at once. A later shard may omit `general.architecture`; all shards that declare it must agree, and at least one must supply it. The target model's second shard has this metadata shape.