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 if !snapshot.operational.safe_for_checkpoint(harness) {
103 return Err(CheckpointDeferred::background_snapshot(
108 &snapshot.operational,
109 harness,
110 )
111 .into());
112 }
113 if snapshot.operational.has_work_in_flight() {
114 return Err(CheckpointDeferred::harness_busy().into());
119 }
120 }
121 if checkpoint_barrier_is_ready(&snapshot, command_id) {
122 if let Some(started_at) = cancel_started_at {
123 tracing::info!(
124 session_id,
125 barrier_command_id = command_id,
126 cancellation_ms = started_at.elapsed().as_millis() as u64,
127 "active turn cancellation settled before checkpoint barrier"
128 );
129 }
130 return Ok(snapshot);
131 }
132 if busy == BarrierBusyPolicy::InterruptWhileRunning
135 && snapshot.operational.activity_state().is_working()
136 && !cancel_submitted
137 {
138 let cancel_command_id = new_command_id("checkpoint-cancel-turn")?;
139 match relay
140 .submit(cancel_command_id, RelayCommand::CancelTurn)
141 .await
142 {
143 Ok(_) => {
144 cancel_submitted = true;
145 cancel_started_at = Some(Instant::now());
146 cancel_deadline = Some(tokio::time::Instant::now() + CHECKPOINT_CANCEL_TIMEOUT);
147 tracing::info!(
148 session_id,
149 barrier_command_id = command_id,
150 "requested active turn cancellation before checkpoint barrier"
151 );
152 }
153 Err(error) if checkpoint_cancel_turn_needs_worker_restart(&error) => {
154 return Err(error.context(
155 CheckpointBarrierUnreachable::cancel_turn_unavailable(
156 command_id,
157 relay.protocol_version(),
158 ),
159 ));
160 }
161 Err(error) if worker_connect_needs_restart(&error) => {
162 return Err(error.context(
163 CheckpointBarrierUnreachable::cancel_turn_unreachable(command_id),
164 ));
165 }
166 Err(error) => {
167 if let Ok(snapshot) = relay.sync().await
171 && checkpoint_barrier_is_ready(&snapshot, command_id)
172 {
173 tracing::info!(
174 session_id,
175 barrier_command_id = command_id,
176 "active turn settled while submitting checkpoint cancellation"
177 );
178 return Ok(snapshot);
179 }
180 return Err(error.context("cancel active ACP turn before checkpoint barrier"));
181 }
182 }
183 continue;
184 }
185 let out_of_time = tokio::time::Instant::now() >= cancel_deadline.unwrap_or(deadline);
186 if let Some(error) = checkpoint_barrier_wait_ended(
187 &snapshot,
188 command_id,
189 busy,
190 out_of_time,
191 cancel_submitted,
192 ) {
193 return Err(error);
194 }
195 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
196 }
197}
198
199pub(super) fn checkpoint_barrier_wait_ended(
209 snapshot: &ManagedSessionSnapshot,
210 command_id: &str,
211 busy: BarrierBusyPolicy,
212 out_of_time: bool,
213 cancel_submitted: bool,
214) -> Option<anyhow::Error> {
215 if snapshot.operational.execution == RelayExecutionState::Closed {
216 return Some(CheckpointBarrierUnreachable::runtime_stopped().into());
217 }
218 if busy == BarrierBusyPolicy::DeferWhileRunning {
219 if snapshot.operational.has_work_in_flight() {
220 return Some(CheckpointDeferred::harness_busy().into());
221 }
222 return out_of_time.then(|| CheckpointBarrierUnreachable::not_admitted(command_id).into());
223 }
224 if snapshot.operational.activity_state().is_working() {
227 return (out_of_time && cancel_submitted)
228 .then(|| CheckpointBarrierUnreachable::cancel_timed_out(command_id).into());
229 }
230 out_of_time.then(|| CheckpointBarrierUnreachable::not_admitted(command_id).into())
231}
232
233#[derive(Debug)]
240pub(super) struct CheckpointBarrierUnreachable(pub(super) String);
241
242impl CheckpointBarrierUnreachable {
243 pub(super) fn runtime_stopped() -> Self {
244 Self("ACP runtime stopped before reaching the checkpoint barrier".to_owned())
245 }
246
247 pub(super) fn not_admitted(command_id: &str) -> Self {
248 Self(format!(
249 "ACP relay did not reach checkpoint barrier {command_id}"
250 ))
251 }
252
253 pub(super) fn cancel_timed_out(command_id: &str) -> Self {
254 Self(format!(
255 "active ACP turn did not settle after cancellation before checkpoint barrier {command_id}"
256 ))
257 }
258
259 pub(super) fn cancel_turn_unavailable(command_id: &str, protocol_version: u32) -> Self {
260 Self(format!(
261 "worker protocol {protocol_version} cannot cancel the active ACP turn before checkpoint barrier {command_id} (requires protocol {})",
262 RelayCommand::CancelTurn.minimum_protocol(),
263 ))
264 }
265
266 pub(super) fn cancel_turn_unreachable(command_id: &str) -> Self {
267 Self(format!(
268 "worker transport became unavailable while cancelling the active ACP turn before checkpoint barrier {command_id}"
269 ))
270 }
271}
272
273impl std::fmt::Display for CheckpointBarrierUnreachable {
274 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
275 formatter.write_str(&self.0)
276 }
277}
278
279impl std::error::Error for CheckpointBarrierUnreachable {}
280
281pub(super) fn checkpoint_barrier_needs_worker_restart(error: &anyhow::Error) -> bool {
282 error
283 .downcast_ref::<CheckpointBarrierUnreachable>()
284 .is_some()
285}
286
287pub(super) fn checkpoint_cancel_turn_needs_worker_restart(error: &anyhow::Error) -> bool {
291 error.chain().any(|cause| {
292 let Some(rejected) = cause.downcast_ref::<RelayRejected>() else {
293 return false;
294 };
295 rejected.0.code == mj_core::relay::RelayErrorCode::IncompatibleProtocol
296 })
297}
298
299#[derive(Debug)]
309pub struct CheckpointDeferred(String);
310
311impl CheckpointDeferred {
312 pub fn harness_busy() -> Self {
313 Self("the agent is working; try again when it is idle".to_owned())
314 }
315
316 pub(super) fn background_work() -> Self {
317 Self("Kimi background-agent state could not be synchronized; checkpoint requires a synchronized empty task list".into())
318 }
319
320 pub(super) fn background_snapshot(
321 state: &mj_core::relay::RelayOperationalState,
322 harness: HarnessKind,
323 ) -> Self {
324 Self(
325 state
326 .checkpoint_background_blocker(harness)
327 .unwrap_or("background state changed during checkpoint")
328 .into(),
329 )
330 }
331
332 pub(super) fn frontier_moved() -> Self {
333 Self(
334 "the session moved past the checkpoint-ready cursor before the barrier latched, so this checkpoint was deferred"
335 .to_owned(),
336 )
337 }
338
339 pub(super) fn harness_turn_during_capture() -> Self {
340 Self(
341 "the agent started a turn of its own while target state was captured, so this checkpoint was deferred"
342 .to_owned(),
343 )
344 }
345}
346
347impl std::fmt::Display for CheckpointDeferred {
348 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
349 formatter.write_str(&self.0)
350 }
351}
352
353impl std::error::Error for CheckpointDeferred {}
354
355pub fn checkpoint_was_deferred(error: &anyhow::Error) -> bool {
362 error.downcast_ref::<CheckpointDeferred>().is_some()
363}