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
30 changes: 28 additions & 2 deletions api/crates/cma/src/agent_manager/relay/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,18 @@ async fn route_request(
};
let reports_handoff = file_read && verified.reports_file_handoff();
let reports_file_write = file_write && verified.reports_file_write_handoff();
let reopen_trace = private
&& request
.uri()
.path()
.starts_with("/internal/agent-manager/v1/control/")
&& request.uri().path().ends_with("/reopen")
&& request.method() == axum::http::Method::POST;
let reopen_trace = reopen_trace
.then(|| layer1_public::rest::request_id_from_headers(request.headers()))
.flatten()
.and_then(|id| uuid::Uuid::parse_str(id).ok())
.map(|id| layer3_adapter::reopen_diagnostics::Trace::new(id, "owner"));
if reports_file_write && relay.coordinator.is_draining() {
return file_write::refusal(
&relay,
Expand All @@ -180,7 +192,10 @@ async fn route_request(
if reports_handoff && relay.coordinator.is_draining() {
return file_read::refusal(diagnostic.as_ref(), Refusal::CoordinatorNotReady);
}
let destination = match if private
let owner_phase = reopen_trace
.as_ref()
.map(|trace| trace.phase("owner_destination"));
let destination = if private
&& request
.uri()
.path()
Expand All @@ -192,7 +207,15 @@ async fn route_request(
.map_err(|_| Refusal::AuthorityChanged)
} else {
relay.destination(&id).await
} {
};
if let Some(phase) = owner_phase {
phase.finish(if destination.is_ok() {
"ok"
} else {
"unavailable"
});
}
let destination = match destination {
Ok(value) => value,
Err(
reason @ (Refusal::OwnerMissing
Expand Down Expand Up @@ -239,6 +262,9 @@ async fn route_request(
}
request.headers_mut().remove(PROOF);
request.extensions_mut().insert(VerifiedPeer);
if let Some(trace) = reopen_trace {
request.extensions_mut().insert(trace);
}
if is_cancellation {
request
.extensions_mut()
Expand Down
51 changes: 41 additions & 10 deletions api/crates/cma/src/agent_manager/relay/reopen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use layer2_core::{
sandbox::{AgentWorkReceipt, Sandbox, SandboxWorkLease},
SandboxId,
};
use layer3_adapter::reopen_diagnostics::{self, Trace};
use tokio::time::Instant;

const REOPEN_LIMIT: Duration = Duration::from_secs(layer3_adapter::DEFAULT_TOTAL_TIMEOUT_SECONDS);
Expand Down Expand Up @@ -45,32 +46,52 @@ impl Relay {
id: &AgentId,
verify_refusal: bool,
) -> layer3_adapter::Result<AgentWorkReceipt> {
self.reopen_call(sandbox, id, verify_refusal)
let trace = reopen_diagnostics::current()
.unwrap_or_else(|| Trace::new(uuid::Uuid::new_v4(), "publisher"));
let phase = trace.phase("owner_relay");
let result = self
.reopen_call(sandbox, id, verify_refusal, &trace)
.await
.map_err(|error| error.into_adapter("Agent owner lifecycle reopen unavailable"))
.map_err(|error| error.into_adapter("Agent owner lifecycle reopen unavailable"));
phase.finish(reopen_diagnostics::outcome(&result));
result
}

async fn reopen_call(
&self,
sandbox: &Sandbox,
id: &AgentId,
verify_refusal: bool,
trace: &Trace,
) -> Result<AgentWorkReceipt, CallFailure> {
let deadline = Instant::now() + REOPEN_LIMIT;
let _permit = self
.acquire(capacity::Class::Control)
.map_err(|_| CallFailure::RelayCapacity)?;
let destination = self.control_destination(id).await?;
let phase = trace.phase("owner_destination");
let destination = self.control_destination(id).await;
phase.finish(if destination.is_ok() {
"ok"
} else {
"unavailable"
});
let destination = destination?;
let call = ReopenCall {
sandbox_id: sandbox.id.clone(),
revision: sandbox.revision,
lease: sandbox.work.lease.clone().ok_or(())?,
};
let reply = if destination.member.instance_id == self.coordinator.instance_id {
let local = destination.member.instance_id == self.coordinator.instance_id;
tracing::info!(attempt_id = %trace.attempt(), agent_id = %id,
local, owner_epoch = destination.token.epoch, "Retained runtime reopen routed");
let reply = if local {
let worker = self.reopen.get().ok_or(())?;
let owner_trace = Trace::new(trace.attempt(), "owner");
tokio::time::timeout_at(
deadline,
destination.authority.run(worker.reopen_at_owner(id, &call)),
destination
.authority
.run(owner_trace.run(worker.reopen_at_owner(id, &call))),
)
.await
.map_err(|_| ())?
Expand All @@ -86,6 +107,10 @@ impl Relay {
.parse()
.map_err(|_| ())?;
let mut headers = axum::http::HeaderMap::new();
headers.insert(
"x-request-id",
trace.attempt().to_string().parse().map_err(|_| ())?,
);
headers.insert(
axum::http::header::CONTENT_TYPE,
axum::http::HeaderValue::from_static("application/json"),
Expand Down Expand Up @@ -176,6 +201,7 @@ async fn verify_refused_owner<T>(
pub(super) async fn serve(
State(relay): State<Arc<Relay>>,
Extension(_peer): Extension<http::VerifiedPeer>,
trace: Option<Extension<Trace>>,
Json(call): Json<ReopenCall>,
) -> Response {
let Some(authority) = layer2_core::agent_ownership::execution_authority() else {
Expand All @@ -184,11 +210,16 @@ pub(super) async fn serve(
let Some(worker) = relay.reopen.get() else {
return http::unavailable();
};
match tokio::time::timeout(
REOPEN_LIMIT,
worker.reopen_at_owner(&authority.token.agent_id, &call),
)
.await
let trace = trace.map_or_else(
|| Trace::new(uuid::Uuid::new_v4(), "owner"),
|Extension(trace)| trace,
);
match trace
.run(tokio::time::timeout(
REOPEN_LIMIT,
worker.reopen_at_owner(&authority.token.agent_id, &call),
))
.await
{
Ok(Ok(receipt)) => Json(Reply {
owner: authority.token.clone(),
Expand Down
17 changes: 17 additions & 0 deletions api/crates/cma/src/sandbox/runtime_attachment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,23 @@ pub(crate) async fn adopt_bound_runtime(
.0)
}

pub(crate) async fn adopt_bound_runtime_for_owner_reopen(
adapter: &dyn SandboxAdapter,
sandbox: &Sandbox,
deployment_id: &str,
) -> layer3_adapter::Result<RuntimeHandle> {
let admission = if sandbox.retained_home_recovery().is_some() {
layer3_adapter::InspectionAdmission::owner_reopen()
} else {
layer3_adapter::InspectionAdmission::ready()
};
Ok(
inspect_bound_runtime_after(adapter, sandbox, deployment_id, &admission)
.await?
.0,
)
}

/// Fresh identity proof and optional capabilities from that same runtime process.
pub(crate) async fn inspect_bound_runtime(
adapter: &dyn SandboxAdapter,
Expand Down
66 changes: 23 additions & 43 deletions api/crates/cma/src/sandbox/worker/lifecycle/conversations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,22 @@ use layer2_core::sandbox::{
Agent, AgentLogKind, AgentStatus, AgentWorkReceipt, AgentWorkStep, FirstMessageDelivery,
Sandbox, SandboxEventKind, SandboxWorkStep, Worktree, WorktreeStatus,
};
use layer3_adapter::AgentOpenRequest;
use layer3_adapter::{reopen_diagnostics::Trace, AgentOpenRequest};
use tokio::sync::mpsc;
use tokio::time::Instant;

use super::super::support::{runtime, WorkerFailure};
use super::super::SandboxWorker;
use super::checkpoint::{pinned_checkpoint, require_quiet_agent};
use super::checkpoint::pinned_checkpoint;
use super::reopen_refusal::within_deadline;
use super::support::{lifecycle_lease, model_error};
use crate::sandbox::live_agents::{LiveAgentAttachment, LiveAgentRegistryError};
use crate::sandbox::runtime_mapping::{runtime_capabilities, runtime_options};

#[path = "conversations_validation.rs"]
mod validation;
use validation::validate_reopen_set;

const UPDATE_BUFFER: usize = 256;
const REOPEN_LIMIT: Duration = Duration::from_secs(layer3_adapter::DEFAULT_TOTAL_TIMEOUT_SECONDS);

Expand Down Expand Up @@ -79,6 +83,7 @@ impl SandboxWorker {

let mut attachments = Vec::new();
let mut receipts = BTreeMap::new();
let mut reopen_traces = Vec::new();
// Earlier restore phases have their own budgets, and an empty set has
// no conversation work to time out.
let deadline = if live.is_empty() {
Expand All @@ -97,9 +102,12 @@ impl SandboxWorker {
let prove_refusal = refusal.is_some();
if let Some(relay) = self.reopen_relay.get() {
let relay = relay.upgrade().ok_or(SandboxStoreError::Conflict)?;
let trace = Trace::new(uuid::Uuid::new_v4(), "publisher");
match within_deadline(
deadline,
relay.reopen_agent(&sandbox, &agent.id, prove_refusal),
trace
.clone()
.run(relay.reopen_agent(&sandbox, &agent.id, prove_refusal)),
refusal,
true,
)
Expand All @@ -110,6 +118,7 @@ impl SandboxWorker {
// timestamp, which can differ from the remote clock.
receipt.completed_at = rfc3339_at(now);
receipts.insert(agent.id.clone(), receipt);
reopen_traces.push(trace);
}
Err(failure) => {
tracing::warn!(sandbox_id = %sandbox.id, agent_id = %agent.id,
Expand Down Expand Up @@ -339,6 +348,10 @@ impl SandboxWorker {
events.push(SandboxEventKind::WorkStepCompleted {
step: SandboxWorkStep::RunLifecycleOperation,
});
let commit_timings: Vec<_> = reopen_traces
.iter()
.map(|trace| trace.phase("parent_ready_commit"))
.collect();
let committed = self
.commit_lifecycle_phase(
&sandbox,
Expand All @@ -349,6 +362,13 @@ impl SandboxWorker {
events,
)
.await;
for phase in commit_timings {
phase.finish(if committed.is_ok() {
"ok"
} else {
"commit_error"
});
}
let durable = match committed {
Ok(()) => true,
Err(error) => match self.lifecycle_state_matches(&next).await {
Expand Down Expand Up @@ -442,46 +462,6 @@ impl SandboxWorker {
}
}

fn validate_reopen_set<'a>(
sandbox: &Sandbox,
agents: &'a [Agent],
checkpoint: Option<&layer2_core::sandbox::SandboxCheckpointRef>,
) -> Result<Vec<&'a Agent>, WorkerFailure> {
let by_id = checkpoint
.into_iter()
.flat_map(|checkpoint| &checkpoint.conversations)
.map(|conversation| {
(
&conversation.agent_id,
conversation.conversation_id.as_str(),
)
})
.collect::<BTreeMap<_, _>>();
let live = agents
.iter()
.filter(|agent| sandbox.restores_agent(agent))
.collect::<Vec<_>>();
let matches = live.iter().all(|agent| {
agent.status == AgentStatus::Paused
&& require_quiet_agent(agent).is_ok()
&& agent
.conversation
.conversation_id
.as_deref()
.is_some_and(|current| {
sandbox.retained_home_recovery().is_some()
|| by_id.get(&agent.id).copied() == Some(current)
})
});
if matches {
Ok(live)
} else {
Err(WorkerFailure::terminal_security(
"restored live agents do not match the pinned checkpoint conversations",
))
}
}

fn rollback_attachments(worker: &SandboxWorker, attachments: &[LiveAgentAttachment]) {
for attachment in attachments {
worker.dependencies.registry.rollback(attachment);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use std::collections::BTreeMap;

use layer2_core::sandbox::{Agent, AgentStatus, Sandbox};

use super::{super::checkpoint::require_quiet_agent, WorkerFailure};

pub(super) fn validate_reopen_set<'a>(
sandbox: &Sandbox,
agents: &'a [Agent],
checkpoint: Option<&layer2_core::sandbox::SandboxCheckpointRef>,
) -> Result<Vec<&'a Agent>, WorkerFailure> {
let by_id = checkpoint
.into_iter()
.flat_map(|checkpoint| &checkpoint.conversations)
.map(|conversation| {
(
&conversation.agent_id,
conversation.conversation_id.as_str(),
)
})
.collect::<BTreeMap<_, _>>();
let live = agents
.iter()
.filter(|agent| sandbox.restores_agent(agent))
.collect::<Vec<_>>();
let matches = live.iter().all(|agent| {
agent.status == AgentStatus::Paused
&& require_quiet_agent(agent).is_ok()
&& agent
.conversation
.conversation_id
.as_deref()
.is_some_and(|current| {
sandbox.retained_home_recovery().is_some()
|| by_id.get(&agent.id).copied() == Some(current)
})
});
if matches {
Ok(live)
} else {
Err(WorkerFailure::terminal_security(
"restored live agents do not match the pinned checkpoint conversations",
))
}
}
Loading
Loading