Skip to content

Commit 5d395de

Browse files
javieratomicclaude
andauthored
Link received payload objects into the core cache instead of copying (#125)
A rank export receives each cache payload object as a complete companion wrapper in a synced temporary file in the core cache. `store_slice` then hashes the received payload, copies it into a new wrapper in cache staging, syncs the copy, and hashes the installed copy again: three full reads and one write and sync per object, on the receiving stream's thread. When the received file already is the wrapper `store_slice` would write, the copy, its write and its sync repeat work whose result is already on disk. In a DeepSeek V4.1 Flash TP3 export on three DGX Spark GB10 hosts with an empty core cache, rank zero receives 203.5 GB from the other two ranks this way. Before this change the receiver always called `store_slice`. Now it first calls the new `Root::adopt_companion`, which links the received file itself into cache staging when it is byte-for-byte that wrapper; both hashes remain. The link step is shared with directory publication, which already hard-linked source files that are canonical wrappers from its own code in `export.rs`; that code moves into `container::link_companion`. It checks the length and leading bytes against `companion_prefix`, links the opened file through its descriptor so that a replaced path cannot be linked instead, checks that the link names the same inode, and hashes the linked file against the declared identity; a mismatched identity is an error. For a file that is not the canonical wrapper, or a link the filesystem refuses, `link_companion` returns false, `adopt_companion` returns `None`, and the receiver stores the slice as before. Adoption checks and links the descriptor the receiver opened, the same one `store_slice` copies from. An already cached identity returns the verified cached object, as `store_slice` does. Publication is unchanged: the object is made immutable, linked under its identity and verified once more, and the receiver closes its writable descriptor before the file is published. Core format, cache layout and object identities are unchanged, and directory publication keeps its behavior, error kinds and messages. Adoption needs Linux (`linkat` through `/proc/self/fd`); on other platforms received objects are copied as before. Expected result: with an empty core cache, "Receive rank export payloads" no longer copies, writes and syncs each received object. On an earlier tree, with an earlier version of this adoption, that phase took 280.6 s instead of 457.8 s; this commit itself was not measured on its current base. Evidence: on `f9aec99c` with this commit, helios `cargo test --features runtime-core,server --lib`: 1431 passed, 4 failed, 33 ignored. The 4 failures are chat-template tests that panic because FLARE_TEST_TEMPLATE_DIR was not set; the same 4 fail on `f9aec99c` without this commit, where 1430 pass. With that directory prepared by tests/frontend/prepare_templates.py, the suite passed with this change on its previous base `bbad44fe` (`--release`: 1335 passed, 0 failed, 26 ignored). heliopause `cargo test` on `f9aec99c` with this commit: 196 passed, 0 failed, 4 ignored. A helios test covers adoption by link (same inode); a wrapper with an extra tensor and a wrapper of the right length with different header bytes, both declined; a mismatched identity, which is rejected; a second arrival of a cached identity, which returns the cached object; and that cache staging is empty after the declined, rejected and cached cases. A heliopause test checks that the receiver's install step adopts a canonical wrapper (same inode) and copies another framing into a new file. The existing directory publication tests cover the shared link step. The 203.5 GB is the byte count reported by "Receive rank export payloads" in an export on `d2b5c5f3` without this change, with an empty core cache; there that phase took 462.3 s. The measurement above used full TP3 exports with the same model and export command, an empty core cache (then named the package cache) and an empty forward compilation cache, built from `ca1f960e` plus an earlier version of #124 that published cache payloads concurrently and without the directory publication changes merged as `e13ecb74`; its adoption step linked the received file by path instead of through `link_companion`. There, with the default 8 transfer streams, "Receive rank export payloads" took 280.6 s with adoption and 457.8 s without it (477.2 s without it and `--transfer-streams 16`), and the whole export phase took 1473.2 s against 1677.4 s; the package exported with adoption served with `flare run` and answered a 262k-token prompt that asks for 16 values placed through the context with all 16 correct, with identical output with an empty and with a warm prefix cache. One export per configuration was measured. The payload is still read twice after it arrives (identity check and post-installation verification) instead of being hashed while it streams. Design-Signed-Off-By: Claude Fable 5.2; design-review=ed22 Signed-off-by: Javier López <59578422+javieratomic@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent e60a70d commit 5d395de

4 files changed

Lines changed: 279 additions & 113 deletions

File tree

‎heliopause/src/export/transfer.rs‎

Lines changed: 65 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -741,9 +741,11 @@ fn verify_cached_payload(
741741

742742
/// Adopt a received cache payload object under its signed payload identity.
743743
///
744-
/// The staged file is a complete companion container; its payload bytes are
745-
/// verified against the declared identity by the cache insertion path, so a
746-
/// corrupt or mislabelled object never enters the cache.
744+
/// The staged file is a complete, synced companion container; its payload bytes
745+
/// are verified against the declared identity by the cache insertion path, so a
746+
/// corrupt or mislabelled object never enters the cache. A canonical wrapper is
747+
/// linked into the cache as is; otherwise, or when the filesystem refuses the
748+
/// link, the slice is copied.
747749
fn install_payload_object(
748750
cache: &Path,
749751
id: helios_core::core::PayloadId,
@@ -758,7 +760,10 @@ fn install_payload_object(
758760
"received payload object length differs from its declared group",
759761
));
760762
}
761-
let object = root.store_slice(Some(id), &slice)?;
763+
let object = match root.adopt_companion(id, &slice, &partial.display().to_string())? {
764+
Some(object) => object,
765+
None => root.store_slice(Some(id), &slice)?,
766+
};
762767
if object.length() != length {
763768
return Err(invalid("received payload object has the wrong length"));
764769
}
@@ -1038,6 +1043,9 @@ fn receive_rank(
10381043
fs::Permissions::from_mode(0o444)
10391044
})?;
10401045
}
1046+
// The synced file may become a cache object itself: close the
1047+
// writable descriptor before it is published.
1048+
drop(file);
10411049
if info.payload.is_some() {
10421050
let id = helios_core::core::PayloadId::parse(
10431051
info.payload.as_deref().unwrap_or_default(),
@@ -1444,6 +1452,59 @@ mod tests {
14441452
(output, id)
14451453
}
14461454

1455+
#[test]
1456+
#[cfg(target_os = "linux")]
1457+
fn received_canonical_wrapper_is_adopted_and_others_are_copied() {
1458+
use std::os::unix::fs::MetadataExt;
1459+
let directory = Directory::new();
1460+
let payload: Vec<u8> = (0..4096u32).map(|i| (i % 97) as u8).collect();
1461+
let (_, id) = cache_backed_output(&directory, &payload);
1462+
let sent = directory.0.join("sender-cache").join("blobs").join(id.file_name());
1463+
let cache = directory.0.join("cache");
1464+
helios_core::core::cache::Root::open(&cache).unwrap();
1465+
1466+
// The receiver writes the sender's object file under the cache's blobs directory.
1467+
let partial = cache.join("blobs").join(".rank-blob-canonical");
1468+
fs::copy(&sent, &partial).unwrap();
1469+
let object = install_payload_object(&cache, id, payload.len() as u64, &partial).unwrap();
1470+
assert_eq!(
1471+
fs::metadata(object.path()).unwrap().ino(),
1472+
fs::metadata(&partial).unwrap().ino(),
1473+
"a canonical received wrapper was copied instead of adopted"
1474+
);
1475+
drop(object);
1476+
1477+
// Another framing of the same payload is stored through its slice in a new file.
1478+
let other = directory.0.join("other-cache");
1479+
helios_core::core::cache::Root::open(&other).unwrap();
1480+
let framed = other.join("blobs").join(".rank-blob-framed");
1481+
let slice = helios_core::core::container::Container::open(&sent)
1482+
.unwrap()
1483+
.tensor(helios_core::core::container::COMPANION_TENSOR)
1484+
.unwrap();
1485+
let mut writer = helios_core::core::container::Writer::new(
1486+
fs::File::create(&framed).unwrap(),
1487+
helios_core::core::container::PAYLOAD_FORMAT,
1488+
)
1489+
.unwrap();
1490+
writer
1491+
.add(
1492+
helios_core::core::container::COMPANION_TENSOR,
1493+
slice.len(),
1494+
helios_core::core::container::Source::Slice(slice),
1495+
)
1496+
.unwrap();
1497+
writer
1498+
.add("extra.tail", 3, helios_core::core::container::Source::Bytes(vec![1, 2, 3]))
1499+
.unwrap();
1500+
writer.finish().unwrap();
1501+
let copied = install_payload_object(&other, id, payload.len() as u64, &framed).unwrap();
1502+
assert_ne!(
1503+
fs::metadata(copied.path()).unwrap().ino(),
1504+
fs::metadata(&framed).unwrap().ino()
1505+
);
1506+
}
1507+
14471508
#[test]
14481509
fn repeated_identical_payload_groups_share_one_object_and_round_trip() {
14491510
let directory = Directory::new();

‎helios/src/core/cache.rs‎

Lines changed: 113 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,8 @@ thread_local! {
4545
}
4646
use crate::Result;
4747
use crate::core::container::{
48-
COMPANION_TENSOR, Container, PAYLOAD_FORMAT, Slice, Source, Writer, open_relative,
49-
validate_relative_path, write_companion,
48+
COMPANION_TENSOR, Container, PAYLOAD_FORMAT, Slice, Source, Writer, link_companion,
49+
open_relative, validate_relative_path, write_companion,
5050
};
5151

5252
const MAX_NAME: usize = 128;
@@ -1502,11 +1502,7 @@ impl Root {
15021502
)
15031503
.into());
15041504
}
1505-
if let Some(object) = self.payload(id)? {
1506-
if object.length() != slice.len() {
1507-
return Err(format!("cached object {id} has a different length").into());
1508-
}
1509-
verify_slice(object.slice(), id, None)?;
1505+
if let Some(object) = self.cached_slice(id, slice.len())? {
15101506
return Ok(object);
15111507
}
15121508
let transaction = Transaction::begin(self)?;
@@ -1528,6 +1524,48 @@ impl Root {
15281524
result
15291525
}
15301526

1527+
/// Adopt the complete, durable companion wrapper file that holds `slice` as
1528+
/// a payload object without copying it.
1529+
///
1530+
/// The opened file is linked into staging only when it is byte-for-byte
1531+
/// the wrapper `store_slice` would write; the linked file must then hash to
1532+
/// `declared`, and publication verifies the installed object again. `None`
1533+
/// means the file is not that canonical wrapper or the filesystem refuses
1534+
/// the link, and the caller stores its slice instead. A mismatched identity
1535+
/// is an error. An already cached identity returns the cached object. The
1536+
/// caller must have synced the file under `slice` and must not modify it
1537+
/// afterwards: it becomes the object. `label` names the payload in errors.
1538+
pub fn adopt_companion(
1539+
&self,
1540+
declared: PayloadId,
1541+
slice: &Slice,
1542+
label: &str,
1543+
) -> Result<Option<PayloadObject>> {
1544+
let transaction = Transaction::begin(self)?;
1545+
let staged = transaction.staging_file("wrapped")?;
1546+
if !link_companion(slice, declared, &staged, label)? {
1547+
return Ok(None);
1548+
}
1549+
let cached = self.cached_slice(declared, slice.len());
1550+
if !matches!(cached, Ok(None)) {
1551+
let _ = fs::remove_file(&staged);
1552+
return cached;
1553+
}
1554+
self.publish_payload(&transaction, &staged, declared, slice.len()).map(Some)
1555+
}
1556+
1557+
/// A cached object for `id`, verified, when one is already installed.
1558+
fn cached_slice(&self, id: PayloadId, length: u64) -> Result<Option<PayloadObject>> {
1559+
let Some(object) = self.payload(id)? else {
1560+
return Ok(None);
1561+
};
1562+
if object.length() != length {
1563+
return Err(format!("cached object {id} has a different length").into());
1564+
}
1565+
verify_slice(object.slice(), id, None)?;
1566+
Ok(Some(object))
1567+
}
1568+
15311569
/// Insert an optional retention source while distinguishing an invalid
15321570
/// source from publication failure. A missing/invalid source yields
15331571
/// `Ok(None)`; object-store or staging I/O errors are returned.
@@ -4882,6 +4920,74 @@ mod tests {
48824920
assert_eq!(root.collect().unwrap().objects, 1);
48834921
}
48844922

4923+
#[test]
4924+
#[cfg(target_os = "linux")]
4925+
fn adopt_companion_links_canonical_wrappers_and_declines_others() {
4926+
use std::os::unix::fs::MetadataExt;
4927+
let temporary = Temporary::new();
4928+
let root = temporary.root();
4929+
let bytes: Vec<u8> = (0..2 * 1024 * 1024 + 77).map(|i| (i % 241) as u8).collect();
4930+
let raw = temporary.0.join("slice.bin");
4931+
fs::write(&raw, &bytes).unwrap();
4932+
let slice = Slice::new(Arc::new(File::open(&raw).unwrap()), 0, bytes.len() as u64).unwrap();
4933+
let id = PayloadId::of(&bytes);
4934+
let adopt = |declared: PayloadId, path: &Path| {
4935+
let slice = Container::open(path).unwrap().tensor(COMPANION_TENSOR).unwrap();
4936+
root.adopt_companion(declared, &slice, "test")
4937+
};
4938+
let staging_is_empty = || {
4939+
fs::read_dir(root.root.join("staging").join("wrapped"))
4940+
.unwrap()
4941+
.count()
4942+
== 0
4943+
};
4944+
4945+
// A framing that is not the canonical wrapper is left to store_slice.
4946+
let framed = temporary.0.join("framed.safetensors");
4947+
let mut writer = Writer::new(File::create(&framed).unwrap(), PAYLOAD_FORMAT).unwrap();
4948+
writer.add(COMPANION_TENSOR, bytes.len() as u64, Source::Slice(slice.clone())).unwrap();
4949+
writer.add("extra.tail", 3, Source::Bytes(vec![1, 2, 3])).unwrap();
4950+
writer.finish().unwrap();
4951+
assert!(adopt(id, &framed).unwrap().is_none());
4952+
4953+
// Same length as the canonical wrapper, but its header padding differs.
4954+
let padded = temporary.0.join("padded.safetensors");
4955+
write_companion(&mut File::create(&padded).unwrap(), &slice).unwrap();
4956+
let mut wrapper = fs::read(&padded).unwrap();
4957+
let header_end = 8 + u64::from_le_bytes(wrapper[..8].try_into().unwrap()) as usize;
4958+
assert_eq!(wrapper[header_end - 1], b' ');
4959+
wrapper[header_end - 1] = b'\n';
4960+
fs::write(&padded, &wrapper).unwrap();
4961+
assert!(adopt(id, &padded).unwrap().is_none());
4962+
assert!(staging_is_empty());
4963+
4964+
let received = temporary.0.join("received.safetensors");
4965+
write_companion(&mut File::create(&received).unwrap(), &slice).unwrap();
4966+
assert!(adopt(PayloadId::of(b"other"), &received).is_err());
4967+
assert!(root.payload(id).unwrap().is_none());
4968+
assert!(staging_is_empty());
4969+
4970+
// The canonical wrapper becomes the object itself: no copy is written.
4971+
let object = adopt(id, &received).unwrap().unwrap();
4972+
assert_eq!(object.id(), id);
4973+
assert_eq!(object.length(), bytes.len() as u64);
4974+
assert_eq!(
4975+
fs::metadata(object.path()).unwrap().ino(),
4976+
fs::metadata(&received).unwrap().ino()
4977+
);
4978+
fs::remove_file(&received).unwrap();
4979+
let mut copy = vec![0; bytes.len()];
4980+
object.slice().read_at(0, &mut copy).unwrap();
4981+
assert_eq!(copy, bytes);
4982+
4983+
// A second arrival of a cached identity returns the cached object.
4984+
let again_path = temporary.0.join("again.safetensors");
4985+
write_companion(&mut File::create(&again_path).unwrap(), &slice).unwrap();
4986+
let again = adopt(id, &again_path).unwrap().unwrap();
4987+
assert_eq!(again.path(), object.path());
4988+
assert!(staging_is_empty());
4989+
}
4990+
48854991
#[test]
48864992
#[cfg(unix)]
48874993
fn legacy_import_streams_large_companions_and_publishes_once() {

‎helios/src/core/container.rs‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -571,6 +571,105 @@ pub(crate) fn companion_prefix(nbytes: u64) -> Result<Vec<u8>> {
571571
Ok(prefix)
572572
}
573573

574+
/// Hard-link the file under `payload` to `to` when that file is exactly the
575+
/// deterministic companion wrapper of the payload, then verify the linked file
576+
/// against `id`. Returns false, creating no file, when the file is not that
577+
/// wrapper or the filesystem refuses the link; the caller then copies. An
578+
/// existing `to` is an error. If the linked file fails verification, the link
579+
/// is removed and the error returned; `label` names the payload in errors.
580+
#[cfg(target_os = "linux")]
581+
pub(crate) fn link_companion(payload: &Slice, id: PayloadId, to: &Path, label: &str) -> Result<bool> {
582+
use std::os::unix::ffi::OsStrExt;
583+
use std::os::unix::fs::MetadataExt;
584+
use std::os::unix::io::AsRawFd;
585+
586+
// I/O failures are state errors; a linked file that is not the payload's wrapper
587+
// or identity, and an unrepresentable path, are manifest errors.
588+
let failed = |context: &str, error: io::Error| -> crate::Error {
589+
format!("{context}: {error}").into()
590+
};
591+
592+
let nbytes = payload.len();
593+
let prefix = companion_prefix(nbytes)?;
594+
let source = payload.file();
595+
let metadata = source
596+
.metadata()
597+
.map_err(|e| failed("inspect payload source", e))?;
598+
let wrapper_len = prefix.len() as u64 + nbytes;
599+
if payload.offset() != prefix.len() as u64
600+
|| !metadata.is_file()
601+
|| metadata.len() != wrapper_len
602+
{
603+
return Ok(false);
604+
}
605+
let mut header = vec![0u8; prefix.len()];
606+
// std `FileExt` keeps the short-read message that directory publication reports.
607+
std::os::unix::fs::FileExt::read_exact_at(&**source, &mut header, 0)
608+
.map_err(|e| failed("read payload wrapper", e))?;
609+
if header != prefix {
610+
return Ok(false);
611+
}
612+
if let Some(parent) = to.parent() {
613+
std::fs::create_dir_all(parent).map_err(|e| failed("create payload directory", e))?;
614+
}
615+
// The descriptor link names the pinned file itself, not a path that could
616+
// have been replaced since the source was opened.
617+
let from = std::ffi::CString::new(format!("/proc/self/fd/{}", source.as_raw_fd()))
618+
.map_err(|_| invalid("payload source descriptor path"))?;
619+
let destination = std::ffi::CString::new(to.as_os_str().as_bytes())
620+
.map_err(|_| invalid(format!("payload path {label:?} contains NUL")))?;
621+
// SAFETY: Both arguments are NUL-terminated paths that outlive the call.
622+
let status = unsafe {
623+
libc::linkat(
624+
libc::AT_FDCWD,
625+
from.as_ptr(),
626+
libc::AT_FDCWD,
627+
destination.as_ptr(),
628+
libc::AT_SYMLINK_FOLLOW,
629+
)
630+
};
631+
if status != 0 {
632+
let error = io::Error::last_os_error();
633+
// An existing destination is a publication conflict, as for a copy.
634+
if error.kind() == io::ErrorKind::AlreadyExists {
635+
return Err(failed("link companion", error));
636+
}
637+
return Ok(false);
638+
}
639+
let result = (|| -> Result<()> {
640+
let linked = File::open(to).map_err(|e| failed("open linked companion", e))?;
641+
let linked_metadata = linked
642+
.metadata()
643+
.map_err(|e| failed("inspect linked companion", e))?;
644+
if (linked_metadata.dev(), linked_metadata.ino()) != (metadata.dev(), metadata.ino()) {
645+
return Err(invalid("linked companion is not the payload source file"));
646+
}
647+
// Verify the file published under `to`, not the pre-link source reads.
648+
let mut header = vec![0u8; prefix.len()];
649+
std::os::unix::fs::FileExt::read_exact_at(&linked, &mut header, 0)
650+
.map_err(|e| failed("read linked companion", e))?;
651+
if header != prefix || linked_metadata.len() != wrapper_len {
652+
return Err(invalid("linked companion is not the payload wrapper"));
653+
}
654+
let slice = Slice::new(Arc::new(linked), prefix.len() as u64, nbytes)?;
655+
if slice.digest()? != id {
656+
return Err(invalid(format!(
657+
"payload {label} bytes do not match the assigned identity"
658+
)));
659+
}
660+
Ok(())
661+
})();
662+
if result.is_err() {
663+
let _ = std::fs::remove_file(to);
664+
}
665+
result.map(|()| true)
666+
}
667+
668+
#[cfg(not(target_os = "linux"))]
669+
pub(crate) fn link_companion(_payload: &Slice, _id: PayloadId, _to: &Path, _label: &str) -> Result<bool> {
670+
Ok(false)
671+
}
672+
574673
fn write_source<W: Write>(
575674
output: &mut W,
576675
name: &str,

0 commit comments

Comments
 (0)