Skip to content

Commit d6c3c43

Browse files
Instrument and streamline retained-home Runtime reopen (#4561)
Correlate owner reopen phase timings and combine the adjacent native-home verifications at RuntimeStatus under exact adopted-state checks. Refs #1509
1 parent 417fe91 commit d6c3c43

21 files changed

Lines changed: 825 additions & 195 deletions

‎api/crates/cma/src/agent_manager/relay/http.rs‎

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,18 @@ async fn route_request(
169169
};
170170
let reports_handoff = file_read && verified.reports_file_handoff();
171171
let reports_file_write = file_write && verified.reports_file_write_handoff();
172+
let reopen_trace = private
173+
&& request
174+
.uri()
175+
.path()
176+
.starts_with("/internal/agent-manager/v1/control/")
177+
&& request.uri().path().ends_with("/reopen")
178+
&& request.method() == axum::http::Method::POST;
179+
let reopen_trace = reopen_trace
180+
.then(|| layer1_public::rest::request_id_from_headers(request.headers()))
181+
.flatten()
182+
.and_then(|id| uuid::Uuid::parse_str(id).ok())
183+
.map(|id| layer3_adapter::reopen_diagnostics::Trace::new(id, "owner"));
172184
if reports_file_write && relay.coordinator.is_draining() {
173185
return file_write::refusal(
174186
&relay,
@@ -180,7 +192,10 @@ async fn route_request(
180192
if reports_handoff && relay.coordinator.is_draining() {
181193
return file_read::refusal(diagnostic.as_ref(), Refusal::CoordinatorNotReady);
182194
}
183-
let destination = match if private
195+
let owner_phase = reopen_trace
196+
.as_ref()
197+
.map(|trace| trace.phase("owner_destination"));
198+
let destination = if private
184199
&& request
185200
.uri()
186201
.path()
@@ -192,7 +207,15 @@ async fn route_request(
192207
.map_err(|_| Refusal::AuthorityChanged)
193208
} else {
194209
relay.destination(&id).await
195-
} {
210+
};
211+
if let Some(phase) = owner_phase {
212+
phase.finish(if destination.is_ok() {
213+
"ok"
214+
} else {
215+
"unavailable"
216+
});
217+
}
218+
let destination = match destination {
196219
Ok(value) => value,
197220
Err(
198221
reason @ (Refusal::OwnerMissing
@@ -239,6 +262,9 @@ async fn route_request(
239262
}
240263
request.headers_mut().remove(PROOF);
241264
request.extensions_mut().insert(VerifiedPeer);
265+
if let Some(trace) = reopen_trace {
266+
request.extensions_mut().insert(trace);
267+
}
242268
if is_cancellation {
243269
request
244270
.extensions_mut()

‎api/crates/cma/src/agent_manager/relay/reopen.rs‎

Lines changed: 41 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ use layer2_core::{
1010
sandbox::{AgentWorkReceipt, Sandbox, SandboxWorkLease},
1111
SandboxId,
1212
};
13+
use layer3_adapter::reopen_diagnostics::{self, Trace};
1314
use tokio::time::Instant;
1415

1516
const REOPEN_LIMIT: Duration = Duration::from_secs(layer3_adapter::DEFAULT_TOTAL_TIMEOUT_SECONDS);
@@ -45,32 +46,52 @@ impl Relay {
4546
id: &AgentId,
4647
verify_refusal: bool,
4748
) -> layer3_adapter::Result<AgentWorkReceipt> {
48-
self.reopen_call(sandbox, id, verify_refusal)
49+
let trace = reopen_diagnostics::current()
50+
.unwrap_or_else(|| Trace::new(uuid::Uuid::new_v4(), "publisher"));
51+
let phase = trace.phase("owner_relay");
52+
let result = self
53+
.reopen_call(sandbox, id, verify_refusal, &trace)
4954
.await
50-
.map_err(|error| error.into_adapter("Agent owner lifecycle reopen unavailable"))
55+
.map_err(|error| error.into_adapter("Agent owner lifecycle reopen unavailable"));
56+
phase.finish(reopen_diagnostics::outcome(&result));
57+
result
5158
}
5259

5360
async fn reopen_call(
5461
&self,
5562
sandbox: &Sandbox,
5663
id: &AgentId,
5764
verify_refusal: bool,
65+
trace: &Trace,
5866
) -> Result<AgentWorkReceipt, CallFailure> {
5967
let deadline = Instant::now() + REOPEN_LIMIT;
6068
let _permit = self
6169
.acquire(capacity::Class::Control)
6270
.map_err(|_| CallFailure::RelayCapacity)?;
63-
let destination = self.control_destination(id).await?;
71+
let phase = trace.phase("owner_destination");
72+
let destination = self.control_destination(id).await;
73+
phase.finish(if destination.is_ok() {
74+
"ok"
75+
} else {
76+
"unavailable"
77+
});
78+
let destination = destination?;
6479
let call = ReopenCall {
6580
sandbox_id: sandbox.id.clone(),
6681
revision: sandbox.revision,
6782
lease: sandbox.work.lease.clone().ok_or(())?,
6883
};
69-
let reply = if destination.member.instance_id == self.coordinator.instance_id {
84+
let local = destination.member.instance_id == self.coordinator.instance_id;
85+
tracing::info!(attempt_id = %trace.attempt(), agent_id = %id,
86+
local, owner_epoch = destination.token.epoch, "Retained runtime reopen routed");
87+
let reply = if local {
7088
let worker = self.reopen.get().ok_or(())?;
89+
let owner_trace = Trace::new(trace.attempt(), "owner");
7190
tokio::time::timeout_at(
7291
deadline,
73-
destination.authority.run(worker.reopen_at_owner(id, &call)),
92+
destination
93+
.authority
94+
.run(owner_trace.run(worker.reopen_at_owner(id, &call))),
7495
)
7596
.await
7697
.map_err(|_| ())?
@@ -86,6 +107,10 @@ impl Relay {
86107
.parse()
87108
.map_err(|_| ())?;
88109
let mut headers = axum::http::HeaderMap::new();
110+
headers.insert(
111+
"x-request-id",
112+
trace.attempt().to_string().parse().map_err(|_| ())?,
113+
);
89114
headers.insert(
90115
axum::http::header::CONTENT_TYPE,
91116
axum::http::HeaderValue::from_static("application/json"),
@@ -176,6 +201,7 @@ async fn verify_refused_owner<T>(
176201
pub(super) async fn serve(
177202
State(relay): State<Arc<Relay>>,
178203
Extension(_peer): Extension<http::VerifiedPeer>,
204+
trace: Option<Extension<Trace>>,
179205
Json(call): Json<ReopenCall>,
180206
) -> Response {
181207
let Some(authority) = layer2_core::agent_ownership::execution_authority() else {
@@ -184,11 +210,16 @@ pub(super) async fn serve(
184210
let Some(worker) = relay.reopen.get() else {
185211
return http::unavailable();
186212
};
187-
match tokio::time::timeout(
188-
REOPEN_LIMIT,
189-
worker.reopen_at_owner(&authority.token.agent_id, &call),
190-
)
191-
.await
213+
let trace = trace.map_or_else(
214+
|| Trace::new(uuid::Uuid::new_v4(), "owner"),
215+
|Extension(trace)| trace,
216+
);
217+
match trace
218+
.run(tokio::time::timeout(
219+
REOPEN_LIMIT,
220+
worker.reopen_at_owner(&authority.token.agent_id, &call),
221+
))
222+
.await
192223
{
193224
Ok(Ok(receipt)) => Json(Reply {
194225
owner: authority.token.clone(),

‎api/crates/cma/src/sandbox/runtime_attachment.rs‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,23 @@ pub(crate) async fn adopt_bound_runtime(
169169
.0)
170170
}
171171

172+
pub(crate) async fn adopt_bound_runtime_for_owner_reopen(
173+
adapter: &dyn SandboxAdapter,
174+
sandbox: &Sandbox,
175+
deployment_id: &str,
176+
) -> layer3_adapter::Result<RuntimeHandle> {
177+
let admission = if sandbox.retained_home_recovery().is_some() {
178+
layer3_adapter::InspectionAdmission::owner_reopen()
179+
} else {
180+
layer3_adapter::InspectionAdmission::ready()
181+
};
182+
Ok(
183+
inspect_bound_runtime_after(adapter, sandbox, deployment_id, &admission)
184+
.await?
185+
.0,
186+
)
187+
}
188+
172189
/// Fresh identity proof and optional capabilities from that same runtime process.
173190
pub(crate) async fn inspect_bound_runtime(
174191
adapter: &dyn SandboxAdapter,

‎api/crates/cma/src/sandbox/worker/lifecycle/conversations.rs‎

Lines changed: 23 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -10,18 +10,22 @@ use layer2_core::sandbox::{
1010
Agent, AgentLogKind, AgentStatus, AgentWorkReceipt, AgentWorkStep, FirstMessageDelivery,
1111
Sandbox, SandboxEventKind, SandboxWorkStep, Worktree, WorktreeStatus,
1212
};
13-
use layer3_adapter::AgentOpenRequest;
13+
use layer3_adapter::{reopen_diagnostics::Trace, AgentOpenRequest};
1414
use tokio::sync::mpsc;
1515
use tokio::time::Instant;
1616

1717
use super::super::support::{runtime, WorkerFailure};
1818
use super::super::SandboxWorker;
19-
use super::checkpoint::{pinned_checkpoint, require_quiet_agent};
19+
use super::checkpoint::pinned_checkpoint;
2020
use super::reopen_refusal::within_deadline;
2121
use super::support::{lifecycle_lease, model_error};
2222
use crate::sandbox::live_agents::{LiveAgentAttachment, LiveAgentRegistryError};
2323
use crate::sandbox::runtime_mapping::{runtime_capabilities, runtime_options};
2424

25+
#[path = "conversations_validation.rs"]
26+
mod validation;
27+
use validation::validate_reopen_set;
28+
2529
const UPDATE_BUFFER: usize = 256;
2630
const REOPEN_LIMIT: Duration = Duration::from_secs(layer3_adapter::DEFAULT_TOTAL_TIMEOUT_SECONDS);
2731

@@ -79,6 +83,7 @@ impl SandboxWorker {
7983

8084
let mut attachments = Vec::new();
8185
let mut receipts = BTreeMap::new();
86+
let mut reopen_traces = Vec::new();
8287
// Earlier restore phases have their own budgets, and an empty set has
8388
// no conversation work to time out.
8489
let deadline = if live.is_empty() {
@@ -97,9 +102,12 @@ impl SandboxWorker {
97102
let prove_refusal = refusal.is_some();
98103
if let Some(relay) = self.reopen_relay.get() {
99104
let relay = relay.upgrade().ok_or(SandboxStoreError::Conflict)?;
105+
let trace = Trace::new(uuid::Uuid::new_v4(), "publisher");
100106
match within_deadline(
101107
deadline,
102-
relay.reopen_agent(&sandbox, &agent.id, prove_refusal),
108+
trace
109+
.clone()
110+
.run(relay.reopen_agent(&sandbox, &agent.id, prove_refusal)),
103111
refusal,
104112
true,
105113
)
@@ -110,6 +118,7 @@ impl SandboxWorker {
110118
// timestamp, which can differ from the remote clock.
111119
receipt.completed_at = rfc3339_at(now);
112120
receipts.insert(agent.id.clone(), receipt);
121+
reopen_traces.push(trace);
113122
}
114123
Err(failure) => {
115124
tracing::warn!(sandbox_id = %sandbox.id, agent_id = %agent.id,
@@ -339,6 +348,10 @@ impl SandboxWorker {
339348
events.push(SandboxEventKind::WorkStepCompleted {
340349
step: SandboxWorkStep::RunLifecycleOperation,
341350
});
351+
let commit_timings: Vec<_> = reopen_traces
352+
.iter()
353+
.map(|trace| trace.phase("parent_ready_commit"))
354+
.collect();
342355
let committed = self
343356
.commit_lifecycle_phase(
344357
&sandbox,
@@ -349,6 +362,13 @@ impl SandboxWorker {
349362
events,
350363
)
351364
.await;
365+
for phase in commit_timings {
366+
phase.finish(if committed.is_ok() {
367+
"ok"
368+
} else {
369+
"commit_error"
370+
});
371+
}
352372
let durable = match committed {
353373
Ok(()) => true,
354374
Err(error) => match self.lifecycle_state_matches(&next).await {
@@ -442,46 +462,6 @@ impl SandboxWorker {
442462
}
443463
}
444464

445-
fn validate_reopen_set<'a>(
446-
sandbox: &Sandbox,
447-
agents: &'a [Agent],
448-
checkpoint: Option<&layer2_core::sandbox::SandboxCheckpointRef>,
449-
) -> Result<Vec<&'a Agent>, WorkerFailure> {
450-
let by_id = checkpoint
451-
.into_iter()
452-
.flat_map(|checkpoint| &checkpoint.conversations)
453-
.map(|conversation| {
454-
(
455-
&conversation.agent_id,
456-
conversation.conversation_id.as_str(),
457-
)
458-
})
459-
.collect::<BTreeMap<_, _>>();
460-
let live = agents
461-
.iter()
462-
.filter(|agent| sandbox.restores_agent(agent))
463-
.collect::<Vec<_>>();
464-
let matches = live.iter().all(|agent| {
465-
agent.status == AgentStatus::Paused
466-
&& require_quiet_agent(agent).is_ok()
467-
&& agent
468-
.conversation
469-
.conversation_id
470-
.as_deref()
471-
.is_some_and(|current| {
472-
sandbox.retained_home_recovery().is_some()
473-
|| by_id.get(&agent.id).copied() == Some(current)
474-
})
475-
});
476-
if matches {
477-
Ok(live)
478-
} else {
479-
Err(WorkerFailure::terminal_security(
480-
"restored live agents do not match the pinned checkpoint conversations",
481-
))
482-
}
483-
}
484-
485465
fn rollback_attachments(worker: &SandboxWorker, attachments: &[LiveAgentAttachment]) {
486466
for attachment in attachments {
487467
worker.dependencies.registry.rollback(attachment);
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
use std::collections::BTreeMap;
2+
3+
use layer2_core::sandbox::{Agent, AgentStatus, Sandbox};
4+
5+
use super::{super::checkpoint::require_quiet_agent, WorkerFailure};
6+
7+
pub(super) fn validate_reopen_set<'a>(
8+
sandbox: &Sandbox,
9+
agents: &'a [Agent],
10+
checkpoint: Option<&layer2_core::sandbox::SandboxCheckpointRef>,
11+
) -> Result<Vec<&'a Agent>, WorkerFailure> {
12+
let by_id = checkpoint
13+
.into_iter()
14+
.flat_map(|checkpoint| &checkpoint.conversations)
15+
.map(|conversation| {
16+
(
17+
&conversation.agent_id,
18+
conversation.conversation_id.as_str(),
19+
)
20+
})
21+
.collect::<BTreeMap<_, _>>();
22+
let live = agents
23+
.iter()
24+
.filter(|agent| sandbox.restores_agent(agent))
25+
.collect::<Vec<_>>();
26+
let matches = live.iter().all(|agent| {
27+
agent.status == AgentStatus::Paused
28+
&& require_quiet_agent(agent).is_ok()
29+
&& agent
30+
.conversation
31+
.conversation_id
32+
.as_deref()
33+
.is_some_and(|current| {
34+
sandbox.retained_home_recovery().is_some()
35+
|| by_id.get(&agent.id).copied() == Some(current)
36+
})
37+
});
38+
if matches {
39+
Ok(live)
40+
} else {
41+
Err(WorkerFailure::terminal_security(
42+
"restored live agents do not match the pinned checkpoint conversations",
43+
))
44+
}
45+
}

0 commit comments

Comments
 (0)