Skip to content
Closed
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
1 change: 1 addition & 0 deletions Cargo.lock

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

43 changes: 23 additions & 20 deletions crates/engram-coordinator/src/api/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,29 +63,28 @@ pub(crate) async fn evict_idle_core(
Ok(EvictIdleResponse { session_id, status })
}

// ---------------------------------------------------------------------
// ADR 0045 Phase F — pause / resume a microVM in place (the freeze/flush
// test surface). Thin admin passthroughs to the FC pause/resume
// primitive: freeze or unfreeze the running guest WITHOUT snapshotting,
// destroying, or changing session state. The session stays `Active`; a
// paused guest simply stops executing until resumed. Distinct from
// teleport/evac (which relocate) and from idle-eviction (which
// snapshots + suspends to `Idle`).
// ---------------------------------------------------------------------
// Pause and resume freeze or unfreeze the guest in place. Session state does not change.
// The HTTP adapters serve orchestrators that do not call the app-gRPC methods.
// Remove them only after no deployed or rollback-target orchestrator calls them.

#[derive(Serialize)]
pub struct PauseResumeResponse {
pub session_id: SessionId,
pub note: &'static str,
}

/// `POST /api/admin/sessions/:id/pause` — freeze the session's running
/// microVM in place. 409 if the session has no live sandbox (idle / not
/// yet started).
/// HTTP compatibility adapter for in-place pause.
pub async fn pause_session(
State(state): State<SharedState>,
Path(session_id): Path<SessionId>,
) -> Result<Json<PauseResumeResponse>, ApiError> {
pause_session_core(&state, session_id).await.map(Json)
}

