Skip to main content

mj_controller/controller/checkpoint/
barrier.rs

1use 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/// What waiting for a barrier does while the session is working.
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub(super) enum BarrierBusyPolicy {
66    /// Give up as soon as the session is seen working. A checkpoint that can
67    /// run again later has nothing to gain from holding a barrier behind a
68    /// prompt or a turn the harness started on its own: the wait would only
69    /// end at the deadline, and the deadline means "wedged", which restarts
70    /// the worker and kills the work in flight.
71    DeferWhileRunning,
72    /// Request non-steering cancellation and wait for the turn to settle.
73    /// Close may interrupt work, but only an unresponsive or incompatible
74    /// worker needs restart recovery.
75    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                // The native task level can change after the controller's
104                // initial idle sync and before the queued BeginCheckpoint is
105                // processed. Defer from the barrier wait rather than allowing
106                // its timeout to classify the worker as wedged and restart it.
107                return Err(CheckpointDeferred::background_snapshot(
108                    &snapshot.operational,
109                    harness,
110                )
111                .into());
112            }
113            if snapshot.operational.has_work_in_flight() {
114                // A foreground tool, a turn the execution flag has not caught
115                // up with, or queued work can all appear after the initial
116                // sync. Defer rather than let the deadline restart the worker
117                // underneath it.
118                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        // A turn the execution flag has not caught up with still has to be
133        // cancelled, so this asks the shared state rather than the flag.
134        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                    // The turn can finish between the status sync and this
168                    // submit. If the barrier won that race, continue from its
169                    // durable ready state; otherwise preserve the rejection.
170                    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
199/// Why one sync of a barrier that is not ready yet ends the wait, or `None` to
200/// keep waiting.
201///
202/// The deadline means "wedged": it restarts the worker only after a close has
203/// already requested cancellation and the turn still has not settled. A
204/// checkpoint that can try again later defers as soon as it sees work. "Work"
205/// is the shared predicate, not the bare execution flag: a stale projection
206/// can report `Idle` while a harness turn or a foreground tool is still live,
207/// and treating that as wedged would restart the worker under it.
208pub(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    // Close already asked to interrupt the active turn, so only a turn that
225    // never settles after cancellation reaches the restart path.
226    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/// The ACP runtime never admitted a checkpoint barrier: it stopped first, or it
234/// never reached the barrier before the deadline.
235///
236/// [`wait_for_checkpoint_barrier`] is the only producer, and the retry decision
237/// downcasts for this marker rather than reading the message, so rewording a
238/// diagnostic cannot silently disable the restart-and-retry path.
239#[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
287/// A worker that cannot decode `CancelTurn` needs to be replaced before the
288/// close can retry the checkpoint with cancellation available. The relay client
289/// refuses the command for an older worker with the same code the worker uses.
290pub(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/// The session was working, so this checkpoint did not run. Nothing is wrong
300/// with the session, the target, or the last archive.
301///
302/// A busy session is the normal state of a session someone is using, including
303/// one working through a turn the harness started on its own after a
304/// background command. Treating that as a checkpoint failure would restart the
305/// worker, record a failure against the session, and back the next attempt off
306/// for hours. Callers that can try again later defer instead; the same work is
307/// copied at the next idle observation.
308#[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
355/// Whether a failed checkpoint only means the session was busy.
356///
357/// The marker is carried by the error, not by its text. It may be the root
358/// error or attached with `context`, and callers wrap checkpoint errors in
359/// further context. `anyhow`'s own downcast walks every context layer;
360/// `chain()` does not expose a context value, so it must not be used here.
361pub fn checkpoint_was_deferred(error: &anyhow::Error) -> bool {
362    error.downcast_ref::<CheckpointDeferred>().is_some()
363}