Reuse sealed KAR archive across Linux inference processes
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
//! Native and explicitly selected experimental CUDA owner actor.
|
||||
//! CUDA owners and borrowed buffers remain ordinary locals on that thread.
|
||||
pub use crate::model_binding::qwen4exp_kar_ple::InheritedKarArchive;
|
||||
use crate::{
|
||||
model_binding::qwen4exp_input::{InputBindingError, InputConstants, ModelBinding},
|
||||
qwen_forward::{
|
||||
@@ -69,6 +70,8 @@ pub struct NativeBackendConfig {
|
||||
pub context_tokens: u32,
|
||||
/// Local archive and private staging parent; never sourced from RPCs.
|
||||
pub kar_ple_source: Option<(PathBuf, PathBuf)>,
|
||||
/// Explicit presealed operator handle; mutually exclusive with kar_ple_source.
|
||||
pub kar_ple_inherited: Option<InheritedKarArchive>,
|
||||
/// Fixed draft pack and its private staging parent, operator supplied only.
|
||||
pub mtp_source: Option<(PathBuf, PathBuf)>,
|
||||
}
|
||||
@@ -89,6 +92,7 @@ pub fn spawn_backend(config: NativeBackendConfig) -> Result<Box<dyn Backend>, Ba
|
||||
|| config.gpu_budget_bytes == 0
|
||||
|| usize::try_from(config.gpu_budget_bytes).is_err()
|
||||
|| i32::try_from(config.gpu_device_ordinal).is_err()
|
||||
|| (config.kar_ple_source.is_some() && config.kar_ple_inherited.is_some())
|
||||
{
|
||||
return Err(invalid("invalid native resource configuration"));
|
||||
}
|
||||
@@ -98,7 +102,7 @@ pub fn spawn_backend(config: NativeBackendConfig) -> Result<Box<dyn Backend>, Ba
|
||||
shutdown: AtomicBool::new(false),
|
||||
active: Mutex::new(None),
|
||||
});
|
||||
let kar_configured = config.kar_ple_source.is_some();
|
||||
let kar_configured = config.kar_ple_source.is_some() || config.kar_ple_inherited.is_some();
|
||||
let mtp_configured = config.mtp_source.is_some();
|
||||
let worker_shared = Arc::clone(&shared);
|
||||
let instance = INSTANCE.fetch_add(1, Ordering::Relaxed);
|
||||
@@ -429,8 +433,11 @@ fn serve_load(
|
||||
identity: (u64, u64),
|
||||
) -> Result<(), BackendError> {
|
||||
validate_load(&model, &requested).map_err(|e| load_failure(LoadPhase::Config, e))?;
|
||||
validate_kar_selection(&requested, config.kar_ple_source.is_some())
|
||||
.map_err(|e| load_failure(LoadPhase::Selection, e))?;
|
||||
validate_kar_selection(
|
||||
&requested,
|
||||
config.kar_ple_source.is_some() || config.kar_ple_inherited.is_some(),
|
||||
)
|
||||
.map_err(|e| load_failure(LoadPhase::Selection, e))?;
|
||||
validate_mtp_selection(&requested, config.mtp_source.is_some())
|
||||
.map_err(|e| load_failure(LoadPhase::Selection, e))?;
|
||||
if requested
|
||||
@@ -477,11 +484,15 @@ fn serve_load(
|
||||
let binding = match &requested.inference_mode {
|
||||
InferenceMode::Native => ModelBinding::from_artifact(artifact),
|
||||
InferenceMode::ExperimentalKarPle { .. } => {
|
||||
let (source, staging) = config
|
||||
.kar_ple_source
|
||||
.as_ref()
|
||||
.ok_or_else(|| unsupported("KAR PLE operator source is absent"))?;
|
||||
ModelBinding::from_artifact_with_pinned_kar_ple(artifact, source, staging)
|
||||
if let Some(source) = config.kar_ple_inherited.as_ref() {
|
||||
ModelBinding::from_artifact_with_inherited_kar_ple(artifact, source)
|
||||
} else {
|
||||
let (source, staging) = config
|
||||
.kar_ple_source
|
||||
.as_ref()
|
||||
.ok_or_else(|| unsupported("KAR PLE operator source is absent"))?;
|
||||
ModelBinding::from_artifact_with_pinned_kar_ple(artifact, source, staging)
|
||||
}
|
||||
}
|
||||
InferenceMode::ExperimentalMtp { profile_id } => {
|
||||
let (source, staging) = config
|
||||
@@ -489,17 +500,23 @@ fn serve_load(
|
||||
.as_ref()
|
||||
.ok_or_else(|| unsupported("MTP operator source is absent"))?;
|
||||
if profile_id == KAR_MTP_PROFILE {
|
||||
let (kar, kar_staging) = config
|
||||
.kar_ple_source
|
||||
.as_ref()
|
||||
.ok_or_else(|| unsupported("KAR PLE operator source is absent"))?;
|
||||
ModelBinding::from_artifact_with_pinned_kar_mtp(
|
||||
artifact,
|
||||
kar,
|
||||
kar_staging,
|
||||
source,
|
||||
staging,
|
||||
)
|
||||
if let Some(kar) = config.kar_ple_inherited.as_ref() {
|
||||
ModelBinding::from_artifact_with_inherited_kar_mtp(
|
||||
artifact, kar, source, staging,
|
||||
)
|
||||
} else {
|
||||
let (kar, kar_staging) = config
|
||||
.kar_ple_source
|
||||
.as_ref()
|
||||
.ok_or_else(|| unsupported("KAR PLE operator source is absent"))?;
|
||||
ModelBinding::from_artifact_with_pinned_kar_mtp(
|
||||
artifact,
|
||||
kar,
|
||||
kar_staging,
|
||||
source,
|
||||
staging,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
ModelBinding::from_artifact_with_pinned_mtp(artifact, source, staging)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
//! New real Linux seal/FD gate; tiny metadata fixture, no CUDA/model capability.
|
||||
#![cfg(target_os = "linux")]
|
||||
use super::*;
|
||||
use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, fcntl_get_seals, memfd_create};
|
||||
use std::{
|
||||
fs::{self, DirBuilder, OpenOptions},
|
||||
io::{Read, Seek, SeekFrom, Write},
|
||||
os::{
|
||||
fd::AsRawFd,
|
||||
unix::fs::{DirBuilderExt, FileExt, MetadataExt, OpenOptionsExt},
|
||||
},
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
};
|
||||
|
||||
const PAYLOAD: [u8; 8] = [0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe];
|
||||
// Independent offline SHA-256 of the literal bytes above, never candidate-derived.
|
||||
const PAYLOAD_SHA: [u8; 32] = [
|
||||
0xae, 0xb7, 0x5d, 0x15, 0x14, 0xcb, 0xdb, 0x00, 0x1a, 0xf6, 0x5f, 0x88, 0x26, 0x55, 0x3d, 0xf8,
|
||||
0xfe, 0x6b, 0x2e, 0x11, 0xc6, 0x7f, 0xf3, 0xa5, 0x44, 0x35, 0xea, 0x40, 0x08, 0x94, 0xd7, 0xea,
|
||||
];
|
||||
static NEXT: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
fn required() -> SealFlags {
|
||||
SealFlags::WRITE | SealFlags::GROW | SealFlags::SHRINK | SealFlags::SEAL
|
||||
}
|
||||
fn memfd(bytes: &[u8], seals: SealFlags) -> File {
|
||||
let mut file = File::from(
|
||||
memfd_create(
|
||||
"leleka-inherited-sdet",
|
||||
MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING,
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
file.write_all(bytes).unwrap();
|
||||
if !seals.is_empty() {
|
||||
fcntl_add_seals(&file, seals).unwrap();
|
||||
}
|
||||
file
|
||||
}
|
||||
fn descriptor(file: &File) -> u32 {
|
||||
u32::try_from(file.as_raw_fd()).unwrap()
|
||||
}
|
||||
|
||||
struct OwnFixture {
|
||||
directory: PathBuf,
|
||||
path: PathBuf,
|
||||
}
|
||||
impl OwnFixture {
|
||||
fn new() -> Self {
|
||||
let directory = std::env::temp_dir().join(format!(
|
||||
"leleka-inherited-sdet-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
DirBuilder::new().mode(0o700).create(&directory).unwrap();
|
||||
let path = directory.join("literal.bin");
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.mode(0o600)
|
||||
.open(&path)
|
||||
.unwrap();
|
||||
file.write_all(&PAYLOAD).unwrap();
|
||||
drop(file);
|
||||
Self { directory, path }
|
||||
}
|
||||
}
|
||||
impl Drop for OwnFixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_file(&self.path);
|
||||
let _ = fs::remove_dir(&self.directory);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inherited_real_memfd_requires_irreversible_seals_and_independent_owned_handle() {
|
||||
let fixture = OwnFixture::new();
|
||||
let mut source = memfd(&PAYLOAD, required());
|
||||
assert!(source.metadata().unwrap().is_file());
|
||||
assert_eq!(source.metadata().unwrap().len(), 8);
|
||||
assert_eq!(source.metadata().unwrap().nlink(), 0);
|
||||
source.seek(SeekFrom::Start(5)).unwrap();
|
||||
let mut reader = open_sealed_archive_fd(descriptor(&source), 8).unwrap();
|
||||
assert_ne!(reader.as_raw_fd(), source.as_raw_fd());
|
||||
assert_eq!(reader.stream_position().unwrap(), 0);
|
||||
let mut bytes = [0; 8];
|
||||
reader.read_exact(&mut bytes).unwrap();
|
||||
assert_eq!(bytes, PAYLOAD);
|
||||
assert_eq!(source.stream_position().unwrap(), 5); // Genuine independent OFD.
|
||||
assert!(fcntl_get_seals(&reader).unwrap().contains(required()));
|
||||
// Each property is enforced by the actual kernel on the original writable
|
||||
// description, not only by a readonly reader access mode.
|
||||
assert!(source.write_at(&[0xff], 0).is_err());
|
||||
assert!(source.set_len(9).is_err());
|
||||
assert!(source.set_len(7).is_err());
|
||||
assert!(fcntl_add_seals(&source, SealFlags::empty()).is_err());
|
||||
drop(source);
|
||||
reader.rewind().unwrap();
|
||||
reader.read_exact(&mut bytes).unwrap();
|
||||
assert_eq!(bytes, PAYLOAD); // Parent/original closure cannot invalidate owner.
|
||||
assert_eq!(reader.metadata().unwrap().nlink(), 0);
|
||||
|
||||
let unsealed = memfd(&PAYLOAD, SealFlags::empty());
|
||||
assert_eq!(
|
||||
open_sealed_archive_fd(descriptor(&unsealed), 8).err(),
|
||||
Some(InputBindingError::Metadata)
|
||||
);
|
||||
drop(unsealed);
|
||||
for omitted in [
|
||||
SealFlags::WRITE,
|
||||
SealFlags::GROW,
|
||||
SealFlags::SHRINK,
|
||||
SealFlags::SEAL,
|
||||
] {
|
||||
let partial = memfd(&PAYLOAD, required() & !omitted);
|
||||
assert_eq!(
|
||||
open_sealed_archive_fd(descriptor(&partial), 8).err(),
|
||||
Some(InputBindingError::Metadata)
|
||||
);
|
||||
drop(partial);
|
||||
}
|
||||
for bytes in [&PAYLOAD[..7], &[0u8; 9][..]] {
|
||||
let wrong = memfd(bytes, required());
|
||||
assert_eq!(
|
||||
open_sealed_archive_fd(descriptor(&wrong), 8).err(),
|
||||
Some(InputBindingError::Range)
|
||||
);
|
||||
drop(wrong);
|
||||
}
|
||||
let regular = File::open(&fixture.path).unwrap();
|
||||
assert_eq!(regular.metadata().unwrap().nlink(), 1);
|
||||
assert_eq!(
|
||||
open_sealed_archive_fd(descriptor(®ular), 8).err(),
|
||||
Some(InputBindingError::Range)
|
||||
);
|
||||
let directory = File::open(&fixture.directory).unwrap();
|
||||
assert_eq!(
|
||||
open_sealed_archive_fd(descriptor(&directory), 8).err(),
|
||||
Some(InputBindingError::Range)
|
||||
);
|
||||
drop(directory);
|
||||
let closed = memfd(&PAYLOAD, required());
|
||||
let closed_fd = descriptor(&closed);
|
||||
drop(closed);
|
||||
assert_eq!(
|
||||
open_sealed_archive_fd(closed_fd, 8).err(),
|
||||
Some(InputBindingError::Read)
|
||||
);
|
||||
for fd in [0, u32::MAX] {
|
||||
assert_eq!(
|
||||
open_sealed_archive_fd(fd, 8).err(),
|
||||
Some(InputBindingError::Range)
|
||||
);
|
||||
}
|
||||
|
||||
// Public admission never uses the tiny override. It cannot return a loader
|
||||
// capability for this legitimate sealed8B inode, even with a real provenance.
|
||||
assert_eq!(PINNED_ARCHIVE_BYTES, 55_295_529_472);
|
||||
assert_eq!(
|
||||
InheritedKarArchive::open(descriptor(&reader), fixture.path.clone()).err(),
|
||||
Some("inherited KAR descriptor is not a pinned sealed archive")
|
||||
);
|
||||
// Exercise the actual bounded pread SHA verifier; independent literal digest
|
||||
// acceptance is metadata-only, never substituted for production pins.
|
||||
let mut regular = regular;
|
||||
regular.seek(SeekFrom::Start(3)).unwrap();
|
||||
assert_eq!(verify_open_provenance(®ular, PAYLOAD_SHA), Ok(()));
|
||||
assert_eq!(regular.stream_position().unwrap(), 3);
|
||||
let mut corrupt = PAYLOAD_SHA;
|
||||
corrupt[31] ^= 1;
|
||||
assert_eq!(
|
||||
verify_open_provenance(®ular, corrupt),
|
||||
Err(InputBindingError::Metadata)
|
||||
);
|
||||
assert_eq!(
|
||||
verify_open_provenance(®ular, PROVENANCE_DIGEST),
|
||||
Err(InputBindingError::Metadata)
|
||||
);
|
||||
assert_eq!(regular.stream_position().unwrap(), 3);
|
||||
drop(regular);
|
||||
drop(reader);
|
||||
let directory = fixture.directory.clone();
|
||||
drop(fixture);
|
||||
assert!(!directory.exists());
|
||||
println!(
|
||||
"INHERITED_KAR_SEALS COMPLETE bytes=8 fd_refusals=13 provenance_refusals=2 kernel_irreversible=4 cleanup=complete"
|
||||
);
|
||||
}
|
||||
@@ -233,6 +233,14 @@ impl ModelBinding {
|
||||
self.expert_count
|
||||
}
|
||||
|
||||
pub(crate) fn from_artifact_with_inherited_kar_ple(
|
||||
artifact: Qwen4ExpArtifact,
|
||||
source: &super::qwen4exp_kar_ple::InheritedKarArchive,
|
||||
) -> InputResult<Self> {
|
||||
let kar = super::qwen4exp_kar_ple::load_pinned_inherited_archive(source)?;
|
||||
Self::from_artifact_with_kar_ple(artifact, kar)
|
||||
}
|
||||
|
||||
/// Construct a fresh unpublished binding; no existing session can retain it.
|
||||
/// A retained pack is metadata/weight admission only, never draft readiness.
|
||||
pub(crate) fn from_artifact_with_pinned_mtp(
|
||||
@@ -276,6 +284,20 @@ impl ModelBinding {
|
||||
self.mtp_weights()?;
|
||||
Ok(mtp::pack_identity())
|
||||
}
|
||||
|
||||
/// Both providers are fully admitted before publishing this fresh binding.
|
||||
pub(crate) fn from_artifact_with_inherited_kar_mtp(
|
||||
artifact: Qwen4ExpArtifact,
|
||||
source: &super::qwen4exp_kar_ple::InheritedKarArchive,
|
||||
mtp_source: &std::path::Path,
|
||||
mtp_root: &std::path::Path,
|
||||
) -> InputResult<Self> {
|
||||
let mut binding = Self::from_artifact_with_inherited_kar_ple(artifact, source)?;
|
||||
let weights = MtpWeights::load_pinned(&binding, mtp_source, mtp_root)?;
|
||||
weights.validate_binding(&binding)?;
|
||||
binding.mtp = Some(weights);
|
||||
Ok(binding)
|
||||
}
|
||||
pub(crate) fn expert_used_count(&self) -> u32 {
|
||||
self.expert_used_count
|
||||
}
|
||||
|
||||
@@ -4,7 +4,131 @@ use super::qwen4exp_input::{BindingIdentity, InputBindingError, InputResult, PLE
|
||||
use leleka_model_format::kar::{
|
||||
KarError, KarPlePartProvenance, KarPleProfile, KarPleProfileSpec, VerifiedKarPleArtifact,
|
||||
};
|
||||
use std::{cell::RefCell, path::Path};
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
fs::File,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
const PINNED_ARCHIVE_BYTES: u64 = 55_295_529_472;
|
||||
|
||||
/// Operator-only ownership of an already irrevocably sealed KAR archive.
|
||||
/// Construction is admission of the handles, not model or GPU verification.
|
||||
pub struct InheritedKarArchive {
|
||||
archive: File,
|
||||
provenance: File,
|
||||
}
|
||||
impl InheritedKarArchive {
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn open(fd: u32, provenance: PathBuf) -> Result<Self, &'static str> {
|
||||
let archive = open_sealed_archive_fd(fd, PINNED_ARCHIVE_BYTES)
|
||||
.map_err(|_| "inherited KAR descriptor is not a pinned sealed archive")?;
|
||||
let provenance = private_copy::open_regular(&provenance, None)
|
||||
.map_err(|_| "inherited KAR provenance is not a regular file")?;
|
||||
verify_open_provenance(&provenance, PROVENANCE_DIGEST)
|
||||
.map_err(|_| "inherited KAR provenance verification failed")?;
|
||||
Ok(Self {
|
||||
archive,
|
||||
provenance,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub fn open(_fd: u32, _provenance: PathBuf) -> Result<Self, &'static str> {
|
||||
Err("inherited KAR archive requires Linux")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn open_sealed_archive_fd(fd: u32, expected_bytes: u64) -> InputResult<File> {
|
||||
use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
|
||||
if !(3..=1_048_576).contains(&fd) || expected_bytes == 0 {
|
||||
return Err(InputBindingError::Range);
|
||||
}
|
||||
// Opening proc creates an independent file description, unlike dup/try_clone.
|
||||
// The retained owned handle remains valid after the supplied descriptor closes.
|
||||
let file = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.custom_flags(0x800) // O_NONBLOCK: reject a pipe/FIFO without waiting for its peer.
|
||||
.open(format!("/proc/self/fd/{fd}"))
|
||||
.map_err(private_copy::provenance_error)?;
|
||||
let meta = file.metadata().map_err(private_copy::provenance_error)?;
|
||||
if !meta.is_file() || meta.len() != expected_bytes || meta.nlink() != 0 {
|
||||
return Err(InputBindingError::Range);
|
||||
}
|
||||
let required = rustix::fs::SealFlags::WRITE
|
||||
| rustix::fs::SealFlags::GROW
|
||||
| rustix::fs::SealFlags::SHRINK
|
||||
| rustix::fs::SealFlags::SEAL;
|
||||
if !rustix::fs::fcntl_get_seals(&file)
|
||||
.map_err(|_| InputBindingError::Read)?
|
||||
.contains(required)
|
||||
{
|
||||
return Err(InputBindingError::Metadata);
|
||||
}
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn verify_open_provenance(file: &File, expected_digest: [u8; 32]) -> InputResult<()> {
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::os::unix::fs::FileExt;
|
||||
let meta = file.metadata().map_err(private_copy::provenance_error)?;
|
||||
let length = meta.len();
|
||||
if !meta.is_file() || length == 0 || length > 1024 * 1024 {
|
||||
return Err(InputBindingError::Range);
|
||||
}
|
||||
let mut digest = Sha256::new();
|
||||
let mut buffer = [0u8; 64 * 1024];
|
||||
let mut offset = 0u64;
|
||||
while offset < length {
|
||||
let count = usize::try_from((length - offset).min(buffer.len() as u64))
|
||||
.map_err(|_| InputBindingError::Range)?;
|
||||
file.read_exact_at(&mut buffer[..count], offset)
|
||||
.map_err(private_copy::provenance_error)?;
|
||||
digest.update(&buffer[..count]);
|
||||
offset += count as u64;
|
||||
}
|
||||
if file
|
||||
.metadata()
|
||||
.map_err(private_copy::provenance_error)?
|
||||
.len()
|
||||
!= length
|
||||
|| digest.finalize().as_slice() != expected_digest
|
||||
{
|
||||
return Err(InputBindingError::Metadata);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) fn load_pinned_inherited_archive(
|
||||
source: &InheritedKarArchive,
|
||||
) -> InputResult<VerifiedKarPleArtifact> {
|
||||
use std::os::fd::AsRawFd;
|
||||
let profile = pinned_profile().map_err(|e| input_failure(LoadPhase::Profile, e))?;
|
||||
let fd = u32::try_from(source.archive.as_raw_fd()).map_err(|_| InputBindingError::Range)?;
|
||||
let reader = open_sealed_archive_fd(fd, PINNED_ARCHIVE_BYTES)
|
||||
.map_err(|e| input_failure(LoadPhase::Source, e))?;
|
||||
verify_open_provenance(&source.provenance, PROVENANCE_DIGEST)
|
||||
.map_err(|e| input_failure(LoadPhase::Provenance, e))?;
|
||||
let inspection = leleka_model_format::kar::KarInspection::inspect(reader)
|
||||
.map_err(|e| kar_failure(LoadPhase::Inspect, e))?;
|
||||
// Only an independently owned, detached, fully sealed inode reaches this boundary.
|
||||
VerifiedKarPleArtifact::verify(inspection.into_owner_controlled(), profile)
|
||||
.map_err(|e| kar_failure(LoadPhase::Verify, e))
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub(crate) fn load_pinned_inherited_archive(
|
||||
_source: &InheritedKarArchive,
|
||||
) -> InputResult<VerifiedKarPleArtifact> {
|
||||
Err(InputBindingError::UnsupportedKind)
|
||||
}
|
||||
|
||||
#[cfg(all(test, target_os = "linux"))]
|
||||
#[path = "qwen4exp_inherited_kar_gpu.rs"]
|
||||
mod inherited_kar_tests;
|
||||
|
||||
pub(crate) struct KarRowPacket {
|
||||
payload: [u8; 50],
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Linux CUDA inference process. Operator-owned artifact paths never enter RPCs.
|
||||
use leleka_runtime::backend::{NativeBackendConfig, spawn_backend};
|
||||
use leleka_runtime::backend::{InheritedKarArchive, NativeBackendConfig, spawn_backend};
|
||||
use std::{net::SocketAddr, path::PathBuf};
|
||||
use strata_desktop_core::runtime_rpc::RuntimeServer;
|
||||
|
||||
@@ -8,7 +8,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
if args.as_slice() == ["--help"] {
|
||||
println!(
|
||||
"leleka-inference --listen IP:PORT --token-env NAME --shard0 PATH --shard1 PATH --gpu ORDINAL --gpu-budget BYTES --context-tokens COUNT [--kar-archive PATH --kar-staging PATH] [--mtp-pack PATH --mtp-staging PATH]"
|
||||
"leleka-inference --listen IP:PORT --token-env NAME --shard0 PATH --shard1 PATH --gpu ORDINAL --gpu-budget BYTES --context-tokens COUNT [--kar-archive PATH --kar-staging PATH | --kar-archive-fd N --kar-provenance PATH] [--mtp-pack PATH --mtp-staging PATH]"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
@@ -17,7 +17,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
} else {
|
||||
return Err("invalid_inference_arguments".into());
|
||||
};
|
||||
let (kar_ple_source, mtp_source) = operator_sources(extra)?;
|
||||
let sources = operator_sources_with_inherited(extra)?;
|
||||
let [
|
||||
l,
|
||||
address,
|
||||
@@ -68,8 +68,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
gpu_device_ordinal: gpu.parse().map_err(|_| "invalid_gpu_ordinal")?,
|
||||
gpu_budget_bytes: budget.parse().map_err(|_| "invalid_gpu_budget")?,
|
||||
context_tokens: context.parse().map_err(|_| "invalid_context_bound")?,
|
||||
kar_ple_source,
|
||||
mtp_source,
|
||||
kar_ple_source: sources.kar,
|
||||
kar_ple_inherited: sources
|
||||
.inherited
|
||||
.map(|(fd, provenance)| InheritedKarArchive::open(fd, provenance))
|
||||
.transpose()?,
|
||||
mtp_source: sources.mtp,
|
||||
};
|
||||
let backend = spawn_backend(config).map_err(|_| "runtime_startup_failed")?;
|
||||
let server = RuntimeServer::new(backend, token.clone())?;
|
||||
@@ -85,6 +89,52 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
|
||||
type OperatorSource = Option<(PathBuf, PathBuf)>;
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct OperatorSources {
|
||||
kar: OperatorSource,
|
||||
mtp: OperatorSource,
|
||||
inherited: Option<(u32, PathBuf)>,
|
||||
}
|
||||
|
||||
fn operator_sources_with_inherited(args: &[String]) -> Result<OperatorSources, &'static str> {
|
||||
if !args.len().is_multiple_of(4) {
|
||||
return Err("invalid_operator_source_pairs");
|
||||
}
|
||||
let mut inherited = None;
|
||||
let mut ordinary = Vec::with_capacity(args.len());
|
||||
for pair in args.as_chunks::<4>().0 {
|
||||
if pair[0] == "--kar-archive-fd" {
|
||||
if inherited.is_some()
|
||||
|| pair[2] != "--kar-provenance"
|
||||
|| pair[1].is_empty()
|
||||
|| !pair[1].bytes().all(|b| b.is_ascii_digit())
|
||||
|| pair[3].is_empty()
|
||||
{
|
||||
return Err("invalid_inherited_kar_arguments");
|
||||
}
|
||||
let fd: u32 = pair[1]
|
||||
.parse()
|
||||
.map_err(|_| "invalid_inherited_kar_arguments")?;
|
||||
if !(3..=1_048_576).contains(&fd) {
|
||||
return Err("invalid_inherited_kar_arguments");
|
||||
}
|
||||
inherited = Some((fd, PathBuf::from(&pair[3])));
|
||||
} else {
|
||||
ordinary.extend_from_slice(pair);
|
||||
}
|
||||
}
|
||||
let (kar, mtp) = operator_sources(&ordinary)?;
|
||||
if kar.is_some() && inherited.is_some() {
|
||||
return Err("conflicting_kar_sources");
|
||||
}
|
||||
Ok(OperatorSources {
|
||||
kar,
|
||||
mtp,
|
||||
inherited,
|
||||
})
|
||||
}
|
||||
|
||||
fn operator_sources(args: &[String]) -> Result<(OperatorSource, OperatorSource), &'static str> {
|
||||
let mut kar = None;
|
||||
let mut mtp = None;
|
||||
@@ -123,6 +173,68 @@ fn kar_source(args: &[String]) -> Result<Option<(PathBuf, PathBuf)>, &'static st
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod inherited_source_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn inherited_kar_pair_is_bounded_exclusive_and_keeps_mtp_independent() {
|
||||
let inherited =
|
||||
["--kar-archive-fd", "9", "--kar-provenance", "proof.json"].map(String::from);
|
||||
let mtp = ["--mtp-pack", "pack", "--mtp-staging", "private"].map(String::from);
|
||||
let expected = OperatorSources {
|
||||
kar: None,
|
||||
mtp: Some(("pack".into(), "private".into())),
|
||||
inherited: Some((9, "proof.json".into())),
|
||||
};
|
||||
for args in [
|
||||
inherited.iter().chain(&mtp).cloned().collect::<Vec<_>>(),
|
||||
mtp.iter().chain(&inherited).cloned().collect(),
|
||||
] {
|
||||
assert_eq!(operator_sources_with_inherited(&args).unwrap(), expected);
|
||||
}
|
||||
let kar = ["--kar-archive", "archive", "--kar-staging", "private"].map(String::from);
|
||||
assert!(
|
||||
operator_sources_with_inherited(
|
||||
&inherited.iter().chain(&kar).cloned().collect::<Vec<_>>()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
operator_sources_with_inherited(
|
||||
&inherited
|
||||
.iter()
|
||||
.chain(&inherited)
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
for fd in ["", "0", "1", "2", "-3", "+9", " 9", "1048577", "4294967296"] {
|
||||
let mut invalid = inherited.clone();
|
||||
invalid[1] = fd.into();
|
||||
assert!(operator_sources_with_inherited(&invalid).is_err());
|
||||
}
|
||||
for length in [1, 2, 3] {
|
||||
assert!(operator_sources_with_inherited(&inherited[..length]).is_err());
|
||||
}
|
||||
let mut invalid = inherited.clone();
|
||||
invalid[2] = "--kar-staging".into();
|
||||
assert!(operator_sources_with_inherited(&invalid).is_err());
|
||||
invalid[2] = "--kar-provenance".into();
|
||||
invalid[3].clear();
|
||||
assert!(operator_sources_with_inherited(&invalid).is_err());
|
||||
assert_eq!(
|
||||
operator_sources_with_inherited(&[]).unwrap(),
|
||||
OperatorSources {
|
||||
kar: None,
|
||||
mtp: None,
|
||||
inherited: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
Reference in New Issue
Block a user