mj_controller/controller/checkpoint/
barrier.rs1use super::*;
2
3pub(super) async fn connect_checkpoint_relay(
4 session_id: &str,
5 manager: Option<&SessionManagerControl>,
6 reconnect: &targets::CommandSpec,
7 project_memory: Option<crate::session_manager::ProjectMemorySyncTarget>,
8) -> Result<ControllerRelayLease> {
9 if let Some(manager) = manager {
10 let handle = manager
11 .wait_for_session(session_id, Duration::from_secs(5))
12 .await?;
13 let mut lease = handle.lease_connection().await?;
14 lease
15 .connection_mut()
16 .set_project_memory_target(project_memory);
17 Ok(ControllerRelayLease::Managed {
18 handle,
19 lease: Some(lease),
20 })
21 } else {
22 let target = crate::session_manager::RelaySessionTarget {
23 session_id: session_id.to_owned(),
24 spec: reconnect.clone(),
25 worker_recovery: None,
26 project_memory,
27 };
28 Ok(ControllerRelayLease::Standalone(
29 StandaloneSession::connect(&target).await?,
30 ))
31 }
32}
33
34pub(super) async fn adopt_restarted_checkpoint_relay(
35 session_id: &str,
36 manager: Option<&SessionManagerControl>,
37 connection: StandaloneSession,
38) -> Result<ControllerRelayLease> {
39 let Some(manager) = manager else {
40 return Ok(ControllerRelayLease::Standalone(connection));
41 };
42 let handle = manager
43 .wait_for_session(session_id, Duration::from_secs(5))
44 .await?;
45 match handle.lease_connection().await {
46 Ok(mut lease) => {
47 lease.replace_connection(connection);
48 Ok(ControllerRelayLease::Managed {
49 handle,
50 lease: Some(lease),
51 })
52 }
53 Err(error) => {
54 tracing::warn!(
55 session_id,
56 "session actor could not lease after worker restart; using the restarted proxy: {error:#}"
57 );
58 Ok(ControllerRelayLease::Standalone(connection))
59 }
60 }
61}
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub(super) enum BarrierBusyPolicy {
66 DeferWhileRunning,
72 InterruptWhileRunning,
76}
77
78impl BarrierBusyPolicy {
79 pub(super) fn of(exclusivity: LatchExclusivity) -> Self {
80 match exclusivity {
81 LatchExclusivity::ReleaseAfterLatch => Self::DeferWhileRunning,
82 LatchExclusivity::HoldThroughClose => Self::InterruptWhileRunning,
83 }
84 }
85}
86
87pub(super) async fn wait_for_checkpoint_barrier(
88 relay: &mut StandaloneSession,
89 session_id: &str,
90 command_id: &str,
91 timeout: Duration,
92 busy: BarrierBusyPolicy,
93 harness: HarnessKind,
94) -> Result<ManagedSessionSnapshot> {
95 let deadline = tokio::time::Instant::now() + timeout;
96 let mut cancel_submitted = false;
97 let mut cancel_deadline = None;
98 let mut cancel_started_at: Option<Instant> = None;
99 loop {
100 let snapshot = relay.sync().await?;
101 if busy == BarrierBusyPolicy::DeferWhileRunning
102 && !snapshot.operational.safe_for_checkpoint(harness)
103 {
104 return Err(
109 CheckpointDeferred::background_snapshot(&snapshot.operational, harness).into(),
110 );
111 }
112 if checkpoint_barrier_is_ready(&snapshot, command_id) {
113 if let Some(started_at) = cancel_started_at {
114 tracing::info!(
115 session_id,
116 barrier_command_id = command_id,
117 cancellation_ms = started_at.elapsed().as_millis() as u64,
118 "active turn cancellation settled before checkpoint barrier"
119 );
120 }
121 return Ok(snapshot);
122 }
123 if busy == BarrierBusyPolicy::InterruptWhileRunning
124 && snapshot.operational.execution == RelayExecutionState::Running
125 && !cancel_submitted
126 {
127 let cancel_command_id = new_command_id("checkpoint-cancel-turn")?;
128 match relay
129 .submit(cancel_command_id, RelayCommand::CancelTurn)
130 .await
131 {
132 Ok(_) => {
133 cancel_submitted = true;
134 cancel_started_at = Some(Instant::now());
135 cancel_deadline = Some(tokio::time::Instant::now() + CHECKPOINT_CANCEL_TIMEOUT);
136 tracing::info!(
137 session_id,
138 barrier_command_id = command_id,
139 "requested active turn cancellation before checkpoint barrier"
140 );
141 }
142 Err(error) if checkpoint_cancel_turn_needs_worker_restart(&error) => {
143 return Err(error.context(
144 CheckpointBarrierUnreachable::cancel_turn_unavailable(
145 command_id,
146 relay.protocol_version(),
147 ),
148 ));
149 }
150 Err(error) if worker_connect_needs_restart(&error) => {
151 return Err(error.context(
152 CheckpointBarrierUnreachable::cancel_turn_unreachable(command_id),
153 ));
154 }
155 Err(error) => {
156 if let Ok(snapshot) = relay.sync().await
160 && checkpoint_barrier_is_ready(&snapshot, command_id)
161 {
162 tracing::info!(
163 session_id,
164 barrier_command_id = command_id,
165 "active turn settled while submitting checkpoint cancellation"
166 );
167 return Ok(snapshot);
168 }
169 return Err(error.context("cancel active ACP turn before checkpoint barrier"));
170 }
171 }
172 continue;
173 }
174 let out_of_time = tokio::time::Instant::now() >= cancel_deadline.unwrap_or(deadline);
175 if let Some(error) = checkpoint_barrier_wait_ended(
176 &snapshot,
177 command_id,
178 busy,
179 out_of_time,
180 cancel_submitted,
181 ) {
182 return Err(error);
183 }
184 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
185 }
186}
187
188pub(super) fn checkpoint_barrier_wait_ended(
195 snapshot: &ManagedSessionSnapshot,
196 command_id: &str,
197 busy: BarrierBusyPolicy,
198 out_of_time: bool,
199 cancel_submitted: bool,
200) -> Option<anyhow::Error> {
201 if snapshot.operational.execution == RelayExecutionState::Closed {
202 return Some(CheckpointBarrierUnreachable::runtime_stopped().into());
203 }
204 if snapshot.operational.execution == RelayExecutionState::Running {
205 return Some(match busy {
206 BarrierBusyPolicy::DeferWhileRunning => CheckpointDeferred::harness_busy().into(),
207 BarrierBusyPolicy::InterruptWhileRunning if out_of_time && cancel_submitted => {
208 CheckpointBarrierUnreachable::cancel_timed_out(command_id).into()
209 }
210 BarrierBusyPolicy::InterruptWhileRunning => return None,
211 });
212 }
213 out_of_time.then(|| CheckpointBarrierUnreachable::not_admitted(command_id).into())
214}
215
216#[derive(Debug)]
223pub(super) struct CheckpointBarrierUnreachable(pub(super) String);
224
225impl CheckpointBarrierUnreachable {
226 pub(super) fn runtime_stopped() -> Self {
227 Self("ACP runtime stopped before reaching the checkpoint barrier".to_owned())
228 }
229
230 pub(super) fn not_admitted(command_id: &str) -> Self {
231 Self(format!(
232 "ACP relay did not reach checkpoint barrier {command_id}"
233 ))
234 }
235
236 pub(super) fn cancel_timed_out(command_id: &str) -> Self {
237 Self(format!(
238 "active ACP turn did not settle after cancellation before checkpoint barrier {command_id}"
239 ))
240 }
241
242 pub(super) fn cancel_turn_unavailable(command_id: &str, protocol_version: u32) -> Self {
243 Self(format!(
244 "worker protocol {protocol_version} cannot cancel the active ACP turn before checkpoint barrier {command_id} (requires protocol {})",
245 RelayCommand::CancelTurn.minimum_protocol(),
246 ))
247 }
248
249 pub(super) fn cancel_turn_unreachable(command_id: &str) -> Self {
250 Self(format!(
251 "worker transport became unavailable while cancelling the active ACP turn before checkpoint barrier {command_id}"
252 ))
253 }
254}
255
256impl std::fmt::Display for CheckpointBarrierUnreachable {
257 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
258 formatter.write_str(&self.0)
259 }
260}
261
262impl std::error::Error for CheckpointBarrierUnreachable {}
263
264pub(super) fn checkpoint_barrier_needs_worker_restart(error: &anyhow::Error) -> bool {
265 error
266 .downcast_ref::<CheckpointBarrierUnreachable>()
267 .is_some()
268}
269
270pub(super) fn checkpoint_cancel_turn_needs_worker_restart(error: &anyhow::Error) -> bool {
274 error.chain().any(|cause| {
275 let Some(rejected) = cause.downcast_ref::<RelayRejected>() else {
276 return false;
277 };
278 rejected.0.code == mj_core::relay::RelayErrorCode::IncompatibleProtocol
279 })
280}
281
282#[derive(Debug)]
292pub struct CheckpointDeferred(String);
293
294impl CheckpointDeferred {
295 pub fn harness_busy() -> Self {
296 Self("the agent is working; try again when it is idle".to_owned())
297 }
298
299 pub(super) fn background_work() -> Self {
300 Self("Kimi background-agent state could not be synchronized; checkpoint requires a synchronized empty task list".into())
301 }
302
303 pub(super) fn background_snapshot(
304 state: &mj_core::relay::RelayOperationalState,
305 harness: HarnessKind,
306 ) -> Self {
307 Self(
308 state
309 .checkpoint_background_blocker(harness)
310 .unwrap_or("background state changed during checkpoint")
311 .into(),
312 )
313 }
314
315 pub(super) fn frontier_moved() -> Self {
316 Self(
317 "the session moved past the checkpoint-ready cursor before the barrier latched, so this checkpoint was deferred"
318 .to_owned(),
319 )
320 }
321
322 pub(super) fn harness_turn_during_capture() -> Self {
323 Self(
324 "the agent started a turn of its own while target state was captured, so this checkpoint was deferred"
325 .to_owned(),
326 )
327 }
328}
329
330impl std::fmt::Display for CheckpointDeferred {
331 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
332 formatter.write_str(&self.0)
333 }
334}
335
336impl std::error::Error for CheckpointDeferred {}
337
338pub fn checkpoint_was_deferred(error: &anyhow::Error) -> bool {
345 error.downcast_ref::<CheckpointDeferred>().is_some()
346}