Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 10 additions & 9 deletions crates/engram-host-agent/src/blk_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -170,15 +171,15 @@ 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(()));
}
}
},
)
});
if let Err(e) = run {
match ready.lock().unwrap().take() {
match ready.lock().take() {
Some(ready) => {
let _ = ready.send(Err(e));
}
Expand Down Expand Up @@ -214,7 +215,7 @@ impl BlkSource {
/// Chunks the guest read before the copy reached them, in first-read
/// order.
pub fn touched(&self) -> Vec<u32> {
self.shared.touched.lock().unwrap().order.clone()
self.shared.touched.lock().order.clone()
}

/// Stop serving and delete the device. Refused while a device still
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -623,14 +624,14 @@ impl Completions {
}

fn push(&self, tag: u16, result: io::Result<Bytes>) {
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<Bytes>)> {
self.done.lock().unwrap().drain(..).collect()
self.done.lock().drain(..).collect()
}
}

Expand Down
132 changes: 55 additions & 77 deletions crates/engram-host-agent/src/capture_job.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -206,11 +207,7 @@ pub struct CaptureJobExecutor {
/// report (`ack`); non-terminal entries are refreshed continuously
/// by the running executor task.
reports: Arc<DashMap<CaptureJobId, CaptureJobReport>>,
/// `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<HashMap<CaptureJobId, RunningJob>>,
/// Self-reference (the `PooledBackend::set_self_ref` pattern
/// verbatim): `start` needs to hand a spawned task an OWNED
Expand Down Expand Up @@ -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))
}
Expand All @@ -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
Expand All @@ -370,7 +359,7 @@ impl CaptureJobExecutor {
let present: std::collections::HashSet<CaptureJobId> =
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))
Expand All @@ -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<Self>, job_id: CaptureJobId, epoch: i64, job_spec: CaptureJobSpec) {
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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<Vec<SandboxId>, SandboxError> {
Expand Down Expand Up @@ -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",
);
Expand Down Expand Up @@ -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",
);
Expand Down Expand Up @@ -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",
);
Expand Down Expand Up @@ -1157,7 +1136,6 @@ mod tests {
if let Some(id) = executor
.running
.lock()
.unwrap()
.get(&job_id)
.and_then(|r| r.sandbox_id)
{
Expand Down
2 changes: 1 addition & 1 deletion crates/engram-host-agent/src/harness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
5 changes: 1 addition & 4 deletions crates/engram-host-agent/src/materialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
},
Expand Down
2 changes: 1 addition & 1 deletion crates/engram-host-agent/src/postcopy_finish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading
Loading