From 181f44dd68ecd950635147c5aa3041bc18e9fb3d Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Tue, 1 Dec 2026 12:38:04 -0800 Subject: [PATCH 1/6] refactor(host,sandboxes): share guest client and primitives in host-core, use parking_lot, tighten VZ Sendable --- Cargo.lock | 5 + crates/engram-host-agent/src/blk_source.rs | 19 +- crates/engram-host-agent/src/capture_job.rs | 132 ++- crates/engram-host-agent/src/harness.rs | 2 +- crates/engram-host-agent/src/materialize.rs | 5 +- .../engram-host-agent/src/postcopy_finish.rs | 2 +- crates/engram-host-agent/src/proxyd_client.rs | 4 +- crates/engram-host-core/Cargo.toml | 7 +- crates/engram-host-core/src/epoch_stream.rs | 179 ++++ crates/engram-host-core/src/guest_client.rs | 685 ++++++++++++++++ crates/engram-host-core/src/lib.rs | 17 +- .../src/pidfd.rs | 41 +- crates/engram-sandbox-firecracker/Cargo.toml | 1 + crates/engram-sandbox-firecracker/src/lib.rs | 763 ++---------------- crates/engram-sandbox-vz/Cargo.toml | 1 + crates/engram-sandbox-vz/src/backend.rs | 242 +----- crates/engram-sandbox-vz/src/lib.rs | 2 + crates/engram-sandbox-vz/src/queue_bound.rs | 35 + crates/engram-sandbox-vz/src/vm.rs | 86 +- crates/engram-sandbox-vz/src/vsock_bridge.rs | 105 +-- crates/engram-upgrade-drain/src/lib.rs | 24 +- 21 files changed, 1192 insertions(+), 1165 deletions(-) create mode 100644 crates/engram-host-core/src/epoch_stream.rs create mode 100644 crates/engram-host-core/src/guest_client.rs rename crates/{engram-sandbox-firecracker => engram-host-core}/src/pidfd.rs (65%) create mode 100644 crates/engram-sandbox-vz/src/queue_bound.rs diff --git a/Cargo.lock b/Cargo.lock index b1a2286a4..89f656060 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2905,15 +2905,18 @@ dependencies = [ "async-trait", "bytes", "chrono", + "engram-agentd", "engram-chunk-store", "engram-core", "engram-fill", + "engram-harness-proto", "engram-storage-local", "libc", "serde", "serde_json", "tempfile", "tokio", + "tokio-stream", "tracing", "uuid", "workspace-hack", @@ -3145,6 +3148,7 @@ dependencies = [ "engram-core", "engram-egress-proxy", "engram-harness-proto", + "engram-host-core", "engram-oci", "engram-rootfs-materializer", "engram-storage-local", @@ -3213,6 +3217,7 @@ dependencies = [ "engram-agentd", "engram-core", "engram-harness-proto", + "engram-host-core", "futures", "libc", "objc2", diff --git a/crates/engram-host-agent/src/blk_source.rs b/crates/engram-host-agent/src/blk_source.rs index c99a04db9..170c6c222 100644 --- a/crates/engram-host-agent/src/blk_source.rs +++ b/crates/engram-host-agent/src/blk_source.rs @@ -20,13 +20,14 @@ //! A store error that can pass stalls the read until it does: an I/O //! error on a guest's root disk outlives the outage that caused it. +use parking_lot::Mutex; use std::collections::{HashMap, VecDeque}; use std::fs::File; use std::io::{self, Write}; use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use std::time::Duration; use async_trait::async_trait; @@ -170,7 +171,7 @@ impl BlkSource { { let ready = ready.clone(); move |_| { - if let Some(ready) = ready.lock().unwrap().take() { + if let Some(ready) = ready.lock().take() { let _ = ready.send(Ok(())); } } @@ -178,7 +179,7 @@ impl BlkSource { ) }); if let Err(e) = run { - match ready.lock().unwrap().take() { + match ready.lock().take() { Some(ready) => { let _ = ready.send(Err(e)); } @@ -214,7 +215,7 @@ impl BlkSource { /// Chunks the guest read before the copy reached them, in first-read /// order. pub fn touched(&self) -> Vec { - self.shared.touched.lock().unwrap().order.clone() + self.shared.touched.lock().order.clone() } /// Stop serving and delete the device. Refused while a device still @@ -370,7 +371,7 @@ impl Shared { // A new device's copy starts at the first delta chunk; fetch it // and the chunks after it before the kernel asks. if fresh && !shared.delta.is_empty() { - let mut window = shared.window.lock().unwrap(); + let mut window = shared.window.lock(); shared.advance(&mut window, 0); } Ok(shared) @@ -481,7 +482,7 @@ impl Shared { /// it still serves, since the copy's reads of one chunk and the next /// overlap in flight. fn classify(&self, chunk: u64, at: u64, len: u64) -> Serve { - let mut window = self.window.lock().unwrap(); + let mut window = self.window.lock(); let near = window.cursor.and_then(|pos| { let before = pos.checked_sub(1).map(|p| self.delta[p]); if chunk == self.delta[pos] || Some(chunk) == before { @@ -558,7 +559,7 @@ impl Shared { } fn touch(&self, chunk: u64) { - let mut touched = self.touched.lock().unwrap(); + let mut touched = self.touched.lock(); if !std::mem::replace(&mut touched.seen[chunk as usize], true) { touched.order.push(chunk as u32); } @@ -623,14 +624,14 @@ impl Completions { } fn push(&self, tag: u16, result: io::Result) { - self.done.lock().unwrap().push_back((tag, result)); + self.done.lock().push_back((tag, result)); if let Err(e) = (&self.event).write_all(&1u64.to_ne_bytes()) { tracing::error!(error = %e, "ublk source: eventfd write failed; a read stays unanswered"); } } fn drain(&self) -> Vec<(u16, io::Result)> { - self.done.lock().unwrap().drain(..).collect() + self.done.lock().drain(..).collect() } } diff --git a/crates/engram-host-agent/src/capture_job.rs b/crates/engram-host-agent/src/capture_job.rs index 31758c469..016b49042 100644 --- a/crates/engram-host-agent/src/capture_job.rs +++ b/crates/engram-host-agent/src/capture_job.rs @@ -34,9 +34,10 @@ //! registry the executor drives from, not a separate flag on the //! backend. +use parking_lot::Mutex; use std::collections::HashMap; use std::path::{Path, PathBuf}; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use dashmap::DashMap; use engram_core::traits::sandbox::SandboxBackend; @@ -206,11 +207,7 @@ pub struct CaptureJobExecutor { /// report (`ack`); non-terminal entries are refreshed continuously /// by the running executor task. reports: Arc>, - /// `std::sync::Mutex`, not `DashMap`: `start` needs an atomic - /// check-current-epoch-then-replace-and-spawn under one lock (a - /// `DashMap` entry API can't hold a non-`Send` guard across the - /// `tokio::spawn` call cleanly, and the critical section here is a - /// few micro-ops — a blocking mutex is the simpler correct choice). + /// Serializes the epoch check, replacement, and task spawn. running: Mutex>, /// Self-reference (the `PooledBackend::set_self_ref` pattern /// verbatim): `start` needs to hand a spawned task an OWNED @@ -325,7 +322,6 @@ impl CaptureJobExecutor { pub fn is_live_sandbox(&self, id: SandboxId) -> bool { self.running .lock() - .unwrap() .values() .any(|j| j.sandbox_id == Some(id)) } @@ -343,13 +339,6 @@ impl CaptureJobExecutor { CaptureJobRecord::delete_acked(&self.records_dir, acked).await; } - /// Whether the heartbeat-ack loop should call - /// `HttpCoordClient::claim_capture_job` for `(job_id, epoch)`: `true` - /// unless this exact epoch is already running. A LOWER epoch than - /// what's running is implicitly "no" too (the assignment is stale — - /// the coordinator hasn't caught up to a reassignment this host - /// already knows about), matching ADR 0084's "ignore a - /// lower-than-running epoch" rule without a separate branch. /// Convergence cancel (ADR 0084 §A): destroy the VM of any /// still-running attempt whose `job_id` is entirely absent from the /// coordinator's AUTHORITATIVE assignment list for this host — it was @@ -370,7 +359,7 @@ impl CaptureJobExecutor { let present: std::collections::HashSet = assignments.iter().map(|a| a.job_id).collect(); let stale: Vec<(CaptureJobId, i64, SandboxId)> = { - let running = self.running.lock().unwrap(); + let running = self.running.lock(); running .iter() .filter(|(job_id, _)| !present.contains(job_id)) @@ -395,75 +384,65 @@ impl CaptureJobExecutor { } } + /// Whether the heartbeat-ack loop should call + /// `HttpCoordClient::claim_capture_job` for `(job_id, epoch)`: `true` + /// unless this exact epoch is already running. A LOWER epoch than + /// what's running is implicitly "no" too (the assignment is stale — + /// the coordinator hasn't caught up to a reassignment this host + /// already knows about), matching ADR 0084's "ignore a + /// lower-than-running epoch" rule without a separate branch. pub fn should_claim(&self, job_id: CaptureJobId, epoch: i64) -> bool { - match self.running.lock().unwrap().get(&job_id) { + match self.running.lock().get(&job_id) { Some(running) => epoch > running.epoch, None => true, } } - /// Start executing `job_id` at `epoch` with the claimed `spec`. If a - /// LOWER-epoch attempt is currently running for the same `job_id`, - /// cancel it first (abort the task, destroy its VM if one exists) — - /// the stale-epoch-cancel invariant that makes a duplicate capture - /// VM unrepresentable host-side. Call only after `should_claim` - /// returned `true` for the same `(job_id, epoch)` (the heartbeat loop - /// claims-then-starts as one sequenced step per job per tick, so - /// there's no concurrent-start race to guard here). + /// Start the claimed epoch unless this job already has an equal or newer + /// attempt. Cancel and destroy an older attempt before replacing it. pub fn start(&self, job_id: CaptureJobId, epoch: i64, spec: CaptureJobSpec) { - { - let mut running = self.running.lock().unwrap(); - if let Some(stale) = running.remove(&job_id) { - if stale.epoch >= epoch { - // Raced with a duplicate `start` call for the same - // (or an already-superseded) epoch — put it back and - // do nothing. - running.insert(job_id, stale); - return; - } - tracing::warn!( - %job_id, - stale_epoch = stale.epoch, - new_epoch = epoch, - sandbox_id = ?stale.sandbox_id, - "capture job reassigned to a fresh epoch while a stale attempt was still \ - running; cancelling the stale attempt", - ); - stale.handle.abort(); - if let Some(sid) = stale.sandbox_id { - let backend = self.backend.clone(); - tokio::spawn(async move { - if let Err(e) = backend.destroy(sid).await { - tracing::debug!(sandbox_id = %sid, error = %e, - "destroy of a stale (reassigned-away) capture VM failed (best-effort)"); - } - }); - } + let mut running = self.running.lock(); + if let Some(stale) = running.remove(&job_id) { + if stale.epoch >= epoch { + // Raced with a duplicate `start` call for the same + // (or an already-superseded) epoch — put it back and + // do nothing. + running.insert(job_id, stale); + return; } - // Reserve the slot with a placeholder immediately (before the - // real task exists) so a concurrent heartbeat tick's - // `should_claim` sees this epoch as already owned. - let placeholder = tokio::spawn(async {}); - running.insert( - job_id, - RunningJob { - epoch, - sandbox_id: None, - handle: placeholder, - }, + tracing::warn!( + %job_id, + stale_epoch = stale.epoch, + new_epoch = epoch, + sandbox_id = ?stale.sandbox_id, + "capture job reassigned to a fresh epoch while a stale attempt was still \ + running; cancelling the stale attempt", ); + stale.handle.abort(); + if let Some(sid) = stale.sandbox_id { + let backend = self.backend.clone(); + tokio::spawn(async move { + if let Err(e) = backend.destroy(sid).await { + tracing::debug!(sandbox_id = %sid, error = %e, + "destroy of a stale (reassigned-away) capture VM failed (best-effort)"); + } + }); + } } let executor = self.strong_self(); + // Tokio does not poll the task synchronously. The task cannot update + // this registry until its real handle is installed and the lock drops. let handle = tokio::spawn(async move { executor.run_one(job_id, epoch, spec).await; }); - // Replace the placeholder handle with the real one. The task - // above may already be racing ahead (updating `sandbox_id` via - // `report_progress`), but the `epoch` key is unchanged so that's - // race-free. - if let Some(entry) = self.running.lock().unwrap().get_mut(&job_id) { - entry.handle = handle; - } + running.insert( + job_id, + RunningJob { + epoch, + sandbox_id: None, + handle, + }, + ); } async fn run_one(self: Arc, job_id: CaptureJobId, epoch: i64, job_spec: CaptureJobSpec) { @@ -510,7 +489,7 @@ impl CaptureJobExecutor { while let Some(progress) = progress_rx.recv().await { if let Some(sid) = progress.sandbox_id { record.sandbox_id = Some(sid); - if let Some(entry) = self.running.lock().unwrap().get_mut(&job_id) { + if let Some(entry) = self.running.lock().get_mut(&job_id) { if entry.epoch == epoch { entry.sandbox_id = Some(sid); } @@ -623,7 +602,7 @@ impl CaptureJobExecutor { // (but only if we're still the epoch of record — a reassignment // may have already replaced this entry, in which case its // teardown is that newer attempt's `start` call's job, not ours). - let mut running = self.running.lock().unwrap(); + let mut running = self.running.lock(); if matches!(running.get(&job_id), Some(r) if r.epoch == epoch) { running.remove(&job_id); } @@ -724,7 +703,7 @@ mod tests { } async fn destroy(&self, id: SandboxId) -> Result<(), SandboxError> { self.destroy_calls.fetch_add(1, Ordering::SeqCst); - *self.last_destroyed.lock().unwrap() = Some(id); + *self.last_destroyed.lock() = Some(id); Ok(()) } async fn list(&self) -> Result, SandboxError> { @@ -926,7 +905,7 @@ mod tests { // Give the abort + destroy a moment to land. tokio::time::sleep(std::time::Duration::from_millis(20)).await; assert_eq!( - *backend.last_destroyed.lock().unwrap(), + *backend.last_destroyed.lock(), Some(stale_sandbox), "the stale (epoch 1) attempt's VM must be destroyed on reassignment", ); @@ -981,7 +960,7 @@ mod tests { executor.rehydrate().await; assert_eq!( - *backend.last_destroyed.lock().unwrap(), + *backend.last_destroyed.lock(), Some(sandbox_id), "rehydrate must destroy the orphaned survivor VM", ); @@ -1060,7 +1039,7 @@ mod tests { // The torn files never wedged startup: the valid survivor was // destroyed and its record rewound to a retryable Failed terminal. assert_eq!( - *backend.last_destroyed.lock().unwrap(), + *backend.last_destroyed.lock(), Some(sandbox_id), "rehydrate must still destroy the one valid survivor VM", ); @@ -1157,7 +1136,6 @@ mod tests { if let Some(id) = executor .running .lock() - .unwrap() .get(&job_id) .and_then(|r| r.sandbox_id) { diff --git a/crates/engram-host-agent/src/harness.rs b/crates/engram-host-agent/src/harness.rs index 38d06a541..3a2fb6d0b 100644 --- a/crates/engram-host-agent/src/harness.rs +++ b/crates/engram-host-agent/src/harness.rs @@ -1595,7 +1595,7 @@ mod tests { hub.accept_connection( sandbox_id, Some(session_id), - engram_sandbox_firecracker::EpochSeveredStream::new(host_side, epoch_rx), + engram_host_core::EpochSeveredStream::new(host_side, epoch_rx), ); let hub_for_harness = hub.clone(); diff --git a/crates/engram-host-agent/src/materialize.rs b/crates/engram-host-agent/src/materialize.rs index 7e20924fc..943bdaee3 100644 --- a/crates/engram-host-agent/src/materialize.rs +++ b/crates/engram-host-agent/src/materialize.rs @@ -248,10 +248,7 @@ pub async fn run( let materializer = Materializer::new( oci, InitInjection { - // Reserved in-guest agentd port; hard-coded here and in - // engram-sandbox-firecracker::ENGRAM_AGENTD_PORT (same - // convention as the retiring bake CLI). - vsock_port: engram_sandbox_firecracker::ENGRAM_AGENTD_PORT, + vsock_port: engram_host_core::ENGRAM_AGENTD_PORT, transport: Transport::Vsock, init_script: None, }, diff --git a/crates/engram-host-agent/src/postcopy_finish.rs b/crates/engram-host-agent/src/postcopy_finish.rs index 5bb87be03..cdafef832 100644 --- a/crates/engram-host-agent/src/postcopy_finish.rs +++ b/crates/engram-host-agent/src/postcopy_finish.rs @@ -49,7 +49,7 @@ impl PostCopyFinish { if !self.clear_persisted_role().await { return; } - let sealed = control_sock.with_file_name(engram_sandbox_firecracker::POST_COPY_SEALED_FILE); + let sealed = control_sock.with_file_name(engram_host_core::POST_COPY_SEALED_FILE); match self.source_manifest { Some(source) if sealed.exists() => { let seed = crate::pooled_backend::ChainSeed::PostCopy { diff --git a/crates/engram-host-agent/src/proxyd_client.rs b/crates/engram-host-agent/src/proxyd_client.rs index 28f231122..0f5d82eda 100644 --- a/crates/engram-host-agent/src/proxyd_client.rs +++ b/crates/engram-host-agent/src/proxyd_client.rs @@ -91,7 +91,7 @@ pub enum ProxydProcess { /// Adopted from a prior generation: the pidfd's readability is the /// exit event (Linux; adoption never happens elsewhere because /// local builds carry no fingerprint). - Adopted(engram_sandbox_firecracker::pidfd::PidFd), + Adopted(engram_host_core::pidfd::PidFd), } /// The control-socket client. Holds one cached connection and @@ -272,7 +272,7 @@ pub async fn ensure_proxyd( match plan { AdoptPlan::Adopt => { let m = manifest.expect("Adopt implies a manifest"); - match engram_sandbox_firecracker::pidfd::open_pidfd(m.pid) { + match engram_host_core::pidfd::open_pidfd(m.pid) { Ok(pidfd) => { tracing::info!( pid = m.pid, diff --git a/crates/engram-host-core/Cargo.toml b/crates/engram-host-core/Cargo.toml index 1d123ed72..8f9fa65d9 100644 --- a/crates/engram-host-core/Cargo.toml +++ b/crates/engram-host-core/Cargo.toml @@ -7,7 +7,7 @@ repository.workspace = true description = "Portable host-agent core: the side-effect seams (CoordControlPlane, HostFs, SessionDisk) and the session-volume owner — the macOS-runnable surface the boundary simulator drives." # The workspace `forbid` cannot be relaxed per function; `deny` can. -# Only `disk::punch_hole` and `disk::filesystem_space` carry an allow. +# Disk operations and Linux pidfd construction carry scoped allowances. [lints.rust] unsafe_code = "deny" @@ -22,6 +22,10 @@ unused_dependencies = "allow" disallowed_methods = "deny" [dependencies] +bytes.workspace = true +engram-agentd.workspace = true +engram-harness-proto.workspace = true +tokio-stream.workspace = true async-trait.workspace = true chrono.workspace = true engram-chunk-store.workspace = true @@ -35,7 +39,6 @@ uuid.workspace = true workspace-hack = { version = "0.1", path = "../../workspace-hack" } [dev-dependencies] -bytes.workspace = true engram-storage-local.workspace = true serde_json.workspace = true tempfile = "3" diff --git a/crates/engram-host-core/src/epoch_stream.rs b/crates/engram-host-core/src/epoch_stream.rs new file mode 100644 index 000000000..eaea9c5fe --- /dev/null +++ b/crates/engram-host-core/src/epoch_stream.rs @@ -0,0 +1,179 @@ +//! Byte streams that end when their snapshot epoch changes. + +use engram_core::SandboxId; +use std::{ + future::Future, + io, + pin::Pin, + task::{Context, Poll}, +}; +use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; + +struct EpochWaiter { + epoch: tokio::sync::watch::Receiver, + observed_epoch: u64, + epoch_change: Option + Send + 'static>>>, +} + +impl EpochWaiter { + fn new(mut epoch: tokio::sync::watch::Receiver) -> Self { + let observed_epoch = *epoch.borrow_and_update(); + let mut waiter_epoch = epoch.clone(); + let epoch_change = Box::pin(async move { + let _ = waiter_epoch.changed().await; + }); + Self { + epoch, + observed_epoch, + epoch_change: Some(epoch_change), + } + } + + fn epoch_changed(&self) -> bool { + match self.epoch.has_changed() { + Ok(changed) => changed, + // `has_changed` reports a closed channel before it reports + // an unseen value. Compare the value to keep the last bump. + Err(_) => *self.epoch.borrow() != self.observed_epoch, + } + } + + fn poll_changed(&mut self, cx: &mut Context<'_>) -> bool { + if self.epoch_changed() { + self.epoch_change = None; + return true; + } + + let Some(epoch_change) = self.epoch_change.as_mut() else { + return false; + }; + if epoch_change.as_mut().poll(cx).is_pending() { + return false; + } + + self.epoch_change = None; + self.epoch_changed() + } +} + +/// Ends a byte stream when a snapshot changes its transport epoch. +/// Read and write polls use separate waiters so one task cannot replace +/// the other's waker. Buffered reads win over severance to preserve bytes +/// received before the transport reset. +pub struct EpochSeveredStream { + inner: S, + read_epoch: EpochWaiter, + write_epoch: EpochWaiter, + severed: bool, + /// Set for a guest-dialed channel: the severance is logged once. + label: Option<(SandboxId, &'static str)>, +} + +impl EpochSeveredStream { + /// Creates a stream that ends when the epoch changes. + pub fn new(inner: S, epoch: tokio::sync::watch::Receiver) -> Self { + Self { + inner, + read_epoch: EpochWaiter::new(epoch.clone()), + write_epoch: EpochWaiter::new(epoch.clone()), + severed: false, + label: None, + } + } + + /// Adds the sandbox and channel to the severance log. + pub fn labelled(mut self, sandbox_id: SandboxId, channel: &'static str) -> Self { + self.label = Some((sandbox_id, channel)); + self + } + + fn poll_epoch_change( + severed: &mut bool, + label: Option<(SandboxId, &'static str)>, + epoch: &mut EpochWaiter, + cx: &mut Context<'_>, + ) -> bool { + if *severed { + return true; + } + if epoch.poll_changed(cx) { + *severed = true; + if let Some((sandbox_id, channel)) = label { + tracing::info!( + %sandbox_id, + channel, + "snapshot transport reset severed the guest's vsock connection", + ); + } + return true; + } + false + } + + fn severed_write_error() -> io::Error { + io::Error::new( + io::ErrorKind::BrokenPipe, + "snapshot capture severed the vsock connection", + ) + } +} + +impl AsyncRead for EpochSeveredStream +where + S: AsyncRead + Unpin, +{ + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + let this = self.get_mut(); + match Pin::new(&mut this.inner).poll_read(cx, buf) { + Poll::Ready(result) => Poll::Ready(result), + Poll::Pending + if Self::poll_epoch_change( + &mut this.severed, + this.label, + &mut this.read_epoch, + cx, + ) => + { + Poll::Ready(Ok(())) + } + Poll::Pending => Poll::Pending, + } + } +} + +impl AsyncWrite for EpochSeveredStream +where + S: AsyncWrite + Unpin, +{ + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + let this = self.get_mut(); + if Self::poll_epoch_change(&mut this.severed, this.label, &mut this.write_epoch, cx) { + return Poll::Ready(Err(Self::severed_write_error())); + } + Pin::new(&mut this.inner).poll_write(cx, buf) + } + + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + if Self::poll_epoch_change(&mut this.severed, this.label, &mut this.write_epoch, cx) { + return Poll::Ready(Err(Self::severed_write_error())); + } + Pin::new(&mut this.inner).poll_flush(cx) + } + + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + if Self::poll_epoch_change(&mut this.severed, this.label, &mut this.write_epoch, cx) { + return Poll::Ready(Err(Self::severed_write_error())); + } + Pin::new(&mut this.inner).poll_shutdown(cx) + } +} diff --git a/crates/engram-host-core/src/guest_client.rs b/crates/engram-host-core/src/guest_client.rs new file mode 100644 index 000000000..cd20bb5e2 --- /dev/null +++ b/crates/engram-host-core/src/guest_client.rs @@ -0,0 +1,685 @@ +//! Guest-agent wire protocol over backend-owned byte streams. + +use bytes::Bytes; +use engram_agentd::{ + read_msg, write_msg, WireExecEvent, WireExecRequest, WireRequest, WireResponse, +}; +use engram_core::types::sandbox::{AgentSpec, ExecEvent, ExecRequest, ExecStream}; +use engram_core::{SandboxError, SandboxId}; +use std::{collections::HashMap, future::Future, pin::Pin, sync::Arc, time::Duration}; +use tokio::{ + io::{AsyncRead, AsyncWrite}, + sync::mpsc, +}; +use tokio_stream::wrappers::ReceiverStream; + +/// Reserved guest-agent vsock port. +pub const ENGRAM_AGENTD_PORT: u32 = 1024; + +/// Connection semantics supported by the backend's exec transport. +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum ExecConnectionMode { + /// Validate each journal generation and reconnect from delivered offsets. + Reattach, + /// Forward one stream; the caller owns subsequent attaches. + Single, +} + +fn vm_err(message: impl Into) -> SandboxError { + SandboxError::Vm(message.into().into()) +} + +/// Send one guest request and read its response on the same connection. +pub async fn request( + stream: &mut S, + request: &WireRequest, +) -> std::io::Result { + write_msg(stream, request).await?; + read_msg(stream).await +} + +/// Add the sandbox attach token and encode the harness spawn request. +pub fn spawn_harness_request(id: SandboxId, mut agent: AgentSpec) -> WireRequest { + agent.env.extend( + engram_harness_proto::attach_token::AttachToken { + sandbox_id: id, + binding_epoch: agent.binding_epoch, + } + .env(), + ); + WireRequest::SpawnHarness(engram_agentd::SpawnHarnessRequest { + argv: agent.argv, + env: agent.env.into_iter().collect(), + session_env: agent.session_env.into_iter().collect(), + host_ca_pem: agent.host_ca_pem, + }) +} + +/// Run a harness spawn exchange. Transport errors retain their operation name. +pub async fn spawn_harness( + stream: &mut S, + request: &WireRequest, +) -> Result { + write_msg(stream, request) + .await + .map_err(|e| vm_err(format!("write SpawnHarness: {e}")))?; + read_msg(stream) + .await + .map_err(|e| vm_err(format!("read SpawnHarness response: {e}"))) +} + +/// Push a sampled host time into the guest. +pub async fn step_guest_clock( + stream: &mut S, + unix_nanos: i64, +) -> Result { + write_msg(stream, &WireRequest::StepClock { unix_nanos }) + .await + .map_err(|e| format!("write StepClock: {e}"))?; + read_msg(stream) + .await + .map_err(|e| format!("read StepClock response: {e}")) +} + +/// Byte stream used by the guest exec protocol. +pub trait ExecIo: AsyncRead + AsyncWrite + Unpin + Send {} +impl ExecIo for T where T: AsyncRead + AsyncWrite + Unpin + Send {} + +/// Owned exec transport. +pub type BoxExecIo = Box; + +type ExecRedialFuture = + Pin> + Send + 'static>>; + +/// Reconnection factory used after an exec connection ends. + +#[derive(Clone)] +pub struct ExecRedial { + connect: Arc ExecRedialFuture + Send + Sync>, +} + +impl ExecRedial { + /// Each invocation must return a fresh connection. + pub fn provided(connect: F) -> Self + where + F: Fn() -> Fut + Send + Sync + 'static, + Fut: Future> + Send + 'static, + { + Self { + connect: Arc::new(move || Box::pin(connect())), + } + } + + async fn connect(&self) -> Result { + (self.connect)().await + } + + async fn reconnect_after_eof(&self) -> Result { + let mut last_error = None; + for attempt in 0..40 { + match self.connect().await { + Ok(connection) => return Ok(connection), + Err(error) => last_error = Some(error), + } + if attempt < 39 { + tokio::time::sleep(Duration::from_millis(25)).await; + } + } + Err(last_error.unwrap_or_else(|| vm_err("durable exec reattach had no dial attempt"))) + } +} + +/// Diagnostic tag for a guest without durable exec support. +pub const DURABLE_EXEC_SKEW: &str = "ENGRAM_DURABLE_EXEC_VERSION_SKEW"; + +/// How many consecutive transport EOFs with no frame in between the durable +/// exec reader tolerates before it ends without Exit. This bounds the +/// reconnect loop against a guest that accepts a dial and closes it before +/// one frame arrives; past the cap, the caller's fresh RPC (same ticket) +/// owns the retry with its own pacing. +pub const MAX_DEAD_RECONNECT_CYCLES: u32 = 3; + +/// Positional exec payload read by guests without durable exec support. +#[derive(serde::Deserialize, serde::Serialize)] +pub struct LegacyWireExecRequest { + command: Vec, + stdin: Option>, + env: HashMap, + workdir: Option, + timeout_ms: Option, +} + +/// The legacy request enum must retain its original variant index. +#[derive(serde::Deserialize, serde::Serialize)] +pub enum LegacyWireRequest { + Exec(LegacyWireExecRequest), +} + +/// Probe support without submitting a command. +pub async fn probe_durable_exec(mut io: BoxExecIo) -> Result { + write_msg( + &mut io, + &WireRequest::CancelExec { + exec_id: engram_agentd::handler::DURABLE_EXEC_CAPABILITY_PROBE.into(), + }, + ) + .await + .map_err(|error| { + SandboxError::Unavailable(format!("durable exec capability probe send: {error}")) + })?; + match read_msg::<_, WireResponse>(&mut io).await { + Ok(WireResponse::ExecCancelled) => Ok(true), + Ok(WireResponse::Error { kind, message }) => { + tracing::warn!( + %kind, + %message, + "guest agentd lacks ADR 0103 durable exec; using stage-1 protocol", + ); + Ok(false) + } + Ok(other) => Err(vm_err(format!( + "durable exec capability probe returned unexpected response: {other:?}" + ))), + Err(error) => Err(SandboxError::Unavailable(format!( + "durable exec capability probe failed before command submission: {error}" + ))), + } +} + +/// Cancel a guest command and await its acknowledgement. +pub async fn cancel_exec_roundtrip(mut io: BoxExecIo, exec_id: &str) -> Result<(), SandboxError> { + write_msg( + &mut io, + &WireRequest::CancelExec { + exec_id: exec_id.to_string(), + }, + ) + .await + .map_err(|error| SandboxError::Unavailable(format!("send CancelExec({exec_id}): {error}")))?; + match read_msg::<_, WireResponse>(&mut io).await { + Ok(WireResponse::ExecCancelled) => Ok(()), + Ok(WireResponse::Error { kind, message }) => Err(vm_err(format!( + "agentd rejected CancelExec({exec_id}) ({kind}): {message}" + ))), + Ok(other) => Err(vm_err(format!( + "CancelExec({exec_id}) returned unexpected response: {other:?}" + ))), + Err(error) => Err(SandboxError::Unavailable(format!( + "CancelExec({exec_id}) response failed; likely host/guest version skew (old guest agent): {error}" + ))), + } +} + +/// Drive one attach-or-start request and translate the guest's durable stream. +/// An EOF re-dials from the exact per-stream byte cursors once the capability +/// probe has succeeded. Every generation must begin with a matching `Started` +/// frame. +/// +/// Reconnects ask attach-or-start until the first `Started` proves the guest +/// journaled the command; after that proof they ask attach-only, so a lost +/// journal entry refuses loudly instead of running the command twice. +/// Consecutive reconnects that deliver no frame are bounded by +/// [`MAX_DEAD_RECONNECT_CYCLES`]; past the cap the stream ends without Exit, +/// which the coordinator surfaces as retryable with the same ticket. +/// +/// `Single` preserves single-connection framing and leaves retries to the caller. +pub async fn drive_exec_protocol( + sandbox_id: SandboxId, + mut io: BoxExecIo, + cmd: ExecRequest, + durable_capable: bool, + redial: Option, + mode: ExecConnectionMode, +) -> Result { + let exec_id = cmd + .exec_id + .clone() + .ok_or_else(|| vm_err("exec request has no ticket"))?; + let mut stdout_offset = cmd.stdout_offset.unwrap_or(0); + let mut stderr_offset = cmd.stderr_offset.unwrap_or(0); + if durable_capable { + let mut req = agent_exec_request(&cmd, &exec_id, stdout_offset, stderr_offset, false); + if mode == ExecConnectionMode::Single { + req.stdout_offset = cmd.stdout_offset; + req.stderr_offset = cmd.stderr_offset; + } + write_msg(&mut io, &WireRequest::Exec(req)) + .await + .map_err(|error| { + SandboxError::Unavailable(format!("send durable exec request: {error}")) + })?; + } else { + let req = LegacyWireRequest::Exec(LegacyWireExecRequest { + command: cmd.command.clone(), + stdin: cmd.stdin.clone(), + env: cmd.env.clone(), + workdir: cmd.workdir.clone(), + timeout_ms: cmd.timeout.map(|duration| duration.as_millis() as u64), + }); + write_msg(&mut io, &req).await.map_err(|error| { + SandboxError::Unavailable(format!("send stage-1 WireRequest::Exec: {error}")) + })?; + } + + // 64 events of buffer is enough that a slow consumer doesn't + // immediately backpressure the agent; the agent has its own + // 64-event channel so total in-flight bound is bounded. + let (tx, rx) = mpsc::channel::(64); + let reader_exec_id = exec_id.clone(); + + tokio::spawn(async move { + let exec_id = reader_exec_id; + let mut durable_capable = durable_capable; + let mut expect_started = durable_capable; + // The guest proves the journal entry exists the first time it sends + // `Started`. Until then a reconnect must ask attach-or-start: the + // request may have died before agentd journaled it, and attach-only + // would be refused as a "second command" when zero commands ran. + let mut journal_proven = false; + // Consecutive EOFs with no frame delivered in between. Bounded by + // MAX_DEAD_RECONNECT_CYCLES so a connectable-but-instantly-closing + // guest cannot spin this loop forever. + let mut dead_cycles = 0u32; + loop { + let msg = match read_msg::<_, WireExecEvent>(&mut io).await { + Ok(msg) => { + dead_cycles = 0; + msg + } + Err(error) if !durable_capable => { + if mode == ExecConnectionMode::Single { + let _ = tx.send(ExecEvent::Exit(None)).await; + return; + } + // A legacy agent or a degraded journal has no safe retry. + // A retry could run the command twice. + durable_exec_fallback( + &tx, + sandbox_id, + format!( + "{DURABLE_EXEC_SKEW}: exec transport ended before a durable result: {error}" + ), + ) + .await; + return; + } + Err(error) => { + let Some(connector) = redial.as_ref() else { + // The journal stays authoritative. End without Exit so + // a fresh coordinator call can use the same ticket. + tracing::warn!( + %sandbox_id, + %exec_id, + stdout_offset, + stderr_offset, + %error, + "durable exec transport ended; reattach is unavailable; ending without Exit", + ); + return; + }; + if tx.is_closed() { + // The consumer dropped the stream; no frame can be + // observed anymore. Do not keep dialing the guest. + tracing::debug!( + %sandbox_id, + %exec_id, + "durable exec consumer gone; ending reader without reconnect", + ); + return; + } + dead_cycles += 1; + if dead_cycles > MAX_DEAD_RECONNECT_CYCLES { + // The journal stays authoritative. End without Exit + // so the caller's fresh RPC owns the retry pacing. + tracing::warn!( + %sandbox_id, + %exec_id, + stdout_offset, + stderr_offset, + dead_cycles, + %error, + "durable exec made no progress across consecutive reconnects; ending without Exit", + ); + return; + } + let mut next = match connector.reconnect_after_eof().await { + Ok(next) => next, + Err(reconnect_error) => { + // A failed dial is not proof that the journal is + // gone. Let the caller open a fresh host RPC. + tracing::warn!( + %sandbox_id, + %exec_id, + stdout_offset, + stderr_offset, + %error, + %reconnect_error, + "durable exec reconnect failed; ending without Exit", + ); + return; + } + }; + let attach = agent_exec_request( + &cmd, + &exec_id, + stdout_offset, + stderr_offset, + journal_proven, + ); + if let Err(write_error) = write_msg(&mut next, &WireRequest::Exec(attach)).await + { + // A failed write did not reach a journal verdict. A + // fresh caller can safely retry the deduped attach. + tracing::warn!( + %sandbox_id, + %exec_id, + stdout_offset, + stderr_offset, + %write_error, + "durable exec reattach request transport failed; ending without Exit", + ); + return; + } + tracing::info!( + %sandbox_id, + %exec_id, + stdout_offset, + stderr_offset, + "durable exec transport ended; re-attached to guest journal", + ); + io = next; + expect_started = true; + continue; + } + }; + if mode == ExecConnectionMode::Reattach + && expect_started + && !matches!(&msg, WireExecEvent::Started(_)) + { + // A real but out-of-contract guest frame is a protocol error. + // A retry could reach an agent that did not honor the ticket. + durable_exec_fallback( + &tx, + sandbox_id, + format!( + "durable exec protocol violation: first frame for exec_id {exec_id} was not Started: {msg:?}" + ), + ) + .await; + return; + } + match msg { + WireExecEvent::Started(started_id) => { + if (mode == ExecConnectionMode::Reattach && !expect_started) + || started_id != exec_id + { + // The guest acknowledged a different lifecycle or + // ticket. Do not retry an identity-ambiguous exec. + durable_exec_fallback( + &tx, + sandbox_id, + format!( + "durable exec protocol violation: expected Started({exec_id}), got Started({started_id})" + ), + ) + .await; + return; + } + if mode == ExecConnectionMode::Reattach { + durable_capable = true; + } + expect_started = false; + journal_proven = true; + } + WireExecEvent::Degraded(reason) => { + if mode == ExecConnectionMode::Reattach { + durable_capable = false; + } + expect_started = false; + tracing::warn!( + %sandbox_id, + %exec_id, + %reason, + "guest journal degraded; keeping stage-1 live stream", + ); + } + WireExecEvent::Stdout(b) => { + // An old agentd emits output/exit without Started. Keep + // serving its stage-1 stream, but never re-attach it: a + // retry would execute the command twice. + expect_started = false; + stdout_offset = stdout_offset.saturating_add(b.len() as u64); + if tx.send(ExecEvent::Stdout(Bytes::from(b))).await.is_err() { + return; + } + } + WireExecEvent::Stderr(b) => { + expect_started = false; + stderr_offset = stderr_offset.saturating_add(b.len() as u64); + if tx.send(ExecEvent::Stderr(Bytes::from(b))).await.is_err() { + return; + } + } + WireExecEvent::Exit(code) => { + let _ = tx.send(ExecEvent::Exit(code)).await; + return; + } + WireExecEvent::Refused { reason } => { + let _ = tx.send(ExecEvent::Refused(reason)).await; + return; + } + } + } + }); + + Ok(ExecStream { + sandbox_id, + exec_id, + events: Box::pin(ReceiverStream::new(rx)), + }) +} + +fn agent_exec_request( + cmd: &ExecRequest, + exec_id: &str, + stdout_offset: u64, + stderr_offset: u64, + attach_only: bool, +) -> WireExecRequest { + WireExecRequest { + command: cmd.command.clone(), + stdin: cmd.stdin.clone(), + env: cmd.env.clone(), + workdir: cmd.workdir.clone(), + timeout_ms: cmd.timeout.map(|duration| duration.as_millis() as u64), + exec_id: Some(exec_id.to_string()), + stdout_offset: Some(stdout_offset), + stderr_offset: Some(stderr_offset), + wake: cmd.wake, + attach_only, + } +} + +async fn durable_exec_fallback( + tx: &mpsc::Sender, + sandbox_id: SandboxId, + reason: String, +) { + tracing::warn!(%sandbox_id, %reason, "durable exec fell back to synthetic Exit(None)"); + let _ = tx + .send(ExecEvent::Stderr(Bytes::from(format!("{reason}\n")))) + .await; + let _ = tx.send(ExecEvent::Exit(None)).await; +} + +#[cfg(test)] +mod tests { + use super::*; + use tokio::io::AsyncReadExt; + + fn command() -> ExecRequest { + ExecRequest { + command: vec!["printf".into(), "hello".into()], + stdin: Some(vec![0, 255]), + env: HashMap::from([("KEY".into(), "value".into())]), + workdir: Some("/workspace".into()), + timeout: Some(Duration::from_millis(123)), + exec_id: Some("exec-test".into()), + stdout_offset: None, + stderr_offset: None, + wake: None, + } + } + + #[tokio::test] + async fn legacy_frame_matches_the_previous_guest_schema_for_both_transports() { + // This frozen schema is independent of the shared client's wire types. + #[derive(serde::Serialize)] + enum PreviousRequest { + Exec { + command: Vec, + stdin: Option>, + env: HashMap, + workdir: Option, + timeout_ms: Option, + }, + } + let previous = PreviousRequest::Exec { + command: vec!["printf".into(), "hello".into()], + stdin: Some(vec![0, 255]), + env: HashMap::from([("KEY".into(), "value".into())]), + workdir: Some("/workspace".into()), + timeout_ms: Some(123), + }; + let mut expected = Vec::new(); + write_msg(&mut expected, &previous).await.unwrap(); + for mode in [ExecConnectionMode::Reattach, ExecConnectionMode::Single] { + let (host, mut guest) = tokio::io::duplex(4096); + let stream = drive_exec_protocol( + SandboxId::new(), + Box::new(host), + command(), + false, + None, + mode, + ) + .await + .unwrap(); + let mut actual = vec![0; expected.len()]; + guest.read_exact(&mut actual).await.unwrap(); + assert_eq!(actual, expected); + write_msg(&mut guest, &WireExecEvent::Exit(Some(0))) + .await + .unwrap(); + drop(stream); + } + } + + #[tokio::test] + async fn durable_request_preserves_each_transports_optional_offsets() { + for mode in [ExecConnectionMode::Reattach, ExecConnectionMode::Single] { + for offsets in [None, Some(7)] { + let (host, mut guest) = tokio::io::duplex(4096); + let mut cmd = command(); + cmd.stdout_offset = offsets; + cmd.stderr_offset = offsets; + let stream = + drive_exec_protocol(SandboxId::new(), Box::new(host), cmd, true, None, mode) + .await + .unwrap(); + let WireRequest::Exec(req) = read_msg(&mut guest).await.unwrap() else { + panic!("expected exec"); + }; + let expected = match mode { + ExecConnectionMode::Reattach => Some(offsets.unwrap_or(0)), + ExecConnectionMode::Single => offsets, + }; + assert_eq!(req.stdout_offset, expected); + assert_eq!(req.stderr_offset, expected); + assert_eq!(req.exec_id.as_deref(), Some("exec-test")); + assert!(!req.attach_only); + drop(stream); + } + } + } + + #[tokio::test] + async fn spawn_preserves_binding_environment_and_ca() { + let id = SandboxId::new(); + let token = engram_harness_proto::attach_token::AttachToken { + sandbox_id: id, + binding_epoch: 42, + } + .env(); + let req = spawn_harness_request( + id, + AgentSpec { + argv: vec!["agent".into()], + env: HashMap::from([("EXTRA".into(), "value".into())]), + session_env: HashMap::from([("SESSION".into(), "value".into())]), + binding_epoch: 42, + host_ca_pem: Some("test-ca".into()), + }, + ); + let (mut host, mut guest) = tokio::io::duplex(4096); + let guest_task = tokio::spawn(async move { + let WireRequest::SpawnHarness(req) = read_msg(&mut guest).await.unwrap() else { + panic!("expected spawn"); + }; + assert_eq!(req.argv, vec!["agent"]); + let env: HashMap<_, _> = req.env.into_iter().collect(); + for (key, value) in token { + assert_eq!(env.get(&key), Some(&value)); + } + assert_eq!(env.get("EXTRA").map(String::as_str), Some("value")); + assert_eq!( + req.session_env, + HashMap::from([("SESSION".into(), "value".into())]) + ); + assert_eq!(req.host_ca_pem.as_deref(), Some("test-ca")); + write_msg( + &mut guest, + &WireResponse::HarnessSpawned { + pid: Some(7), + ca_changed: Some(true), + }, + ) + .await + .unwrap(); + }); + assert!(matches!( + spawn_harness(&mut host, &req).await.unwrap(), + WireResponse::HarnessSpawned { + pid: Some(7), + ca_changed: Some(true) + } + )); + guest_task.await.unwrap(); + } + + #[tokio::test] + async fn clock_request_uses_the_supplied_sample_and_preserves_response() { + let (mut host, mut guest) = tokio::io::duplex(4096); + let guest_task = tokio::spawn(async move { + assert!(matches!( + read_msg(&mut guest).await.unwrap(), + WireRequest::StepClock { unix_nanos: 123 } + )); + write_msg( + &mut guest, + &WireResponse::ClockStepped { + applied_offset_nanos: Some(-456), + }, + ) + .await + .unwrap(); + }); + assert!(matches!( + step_guest_clock(&mut host, 123).await.unwrap(), + WireResponse::ClockStepped { + applied_offset_nanos: Some(-456) + } + )); + guest_task.await.unwrap(); + } +} diff --git a/crates/engram-host-core/src/lib.rs b/crates/engram-host-core/src/lib.rs index 989f148c1..cc2a2e66b 100644 --- a/crates/engram-host-core/src/lib.rs +++ b/crates/engram-host-core/src/lib.rs @@ -1,12 +1,9 @@ //! Portable host-agent core (ADR 0098 Phase 2, the P-series). //! //! This crate holds the host-agent's side-effect seams and the -//! prod-portable impls of them. It depends on `engram-core` and -//! `engram-chunk-store` (plus the ambient async/serde/time crates) — -//! deliberately NOT on `engram-host-agent`, reqwest, or anything -//! Linux-gated — which is what makes the extracted lifecycle logic -//! **runnable on macOS** and drivable by the boundary simulator -//! (`engram-dst-cosim`). +//! portable implementations, guest wire client, and transport primitives. +//! Lifecycle logic runs on macOS and in the boundary simulator. +//! Linux process operations have explicit unsupported results on other hosts. //! //! # Seams //! @@ -30,9 +27,12 @@ pub mod checkpoint; pub mod coord; pub mod disk; pub mod disk_flows; +pub mod epoch_stream; pub mod finalize; pub mod fs; +pub mod guest_client; pub mod image_volumes; +pub mod pidfd; pub mod session_volumes; pub mod shutdown; #[cfg(test)] @@ -45,7 +45,12 @@ pub use disk::{ SourceDevice, SourceServer, Volume, VolumeName, }; pub use disk_flows::{checkpoint, checkpoint_split, hydration_plan, stage, HydrationPlan}; +pub use epoch_stream::EpochSeveredStream; pub use finalize::{plan_finalize_retry, FinalizeRetry, FinalizeStage}; pub use fs::{HostFs, TokioFs}; +pub use guest_client::ENGRAM_AGENTD_PORT; pub use session_volumes::SessionVolumes; pub use shutdown::{capture_drain_budget, HandoffMarker}; + +/// Completed record of chunks supplied by a post-copy source. +pub const POST_COPY_SEALED_FILE: &str = "postcopy-sealed.bin"; diff --git a/crates/engram-sandbox-firecracker/src/pidfd.rs b/crates/engram-host-core/src/pidfd.rs similarity index 65% rename from crates/engram-sandbox-firecracker/src/pidfd.rs rename to crates/engram-host-core/src/pidfd.rs index b56154298..b0a27e43d 100644 --- a/crates/engram-sandbox-firecracker/src/pidfd.rs +++ b/crates/engram-host-core/src/pidfd.rs @@ -1,28 +1,4 @@ -//! ADR 0009 Phase 6: pidfd wrapper for live-VM reattach. -//! -//! `pidfd_open(2)` returns a file descriptor that references a -//! process by its PID. The fd is immune to PID recycling — once -//! opened, it always refers to the same process, even if the kernel -//! later reuses the integer pid for an unrelated process. That's -//! the property the Phase 6 reattach pass relies on: after a -//! host-agent restart we re-open `pidfd_open(recorded_pid)` and -//! the fd's identity ties us to the *original* FC process, not a -//! lookalike. -//! -//! The fd is `poll`-readable when the process exits (since Linux -//! 5.3). We wrap it in `tokio::io::unix::AsyncFd` so the -//! supervisor task can `.readable().await` and detect exit without -//! a polling loop. -//! -//! `waitid(P_PIDFD, fd, WNOHANG)` reaps the zombie (since 5.4). On -//! kernels older than 5.4 we'd need a different reaper; the FC -//! production target is engram's own guest kernel (ADR 0025, Linux -//! 6.1.x), well above the 5.4 floor. -//! -//! Linux-only by construction. On macOS this module compiles -//! (cfg(target_os = "linux")-gated) but every function is a stub -//! returning `Err(PidFdError::Unsupported)` so the FC backend's -//! tests can still build on macOS-only contributors' laptops. +//! Process handles whose identity is stable after the descriptor is opened. use std::io; #[cfg(target_os = "linux")] @@ -36,9 +12,6 @@ pub enum PidFdError { /// Kernel rejected the pidfd_open: ESRCH (no such process), /// EINVAL (bad pid), ENOSYS (Linux < 5.3), etc. Open(io::Error), - /// `waitid(P_PIDFD)` failed for some reason other than "process - /// still running" (the latter returns `Ok(None)` from `try_wait`). - Wait(io::Error), /// pidfd isn't supported on this platform. macOS, Windows, FreeBSD /// all fall here. Caller falls back to clean-slate. Unsupported, @@ -48,7 +21,6 @@ impl std::fmt::Display for PidFdError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Open(e) => write!(f, "pidfd_open: {e}"), - Self::Wait(e) => write!(f, "waitid(P_PIDFD): {e}"), Self::Unsupported => write!(f, "pidfd not supported on this platform"), } } @@ -77,15 +49,10 @@ impl AsRawFd for PidFd { } } -/// Open a pidfd for `pid`. Linux 5.3+; returns -/// `Err(PidFdError::Unsupported)` on other platforms or kernels -/// that don't implement the syscall. -/// -/// Returns `Err(PidFdError::Open(e))` where `e.kind() == -/// io::ErrorKind::NotFound` when the pid doesn't exist (ESRCH). The -/// caller (live-attach) treats that as "FC process is already gone; -/// fall through to NVMe-restore or orphan-reap." +/// Open a pidfd for `pid` on Linux 5.3 or later. Other platforms return +/// `Unsupported`; syscall failures return `Open` with the kernel error. #[cfg(target_os = "linux")] +#[allow(unsafe_code)] // The syscall returns a fresh descriptor owned by this function. pub fn open_pidfd(pid: u32) -> Result { // SAFETY: SYS_pidfd_open takes a pid and flags. Passing // pid (the integer we recorded at FC spawn time, a u32 cast to diff --git a/crates/engram-sandbox-firecracker/Cargo.toml b/crates/engram-sandbox-firecracker/Cargo.toml index c46b9c0d6..00eae19c7 100644 --- a/crates/engram-sandbox-firecracker/Cargo.toml +++ b/crates/engram-sandbox-firecracker/Cargo.toml @@ -21,6 +21,7 @@ unsafe_code = "allow" unused_dependencies = "allow" [dependencies] +engram-host-core.workspace = true engram-chunk-store.workspace = true engram-core.workspace = true engram-telemetry.workspace = true diff --git a/crates/engram-sandbox-firecracker/src/lib.rs b/crates/engram-sandbox-firecracker/src/lib.rs index 48141645e..0939fb87f 100644 --- a/crates/engram-sandbox-firecracker/src/lib.rs +++ b/crates/engram-sandbox-firecracker/src/lib.rs @@ -68,45 +68,36 @@ //! immediately; pages stream in lazily on guest fault. This is the //! load-bearing economic of the snapshot-evict mechanic. -use std::collections::HashMap; -use std::future::Future; -use std::io; use std::os::unix::ffi::OsStringExt; use std::path::{Path, PathBuf}; -use std::pin::Pin; use std::process::Stdio; use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::Arc; -use std::task::{Context, Poll}; use std::time::Duration; use async_trait::async_trait; -use bytes::Bytes; use chrono::{DateTime, Utc}; use dashmap::DashMap; -use engram_agentd::{ - read_msg, write_msg, WireExecEvent, WireExecRequest, WireRequest, WireResponse, -}; +use engram_agentd::WireRequest; use engram_core::traits::sandbox::{AgentRefresh, HarnessByteStream, SandboxBackend}; use engram_core::types::endpoints::GuestEndpoints; use engram_core::types::ids::{SandboxId, SnapshotId}; use engram_core::types::sandbox::{ - AuxBundleRef, AuxRoDrive, ExecEvent, ExecRequest, ExecStream, SandboxProbe, SandboxSpec, - SessionDisks, SessionFileMetadata, SessionFileSpec, SessionFileStream, + AuxBundleRef, AuxRoDrive, ExecRequest, ExecStream, SandboxProbe, SandboxSpec, SessionDisks, + SessionFileMetadata, SessionFileSpec, SessionFileStream, }; use engram_core::types::snapshot::SnapshotMetadata; use engram_core::SandboxError; use serde::{Deserialize, Serialize}; -use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, ReadBuf}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::UnixStream; use tokio::process::{Child, Command}; -use tokio::sync::mpsc; -use tokio_stream::wrappers::ReceiverStream; pub mod client; pub mod net; pub mod paths; -pub mod pidfd; +pub use engram_host_core::EpochSeveredStream; +use engram_host_core::{pidfd, POST_COPY_SEALED_FILE}; pub mod sandbox_manifest; pub use client::{ @@ -157,8 +148,15 @@ pub struct SandboxState { pub memory_backing: Option, } -/// Reserved vsock port `engram-agentd` listens on inside the guest. -pub const ENGRAM_AGENTD_PORT: u32 = 1024; +use engram_host_core::guest_client::{ + cancel_exec_roundtrip, probe_durable_exec, ExecConnectionMode, +}; +pub use engram_host_core::guest_client::{BoxExecIo, ExecIo, ExecRedial}; +#[cfg(test)] +use engram_host_core::guest_client::{ + LegacyWireRequest, DURABLE_EXEC_SKEW, MAX_DEAD_RECONNECT_CYCLES, +}; +pub use engram_host_core::ENGRAM_AGENTD_PORT; /// Filename FC uses for the per-port host-side UDS when the guest /// dials out via vsock: `_`. Build the path for an @@ -183,190 +181,6 @@ pub fn harness_uds_for(base_vsock_uds: &Path) -> PathBuf { per_port_uds(base_vsock_uds, engram_harness_proto::HARNESS_VSOCK_PORT) } -struct EpochWaiter { - epoch: tokio::sync::watch::Receiver, - observed_epoch: u64, - epoch_change: Option + Send + 'static>>>, -} - -impl EpochWaiter { - fn new(mut epoch: tokio::sync::watch::Receiver) -> Self { - let observed_epoch = *epoch.borrow_and_update(); - let mut waiter_epoch = epoch.clone(); - let epoch_change = Box::pin(async move { - let _ = waiter_epoch.changed().await; - }); - Self { - epoch, - observed_epoch, - epoch_change: Some(epoch_change), - } - } - - fn epoch_changed(&self) -> bool { - match self.epoch.has_changed() { - Ok(changed) => changed, - // `has_changed` reports a closed channel before it reports - // an unseen value. Compare the value to keep the last bump. - Err(_) => *self.epoch.borrow() != self.observed_epoch, - } - } - - fn poll_changed(&mut self, cx: &mut Context<'_>) -> bool { - if self.epoch_changed() { - self.epoch_change = None; - return true; - } - - let Some(epoch_change) = self.epoch_change.as_mut() else { - return false; - }; - if epoch_change.as_mut().poll(cx).is_pending() { - return false; - } - - self.epoch_change = None; - self.epoch_changed() - } -} - -/// Ends a long-lived vsock stream when a snapshot changes its epoch. -/// Firecracker queues a `TRANSPORT_RESET` during snapshot capture -/// (ADR 0074). The guest then drops the connection without sending EOF -/// to the host. The exec path already races its I/O against this epoch. -/// This wrapper extends that protection to the harness data channel. -/// -/// `run_connection` in `engram-host-agent/src/harness.rs` splits this stream. -/// It gives the read half to `reader_loop`. -/// It gives the write half to `writer_loop` in a new task. -/// Each epoch change future has one waker slot. -/// The read path and the write path therefore use separate waiters. -/// A write poll must never replace the reader task's waker. -/// -/// Each change future owns a cloned receiver. It stays allocated while -/// it is pending. The watch channel can then keep each task waker registered. -/// A ready inner read wins over an epoch change. This preserves bytes -/// that Firecracker delivered before it severed the connection. -/// -/// This type is public for the host-agent behavioral test. Reuse it as -/// the single vsock severance primitive. -pub struct EpochSeveredStream { - inner: S, - read_epoch: EpochWaiter, - write_epoch: EpochWaiter, - severed: bool, - /// Set for a guest-dialed channel: the severance is logged once. - label: Option<(SandboxId, &'static str)>, -} - -impl EpochSeveredStream { - /// Creates a stream that ends when the epoch changes. - pub fn new(inner: S, epoch: tokio::sync::watch::Receiver) -> Self { - Self { - inner, - read_epoch: EpochWaiter::new(epoch.clone()), - write_epoch: EpochWaiter::new(epoch.clone()), - severed: false, - label: None, - } - } - - fn labelled(mut self, sandbox_id: SandboxId, channel: &'static str) -> Self { - self.label = Some((sandbox_id, channel)); - self - } - - fn poll_epoch_change( - severed: &mut bool, - label: Option<(SandboxId, &'static str)>, - epoch: &mut EpochWaiter, - cx: &mut Context<'_>, - ) -> bool { - if *severed { - return true; - } - if epoch.poll_changed(cx) { - *severed = true; - if let Some((sandbox_id, channel)) = label { - tracing::info!( - %sandbox_id, - channel, - "snapshot transport reset severed the guest's vsock connection", - ); - } - return true; - } - false - } - - fn severed_write_error() -> io::Error { - io::Error::new( - io::ErrorKind::BrokenPipe, - "snapshot capture severed the vsock connection", - ) - } -} - -impl AsyncRead for EpochSeveredStream -where - S: AsyncRead + Unpin, -{ - fn poll_read( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - buf: &mut ReadBuf<'_>, - ) -> Poll> { - let this = self.get_mut(); - match Pin::new(&mut this.inner).poll_read(cx, buf) { - Poll::Ready(result) => Poll::Ready(result), - Poll::Pending - if Self::poll_epoch_change( - &mut this.severed, - this.label, - &mut this.read_epoch, - cx, - ) => - { - Poll::Ready(Ok(())) - } - Poll::Pending => Poll::Pending, - } - } -} - -impl AsyncWrite for EpochSeveredStream -where - S: AsyncWrite + Unpin, -{ - fn poll_write( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - buf: &[u8], - ) -> Poll> { - let this = self.get_mut(); - if Self::poll_epoch_change(&mut this.severed, this.label, &mut this.write_epoch, cx) { - return Poll::Ready(Err(Self::severed_write_error())); - } - Pin::new(&mut this.inner).poll_write(cx, buf) - } - - fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - let this = self.get_mut(); - if Self::poll_epoch_change(&mut this.severed, this.label, &mut this.write_epoch, cx) { - return Poll::Ready(Err(Self::severed_write_error())); - } - Pin::new(&mut this.inner).poll_flush(cx) - } - - fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - let this = self.get_mut(); - if Self::poll_epoch_change(&mut this.severed, this.label, &mut this.write_epoch, cx) { - return Poll::Ready(Err(Self::severed_write_error())); - } - Pin::new(&mut this.inner).poll_shutdown(cx) - } -} - /// ADR 0023: host-side UDS Firecracker proxies the in-guest forge /// helper's `FORGE_VSOCK_PORT` dials through. fn forge_uds_for(base_vsock_uds: &Path) -> PathBuf { @@ -459,11 +273,6 @@ async fn read_base_shm_ack( /// (Sealed/DrainProgress/DrainDone/PeerLost), bound in the jail dir. pub const UFFD_CONTROL_SOCK_FILE: &str = "uffd-control.sock"; -/// The peer-mode handler's record of the chunks the source supplied, -/// in the jail dir beside [`UFFD_CONTROL_SOCK_FILE`]. It exists under -/// this name only once the drain is done. -pub const POST_COPY_SEALED_FILE: &str = "postcopy-sealed.bin"; - /// ADR 0045 C2: the marker the destination's prestage writes into the /// snapshot dir to arm a POST-COPY restore (peer-mode handler spawn, /// state.bin appears late via the fetch poller). @@ -1685,7 +1494,7 @@ impl FirecrackerBackend { Box::new(conn), cmd, durable_capable, - Some(ExecRedial::unix(agent_socket.to_path_buf())), + Some(unix_exec_redial(agent_socket.to_path_buf())), ) .await } @@ -1737,7 +1546,7 @@ impl FirecrackerBackend { Box::new(conn), cmd, durable_capable, - Some(ExecRedial::firecracker( + Some(firecracker_exec_redial( sandboxes.clone(), sandbox_id, vsock_uds_path.to_path_buf(), @@ -4260,455 +4069,59 @@ fn spawn_process_supervisor( }); } -/// Object-safe exec transport used by the ADR 0103 host protocol driver. -/// -/// Public only for `engram-dst-cosim`, which composes this real host reader -/// with a real agentd handler across a simulated snapshot severance. -pub trait ExecIo: AsyncRead + AsyncWrite + Unpin + Send {} -impl ExecIo for T where T: AsyncRead + AsyncWrite + Unpin + Send {} - -/// Boxed exec transport for the ADR 0103 co-simulation boundary. -pub type BoxExecIo = Box; - -type ExecRedialFuture = - Pin> + Send + 'static>>; - -/// Reconnection factory used after an exec connection ends. -/// -/// Production constructs this from private Unix/Firecracker helpers. -/// [`ExecRedial::provided`] is the narrow co-simulation seam: each call can -/// create a fresh duplex backed by a new real agentd connection handler. -#[derive(Clone)] -pub struct ExecRedial { - connect: Arc ExecRedialFuture + Send + Sync>, -} - -impl ExecRedial { - fn unix(path: PathBuf) -> Self { - Self::provided(move || { - let path = path.clone(); - async move { - UnixStream::connect(&path) - .await - .map(|stream| Box::new(stream) as BoxExecIo) - .map_err(|error| { - vm_err(format!( - "durable exec reattach connect to {}: {error}", - path.display() - )) - }) - } - }) - } - - fn firecracker( - sandboxes: Arc>, - sandbox_id: SandboxId, - vsock_uds_path: PathBuf, - port: u32, - ) -> Self { - Self::provided(move || { - let sandboxes = sandboxes.clone(); - let vsock_uds_path = vsock_uds_path.clone(); - async move { - FirecrackerBackend::connect_fc_vsock(&sandboxes, sandbox_id, &vsock_uds_path, port) - .await - .map(|stream| Box::new(stream) as BoxExecIo) - } - }) - } - - /// Construct a reusable redial factory for the coordinator↔host - /// co-simulator. Each invocation must return a fresh connection. - pub fn provided(connect: F) -> Self - where - F: Fn() -> Fut + Send + Sync + 'static, - Fut: Future> + Send + 'static, - { - Self { - connect: Arc::new(move || Box::pin(connect())), - } - } - - async fn connect(&self) -> Result { - (self.connect)().await - } - - async fn reconnect_after_eof(&self) -> Result { - let mut last_error = None; - for attempt in 0..40 { - match self.connect().await { - Ok(connection) => return Ok(connection), - Err(error) => last_error = Some(error), - } - if attempt < 39 { - tokio::time::sleep(Duration::from_millis(25)).await; - } +fn unix_exec_redial(path: PathBuf) -> ExecRedial { + ExecRedial::provided(move || { + let path = path.clone(); + async move { + UnixStream::connect(&path) + .await + .map(|stream| Box::new(stream) as BoxExecIo) + .map_err(|error| { + vm_err(format!( + "durable exec reattach connect to {}: {error}", + path.display() + )) + }) } - Err(last_error.unwrap_or_else(|| vm_err("durable exec reattach had no dial attempt"))) - } -} - -const DURABLE_EXEC_SKEW: &str = "ENGRAM_DURABLE_EXEC_VERSION_SKEW"; - -/// How many consecutive transport EOFs with no frame in between the durable -/// exec reader tolerates before it ends without Exit. This bounds the -/// reconnect loop against a guest that accepts a dial and closes it before -/// one frame arrives; past the cap, the caller's fresh RPC (same ticket) -/// owns the retry with its own pacing. -const MAX_DEAD_RECONNECT_CYCLES: u32 = 3; - -#[derive(serde::Deserialize, serde::Serialize)] -struct LegacyWireExecRequest { - command: Vec, - stdin: Option>, - env: HashMap, - workdir: Option, - timeout_ms: Option, -} - -#[derive(serde::Deserialize, serde::Serialize)] -enum LegacyWireRequest { - Exec(LegacyWireExecRequest), + }) } -async fn probe_durable_exec(mut io: BoxExecIo) -> Result { - write_msg( - &mut io, - &WireRequest::CancelExec { - exec_id: engram_agentd::handler::DURABLE_EXEC_CAPABILITY_PROBE.into(), - }, - ) - .await - .map_err(|error| { - SandboxError::Unavailable(format!("durable exec capability probe send: {error}")) - })?; - match read_msg::<_, WireResponse>(&mut io).await { - Ok(WireResponse::ExecCancelled) => Ok(true), - Ok(WireResponse::Error { kind, message }) => { - tracing::warn!( - %kind, - %message, - "guest agentd lacks ADR 0103 durable exec; using stage-1 protocol", - ); - Ok(false) +fn firecracker_exec_redial( + sandboxes: Arc>, + sandbox_id: SandboxId, + vsock_uds_path: PathBuf, + port: u32, +) -> ExecRedial { + ExecRedial::provided(move || { + let sandboxes = sandboxes.clone(); + let vsock_uds_path = vsock_uds_path.clone(); + async move { + FirecrackerBackend::connect_fc_vsock(&sandboxes, sandbox_id, &vsock_uds_path, port) + .await + .map(|stream| Box::new(stream) as BoxExecIo) } - Ok(other) => Err(vm_err(format!( - "durable exec capability probe returned unexpected response: {other:?}" - ))), - Err(error) => Err(SandboxError::Unavailable(format!( - "durable exec capability probe failed before command submission: {error}" - ))), - } -} - -/// One `CancelExec` request/response round-trip against agentd. Split out of -/// `SandboxBackend::cancel_exec` so the severance unit test can drive it -/// over a duplex pair without a live sandbox (run_once pattern, ADR 0098). -async fn cancel_exec_roundtrip(mut io: BoxExecIo, exec_id: &str) -> Result<(), SandboxError> { - write_msg( - &mut io, - &WireRequest::CancelExec { - exec_id: exec_id.to_string(), - }, - ) - .await - .map_err(|error| SandboxError::Unavailable(format!("send CancelExec({exec_id}): {error}")))?; - match read_msg::<_, WireResponse>(&mut io).await { - Ok(WireResponse::ExecCancelled) => Ok(()), - Ok(WireResponse::Error { kind, message }) => Err(vm_err(format!( - "agentd rejected CancelExec({exec_id}) ({kind}): {message}" - ))), - Ok(other) => Err(vm_err(format!( - "CancelExec({exec_id}) returned unexpected response: {other:?}" - ))), - Err(error) => Err(SandboxError::Unavailable(format!( - "CancelExec({exec_id}) response failed; likely host/guest version skew (old agentd without ADR 0103): {error}" - ))), - } + }) } -/// Drive one attach-or-start request and translate the guest's durable stream. -/// An EOF re-dials from the exact per-stream byte cursors once the capability -/// probe has succeeded. Every generation must begin with a matching `Started` -/// frame. -/// -/// Reconnects ask attach-or-start until the first `Started` proves the guest -/// journaled the command; after that proof they ask attach-only, so a lost -/// journal entry refuses loudly instead of running the command twice. -/// Consecutive reconnects that deliver no frame are bounded by -/// [`MAX_DEAD_RECONNECT_CYCLES`]; past the cap the stream ends without Exit, -/// which the coordinator surfaces as retryable with the same ticket. -/// -/// Production enters through `SandboxBackend::exec_stream`; this is public -/// only so `engram-dst-cosim` can pair the real reader with real agentd and -/// exercise checkpoint severance/re-attach at their shared boundary. +/// Runs the guest exec protocol over a connected transport. pub async fn drive_exec_protocol( sandbox_id: SandboxId, - mut io: BoxExecIo, - cmd: ExecRequest, + io: BoxExecIo, + mut cmd: ExecRequest, durable_capable: bool, redial: Option, ) -> Result { - let exec_id = cmd - .exec_id - .clone() - .unwrap_or_else(|| format!("fc-{}", uuid::Uuid::new_v4().simple())); - let mut stdout_offset = cmd.stdout_offset.unwrap_or(0); - let mut stderr_offset = cmd.stderr_offset.unwrap_or(0); - if durable_capable { - let req = agent_exec_request(&cmd, &exec_id, stdout_offset, stderr_offset, false); - write_msg(&mut io, &req).await.map_err(|error| { - SandboxError::Unavailable(format!("send durable exec request: {error}")) - })?; - } else { - let req = LegacyWireRequest::Exec(LegacyWireExecRequest { - command: cmd.command.clone(), - stdin: cmd.stdin.clone(), - env: cmd.env.clone(), - workdir: cmd.workdir.clone(), - timeout_ms: cmd.timeout.map(|duration| duration.as_millis() as u64), - }); - write_msg(&mut io, &req).await.map_err(|error| { - SandboxError::Unavailable(format!("send stage-1 WireRequest::Exec: {error}")) - })?; - } - - // 64 events of buffer is enough that a slow consumer doesn't - // immediately backpressure the agent; the agent has its own - // 64-event channel so total in-flight bound is bounded. - let (tx, rx) = mpsc::channel::(64); - let reader_exec_id = exec_id.clone(); - - tokio::spawn(async move { - let exec_id = reader_exec_id; - let mut durable_capable = durable_capable; - let mut expect_started = durable_capable; - // The guest proves the journal entry exists the first time it sends - // `Started`. Until then a reconnect must ask attach-or-start: the - // request may have died before agentd journaled it, and attach-only - // would be refused as a "second command" when zero commands ran. - let mut journal_proven = false; - // Consecutive EOFs with no frame delivered in between. Bounded by - // MAX_DEAD_RECONNECT_CYCLES so a connectable-but-instantly-closing - // guest cannot spin this loop forever. - let mut dead_cycles = 0u32; - loop { - let msg = match read_msg::<_, WireExecEvent>(&mut io).await { - Ok(msg) => { - dead_cycles = 0; - msg - } - Err(error) if !durable_capable => { - // A legacy agent or a degraded journal has no safe retry. - // A retry could run the command twice. - durable_exec_fallback( - &tx, - sandbox_id, - format!( - "{DURABLE_EXEC_SKEW}: exec transport ended before a durable result: {error}" - ), - ) - .await; - return; - } - Err(error) => { - let Some(connector) = redial.as_ref() else { - // The journal stays authoritative. End without Exit so - // a fresh coordinator call can use the same ticket. - tracing::warn!( - %sandbox_id, - %exec_id, - stdout_offset, - stderr_offset, - %error, - "durable exec transport ended; reattach is unavailable; ending without Exit", - ); - return; - }; - if tx.is_closed() { - // The consumer dropped the stream; no frame can be - // observed anymore. Do not keep dialing the guest. - tracing::debug!( - %sandbox_id, - %exec_id, - "durable exec consumer gone; ending reader without reconnect", - ); - return; - } - dead_cycles += 1; - if dead_cycles > MAX_DEAD_RECONNECT_CYCLES { - // The journal stays authoritative. End without Exit - // so the caller's fresh RPC owns the retry pacing. - tracing::warn!( - %sandbox_id, - %exec_id, - stdout_offset, - stderr_offset, - dead_cycles, - %error, - "durable exec made no progress across consecutive reconnects; ending without Exit", - ); - return; - } - let mut next = match connector.reconnect_after_eof().await { - Ok(next) => next, - Err(reconnect_error) => { - // A failed dial is not proof that the journal is - // gone. Let the caller open a fresh host RPC. - tracing::warn!( - %sandbox_id, - %exec_id, - stdout_offset, - stderr_offset, - %error, - %reconnect_error, - "durable exec reconnect failed; ending without Exit", - ); - return; - } - }; - let attach = agent_exec_request( - &cmd, - &exec_id, - stdout_offset, - stderr_offset, - journal_proven, - ); - if let Err(write_error) = write_msg(&mut next, &attach).await { - // A failed write did not reach a journal verdict. A - // fresh caller can safely retry the deduped attach. - tracing::warn!( - %sandbox_id, - %exec_id, - stdout_offset, - stderr_offset, - %write_error, - "durable exec reattach request transport failed; ending without Exit", - ); - return; - } - tracing::info!( - %sandbox_id, - %exec_id, - stdout_offset, - stderr_offset, - "durable exec transport ended; re-attached to guest journal", - ); - io = next; - expect_started = true; - continue; - } - }; - if expect_started && !matches!(&msg, WireExecEvent::Started(_)) { - // A real but out-of-contract guest frame is a protocol error. - // A retry could reach an agent that did not honor the ticket. - durable_exec_fallback( - &tx, - sandbox_id, - format!( - "durable exec protocol violation: first frame for exec_id {exec_id} was not Started: {msg:?}" - ), - ) - .await; - return; - } - match msg { - WireExecEvent::Started(started_id) => { - if !expect_started || started_id != exec_id { - // The guest acknowledged a different lifecycle or - // ticket. Do not retry an identity-ambiguous exec. - durable_exec_fallback( - &tx, - sandbox_id, - format!( - "durable exec protocol violation: expected Started({exec_id}), got Started({started_id})" - ), - ) - .await; - return; - } - durable_capable = true; - expect_started = false; - journal_proven = true; - } - WireExecEvent::Degraded(reason) => { - durable_capable = false; - expect_started = false; - tracing::warn!( - %sandbox_id, - %exec_id, - %reason, - "guest journal degraded; keeping stage-1 live stream", - ); - } - WireExecEvent::Stdout(b) => { - // An old agentd emits output/exit without Started. Keep - // serving its stage-1 stream, but never re-attach it: a - // retry would execute the command twice. - expect_started = false; - stdout_offset = stdout_offset.saturating_add(b.len() as u64); - if tx.send(ExecEvent::Stdout(Bytes::from(b))).await.is_err() { - return; - } - } - WireExecEvent::Stderr(b) => { - expect_started = false; - stderr_offset = stderr_offset.saturating_add(b.len() as u64); - if tx.send(ExecEvent::Stderr(Bytes::from(b))).await.is_err() { - return; - } - } - WireExecEvent::Exit(code) => { - let _ = tx.send(ExecEvent::Exit(code)).await; - return; - } - WireExecEvent::Refused { reason } => { - let _ = tx.send(ExecEvent::Refused(reason)).await; - return; - } - } - } - }); - - Ok(ExecStream { + cmd.exec_id + .get_or_insert_with(|| format!("fc-{}", uuid::Uuid::new_v4().simple())); + engram_host_core::guest_client::drive_exec_protocol( sandbox_id, - exec_id, - events: Box::pin(ReceiverStream::new(rx)), - }) -} - -fn agent_exec_request( - cmd: &ExecRequest, - exec_id: &str, - stdout_offset: u64, - stderr_offset: u64, - attach_only: bool, -) -> WireRequest { - WireRequest::Exec(WireExecRequest { - command: cmd.command.clone(), - stdin: cmd.stdin.clone(), - env: cmd.env.clone(), - workdir: cmd.workdir.clone(), - timeout_ms: cmd.timeout.map(|duration| duration.as_millis() as u64), - exec_id: Some(exec_id.to_string()), - stdout_offset: Some(stdout_offset), - stderr_offset: Some(stderr_offset), - wake: cmd.wake, - attach_only, - }) -} - -async fn durable_exec_fallback( - tx: &mpsc::Sender, - sandbox_id: SandboxId, - reason: String, -) { - tracing::warn!(%sandbox_id, %reason, "durable exec fell back to synthetic Exit(None)"); - let _ = tx - .send(ExecEvent::Stderr(Bytes::from(format!("{reason}\n")))) - .await; - let _ = tx.send(ExecEvent::Exit(None)).await; + io, + cmd, + durable_capable, + redial, + ExecConnectionMode::Reattach, + ) + .await } /// How [`wait_for_socket`] decides the spawned process's socket is ready. @@ -6053,38 +5466,7 @@ impl SandboxBackend for FirecrackerBackend { }); } - // ADR 0021 P1.4: no harness drive — argv points at a path - // inside the rootfs (the image manifest's `[harness] exec`). - // The `harness_substrate` / `harness_pack_uri` plumbing on - // SandboxSpec stays (always-None on the new coord path) - // until P1.5 retires it together with option-D. - // - // 2026-07 core-ops fold: this single frame also carries the - // per-host egress-proxy CA (ADR 0021 P1). agentd installs it - // (if present) before spawning, so there is exactly ONE - // host→guest first-contact RPC per `start_agent` instead of - // two — the CA-specific retry ladder that used to precede - // this call is gone; its bounded first-contact retry moves - // to wrap this round trip instead (below). Idempotent — - // agentd's `last_pem` cache makes a resume-with-same-cert a - // zero-I/O hot path, and an empty/`None` PEM is a no-op. - // ADR 0067: stamp the attach token into the harness child env — - // the backend is the only party that knows the sandbox id - // pre-boot; the epoch was minted coordinator-side into the spec. - let token_env = engram_harness_proto::attach_token::AttachToken { - sandbox_id: id, - binding_epoch: agent.binding_epoch, - } - .env(); - let mut agent = agent; - agent.env.extend(token_env); - - let req = engram_agentd::WireRequest::SpawnHarness(engram_agentd::SpawnHarnessRequest { - argv: agent.argv, - env: agent.env.into_iter().collect(), - session_env: agent.session_env.into_iter().collect(), - host_ca_pem: agent.host_ca_pem, - }); + let req = engram_host_core::guest_client::spawn_harness_request(id, agent); // Harness spawn: connect to agentd-1024 and round-trip SpawnHarness. // @@ -6188,19 +5570,7 @@ impl SandboxBackend for FirecrackerBackend { // must not fail the spawn. let mut clock_done = clock_done_rx.clone(); let _ = clock_done.wait_for(|done| *done).await; - engram_agentd::write_msg(&mut conn, &req) - .await - .map_err(|e| SandboxError::Vm(format!("write SpawnHarness: {e}").into()))?; - let resp = engram_agentd::read_msg(&mut conn).await.map_err(|e| { - SandboxError::Vm(format!("read SpawnHarness response: {e}").into()) - })?; - // Pin the block's error type to SandboxError. Without this the - // inference is ambiguous (connect/write yield SandboxError, the - // raw read_msg yields io::Error) and resolves differently under - // `-p coord -p host-agent` unification vs `--workspace` — which - // is why single-crate check + workspace clippy passed but the - // integration `-p` build failed. - Ok::<_, SandboxError>(resp) + engram_host_core::guest_client::spawn_harness(&mut conn, &req).await }; let outcome = match tokio::time::timeout( attempt_timeout, @@ -6573,7 +5943,6 @@ impl FirecrackerBackend { // Pre-1970 host clock: nothing useful to push. Err(_) => return, }; - let req = engram_agentd::WireRequest::StepClock { unix_nanos }; let deadline = tokio::time::Instant::now() + CLOCK_PUSH_BUDGET; let mut last_err: Option = None; @@ -6587,12 +5956,7 @@ impl FirecrackerBackend { Self::connect_fc_vsock(sandboxes, id, vsock_uds_path, ENGRAM_AGENTD_PORT) .await .map_err(|e| format!("connect: {e}"))?; - engram_agentd::write_msg(&mut conn, &req) - .await - .map_err(|e| format!("write StepClock: {e}"))?; - engram_agentd::read_msg(&mut conn) - .await - .map_err(|e| format!("read StepClock response: {e}")) + engram_host_core::guest_client::step_guest_clock(&mut conn, unix_nanos).await }; match tokio::time::timeout(remaining, inner).await { Ok(Ok(engram_agentd::WireResponse::ClockStepped { @@ -7026,7 +6390,12 @@ impl FirecrackerBackend { #[cfg(test)] mod tests { use super::*; + use bytes::Bytes; + use engram_agentd::{read_msg, write_msg, WireResponse}; + use engram_agentd::{WireExecEvent, WireExecRequest}; + use engram_core::types::sandbox::ExecEvent; use std::collections::HashMap; + use std::io; #[tokio::test] async fn epoch_severed_stream_idle_read_returns_eof_after_epoch_bump() { diff --git a/crates/engram-sandbox-vz/Cargo.toml b/crates/engram-sandbox-vz/Cargo.toml index ed8d0f18a..5ef55aecc 100644 --- a/crates/engram-sandbox-vz/Cargo.toml +++ b/crates/engram-sandbox-vz/Cargo.toml @@ -27,6 +27,7 @@ unsafe_code = "allow" unused_dependencies = "allow" [dependencies] +engram-host-core.workspace = true engram-core.workspace = true engram-agentd.workspace = true engram-harness-proto.workspace = true diff --git a/crates/engram-sandbox-vz/src/backend.rs b/crates/engram-sandbox-vz/src/backend.rs index 4d88ce1a0..0536ca2c6 100644 --- a/crates/engram-sandbox-vz/src/backend.rs +++ b/crates/engram-sandbox-vz/src/backend.rs @@ -3,17 +3,13 @@ //! drives its guests. The non-macOS shell in `lib.rs` shadows these //! types so the workspace compiles everywhere. -use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::Duration; use async_trait::async_trait; -use bytes::Bytes; use dashmap::DashMap; -use engram_agentd::{ - read_msg, write_msg, WireExecEvent, WireExecRequest, WireRequest, WireResponse, -}; +use engram_agentd::{read_msg, write_msg, WireRequest, WireResponse}; use engram_core::traits::sandbox::{ ForgeSink, HarnessByteStream, HarnessSink, SandboxBackend, UploadSink, }; @@ -21,16 +17,15 @@ use engram_core::types::endpoints::GuestEndpoints; use engram_core::types::ids::{SandboxId, SnapshotId}; use engram_core::types::sandbox::SandboxProbe; use engram_core::types::sandbox::{ - AgentSpec, AuxRoDrive, ExecEvent, ExecRequest, ExecStream, SandboxSpec, SessionDisks, - SessionFileMetadata, SessionFileSpec, SessionFileStream, + AgentSpec, AuxRoDrive, ExecRequest, ExecStream, SandboxSpec, SessionDisks, SessionFileMetadata, + SessionFileSpec, SessionFileStream, }; use engram_core::types::snapshot::SnapshotMetadata; use engram_core::SandboxError; +use engram_host_core::{guest_client, ENGRAM_AGENTD_PORT}; use parking_lot::Mutex; use tokio::io::{AsyncRead, AsyncWrite}; use tokio::net::UnixStream; -use tokio::sync::mpsc; -use tokio_stream::wrappers::ReceiverStream; use crate::vm::{VmConfig, VzVm}; use crate::vsock_bridge::{port_uds_path, VsockBridge, VsockConnector}; @@ -39,24 +34,6 @@ use crate::vsock_bridge::{port_uds_path, VsockBridge, VsockConnector}; /// a snapshot or a restore. const GUEST_RPC_BOUND: Duration = Duration::from_secs(5); -/// Vsock port engram-agentd binds inside the rootfs. Same number FC -/// uses; the in-VM binary doesn't know which VMM is hosting it. -const ENGRAM_AGENTD_PORT: u32 = 1024; - -#[derive(serde::Serialize)] -struct LegacyWireExecRequest { - command: Vec, - stdin: Option>, - env: HashMap, - workdir: Option, - timeout_ms: Option, -} - -#[derive(serde::Serialize)] -enum LegacyWireRequest { - Exec(LegacyWireExecRequest), -} - /// Static config for the VZ backend — values that are the same for /// every sandbox the backend creates. Per-sandbox overrides ride on /// `SandboxSpec` (cpu/memory/disk). @@ -305,10 +282,15 @@ impl VzBackend { ) -> Option { let agent_uds = port_uds_path(vsock_uds_path, ENGRAM_AGENTD_PORT); let fut = async { - let conn = UnixStream::connect(&agent_uds).await.ok()?; - let (mut reader, mut writer) = tokio::io::split(conn); - write_msg(&mut writer, &req).await.ok()?; - read_msg::<_, WireResponse>(&mut reader).await.ok() + let mut conn = UnixStream::connect(&agent_uds).await.ok()?; + match req { + WireRequest::StepClock { unix_nanos } => { + guest_client::step_guest_clock(&mut conn, unix_nanos) + .await + .ok() + } + _ => guest_client::request(&mut conn, &req).await.ok(), + } }; tokio::time::timeout(within, fut).await.ok().flatten() } @@ -572,151 +554,29 @@ impl VzBackend { } } -/// Run the agentd exec protocol over a connected byte stream. The -/// Firecracker backend carries the same function; only the connection -/// setup differs. +/// Run a single guest exec connection; later attaches belong to the caller. async fn drive_exec_protocol( sandbox_id: SandboxId, - mut reader: R, - mut writer: W, - cmd: ExecRequest, + reader: R, + writer: W, + mut cmd: ExecRequest, durable_capable: bool, ) -> Result where R: AsyncRead + Unpin + Send + 'static, W: AsyncWrite + Unpin + Send + 'static, { - let exec_id = cmd - .exec_id - .clone() - .unwrap_or_else(|| format!("vz-{}", uuid::Uuid::new_v4().simple())); - if durable_capable { - let req = WireRequest::Exec(WireExecRequest { - command: cmd.command.clone(), - stdin: cmd.stdin.clone(), - env: cmd.env.clone(), - workdir: cmd.workdir.clone(), - timeout_ms: cmd.timeout.map(|d| d.as_millis() as u64), - exec_id: Some(exec_id.clone()), - stdout_offset: cmd.stdout_offset, - stderr_offset: cmd.stderr_offset, - wake: cmd.wake, - attach_only: false, - }); - write_msg(&mut writer, &req) - .await - .map_err(|e| SandboxError::Vm(format!("send durable WireRequest::Exec: {e}").into()))?; - } else { - write_msg( - &mut writer, - &LegacyWireRequest::Exec(LegacyWireExecRequest { - command: cmd.command.clone(), - stdin: cmd.stdin.clone(), - env: cmd.env.clone(), - workdir: cmd.workdir.clone(), - timeout_ms: cmd.timeout.map(|duration| duration.as_millis() as u64), - }), - ) - .await - .map_err(|e| SandboxError::Vm(format!("send stage-1 WireRequest::Exec: {e}").into()))?; - } - - let (tx, rx) = mpsc::channel::(64); - let reader_exec_id = exec_id.clone(); - tokio::spawn(async move { - let exec_id = reader_exec_id; - loop { - match read_msg::<_, WireExecEvent>(&mut reader).await { - Ok(WireExecEvent::Started(started_id)) => { - if started_id != exec_id { - let _ = tx - .send(ExecEvent::Stderr(Bytes::from(format!( - "durable exec protocol violation: expected Started({exec_id}), got Started({started_id})\n" - )))) - .await; - let _ = tx.send(ExecEvent::Exit(None)).await; - return; - } - } - Ok(WireExecEvent::Degraded(reason)) => { - tracing::warn!(%reason, "guest durable exec journal degraded"); - } - Ok(WireExecEvent::Stdout(b)) => { - if tx.send(ExecEvent::Stdout(Bytes::from(b))).await.is_err() { - return; - } - } - Ok(WireExecEvent::Stderr(b)) => { - if tx.send(ExecEvent::Stderr(Bytes::from(b))).await.is_err() { - return; - } - } - Ok(WireExecEvent::Exit(code)) => { - let _ = tx.send(ExecEvent::Exit(code)).await; - return; - } - Ok(WireExecEvent::Refused { reason }) => { - let _ = tx.send(ExecEvent::Refused(reason)).await; - return; - } - Err(e) => { - if durable_capable { - // EOF/read failure is transport state, not a guest - // journal verdict. End without Exit so the coordinator - // exposes a retryable Unavailable and the caller can - // attach again with its delivered offsets. - tracing::warn!( - %sandbox_id, - %exec_id, - error = %e, - "durable vz exec connection ended without explicit Exit; ending event stream", - ); - return; - } - // An old agent has no spawn-dedupe journal. Retrying may - // double-run the command, so keep the stage-1 terminal - // floor for the legacy path. - tracing::warn!( - %sandbox_id, - %exec_id, - error = %e, - "legacy vz exec connection ended without explicit Exit; emitting Exit(None)", - ); - let _ = tx.send(ExecEvent::Exit(None)).await; - return; - } - } - } - }); - Ok(ExecStream { + cmd.exec_id + .get_or_insert_with(|| format!("vz-{}", uuid::Uuid::new_v4().simple())); + guest_client::drive_exec_protocol( sandbox_id, - exec_id, - events: Box::pin(ReceiverStream::new(rx)), - }) -} - -async fn probe_durable_exec(mut stream: UnixStream) -> Result { - write_msg( - &mut stream, - &WireRequest::CancelExec { - exec_id: engram_agentd::handler::DURABLE_EXEC_CAPABILITY_PROBE.into(), - }, + Box::new(tokio::io::join(reader, writer)), + cmd, + durable_capable, + None, + guest_client::ExecConnectionMode::Single, ) .await - .map_err(|error| SandboxError::Vm(format!("durable exec capability send: {error}").into()))?; - match read_msg::<_, WireResponse>(&mut stream).await { - Ok(WireResponse::ExecCancelled) => Ok(true), - Ok(WireResponse::Error { kind, message }) => { - tracing::warn!(%kind, %message, "guest agentd has no durable exec; using stage-1 exec"); - Ok(false) - } - Ok(other) => Err(SandboxError::Vm( - format!("durable exec capability returned {other:?}").into(), - )), - Err(error) => Err(SandboxError::Vm( - format!("durable exec capability failed before submission: {error}").into(), - )), - } } /// A fresh per-VM identity: a platform machine identifier plus a random @@ -847,28 +707,8 @@ impl SandboxBackend for VzBackend { SandboxError::Vm(format!("connect agentd UDS {}: {e}", agent_uds.display()).into()) })?; - // The backend is the only party that knows the sandbox id before - // boot, so it stamps the attach token into the harness env. - let token_env = engram_harness_proto::attach_token::AttachToken { - sandbox_id: id, - binding_epoch: agent.binding_epoch, - } - .env(); - let mut agent = agent; - agent.env.extend(token_env); - - let req = engram_agentd::WireRequest::SpawnHarness(engram_agentd::SpawnHarnessRequest { - argv: agent.argv, - env: agent.env.into_iter().collect(), - session_env: agent.session_env.into_iter().collect(), - host_ca_pem: agent.host_ca_pem, - }); - engram_agentd::write_msg(&mut conn, &req) - .await - .map_err(|e| SandboxError::Vm(format!("write SpawnHarness: {e}").into()))?; - let resp: engram_agentd::WireResponse = engram_agentd::read_msg(&mut conn) - .await - .map_err(|e| SandboxError::Vm(format!("read SpawnHarness response: {e}").into()))?; + let req = guest_client::spawn_harness_request(id, agent); + let resp = guest_client::spawn_harness(&mut conn, &req).await?; match resp { engram_agentd::WireResponse::HarnessSpawned { pid, ca_changed } => { tracing::debug!( @@ -915,7 +755,7 @@ impl SandboxBackend for VzBackend { format!("connect engram-agentd UDS {}: {e}", agent_uds.display()).into(), ) })?; - let durable_capable = probe_durable_exec(probe).await?; + let durable_capable = guest_client::probe_durable_exec(Box::new(probe)).await?; let conn = UnixStream::connect(&agent_uds).await.map_err(|e| { SandboxError::Vm( format!( @@ -935,31 +775,12 @@ impl SandboxBackend for VzBackend { live.vsock_uds_path.clone() }; let agent_uds = port_uds_path(&vsock_uds_path, ENGRAM_AGENTD_PORT); - let mut stream = UnixStream::connect(&agent_uds).await.map_err(|error| { + let stream = UnixStream::connect(&agent_uds).await.map_err(|error| { SandboxError::Vm( format!("connect engram-agentd UDS {}: {error}", agent_uds.display()).into(), ) })?; - write_msg( - &mut stream, - &WireRequest::CancelExec { - exec_id: exec_id.clone(), - }, - ) - .await - .map_err(|error| SandboxError::Vm(format!("send CancelExec: {error}").into()))?; - match read_msg::<_, WireResponse>(&mut stream).await { - Ok(WireResponse::ExecCancelled) => Ok(()), - Ok(WireResponse::Error { kind, message }) => Err(SandboxError::Vm( - format!("CancelExec({exec_id}) rejected ({kind}): {message}").into(), - )), - Ok(other) => Err(SandboxError::Vm( - format!("CancelExec({exec_id}) returned {other:?}").into(), - )), - Err(error) => Err(SandboxError::Vm( - format!("CancelExec({exec_id}) failed (old agentd protocol skew): {error}").into(), - )), - } + guest_client::cancel_exec_roundtrip(Box::new(stream), &exec_id).await } async fn write_file( @@ -1452,7 +1273,10 @@ impl SandboxBackend for VzBackend { #[cfg(test)] mod tests { use super::*; + use engram_agentd::WireExecEvent; + use engram_core::types::sandbox::ExecEvent; use futures::StreamExt; + use std::collections::HashMap; fn protocol_exec(exec_id: &str) -> ExecRequest { ExecRequest { diff --git a/crates/engram-sandbox-vz/src/lib.rs b/crates/engram-sandbox-vz/src/lib.rs index a6ca58f44..db78467a6 100644 --- a/crates/engram-sandbox-vz/src/lib.rs +++ b/crates/engram-sandbox-vz/src/lib.rs @@ -36,6 +36,8 @@ #[cfg(target_os = "macos")] mod backend; +#[cfg(target_os = "macos")] +mod queue_bound; #[cfg(target_os = "macos")] mod vm; diff --git a/crates/engram-sandbox-vz/src/queue_bound.rs b/crates/engram-sandbox-vz/src/queue_bound.rs new file mode 100644 index 000000000..b54cceba8 --- /dev/null +++ b/crates/engram-sandbox-vz/src/queue_bound.rs @@ -0,0 +1,35 @@ +//! Explicit transfer of retained values to their owning dispatch queue. + +use objc2::{rc::Retained, Message}; + +/// A value whose access requires the owning serial queue. +pub(crate) struct Sendable(T); + +// SAFETY: construction requires safe transfer and destruction on any thread. +// Access to the value requires the caller to prove queue ownership. +unsafe impl Send for Sendable {} +// SAFETY: no safe method exposes the value; shared access also requires its queue. +unsafe impl Sync for Sendable {} + +impl Sendable { + /// # Safety + /// Moving and dropping `value` must be safe on any thread. All access + /// must occur on its owning serial queue, except thread-safe ARC operations. + pub(crate) unsafe fn new(value: T) -> Self { + Self(value) + } + + /// # Safety + /// The caller must run on the value's owning serial queue and keep + /// the returned reference on that queue for its entire use. + pub(crate) unsafe fn as_ref_on_queue(&self) -> &T { + &self.0 + } +} + +impl Clone for Sendable> { + fn clone(&self) -> Self { + // ARC retain is thread-safe. The clone has the same access contract. + Self(self.0.clone()) + } +} diff --git a/crates/engram-sandbox-vz/src/vm.rs b/crates/engram-sandbox-vz/src/vm.rs index 53c67ad7d..a13c6f44a 100644 --- a/crates/engram-sandbox-vz/src/vm.rs +++ b/crates/engram-sandbox-vz/src/vm.rs @@ -233,37 +233,7 @@ impl From for engram_core::SandboxError { } } -/// Send-wrapper to ferry an ObjC reference (Retained, RcBlock, -/// etc.) into a closure dispatched onto the queue. ObjC objects -/// are `!Send` in objc2 0.6, but ARC retain/release is thread-safe -/// and our access pattern serializes through the queue, so the -/// move itself is sound. -/// -/// SAFETY: the inner value is dereferenced only inside a closure -/// dispatched onto the per-VM serial `DispatchQueue`. The queue -/// runs that closure on one of its worker threads, never two -/// simultaneously, so there's no concurrent access. Non-mutating -/// retain/release across threads is safe because Apple's ARC -/// counters are atomic. -pub(crate) struct Sendable(pub(crate) T); -unsafe impl Send for Sendable {} -unsafe impl Sync for Sendable {} - -impl std::ops::Deref for Sendable { - type Target = T; - fn deref(&self) -> &T { - &self.0 - } -} - -impl Clone for Sendable { - /// Cloning a `Sendable>` bumps the ObjC refcount, which - /// is atomic — sound to do off the dispatch queue. Consumers still - /// dereference the clone only on the queue. - fn clone(&self) -> Self { - Sendable(self.0.clone()) - } -} +pub(crate) use crate::queue_bound::Sendable; // ---- VZVirtualMachineDelegate (crash detection, ADR 0096) ------------ @@ -341,10 +311,8 @@ pub(crate) struct VzVm { _delegate: Retained, } -// SAFETY: see `SendableVm` for the full argument. The `VzVm` itself -// is treated the same way — the `vm` field is only ever cloned into -// `SendableVm` for dispatch onto the queue; nothing reads or mutates -// it directly across threads. +// SAFETY: VM access runs on its serial queue. Retain and release are +// thread-safe; the delegate only shares an atomic flag. unsafe impl Send for VzVm {} unsafe impl Sync for VzVm {} @@ -355,7 +323,8 @@ impl VzVm { /// long as every consumer dereferences only on the dispatch queue /// (the bridge does). pub(crate) fn raw_clone(&self) -> Sendable> { - Sendable(self.vm.clone()) + // SAFETY: only queue-bound access is exposed; ARC retain/release is thread-safe. + unsafe { Sendable::new(self.vm.clone()) } } /// Clone the queue handle. The vsock bridge / connector hold onto @@ -421,16 +390,17 @@ impl VzVm { let dead = Arc::new(AtomicBool::new(false)); let delegate = VmStopDelegate::new(dead.clone()); { - let vm = Sendable(vm.clone()); - let delegate = Sendable(delegate.clone()); + // SAFETY: access stays on the VM queue; moving and dropping the retained value is safe. + let vm = unsafe { Sendable::new(vm.clone()) }; + // SAFETY: access stays on the VM queue; moving and dropping the retained value is safe. + let delegate = unsafe { Sendable::new(delegate.clone()) }; queue.exec_async(move || { - // Move the WHOLE wrappers in (edition-2021 disjoint - // capture would otherwise grab the bare Retained fields). - let (vm, delegate) = (vm, delegate); // SAFETY: on the VM's queue; delegate outlives the VM // (kept retained in `_delegate` — the property is weak). unsafe { - vm.0.setDelegate(Some(objc2::runtime::ProtocolObject::from_ref(&*delegate.0))); + vm.as_ref_on_queue().setDelegate(Some( + objc2::runtime::ProtocolObject::from_ref(&**delegate.as_ref_on_queue()), + )); } }); } @@ -490,16 +460,13 @@ impl VzVm { /// liveness check both key off this. pub async fn state(&self) -> VZVirtualMachineState { let (tx, rx) = oneshot::channel(); - let vm = Sendable(self.vm.clone()); + // SAFETY: access stays on the VM queue; moving and dropping the retained value is safe. + let vm = unsafe { Sendable::new(self.vm.clone()) }; let tx = std::sync::Mutex::new(Some(tx)); self.queue.exec_async(move || { - // Move the WHOLE `Sendable` in — edition-2021 disjoint - // capture would otherwise capture only the `.0` field (a - // bare non-Send `Retained`), defeating the wrapper. - let vm = vm; // SAFETY: vm is retained for the closure's lifetime and we // are on the VM's dispatch queue. - let st = unsafe { vm.0.state() }; + let st = unsafe { vm.as_ref_on_queue().state() }; if let Some(tx) = tx.lock().expect("state oneshot mutex").take() { let _ = tx.send(st); } @@ -544,12 +511,13 @@ impl VzVm { /// Save the paused VM's full state (memory + device state) to /// `dest`. VM must be in `.paused`. Used by snapshot in task 29. pub async fn save(&self, dest: &Path) -> Result<(), VzError> { - let url = Sendable(nsurl_for_path(dest)); + // SAFETY: access stays on the VM queue; moving and dropping the retained value is safe. + let url = unsafe { Sendable::new(nsurl_for_path(dest)) }; self.dispatch_op_save_restore("save", move |vm, completion| { // SAFETY: see `start`. url lives until the handler fires // because it's captured by the FnOnce that we passed to // dispatch_op_save_restore. - unsafe { vm.saveMachineStateToURL_completionHandler(&url, completion) } + unsafe { vm.saveMachineStateToURL_completionHandler(url.as_ref_on_queue(), completion) } }) .await } @@ -558,10 +526,13 @@ impl VzVm { /// VM with a configuration that matches the source. Used by /// snapshot in task 29. pub async fn restore(&self, src: &Path) -> Result<(), VzError> { - let url = Sendable(nsurl_for_path(src)); + // SAFETY: access stays on the VM queue; moving and dropping the retained value is safe. + let url = unsafe { Sendable::new(nsurl_for_path(src)) }; self.dispatch_op_save_restore("restore", move |vm, completion| { // SAFETY: see `start`. - unsafe { vm.restoreMachineStateFromURL_completionHandler(&url, completion) } + unsafe { + vm.restoreMachineStateFromURL_completionHandler(url.as_ref_on_queue(), completion) + } }) .await } @@ -607,7 +578,8 @@ impl VzVm { F: FnOnce(&VZVirtualMachine, &block2::DynBlock) + Send + 'static, { let (tx, rx) = oneshot::channel::>(); - let vm = Sendable(self.vm.clone()); + // SAFETY: access stays on the VM queue; moving and dropping the retained value is safe. + let vm = unsafe { Sendable::new(self.vm.clone()) }; let tx = Mutex::new(Some(tx)); let block = RcBlock::new(move |err: *mut NSError| { let result: Result<(), VzError> = if err.is_null() { @@ -629,9 +601,13 @@ impl VzVm { let _ = tx.send(result); } }); - let block = Sendable(block); + // SAFETY: access stays on the VM queue; moving and dropping the retained value is safe. + let block = unsafe { Sendable::new(block) }; self.queue.exec_async(move || { - schedule(&vm, &block); + // SAFETY: both values are retained and this closure runs on the VM queue. + unsafe { + schedule(vm.as_ref_on_queue(), block.as_ref_on_queue()); + } }); rx.await .map_err(|_| VzError::Internal(format!("{op}: completion channel dropped")))? diff --git a/crates/engram-sandbox-vz/src/vsock_bridge.rs b/crates/engram-sandbox-vz/src/vsock_bridge.rs index 910c17aaf..1aa8c2f97 100644 --- a/crates/engram-sandbox-vz/src/vsock_bridge.rs +++ b/crates/engram-sandbox-vz/src/vsock_bridge.rs @@ -84,7 +84,7 @@ use crate::vm::Sendable; /// Vsock ports — same well-known values as `engram-sandbox-firecracker` /// since the in-guest agentd / harness / share binaries listen on the /// same numbers regardless of which VMM is hosting the VM. -const VSOCK_PORT_AGENTD: u32 = 1024; +use engram_host_core::ENGRAM_AGENTD_PORT; const VSOCK_PORT_HARNESS: u32 = 1026; /// Readiness handshake port (guest→host). agentd on the vsock transport /// dials this once at startup (`engram_agentd::ENGRAM_AGENTD_READY_PORT`). @@ -202,13 +202,16 @@ impl VsockConnector { } }, ); - let block = Sendable(block); + // SAFETY: the block captures only a thread-safe sender and is invoked on the VM queue. + let block = unsafe { Sendable::new(block) }; self.queue.exec_async(move || { // SAFETY: dispatched onto the VM's serial queue, so the // device call is on a VZ-safe thread; `block` outlives the // call (owned by the queue until the handler fires). unsafe { - device.connectToPort_completionHandler(port, &block); + device + .as_ref_on_queue() + .connectToPort_completionHandler(port, block.as_ref_on_queue()); } }); rx.await @@ -302,10 +305,9 @@ impl VsockBridge { forge_sink: Option, upload_sink: Option, ) -> Result<(Self, VsockConnector), BridgeError> { - let socket_device = lookup_socket_device(&queue, &vm) + let device = lookup_socket_device(&queue, &vm) .await .ok_or(BridgeError::NoSocketDevice)?; - let device = Sendable(socket_device); let connector = VsockConnector { device: device.clone(), queue: queue.clone(), @@ -322,15 +324,15 @@ impl VsockBridge { // start_agent / exec_stream dial doesn't race a not-yet-bound // window between create() returning and the bridge going live. { - let uds_path = port_uds_path(&base_path, VSOCK_PORT_AGENTD); + let uds_path = port_uds_path(&base_path, ENGRAM_AGENTD_PORT); let _ = tokio::fs::remove_file(&uds_path).await; // tolerate stale let listener = UnixListener::bind(&uds_path) .map_err(|e| BridgeError::Bind(uds_path.clone(), e))?; - tracing::debug!(port = VSOCK_PORT_AGENTD, path = %uds_path.display(), "vz vsock host-initiated bound"); + tracing::debug!(port = ENGRAM_AGENTD_PORT, path = %uds_path.display(), "vz vsock host-initiated bound"); tasks.push(tokio::spawn(agentd_uds_pump( listener, connector.clone(), - VSOCK_PORT_AGENTD, + ENGRAM_AGENTD_PORT, ))); } @@ -355,8 +357,7 @@ impl VsockBridge { ); continue; }; - let (conn_tx, conn_rx) = - mpsc::unbounded_channel::>>(); + let (conn_tx, conn_rx) = mpsc::unbounded_channel::(); let delegate = VsockListenerDelegate::new(conn_tx); // SAFETY: VZVirtioSocketListener::new returns a freshly // retained, non-nil instance; we attach our delegate before @@ -373,14 +374,18 @@ impl VsockBridge { }; // Wrap in `Sendable` before the `.await` below so no raw ObjC // `Retained` (non-Send) crosses the await boundary. - let listener = Sendable(listener); - let delegate = Sendable(delegate); + // SAFETY: access stays on the VM queue; ARC retain/release is thread-safe. + let listener = unsafe { Sendable::new(listener) }; + // SAFETY: the delegate contains a thread-safe channel; VZ invokes it on its queue. + let delegate = unsafe { Sendable::new(delegate) }; // setSocketListener:forPort: must run on the VM's queue. run_on_queue(&queue, { let device = device.clone(); let listener = listener.clone(); move || unsafe { - device.setSocketListener_forPort(&listener, port); + device + .as_ref_on_queue() + .setSocketListener_forPort(listener.as_ref_on_queue(), port); } }) .await; @@ -413,11 +418,11 @@ impl VsockBridge { for &port in &std::mem::take(&mut self.registered_listener_ports) { let device = self.device.clone(); run_on_queue(&self.queue, move || unsafe { - device.removeSocketListenerForPort(port); + device.as_ref_on_queue().removeSocketListenerForPort(port); }) .await; } - let _ = tokio::fs::remove_file(port_uds_path(&self.base_path, VSOCK_PORT_AGENTD)).await; + let _ = tokio::fs::remove_file(port_uds_path(&self.base_path, ENGRAM_AGENTD_PORT)).await; } } @@ -444,7 +449,7 @@ pub(crate) fn port_uds_path(base: &Path, port: u32) -> PathBuf { async fn lookup_socket_device( queue: &DispatchQueue, vm: &Sendable>, -) -> Option> { +) -> Option>> { let (tx, rx) = oneshot::channel::>>>(); let vm = vm.clone(); let tx = Mutex::new(Some(tx)); @@ -453,20 +458,21 @@ async fn lookup_socket_device( // socketDevices array is sound. The retained NSArray + elements // live for the closure. let result = unsafe { - let array = vm.socketDevices(); + let array = vm.as_ref_on_queue().socketDevices(); if array.count() == 0 { None } else { let any: Retained = array.objectAtIndex(0); - any.downcast::().ok().map(Sendable) + any.downcast::() + .ok() + .map(|device| Sendable::new(device)) } }; if let Some(tx) = tx.lock().expect("oneshot mutex poisoned").take() { let _ = tx.send(result); } }); - let device = rx.await.ok()??; - Some(device.0) + rx.await.ok()? } // ---- Host-initiated agentd pump -------------------------------------- @@ -598,33 +604,13 @@ fn ready_drain_delivery() -> ConnDelivery { }) } -/// Consume each connection the delegate accepts on a guest-initiated -/// port: `dup` its fd and hand it to the port's [`ConnDelivery`]. +/// Deliver file descriptors copied on the VM queue by the listener callback. async fn guest_listener_consumer( - mut conn_rx: mpsc::UnboundedReceiver>>, + mut conn_rx: mpsc::UnboundedReceiver, delivery: ConnDelivery, ) { - while let Some(conn) = conn_rx.recv().await { - // SAFETY: `conn` is a valid retained connection; `fileDescriptor` - // is its socket fd, valid while retained. - let raw = unsafe { conn.fileDescriptor() }; - if raw < 0 { - tracing::warn!("vz guest conn returned -1 fd; dropping"); - continue; - } - // SAFETY: dup'ing a valid fd is sound; we own the dup and the - // connection closes its own copy when `conn` drops below. - let dup = unsafe { libc::dup(raw) }; - if dup < 0 { - tracing::warn!(error = %std::io::Error::last_os_error(), "dup guest conn fd failed"); - continue; - } - // SAFETY: `dup` returned a fresh valid fd we now own. - let owned_fd = unsafe { OwnedFd::from_raw_fd(dup) }; - delivery(owned_fd); - // `conn` drops here — VZ's ObjC-level fd closes, but our dup keeps - // the kernel-side connection open for the delivered stream. - drop(conn); + while let Some(fd) = conn_rx.recv().await { + delivery(fd); } } @@ -784,8 +770,7 @@ mod listener_delegate { /// State held inside the delegate instance — the channel accepted /// connections are pushed through. pub(crate) struct DelegateIvars { - pub(crate) tx: - Mutex>>>>, + pub(crate) tx: Mutex>>, } use objc2::runtime::NSObjectProtocol; @@ -811,9 +796,18 @@ mod listener_delegate { let ivars = self.ivars(); let tx = ivars.tx.lock().expect("delegate tx mutex poisoned"); if let Some(tx) = tx.as_ref() { - let conn = Sendable(super::retain_connection(connection)); - // YES = accept: the consumer takes ownership of the fd. - tx.send(conn).is_ok() + // SAFETY: VZ invokes this callback on the VM queue and keeps + // the connection alive through the callback. + let raw = unsafe { connection.fileDescriptor() }; + // SAFETY: the connection owns this descriptor until the callback returns. + let fd = unsafe { libc::dup(raw) }; + if fd < 0 { + tracing::warn!(error = %std::io::Error::last_os_error(), "dup guest conn fd failed"); + false + } else { + // SAFETY: dup returned a fresh descriptor owned by the consumer. + tx.send(unsafe { OwnedFd::from_raw_fd(fd) }).is_ok() + } } else { false } @@ -822,9 +816,7 @@ mod listener_delegate { ); impl VsockListenerDelegate { - pub(crate) fn new( - tx: mpsc::UnboundedSender>>, - ) -> Retained { + pub(crate) fn new(tx: mpsc::UnboundedSender) -> Retained { let this = Self::alloc().set_ivars(DelegateIvars { tx: Mutex::new(Some(tx)), }); @@ -834,15 +826,6 @@ mod listener_delegate { } } -/// Re-retain a borrowed `VZVirtioSocketConnection` (objc2 doesn't expose -/// a public `retain()` on the generated binding). -fn retain_connection(conn: &VZVirtioSocketConnection) -> Retained { - // SAFETY: `conn` is a valid pointer; `retain` returns a +1 reference - // per ObjC ARC convention. - unsafe { Retained::retain(conn as *const _ as *mut _) } - .expect("VZVirtioSocketConnection retain returned nil") -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/engram-upgrade-drain/src/lib.rs b/crates/engram-upgrade-drain/src/lib.rs index f0c22bb4a..ccc266413 100644 --- a/crates/engram-upgrade-drain/src/lib.rs +++ b/crates/engram-upgrade-drain/src/lib.rs @@ -10,6 +10,7 @@ mod client; +use engram_core::SessionState; use std::collections::{BTreeMap, BTreeSet}; use std::fmt; use std::time::Duration; @@ -110,10 +111,25 @@ pub fn plan(target: u32, hosts: &[UpgradeHost], sessions: &[UpgradeSession]) -> continue; } match s.state.as_str() { - "active" => actions.push(DrainAction::Evict(s.id.clone())), - "parked" => actions.push(DrainAction::Resume(s.id.clone())), - "pending" | "created" | "evacuating" | "evicting" => waiting.push(s.id.clone()), - "unreachable" => unreachable.push(s.id.clone()), + state if state == SessionState::Active.as_str() => { + actions.push(DrainAction::Evict(s.id.clone())) + } + state if state == SessionState::Parked.as_str() => { + actions.push(DrainAction::Resume(s.id.clone())) + } + state + if [ + SessionState::Pending, + SessionState::Created, + SessionState::Evacuating, + SessionState::Evicting, + ] + .iter() + .any(|s| s.as_str() == state) => + { + waiting.push(s.id.clone()) + } + state if state == SessionState::Unreachable.as_str() => unreachable.push(s.id.clone()), _ => {} } } From 07b83773a34358a790feb1b8058072e261361567 Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Wed, 2 Dec 2026 11:12:38 -0800 Subject: [PATCH 2/6] fix(sandbox-firecracker): name HashMap in the Linux-only PSS sample map The shared guest client move dropped the module-level HashMap import. The only remaining non-test user is the cfg(target_os = "linux") pss_samples field, so macOS clippy did not see the error and every Linux lane failed to compile. Co-Authored-By: Claude Opus 5.5 --- crates/engram-sandbox-firecracker/src/lib.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engram-sandbox-firecracker/src/lib.rs b/crates/engram-sandbox-firecracker/src/lib.rs index 0939fb87f..e41be220f 100644 --- a/crates/engram-sandbox-firecracker/src/lib.rs +++ b/crates/engram-sandbox-firecracker/src/lib.rs @@ -865,7 +865,9 @@ pub struct FirecrackerBackend { /// `(sandbox, fc_pid)`. Only `guest_memory_stats` reads or writes it, /// and it drops the entries of sandboxes that are gone. #[cfg(target_os = "linux")] - pss_samples: parking_lot::Mutex>, + pss_samples: parking_lot::Mutex< + std::collections::HashMap<(SandboxId, u32), (tokio::time::Instant, u64)>, + >, } /// Restore-time inputs that the capture-time sidecar cannot carry. From 7568131ac32660c26cfc9189f0a0c4c6ceab5cda Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Wed, 2 Dec 2026 11:12:38 -0800 Subject: [PATCH 3/6] refactor(sandbox-vz): import Sendable from queue_bound and drop the clock special case - vm.rs no longer re-exports Sendable; vsock_bridge imports it from queue_bound, its owner. The agentd port import moves into the import block, so the vsock port doc comment attaches to its constant again. - agentd_request sends every request through guest_client::request. The StepClock arm rebuilt the same frame through step_guest_clock. - The Sync SAFETY text states that Clone only retains, and the socket device lookup states why its wrapper is sound. Co-Authored-By: Claude Opus 5.5 --- crates/engram-sandbox-vz/src/backend.rs | 9 +-------- crates/engram-sandbox-vz/src/queue_bound.rs | 3 ++- crates/engram-sandbox-vz/src/vm.rs | 4 ++-- crates/engram-sandbox-vz/src/vsock_bridge.rs | 8 +++++--- 4 files changed, 10 insertions(+), 14 deletions(-) diff --git a/crates/engram-sandbox-vz/src/backend.rs b/crates/engram-sandbox-vz/src/backend.rs index 0536ca2c6..f21d81cf6 100644 --- a/crates/engram-sandbox-vz/src/backend.rs +++ b/crates/engram-sandbox-vz/src/backend.rs @@ -283,14 +283,7 @@ impl VzBackend { let agent_uds = port_uds_path(vsock_uds_path, ENGRAM_AGENTD_PORT); let fut = async { let mut conn = UnixStream::connect(&agent_uds).await.ok()?; - match req { - WireRequest::StepClock { unix_nanos } => { - guest_client::step_guest_clock(&mut conn, unix_nanos) - .await - .ok() - } - _ => guest_client::request(&mut conn, &req).await.ok(), - } + guest_client::request(&mut conn, &req).await.ok() }; tokio::time::timeout(within, fut).await.ok().flatten() } diff --git a/crates/engram-sandbox-vz/src/queue_bound.rs b/crates/engram-sandbox-vz/src/queue_bound.rs index b54cceba8..8d24c7bca 100644 --- a/crates/engram-sandbox-vz/src/queue_bound.rs +++ b/crates/engram-sandbox-vz/src/queue_bound.rs @@ -8,7 +8,8 @@ pub(crate) struct Sendable(T); // SAFETY: construction requires safe transfer and destruction on any thread. // Access to the value requires the caller to prove queue ownership. unsafe impl Send for Sendable {} -// SAFETY: no safe method exposes the value; shared access also requires its queue. +// SAFETY: no safe method exposes the value. `Clone` only retains, which is +// thread-safe; all other shared access also requires the owning queue. unsafe impl Sync for Sendable {} impl Sendable { diff --git a/crates/engram-sandbox-vz/src/vm.rs b/crates/engram-sandbox-vz/src/vm.rs index a13c6f44a..9a9c0262f 100644 --- a/crates/engram-sandbox-vz/src/vm.rs +++ b/crates/engram-sandbox-vz/src/vm.rs @@ -32,6 +32,8 @@ use objc2_virtualization::{ use engram_core::types::sandbox::AuxRoDrive; use tokio::sync::oneshot; +use crate::queue_bound::Sendable; + /// Per-VM declarative inputs. Built once at create time. #[derive(Clone, Debug)] pub(crate) struct VmConfig { @@ -233,8 +235,6 @@ impl From for engram_core::SandboxError { } } -pub(crate) use crate::queue_bound::Sendable; - // ---- VZVirtualMachineDelegate (crash detection, ADR 0096) ------------ use vm_delegate::VmStopDelegate; diff --git a/crates/engram-sandbox-vz/src/vsock_bridge.rs b/crates/engram-sandbox-vz/src/vsock_bridge.rs index 1aa8c2f97..2882d793a 100644 --- a/crates/engram-sandbox-vz/src/vsock_bridge.rs +++ b/crates/engram-sandbox-vz/src/vsock_bridge.rs @@ -79,12 +79,13 @@ use tokio::net::{UnixListener, UnixStream}; use tokio::sync::{mpsc, oneshot}; use tokio::task::JoinHandle; -use crate::vm::Sendable; +use engram_host_core::ENGRAM_AGENTD_PORT; + +use crate::queue_bound::Sendable; /// Vsock ports — same well-known values as `engram-sandbox-firecracker` /// since the in-guest agentd / harness / share binaries listen on the /// same numbers regardless of which VMM is hosting the VM. -use engram_host_core::ENGRAM_AGENTD_PORT; const VSOCK_PORT_HARNESS: u32 = 1026; /// Readiness handshake port (guest→host). agentd on the vsock transport /// dials this once at startup (`engram_agentd::ENGRAM_AGENTD_READY_PORT`). @@ -456,7 +457,8 @@ async fn lookup_socket_device( queue.exec_async(move || { // SAFETY: dispatched onto the VM's queue, so reaching into the // socketDevices array is sound. The retained NSArray + elements - // live for the closure. + // live for the closure. The device wrapper is only read again on + // this queue, and its retain/release is thread-safe. let result = unsafe { let array = vm.as_ref_on_queue().socketDevices(); if array.count() == 0 { From 2ceea542080028e49344a5d7883266f251176407 Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Wed, 2 Dec 2026 11:12:39 -0800 Subject: [PATCH 4/6] refactor(upgrade-drain): match the typed session state, not guarded strings Resolve the coordinator's state name to a SessionState once, then match on variants. The names come from SessionState::as_str, so the mapping is unchanged: active evicts, parked resumes, pending/created/evacuating/ evicting wait, unreachable is reported, and other states are ignored. Co-Authored-By: Claude Opus 5.5 --- crates/engram-upgrade-drain/src/lib.rs | 37 ++++++++++++-------------- 1 file changed, 17 insertions(+), 20 deletions(-) diff --git a/crates/engram-upgrade-drain/src/lib.rs b/crates/engram-upgrade-drain/src/lib.rs index ccc266413..2a4174a77 100644 --- a/crates/engram-upgrade-drain/src/lib.rs +++ b/crates/engram-upgrade-drain/src/lib.rs @@ -110,26 +110,23 @@ pub fn plan(target: u32, hosts: &[UpgradeHost], sessions: &[UpgradeSession]) -> if !s.host_id.is_some_and(|h| old.contains(&h)) { continue; } - match s.state.as_str() { - state if state == SessionState::Active.as_str() => { - actions.push(DrainAction::Evict(s.id.clone())) - } - state if state == SessionState::Parked.as_str() => { - actions.push(DrainAction::Resume(s.id.clone())) - } - state - if [ - SessionState::Pending, - SessionState::Created, - SessionState::Evacuating, - SessionState::Evicting, - ] - .iter() - .any(|s| s.as_str() == state) => - { - waiting.push(s.id.clone()) - } - state if state == SessionState::Unreachable.as_str() => unreachable.push(s.id.clone()), + use SessionState::*; + let state = [ + Active, + Parked, + Pending, + Created, + Evacuating, + Evicting, + Unreachable, + ] + .into_iter() + .find(|state| state.as_str() == s.state); + match state { + Some(Active) => actions.push(DrainAction::Evict(s.id.clone())), + Some(Parked) => actions.push(DrainAction::Resume(s.id.clone())), + Some(Pending | Created | Evacuating | Evicting) => waiting.push(s.id.clone()), + Some(Unreachable) => unreachable.push(s.id.clone()), _ => {} } } From d75541603512accd80a78b9f94b8132764aafbbf Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Wed, 2 Dec 2026 11:12:39 -0800 Subject: [PATCH 5/6] chore(host-core): sort dependencies and point agentd port docs at host-core Also restore the pidfd module's statement of the two kernel properties callers rely on: identity survives pid reuse, and the fd is readable at process exit. Co-Authored-By: Claude Opus 5.5 --- crates/engram-host-core/Cargo.toml | 10 +++++----- crates/engram-host-core/src/pidfd.rs | 2 ++ crates/engram-rootfs-materializer/src/inject.rs | 6 ++---- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/crates/engram-host-core/Cargo.toml b/crates/engram-host-core/Cargo.toml index 8f9fa65d9..dfeef3de0 100644 --- a/crates/engram-host-core/Cargo.toml +++ b/crates/engram-host-core/Cargo.toml @@ -22,18 +22,18 @@ unused_dependencies = "allow" disallowed_methods = "deny" [dependencies] -bytes.workspace = true -engram-agentd.workspace = true -engram-harness-proto.workspace = true -tokio-stream.workspace = true async-trait.workspace = true +bytes.workspace = true chrono.workspace = true +engram-agentd.workspace = true engram-chunk-store.workspace = true -engram-fill.workspace = true engram-core.workspace = true +engram-fill.workspace = true +engram-harness-proto.workspace = true libc = "0.2" serde.workspace = true tokio.workspace = true +tokio-stream.workspace = true tracing.workspace = true uuid.workspace = true workspace-hack = { version = "0.1", path = "../../workspace-hack" } diff --git a/crates/engram-host-core/src/pidfd.rs b/crates/engram-host-core/src/pidfd.rs index b0a27e43d..03df3b0ea 100644 --- a/crates/engram-host-core/src/pidfd.rs +++ b/crates/engram-host-core/src/pidfd.rs @@ -1,4 +1,6 @@ //! Process handles whose identity is stable after the descriptor is opened. +//! A pidfd stays bound to its process when the kernel reuses the pid, and +//! it becomes poll-readable when the process exits. use std::io; #[cfg(target_os = "linux")] diff --git a/crates/engram-rootfs-materializer/src/inject.rs b/crates/engram-rootfs-materializer/src/inject.rs index ffe3e3ad1..2604adfe6 100644 --- a/crates/engram-rootfs-materializer/src/inject.rs +++ b/crates/engram-rootfs-materializer/src/inject.rs @@ -17,10 +17,8 @@ use std::path::{Path, PathBuf}; /// and the shim is the only engrams file in the rootfs. #[derive(Clone, Debug)] pub struct InitInjection { - /// Vsock port the agent should listen on inside the guest. Pair - /// this with the host-side `ENGRAM_AGENTD_PORT` constant - /// (`engram_sandbox_firecracker::ENGRAM_AGENTD_PORT`, currently - /// 1024). + /// Vsock port the agent listens on inside the guest. Hosts pass + /// `engram_host_core::ENGRAM_AGENTD_PORT`. pub vsock_port: u32, /// Which host↔guest transport the in-VM binaries (agentd, /// bootstrap, harness) should use. The default init shim sets From 25dfe4af7119b7658e7e1a23b7167fddd3b33565 Mon Sep 17 00:00:00 2001 From: Nikhil Unni Date: Wed, 2 Dec 2026 11:16:04 -0800 Subject: [PATCH 6/6] chore(host-core): keep the original dependency order Sorting the list conflicts with a parallel change that adds a dependency in the same block. The order has no effect on the build. Co-Authored-By: Claude Opus 5.5 --- crates/engram-host-core/Cargo.toml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/engram-host-core/Cargo.toml b/crates/engram-host-core/Cargo.toml index dfeef3de0..8f9fa65d9 100644 --- a/crates/engram-host-core/Cargo.toml +++ b/crates/engram-host-core/Cargo.toml @@ -22,18 +22,18 @@ unused_dependencies = "allow" disallowed_methods = "deny" [dependencies] -async-trait.workspace = true bytes.workspace = true -chrono.workspace = true engram-agentd.workspace = true +engram-harness-proto.workspace = true +tokio-stream.workspace = true +async-trait.workspace = true +chrono.workspace = true engram-chunk-store.workspace = true -engram-core.workspace = true engram-fill.workspace = true -engram-harness-proto.workspace = true +engram-core.workspace = true libc = "0.2" serde.workspace = true tokio.workspace = true -tokio-stream.workspace = true tracing.workspace = true uuid.workspace = true workspace-hack = { version = "0.1", path = "../../workspace-hack" }