pub(crate) async fn pause_session_core(
state: &SharedState,
session_id: SessionId,
) -> Result<PauseResumeResponse, ApiError> {
let sandbox_id = state.resolve_sandbox(session_id).await.ok_or_else(|| {
ApiError::Conflict(
"session has no live sandbox to pause — it is idle or not yet started".into(),
Expand All @@ -99,20 +98,24 @@ pub async fn pause_session(
.await
.map_err(|e| ApiError::Internal(format!("pause sandbox: {e}")))?;
tracing::info!(%session_id, %sandbox_id, "admin: froze microVM in place");
Ok(Json(PauseResumeResponse {
Ok(PauseResumeResponse {
session_id,
note: "paused",
}))
})
}

/// `POST /api/admin/sessions/:id/resume` — unfreeze a `pause`d microVM in
/// place. Note: this is the *in-place* unfreeze, NOT `/sessions/:id/resume`
/// (which rehydrates an `Idle` session from a snapshot). 409 if the
/// session has no live sandbox.
/// HTTP compatibility adapter for in-place resume.
pub async fn resume_session(
State(state): State<SharedState>,
Path(session_id): Path<SessionId>,
) -> Result<Json<PauseResumeResponse>, ApiError> {
resume_session_core(&state, session_id).await.map(Json)
}

pub(crate) async fn resume_session_core(
state: &SharedState,
session_id: SessionId,
) -> Result<PauseResumeResponse, ApiError> {
let sandbox_id = state.resolve_sandbox(session_id).await.ok_or_else(|| {
ApiError::Conflict(
"session has no live sandbox to resume in place — it is idle or not yet started".into(),
Expand All @@ -126,10 +129,10 @@ pub async fn resume_session(
.await
.map_err(|e| ApiError::Internal(format!("resume sandbox: {e}")))?;
tracing::info!(%session_id, %sandbox_id, "admin: unfroze microVM in place");
Ok(Json(PauseResumeResponse {
Ok(PauseResumeResponse {
session_id,
note: "resumed",
}))
})
}

// ---------------------------------------------------------------------
Expand Down
40 changes: 1 addition & 39 deletions crates/engram-coordinator/src/api/host_http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ use engram_core::types::BindingDisposition;
use engram_core::{HostId, SandboxId, SessionId, SessionState};
use engram_harness_proto::HarnessEvent;
use engram_protocol::heartbeat::{EnabledImageRef, HostCapacityReport, ManifestDigest};
use engram_protocol::HandoffMarker;
use serde::{Deserialize, Serialize};
use tracing::Instrument as _;

Expand Down Expand Up @@ -72,23 +73,6 @@ pub struct RegisterRequest {
pub handoff_marker: Option<HandoffMarker>,
}

/// ADR 0116 A-D2: the durable note a shutting-down host-agent leaves
/// beside its binding records for the successor generation. Mirrored in
/// `engram-host-core::shutdown` (the writer); duplicated shape rather
/// than a shared dep because the coordinator only OBSERVES it.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct HandoffMarker {
/// Predecessor's wall clock at declaration (unix ms). Same-node
/// clock, so adoption latency derived from it is honest to within
/// node clock error — fine for a histogram, never a decision input.
pub declared_at_unix_ms: i64,
/// The TTL the predecessor asked its belt POST for.
pub ttl_secs: u64,
/// Sandboxes resident at declaration (diagnostics only).
#[serde(default)]
pub resident_sandboxes: u32,
}

#[derive(Serialize)]
pub struct RegisterResponse {
pub server_time: DateTime<Utc>,
Expand Down Expand Up @@ -1954,28 +1938,6 @@ mod tests {
assert!(!ingest_span(session_id, &idle, None).is_none());
}

/// ADR 0116 A-D2 wire pin: the coordinator's `HandoffMarker` mirror
/// must decode exactly what `engram_host_core::shutdown::HandoffMarker`
/// serializes — the shapes are deliberately duplicated (the coord only
/// OBSERVES the marker), so this JSON literal is the interop contract.
/// A field rename on either side fails here, not in a mixed fleet.
#[test]
fn handoff_marker_wire_shape_is_pinned() {
let from_host = r#"{
"declared_at_unix_ms": 1765432100000,
"ttl_secs": 600,
"resident_sandboxes": 4
}"#;
let m: HandoffMarker = serde_json::from_str(from_host).expect("decode host marker");
assert_eq!(m.declared_at_unix_ms, 1_765_432_100_000);
assert_eq!(m.ttl_secs, 600);
assert_eq!(m.resident_sandboxes, 4);
// Legacy host (no resident count field) decodes with the default.
let minimal = r#"{"declared_at_unix_ms": 1, "ttl_secs": 2}"#;
let m: HandoffMarker = serde_json::from_str(minimal).expect("decode minimal");
assert_eq!(m.resident_sandboxes, 0);
}

use engram_core::types::session::SessionMode;
use engram_core::types::Session;
use engram_core::types::SessionState;
Expand Down
20 changes: 5 additions & 15 deletions crates/engram-coordinator/src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,27 +41,17 @@ pub(crate) mod storage;
pub(crate) mod upload;

pub fn router(state: SharedState) -> Router {
// ADR 0051: the web-facing (protected / session-scoped / member / admin /
// auth-flow) human routers are GONE. The orchestrator owns all web traffic
// and calls the coordinator exclusively over the app-gRPC surface
// (`grpc_app/*`), which delegates to the transport-agnostic `*_core` fns.
// Only the internal (host → coord) ingestion, the in-guest forge seam, the
// admin pause/resume control plane, and health probes remain on HTTP.
//
// Production note: ENGRAM_AUTH_TOKENS must include the orchestrator's
// bearer so its REST proxy calls to /admin/sessions/:id/pause and
// /admin/sessions/:id/resume (the only remaining REST control verbs,
// pending their gRPC promotion) are authenticated. The orchestrator sends
// CONTROL_PLANE_BEARER on those requests; ensure both tokens agree at
// deploy time.
// The orchestrator uses app-gRPC. HTTP serves host ingestion, in-guest
// forge requests, health probes, and the admin pause/resume routes for
// orchestrators that do not call the app-gRPC methods. While those routes
// exist, ENGRAM_AUTH_TOKENS must include the orchestrator's bearer.
let auth_state = auth::AuthState::new(state.cfg.auth_tokens.clone());

// ADR 0031 internal control-plane: host → coord ingestion. Machine
// traffic authenticated by the deployment bearer (`require_bearer`).
// pause/resume live here (not a human surface) behind the same bearer.
let internal = Router::new()
// ADR 0045 Phase F: freeze / unfreeze a microVM in place.
// In prod: ENGRAM_AUTH_TOKENS must include the orchestrator's bearer.
// In-place freeze / unfreeze for orchestrators that do not use app-gRPC.
.route("/admin/sessions/{id}/pause", post(admin::pause_session))
.route("/admin/sessions/{id}/resume", post(admin::resume_session))
.route("/hosts/register", post(host_http::register))
Expand Down
30 changes: 30 additions & 0 deletions crates/engram-coordinator/src/grpc_app/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -680,6 +680,36 @@ impl app::session_service_server::SessionService for AppSessionService {
}))
}

async fn pause_session(
&self,
req: Request<app::PauseSessionRequest>,
) -> Result<Response<app::PauseSessionResponse>, Status> {
self.auth.check(&req)?;
let id = parse_session_id(&req.get_ref().session_id)?;
let result = crate::api::admin::pause_session_core(&self.state, id)
.await
.map_err(into_status)?;
Ok(Response::new(app::PauseSessionResponse {
session_id: result.session_id.to_string(),
note: result.note.to_string(),
}))
}

async fn resume_session(
&self,
req: Request<app::ResumeSessionRequest>,
) -> Result<Response<app::ResumeSessionResponse>, Status> {
self.auth.check(&req)?;
let id = parse_session_id(&req.get_ref().session_id)?;
let result = crate::api::admin::resume_session_core(&self.state, id)
.await
.map_err(into_status)?;
Ok(Response::new(app::ResumeSessionResponse {
session_id: result.session_id.to_string(),
note: result.note.to_string(),
}))
}

async fn evict_local(
&self,
req: Request<app::EvictLocalRequest>,
Expand Down
153 changes: 153 additions & 0 deletions crates/engram-coordinator/tests/grpc_app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1340,3 +1340,156 @@ async fn session_stream_events_replays_past_one_page() {

server.abort();
}

#[tokio::test]
async fn admin_pause_resume_preserves_state_and_error_mapping() {
let (state, meta) = test_state(vec![TEST_TOKEN.into()]);
let service = grpc_app::AppSessionService {
state: state.clone(),
auth: Arc::new(grpc_app::auth::BearerAuth::new(vec![TEST_TOKEN.into()])),
};
let sid = meta
.create_session(SessionSpec {
image: "test-image".into(),
mode: Default::default(),
})
.await
.unwrap();

async fn invoke(
service: &grpc_app::AppSessionService,
pause: bool,
id: &str,
token: Option<&str>,
) -> Result<(String, String), tonic::Status> {
let mut metadata = tonic::metadata::MetadataMap::new();
if let Some(token) = token {
metadata.insert("authorization", format!("Bearer {token}").parse().unwrap());
}
if pause {
let mut req = tonic::Request::new(app::PauseSessionRequest {
session_id: id.into(),
});
*req.metadata_mut() = metadata;
let result = service.pause_session(req).await?.into_inner();
Ok((result.session_id, result.note))
} else {
let mut req = tonic::Request::new(app::ResumeSessionRequest {
session_id: id.into(),
});
*req.metadata_mut() = metadata;
let result = service.resume_session(req).await?.into_inner();
Ok((result.session_id, result.note))
}
}

for pause in [true, false] {
for token in [None, Some("wrong")] {
assert_eq!(
invoke(&service, pause, "invalid", token)
.await
.unwrap_err()
.code(),
tonic::Code::Unauthenticated
);
}
assert_eq!(
invoke(&service, pause, "bad/id?query", Some(TEST_TOKEN))
.await
.unwrap_err()
.code(),
tonic::Code::InvalidArgument
);
for id in [sid, SessionId::new()] {
let error = invoke(&service, pause, &id.to_string(), Some(TEST_TOKEN))
.await
.unwrap_err();
assert_eq!(error.code(), tonic::Code::FailedPrecondition);
assert_eq!(
error.metadata().get("engram-error-slug").unwrap(),
"conflict"
);
}
}

use engram_core::types::sandbox::{CpuLimit, DiskLimit, MemoryLimit, SandboxSpec};
let sandbox = state
.services
.host
.create(SandboxSpec {
image: "test-image".into(),
rootfs_source: None,
image_uri: None,
rootfs_manifest: None,
cpu: CpuLimit { vcpus: 1 },
memory: MemoryLimit { max_mib: 256 },
disk: DiskLimit { max_gib: 1 },
ttl: None,
env: HashMap::new(),
workdir: None,
network: Default::default(),
aux_ro_drives: Vec::new(),
swap_mib: None,
swap_source: None,
swap_manifest: None,
})
.await
.unwrap();
meta.rebind_session(sid, engram_core::HostId::new(), sandbox)
.await
.unwrap();
for target in [SessionState::Created, SessionState::Active] {
meta.transition_session(sid, target, BindingDisposition::Retain)
.await
.unwrap();
}
let before = meta.get_session(sid).await.unwrap();
for (pause, note) in [(true, "paused"), (false, "resumed")] {
let response = invoke(&service, pause, &sid.to_string(), Some(TEST_TOKEN))
.await
.unwrap();
assert_eq!(response, (sid.to_string(), note.into()));
use tower::ServiceExt as _;
let operation = if pause { "pause" } else { "resume" };
let http = engram_coordinator::api::router(state.clone())
.oneshot(
axum::http::Request::builder()
.method("POST")
.uri(format!("/api/v1/admin/sessions/{sid}/{operation}"))
.body(axum::body::Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(http.status(), axum::http::StatusCode::OK);
let body = axum::body::to_bytes(http.into_body(), 4096).await.unwrap();
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&body).unwrap(),
serde_json::json!({"session_id": sid.to_string(), "note": note})
);
let after = meta.get_session(sid).await.unwrap();
assert_eq!(after.status, before.status);
assert_eq!(after.sandbox_id, before.sandbox_id);
assert_eq!(after.last_active_at, before.last_active_at);
assert_eq!(after.park_rung, before.park_rung);
}

// A stale binding reaches the host and retains the HTTP core's Internal error.
meta.rebind_session(
sid,
engram_core::HostId::new(),
engram_core::SandboxId::new(),
)
.await
.unwrap();
for pause in [true, false] {
let error = invoke(&service, pause, &sid.to_string(), Some(TEST_TOKEN))
.await
.unwrap_err();
assert_eq!(error.code(), tonic::Code::Internal);
assert_eq!(
error.metadata().get("engram-error-slug").unwrap(),
"internal"
);
}
}
Loading
Loading