1use crate::addressing::{Hash, PartitionId, HASH_LEN, PARTITION_ID_LEN};
63use crate::error::{Result, StorageError};
64use std::collections::HashMap;
65use std::fs::{self, File, OpenOptions};
66use std::io::{Read, Seek, SeekFrom, Write};
67use std::path::{Path, PathBuf};
68
69pub const PACK_MAGIC: [u8; 4] = *b"BCPK";
70pub const IDX_MAGIC: [u8; 4] = *b"BCIX";
71pub const FORMAT_VERSION: u32 = 3;
72pub const HEADER_LEN: usize = 4 + 4 + PARTITION_ID_LEN;
73pub const TRAILER_LEN: usize = 8 + HASH_LEN;
74pub const ENTRY_META_LEN: usize = HASH_LEN + 1 + 1 + 4 + 8 + 8;
78
79const _ENTRY_META_LEN_IS_54: () = assert!(
80 ENTRY_META_LEN == 54,
81 "ENTRY_META_LEN must be 54 per the 2026-09-23 storage-addressing rulings (Branch A) \
82 — see storage-addressing-hash-context-ruling-2026-09-23.md"
83);
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum Codec {
88 Raw = 0,
91 Zstd = 1,
93 Sealed = 2,
99}
100
101impl Codec {
102 fn from_u8(b: u8) -> Result<Self> {
103 match b {
104 0 => Ok(Codec::Raw),
105 1 => Ok(Codec::Zstd),
106 2 => Ok(Codec::Sealed),
107 other => Err(StorageError::CorruptPack(format!(
108 "unknown codec byte {other}"
109 ))),
110 }
111 }
112}
113
114#[derive(Debug, Clone, Copy, PartialEq, Eq)]
116pub struct EntryMeta {
117 pub hash: Hash,
118 pub codec: Codec,
119 pub flags: u8,
126 pub key_epoch: u32,
132 pub uncompressed_len: u64,
133 pub stored_len: u64,
134}
135
136impl EntryMeta {
137 pub fn validate_reserved(&self) -> Result<()> {
147 if self.flags != 0x00 {
148 return Err(StorageError::CorruptPack(format!(
149 "entry {}: flags is reserved and must be 0x00, got {:#04x}",
150 self.hash, self.flags
151 )));
152 }
153 if self.key_epoch != 0 {
154 return Err(StorageError::CorruptPack(format!(
155 "entry {}: key_epoch is reserved and must be 0, got {}",
156 self.hash, self.key_epoch
157 )));
158 }
159 if self.codec == Codec::Sealed {
160 return Err(StorageError::CorruptPack(format!(
161 "entry {}: codec Sealed is reserved and rejected at format v3",
162 self.hash
163 )));
164 }
165 Ok(())
166 }
167}
168
169#[derive(Debug, Clone, Copy)]
172pub struct SealedLocation {
173 pub pack_id: Hash,
174 pub offset: u64,
175}
176
177const ZSTD_LEVEL: i32 = 3;
178
179pub fn encode(data: &[u8]) -> Result<(Codec, Vec<u8>)> {
182 if data.is_empty() {
183 return Ok((Codec::Raw, Vec::new()));
184 }
185 let compressed = zstd::stream::encode_all(data, ZSTD_LEVEL)
186 .map_err(|e| StorageError::Compression(e.to_string()))?;
187 if compressed.len() < data.len() {
188 Ok((Codec::Zstd, compressed))
189 } else {
190 Ok((Codec::Raw, data.to_vec()))
191 }
192}
193
194pub fn decode(codec: Codec, stored: &[u8]) -> Result<Vec<u8>> {
195 match codec {
196 Codec::Raw => Ok(stored.to_vec()),
197 Codec::Zstd => {
198 zstd::stream::decode_all(stored).map_err(|e| StorageError::Compression(e.to_string()))
199 }
200 Codec::Sealed => Err(StorageError::CorruptPack(
205 "codec Sealed is reserved and rejected at format v3; decode() must not be called \
206 without EntryMeta::validate_reserved() first"
207 .into(),
208 )),
209 }
210}
211
212fn write_header<W: Write>(w: &mut W, partition_id: &PartitionId) -> Result<()> {
213 w.write_all(&PACK_MAGIC)?;
214 w.write_all(&FORMAT_VERSION.to_le_bytes())?;
215 w.write_all(partition_id.as_bytes())?;
216 Ok(())
217}
218
219fn read_header<R: Read>(r: &mut R) -> Result<PartitionId> {
220 let mut magic = [0u8; 4];
221 r.read_exact(&mut magic)?;
222 if magic != PACK_MAGIC {
223 return Err(StorageError::CorruptPack("bad magic".into()));
224 }
225 let mut ver = [0u8; 4];
226 r.read_exact(&mut ver)?;
227 let ver = u32::from_le_bytes(ver);
228 if ver != FORMAT_VERSION {
229 return Err(StorageError::CorruptPack(format!(
230 "unsupported pack format_ver {ver} (expected {FORMAT_VERSION})"
231 )));
232 }
233 let mut pid = [0u8; PARTITION_ID_LEN];
234 r.read_exact(&mut pid)?;
235 Ok(PartitionId::from_bytes(pid))
236}
237
238pub struct PackWriter {
241 path: PathBuf,
242 partition_id: PartitionId,
243 file: File,
244 pub len: u64,
246 pub entry_count: u64,
247 pub offsets: HashMap<Hash, u64>,
250}
251
252impl PackWriter {
253 pub fn open_active(path: &Path, partition_id: PartitionId) -> Result<Self> {
257 if let Some(parent) = path.parent() {
258 fs::create_dir_all(parent)?;
259 }
260 let is_new = !path.exists();
261 let mut file = OpenOptions::new()
262 .create(true)
263 .read(true)
264 .append(true)
265 .open(path)?;
266
267 if is_new {
268 write_header(&mut file, &partition_id)?;
269 file.flush()?;
270 return Ok(PackWriter {
271 path: path.to_path_buf(),
272 partition_id,
273 file,
274 len: HEADER_LEN as u64,
275 entry_count: 0,
276 offsets: HashMap::new(),
277 });
278 }
279
280 let mut reader = File::open(path)?;
282 let found_partition = read_header(&mut reader)?;
283 if found_partition != partition_id {
284 return Err(StorageError::PartitionBoundary(format!(
285 "active pack at {} belongs to partition {}, not {}",
286 path.display(),
287 found_partition.to_hex(),
288 partition_id.to_hex()
289 )));
290 }
291 let mut offsets = HashMap::new();
292 let mut pos = HEADER_LEN as u64;
293 let mut count = 0u64;
294 loop {
295 let entry_start = pos;
296 match read_entry_meta_at(&mut reader, entry_start) {
297 Ok(Some(meta)) => {
298 offsets.insert(meta.hash, entry_start);
299 pos = entry_start + ENTRY_META_LEN as u64 + meta.stored_len;
300 count += 1;
301 }
302 Ok(None) => break, Err(_) => break, }
305 }
306 Ok(PackWriter {
307 path: path.to_path_buf(),
308 partition_id,
309 file,
310 len: pos,
311 entry_count: count,
312 offsets,
313 })
314 }
315
316 pub fn append(
322 &mut self,
323 hash: Hash,
324 codec: Codec,
325 uncompressed_len: u64,
326 payload: &[u8],
327 ) -> Result<u64> {
328 let meta = EntryMeta {
329 hash,
330 codec,
331 flags: 0x00,
332 key_epoch: 0,
333 uncompressed_len,
334 stored_len: payload.len() as u64,
335 };
336 self.append_raw(&meta, payload)
337 }
338
339 pub fn append_raw(&mut self, meta: &EntryMeta, payload: &[u8]) -> Result<u64> {
349 let offset = self.len;
350 let mut buf = Vec::with_capacity(ENTRY_META_LEN + payload.len());
351 buf.extend_from_slice(meta.hash.as_bytes());
352 buf.push(meta.codec as u8);
353 buf.push(meta.flags);
354 buf.extend_from_slice(&meta.key_epoch.to_le_bytes());
355 buf.extend_from_slice(&meta.uncompressed_len.to_le_bytes());
356 buf.extend_from_slice(&(payload.len() as u64).to_le_bytes());
357 buf.extend_from_slice(payload);
358 self.file.write_all(&buf)?;
359 self.file.flush()?;
360 self.len += buf.len() as u64;
361 self.entry_count += 1;
362 self.offsets.insert(meta.hash, offset);
363 Ok(offset)
364 }
365
366 pub fn read_payload_at(&self, offset: u64) -> Result<(EntryMeta, Vec<u8>)> {
367 let mut f = File::open(&self.path)?;
368 read_entry_full_at(&mut f, offset)
369 }
370
371 pub fn seal(mut self, packs_dir: &Path) -> Result<(Hash, PathBuf)> {
376 self.file.flush()?;
377 let mut hasher = blake3::Hasher::new();
380 let mut reader = File::open(&self.path)?;
381 std::io::copy(&mut reader, &mut hasher)?;
382 let pack_content_hash = Hash::from_bytes(*hasher.finalize().as_bytes());
383
384 self.file.write_all(&self.entry_count.to_le_bytes())?;
385 self.file.write_all(pack_content_hash.as_bytes())?;
386 self.file.flush()?;
387
388 let pack_id_hex = pack_content_hash.to_hex();
389 let shard = PartitionId::shard_prefix(&pack_id_hex).to_string();
390 let dest_dir = packs_dir.join(&shard);
391 fs::create_dir_all(&dest_dir)?;
392 let dest_path = dest_dir.join(format!("{pack_id_hex}.pack"));
393 fs::rename(&self.path, &dest_path)?;
394
395 let entries = rebuild_index_entries(&dest_path)?;
397 write_index(
398 &dest_path.with_extension("idx"),
399 &self.partition_id,
400 &entries,
401 )?;
402
403 Ok((pack_content_hash, dest_path))
404 }
405
406 pub fn partition_id(&self) -> PartitionId {
407 self.partition_id
408 }
409}
410
411fn read_entry_meta_at<R: Read + Seek>(r: &mut R, offset: u64) -> Result<Option<EntryMeta>> {
412 r.seek(SeekFrom::Start(offset))?;
413 let mut meta_buf = [0u8; ENTRY_META_LEN];
414 match r.read_exact(&mut meta_buf) {
415 Ok(()) => {}
416 Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(None),
417 Err(e) => return Err(e.into()),
418 }
419 let hash = Hash::from_bytes(meta_buf[0..32].try_into().unwrap());
420 let codec = Codec::from_u8(meta_buf[32])?;
421 let flags = meta_buf[33];
422 let key_epoch = u32::from_le_bytes(meta_buf[34..38].try_into().unwrap());
423 let uncompressed_len = u64::from_le_bytes(meta_buf[38..46].try_into().unwrap());
424 let stored_len = u64::from_le_bytes(meta_buf[46..54].try_into().unwrap());
425 let mut probe = vec![0u8; stored_len as usize];
427 match r.read_exact(&mut probe) {
428 Ok(()) => {}
429 Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(None),
430 Err(e) => return Err(e.into()),
431 }
432 Ok(Some(EntryMeta {
433 hash,
434 codec,
435 flags,
436 key_epoch,
437 uncompressed_len,
438 stored_len,
439 }))
440}
441
442fn read_entry_full_at<R: Read + Seek>(r: &mut R, offset: u64) -> Result<(EntryMeta, Vec<u8>)> {
443 r.seek(SeekFrom::Start(offset))?;
444 let mut meta_buf = [0u8; ENTRY_META_LEN];
445 r.read_exact(&mut meta_buf)?;
446 let hash = Hash::from_bytes(meta_buf[0..32].try_into().unwrap());
447 let codec = Codec::from_u8(meta_buf[32])?;
448 let flags = meta_buf[33];
449 let key_epoch = u32::from_le_bytes(meta_buf[34..38].try_into().unwrap());
450 let uncompressed_len = u64::from_le_bytes(meta_buf[38..46].try_into().unwrap());
451 let stored_len = u64::from_le_bytes(meta_buf[46..54].try_into().unwrap());
452 let mut payload = vec![0u8; stored_len as usize];
453 r.read_exact(&mut payload)?;
454 Ok((
455 EntryMeta {
456 hash,
457 codec,
458 flags,
459 key_epoch,
460 uncompressed_len,
461 stored_len,
462 },
463 payload,
464 ))
465}
466
467pub fn get_raw_at(pack_path: &Path, offset: u64) -> Result<(EntryMeta, Vec<u8>)> {
473 let mut f = File::open(pack_path)?;
474 read_entry_full_at(&mut f, offset)
475}
476
477pub fn rebuild_index_entries(pack_path: &Path) -> Result<Vec<(u64, EntryMeta)>> {
480 let mut f = File::open(pack_path)?;
481 let _partition_id = read_header(&mut f)?;
482 let file_len = f.metadata()?.len();
483 let scan_end = file_len.saturating_sub(TRAILER_LEN as u64);
484
485 let mut out = Vec::new();
486 let mut pos = HEADER_LEN as u64;
487 while pos < scan_end {
488 let entry_start = pos;
489 let meta = read_entry_meta_at(&mut f, entry_start)?.ok_or_else(|| {
490 StorageError::CorruptPack(format!(
491 "truncated entry at offset {entry_start} in {}",
492 pack_path.display()
493 ))
494 })?;
495 pos = entry_start + ENTRY_META_LEN as u64 + meta.stored_len;
496 out.push((entry_start, meta));
497 }
498 if pos != scan_end {
499 return Err(StorageError::CorruptPack(format!(
500 "entry scan did not land on trailer boundary in {}",
501 pack_path.display()
502 )));
503 }
504 Ok(out)
505}
506
507pub fn verify_trailer(pack_path: &Path) -> Result<(u64, Hash)> {
510 let mut f = File::open(pack_path)?;
511 let file_len = f.metadata()?.len();
512 if file_len < (HEADER_LEN + TRAILER_LEN) as u64 {
513 return Err(StorageError::CorruptPack(
514 "pack too short for trailer".into(),
515 ));
516 }
517 f.seek(SeekFrom::Start(file_len - TRAILER_LEN as u64))?;
518 let mut trailer = [0u8; TRAILER_LEN];
519 f.read_exact(&mut trailer)?;
520 let entry_count = u64::from_le_bytes(trailer[0..8].try_into().unwrap());
521 let recorded_hash = Hash::from_bytes(trailer[8..40].try_into().unwrap());
522
523 let mut hasher = blake3::Hasher::new();
524 let body = File::open(pack_path)?;
525 let mut limited = Read::take(body, file_len - TRAILER_LEN as u64);
526 std::io::copy(&mut limited, &mut hasher)?;
527 let actual_hash = Hash::from_bytes(*hasher.finalize().as_bytes());
528
529 if actual_hash != recorded_hash {
530 return Err(StorageError::CorruptPack(format!(
531 "pack_content_hash mismatch in {}: trailer says {}, computed {}",
532 pack_path.display(),
533 recorded_hash,
534 actual_hash
535 )));
536 }
537 Ok((entry_count, actual_hash))
538}
539
540pub fn get_at(pack_path: &Path, offset: u64) -> Result<Vec<u8>> {
546 let mut f = File::open(pack_path)?;
547 let (meta, payload) = read_entry_full_at(&mut f, offset)?;
548 meta.validate_reserved()?;
549 let decoded = decode(meta.codec, &payload)?;
550 let actual = Hash::of(&decoded);
551 if actual != meta.hash {
552 return Err(StorageError::HashMismatch {
553 expected: meta.hash.to_hex(),
554 actual: actual.to_hex(),
555 });
556 }
557 if decoded.len() as u64 != meta.uncompressed_len {
558 return Err(StorageError::CorruptPack(format!(
559 "uncompressed_len mismatch for {}",
560 meta.hash
561 )));
562 }
563 Ok(decoded)
564}
565
566const IDX_RECORD_LEN: usize = HASH_LEN + 8 + 1 + 1 + 4 + 8 + 8;
577
578const _IDX_RECORD_LEN_IS_ENTRY_META_LEN_PLUS_8: () = assert!(
579 IDX_RECORD_LEN == ENTRY_META_LEN + 8,
580 "IDX_RECORD_LEN must equal ENTRY_META_LEN + 8 — the idx adds only the byte offset, the one \
581 fact the pack cannot carry about itself"
582);
583
584pub fn write_index(
585 idx_path: &Path,
586 partition_id: &PartitionId,
587 entries: &[(u64, EntryMeta)],
588) -> Result<()> {
589 let mut sorted: Vec<&(u64, EntryMeta)> = entries.iter().collect();
590 sorted.sort_by_key(|(_, m)| *m.hash.as_bytes());
591
592 let mut buf = Vec::with_capacity(4 + 4 + PARTITION_ID_LEN + 8 + sorted.len() * IDX_RECORD_LEN);
593 buf.extend_from_slice(&IDX_MAGIC);
594 buf.extend_from_slice(&FORMAT_VERSION.to_le_bytes());
595 buf.extend_from_slice(partition_id.as_bytes());
596 buf.extend_from_slice(&(sorted.len() as u64).to_le_bytes());
597 for (offset, meta) in sorted {
598 buf.extend_from_slice(meta.hash.as_bytes());
599 buf.extend_from_slice(&offset.to_le_bytes());
600 buf.push(meta.codec as u8);
601 buf.push(meta.flags);
602 buf.extend_from_slice(&meta.key_epoch.to_le_bytes());
603 buf.extend_from_slice(&meta.uncompressed_len.to_le_bytes());
604 buf.extend_from_slice(&meta.stored_len.to_le_bytes());
605 }
606 fs::write(idx_path, buf)?;
607 Ok(())
608}
609
610pub fn read_index(idx_path: &Path) -> Result<HashMap<Hash, (u64, EntryMeta)>> {
619 let bytes = fs::read(idx_path)?;
620 if bytes.len() < 4 + 4 + PARTITION_ID_LEN + 8 {
621 return Err(StorageError::CorruptPack("idx too short".into()));
622 }
623 if bytes[0..4] != IDX_MAGIC {
624 return Err(StorageError::CorruptPack("bad idx magic".into()));
625 }
626 let count_off = 4 + 4 + PARTITION_ID_LEN;
627 let count = u64::from_le_bytes(bytes[count_off..count_off + 8].try_into().unwrap()) as usize;
628 let mut out = HashMap::with_capacity(count);
629 let mut pos = count_off + 8;
630 for _ in 0..count {
631 if pos + IDX_RECORD_LEN > bytes.len() {
632 return Err(StorageError::CorruptPack("idx truncated".into()));
633 }
634 let hash = Hash::from_bytes(bytes[pos..pos + 32].try_into().unwrap());
635 let offset = u64::from_le_bytes(bytes[pos + 32..pos + 40].try_into().unwrap());
636 let codec = Codec::from_u8(bytes[pos + 40])?;
637 let flags = bytes[pos + 41];
638 let key_epoch = u32::from_le_bytes(bytes[pos + 42..pos + 46].try_into().unwrap());
639 let uncompressed_len = u64::from_le_bytes(bytes[pos + 46..pos + 54].try_into().unwrap());
640 let stored_len = u64::from_le_bytes(bytes[pos + 54..pos + 62].try_into().unwrap());
641 out.insert(
642 hash,
643 (
644 offset,
645 EntryMeta {
646 hash,
647 codec,
648 flags,
649 key_epoch,
650 uncompressed_len,
651 stored_len,
652 },
653 ),
654 );
655 pos += IDX_RECORD_LEN;
656 }
657 Ok(out)
658}
659
660#[cfg(test)]
661mod tests {
662 use super::*;
663 use tempfile::tempdir;
664
665 #[test]
666 fn append_seal_and_read_back() {
667 let dir = tempdir().unwrap();
668 let packs_dir = dir.path().join("packs");
669 let partition_id = PartitionId::derive("test-partition");
670
671 let mut writer =
672 PackWriter::open_active(&dir.path().join("active/active.pack"), partition_id).unwrap();
673 let data = b"hello, packfile";
674 let hash = Hash::of(data);
675 let (codec, payload) = encode(data).unwrap();
676 let offset = writer
677 .append(hash, codec, data.len() as u64, &payload)
678 .unwrap();
679
680 let (pack_id, pack_path) = writer.seal(&packs_dir).unwrap();
681 assert!(pack_path.exists());
682
683 let (entry_count, content_hash) = verify_trailer(&pack_path).unwrap();
684 assert_eq!(entry_count, 1);
685 assert_eq!(content_hash, pack_id);
686
687 let round_tripped = get_at(&pack_path, offset).unwrap();
688 assert_eq!(round_tripped, data);
689 }
690
691 #[test]
692 fn active_pack_resumes_after_reopen() {
693 let dir = tempdir().unwrap();
694 let active_path = dir.path().join("active/active.pack");
695 let partition_id = PartitionId::derive("resume-partition");
696
697 {
698 let mut writer = PackWriter::open_active(&active_path, partition_id).unwrap();
699 let (codec, payload) = encode(b"first").unwrap();
700 writer
701 .append(Hash::of(b"first"), codec, 5, &payload)
702 .unwrap();
703 }
704 let writer = PackWriter::open_active(&active_path, partition_id).unwrap();
705 assert_eq!(writer.entry_count, 1);
706 assert!(writer.offsets.contains_key(&Hash::of(b"first")));
707 }
708
709 #[test]
710 fn index_roundtrips() {
711 let dir = tempdir().unwrap();
712 let packs_dir = dir.path().join("packs");
713 let partition_id = PartitionId::derive("idx-partition");
714 let mut writer =
715 PackWriter::open_active(&dir.path().join("active/active.pack"), partition_id).unwrap();
716 let (codec, payload) = encode(b"index me").unwrap();
717 writer
718 .append(Hash::of(b"index me"), codec, 8, &payload)
719 .unwrap();
720 let (_pack_id, pack_path) = writer.seal(&packs_dir).unwrap();
721
722 let idx_path = pack_path.with_extension("idx");
723 let idx = read_index(&idx_path).unwrap();
724 assert_eq!(idx.len(), 1);
725 assert!(idx.contains_key(&Hash::of(b"index me")));
726
727 let rebuilt = rebuild_index_entries(&pack_path).unwrap();
729 assert_eq!(rebuilt.len(), 1);
730 assert_eq!(rebuilt[0].1.hash, Hash::of(b"index me"));
731 }
732
733 #[test]
734 fn entry_meta_len_is_54_and_idx_record_len_is_62() {
735 assert_eq!(ENTRY_META_LEN, 54);
736 assert_eq!(IDX_RECORD_LEN, 62);
737 }
738
739 #[test]
740 fn append_always_emits_reserved_flags_and_key_epoch() {
741 let dir = tempdir().unwrap();
742 let partition_id = PartitionId::derive("reserved-values-partition");
743 let mut writer =
744 PackWriter::open_active(&dir.path().join("active/active.pack"), partition_id).unwrap();
745 let (codec, payload) = encode(b"ordinary entry").unwrap();
746 let offset = writer
747 .append(Hash::of(b"ordinary entry"), codec, 14, &payload)
748 .unwrap();
749 let (meta, _) = writer.read_payload_at(offset).unwrap();
750 assert_eq!(meta.flags, 0x00);
751 assert_eq!(meta.key_epoch, 0);
752 meta.validate_reserved().unwrap();
753 }
754
755 #[test]
756 fn get_at_rejects_non_reserved_flags() {
757 let dir = tempdir().unwrap();
758 let packs_dir = dir.path().join("packs");
759 let partition_id = PartitionId::derive("bad-flags-partition");
760 let mut writer =
761 PackWriter::open_active(&dir.path().join("active/active.pack"), partition_id).unwrap();
762 let data = b"tampered meta";
763 let (codec, payload) = encode(data).unwrap();
764 let meta = EntryMeta {
765 hash: Hash::of(data),
766 codec,
767 flags: 0x01, key_epoch: 0,
769 uncompressed_len: data.len() as u64,
770 stored_len: payload.len() as u64,
771 };
772 let offset = writer.append_raw(&meta, &payload).unwrap();
773 let (_pack_id, pack_path) = writer.seal(&packs_dir).unwrap();
774
775 let err = get_at(&pack_path, offset).expect_err("non-reserved flags must be rejected");
776 assert!(matches!(err, StorageError::CorruptPack(_)));
777
778 let (raw_meta, raw_payload) = get_raw_at(&pack_path, offset).unwrap();
781 assert_eq!(raw_meta.flags, 0x01);
782 assert_eq!(raw_payload, payload);
783 }
784
785 #[test]
786 fn get_at_rejects_non_reserved_key_epoch() {
787 let dir = tempdir().unwrap();
788 let packs_dir = dir.path().join("packs");
789 let partition_id = PartitionId::derive("bad-key-epoch-partition");
790 let mut writer =
791 PackWriter::open_active(&dir.path().join("active/active.pack"), partition_id).unwrap();
792 let data = b"tampered epoch";
793 let (codec, payload) = encode(data).unwrap();
794 let meta = EntryMeta {
795 hash: Hash::of(data),
796 codec,
797 flags: 0x00,
798 key_epoch: 7, uncompressed_len: data.len() as u64,
800 stored_len: payload.len() as u64,
801 };
802 let offset = writer.append_raw(&meta, &payload).unwrap();
803 let (_pack_id, pack_path) = writer.seal(&packs_dir).unwrap();
804
805 let err = get_at(&pack_path, offset).expect_err("non-reserved key_epoch must be rejected");
806 assert!(matches!(err, StorageError::CorruptPack(_)));
807 }
808
809 #[test]
810 fn get_at_rejects_sealed_codec_at_v3() {
811 let dir = tempdir().unwrap();
812 let packs_dir = dir.path().join("packs");
813 let partition_id = PartitionId::derive("sealed-codec-partition");
814 let mut writer =
815 PackWriter::open_active(&dir.path().join("active/active.pack"), partition_id).unwrap();
816 let data = b"sealed at v3, rejected";
817 let meta = EntryMeta {
818 hash: Hash::of(data),
819 codec: Codec::Sealed,
820 flags: 0x00,
821 key_epoch: 0,
822 uncompressed_len: data.len() as u64,
823 stored_len: data.len() as u64,
824 };
825 let offset = writer.append_raw(&meta, data).unwrap();
826 let (_pack_id, pack_path) = writer.seal(&packs_dir).unwrap();
827
828 let err = get_at(&pack_path, offset).expect_err("Codec::Sealed must be rejected at v3");
829 assert!(matches!(err, StorageError::CorruptPack(_)));
830 }
831
832 #[test]
833 fn append_raw_preserves_meta_through_a_copy() {
834 let source_dir = tempdir().unwrap();
838 let dest_dir = tempdir().unwrap();
839 let partition_id = PartitionId::derive("append-raw-copy-partition");
840
841 let mut source =
842 PackWriter::open_active(&source_dir.path().join("active/active.pack"), partition_id)
843 .unwrap();
844 let data = b"copy me forward with meta intact";
845 let (codec, payload) = encode(data).unwrap();
846 let source_meta = EntryMeta {
847 hash: Hash::of(data),
848 codec,
849 flags: 0x00,
850 key_epoch: 0,
851 uncompressed_len: data.len() as u64,
852 stored_len: payload.len() as u64,
853 };
854 let source_offset = source.append_raw(&source_meta, &payload).unwrap();
855 let (fetched_meta, fetched_payload) = source.read_payload_at(source_offset).unwrap();
856 assert_eq!(fetched_meta, source_meta);
857
858 let mut dest =
859 PackWriter::open_active(&dest_dir.path().join("active/active.pack"), partition_id)
860 .unwrap();
861 let dest_offset = dest.append_raw(&fetched_meta, &fetched_payload).unwrap();
862 let (copied_meta, copied_payload) = dest.read_payload_at(dest_offset).unwrap();
863
864 assert_eq!(
865 copied_meta, source_meta,
866 "meta must survive the copy exactly"
867 );
868 assert_eq!(copied_payload, payload);
869 }
870}