返回 CodeWhale
model_step.rs
根目录 / crates / engine / src / core / engine / turn_loop / model_step.rs
1 //! One private phase of the existing Engine turn loop.
2
3 use super::*;
4 use anyhow::anyhow;
5
6 impl Engine {
7 pub(super) async fn run_model_step(
8 &mut self,
9 turn: &mut TurnContext,
10 progress: &mut TurnLoopProgress,
11 client: &SharedModelClient,
12 prepared: PreparedModelStep,
13 ) -> PhaseResult<AcceptedModelStep> {
14 let _timing = codewhale_runtime::logging::PhaseTimer::start("model_step");
15 let PreparedModelStep {
16 request_nudge,
17 prefix_check,
18 request: stream_request,
19 zero_tool_turn,
20 fleet_report_response,
21 } = prepared;
22 let child_job = self.child_job();
23 if let Some(job) = child_job.as_ref() {
24 if let Err(error) = job.project(&self.session.messages, job.steps()).await {
25 return PhaseResult::Return((
26 TurnOutcomeStatus::Failed,
27 Some(format!(
28 "child checkpoint failed before dispatch: {error:#}"
29 )),
30 ));
31 }
32 if job.authority.runtime.cancel_token.is_cancelled() {
33 return PhaseResult::Return((TurnOutcomeStatus::Interrupted, None));
34 }
35 }
36 if let Some(nudge) = request_nudge {
37 if let Some(job) = child_job.as_ref()
38 && let Err(error) = job
39 .record_request_nudge(
40 &turn.id,
41 turn.stop_diagnostics
42 .model_requests_started
43 .saturating_add(1),
44 &nudge,
45 &self.cancel_token,
46 )
47 .await
48 {
49 if self.cancel_token.is_cancelled()
50 || job.authority.runtime.cancel_token.is_cancelled()
51 {
52 return PhaseResult::Return((TurnOutcomeStatus::Interrupted, None));
53 }
54 return PhaseResult::Return((
55 TurnOutcomeStatus::Failed,
56 Some(format!(
57 "child request receipt failed before dispatch: {error:#}"
58 )),
59 ));
60 }
61 if self.cancel_token.is_cancelled() {
62 return PhaseResult::Return((TurnOutcomeStatus::Interrupted, None));
63 }
64 if let Err(error) = self
65 .send_event(Event::status(format!(
66 "{}{nudge}",
67 crate::core::events::REQUEST_NUDGE_RECEIPT_PREFIX
68 )))
69 .await
70 {
71 if self.cancel_token.is_cancelled() {
72 return PhaseResult::Return((TurnOutcomeStatus::Interrupted, None));
73 }
74 return PhaseResult::Return((
75 TurnOutcomeStatus::Failed,
76 Some(format!(
77 "request nudge receipt could not be delivered before dispatch: {error:?}"
78 )),
79 ));
80 }
81 }
82 // Session metrics: the model call is measured from this dispatch
83 // instant (connection setup included), and time-to-first-token is
84 // the gap to the first content-bearing stream event.
85 let request_dispatched_at = Instant::now();
86 let awaiting_detail = format!(
87 "{} / {}",
88 self.api_provider_identity
89 .as_ref()
90 .map_or("unavailable", |identity| {
91 identity
92 .compatibility()
93 .map_or(identity.key.as_str(), |row| row.label)
94 }),
95 stream_request.model
96 );
97 self.turn_heartbeat.enter_declared(
98 super::turn_heartbeat::TurnPhase::AwaitingModel,
99 Some(awaiting_detail.clone()),
100 Some(self.config.stream_open_timeout),
101 Some(awaiting_model_bound(&self.config)),
102 );
103 let mut rlm_dispatch = None;
104 let request_cancel = self.cancel_token.clone();
105 let mut child_dispatch = None;
106 let child_logical_step = child_job
107 .as_ref()
108 .map(|_| turn.steps_used().saturating_add(1));
109 let retry_observation = self.request_retry_observation();
110 let transport_retries = retry_observation.retries.clone();
111 let request_route =
112 client.effective_route_envelope(&stream_request.model, chrono::Utc::now());
113 let accounting_origin = self.turn_accounting_origin();
114 let accounting_source = crate::cost_status::NativeUsageSource::capture_with_origin(
115 retry_observation.request_id.clone(),
116 crate::cost_status::UsageSpendOwner::Primary,
117 accounting_origin
118 .clone()
119 .filter(|_| self.child_host.is_none() && self.rlm_host.is_none()),
120 );
121 let mut request_receipt = Some(PendingProviderRequestReceipt {
122 request_id: retry_observation.request_id.clone(),
123 accounting_source,
124 accounting_scope: accounting_origin.as_ref().map_or_else(
125 crate::cost_status::scope_token,
126 crate::cost_status::NativeUsageOrigin::scope,
127 ),
128 accounting_origin,
129 route: request_route,
130 primary: self.child_host.is_none() && self.rlm_host.is_none(),
131 accounting_owned_elsewhere: false,
132 invoked: false,
133 turn_id: turn.id.clone(),
134 request_index: turn
135 .stop_diagnostics
136 .model_requests_started
137 .saturating_add(1),
138 prefix_check,
139 reused_preparation: false,
140 wire: retry_observation.wire_observations.clone(),
141 transport_retries: transport_retries.clone(),
142 started_at: request_dispatched_at,
143 });
144 let rlm_request = tokio::select! {
145 biased;
146 () = request_cancel.cancelled() => {
147 let _ = self.settle_provider_request_receipt(&mut request_receipt, None, "cancelled_before_stream").await;
148 let _ = self.send_event(Event::status("Request cancelled")).await;
149 return PhaseResult::Return((TurnOutcomeStatus::Interrupted, None));
150 }
151 result = self.rlm_provider_request(client, &stream_request) => result.map_err(|error| anyhow!(error)),
152 };
153 let mut opening_steer = None;
154 let mut request_started = false;
155 let stream_result = match rlm_request {
156 Err(error) => Some(Err(error)),
157 Ok(request) => {
158 rlm_dispatch = request;
159 let opening =
160 crate::llm_client::observe_request_retries(Some(retry_observation), async {
161 request_started = true;
162 if let Some(receipt) = request_receipt.as_mut() {
163 receipt.invoked = true;
164 }
165 turn.stop_diagnostics.model_requests_started = turn
166 .stop_diagnostics
167 .model_requests_started
168 .saturating_add(1);
169 if let Some(job) = child_job.as_ref() {
170 let child = &job.authority;
171 let route = client.effective_route_envelope(
172 &stream_request.model,
173 chrono::Utc::now(),
174 );
175 let source = format!(
176 "child:{}:turn:{}:request:{}:dispatch:{}",
177 child.owner_agent_id,
178 turn.id,
179 turn.stop_diagnostics.model_requests_started,
180 route
181 .dispatched_at
182 .timestamp_nanos_opt()
183 .unwrap_or_default()
184 );
185 child_dispatch = Some(job.dispatched(
186 child_logical_step.expect("captured child step"),
187 source,
188 route,
189 ));
190 }
191 if let Some(job) = child_job.as_ref() {
192 tokio::time::timeout(
193 job.authority.runtime.step_api_timeout,
194 client.create_message_stream(stream_request.clone()),
195 )
196 .await
197 .unwrap_or_else(|_| {
198 Err(anyhow::Error::new(LlmError::Timeout(
199 job.authority.runtime.step_api_timeout,
200 )))
201 })
202 } else {
203 client.create_message_stream(stream_request.clone()).await
204 }
205 });
206 tokio::pin!(opening);
207 tokio::select! {
208 biased;
209 () = request_cancel.cancelled() => None,
210 pending = self.wait_turn_steer() => {
211 opening_steer = Some(pending);
212 None
213 },
214 result = &mut opening => Some(result),
215 }
216 }
217 };
218 turn.stop_diagnostics.transport_retries = turn
219 .stop_diagnostics
220 .transport_retries
221 .saturating_add(transport_retries.load(std::sync::atomic::Ordering::Relaxed));
222 let Some(stream_result) = stream_result else {
223 let _ = self
224 .settle_provider_request_receipt(
225 &mut request_receipt,
226 None,
227 if opening_steer.is_some() {
228 "steered_before_stream"
229 } else {
230 "cancelled_before_stream"
231 },
232 )
233 .await;
234 if let Some(dispatch) = rlm_dispatch.as_mut() {
235 if request_started {
236 dispatch.settle(&Usage::default(), false).await;
237 } else {
238 dispatch.cancel_unexecuted().await;
239 if let Some(state) = self.rlm_host.as_mut() {
240 state.model_rounds = state.model_rounds.saturating_sub(1);
241 }
242 }
243 }
244 if let Some(dispatch) = child_dispatch.as_mut() {
245 dispatch.settle(&Usage::default(), false).await;
246 }
247 drop(child_dispatch.take());
248 if let Some(pending) = opening_steer {
249 return self
250 .resume_after_model_steer(turn, progress, vec![pending], request_started)
251 .await;
252 }
253 let _ = self.send_event(Event::status("Request cancelled")).await;
254 return PhaseResult::Return((TurnOutcomeStatus::Interrupted, None));
255 };
256 let stream = match stream_result {
257 Ok(s) => {
258 self.turn_heartbeat.enter_declared(
259 super::turn_heartbeat::TurnPhase::AwaitingModel,
260 Some(awaiting_detail),
261 Some(first_stream_event_timeout(&self.config)),
262 Some(awaiting_model_bound(&self.config)),
263 );
264 let open_timeout_retries = progress.stream_open_timeout_retry_budget.spent();
265 if open_timeout_retries > 0 {
266 progress.stream_open_timeout_retry_budget.reset();
267 let _ = self
268 .send_retry_status(format!(
269 "Retry recovery: stream-open-timeout recovered after {open_timeout_retries} retries"
270 ))
271 .await;
272 }
273 if let Some(job) = child_job.as_ref() {
274 job.provider_responded();
275 }
276 progress.context_recovery_attempts = 0;
277 // The route answered, so any run of identical upstream
278 // failures is over (#6889).
279 self.repeated_upstream_failure = None;
280 // A model has the question now; a later credential
281 // failure in this turn (a token expiring mid-turn, say)
282 // must not take it back (#6566).
283 turn.unanswered_user_message = None;
284 s
285 }
286 Err(mut e) => {
287 let open_cause = crate::llm_error_envelope::ProviderFailureCause::from_llm_error(
288 &e,
289 Some("open"),
290 );
291 let _ = self
292 .settle_provider_request_receipt_with_cause(
293 &mut request_receipt,
294 None,
295 "open_failed",
296 Some(&open_cause),
297 )
298 .await;
299 if let Some(dispatch) = rlm_dispatch.as_mut() {
300 dispatch.settle_open_error(&e).await;
301 }
302 if let Some(job) = child_job.as_ref() {
303 job.provider_refused(&e);
304 job.response_settled(false);
305 if let Some(dispatch) = child_dispatch.as_mut() {
306 dispatch.settle_open_error(&e).await;
307 }
308 drop(child_dispatch.take());
309 }
310 // Replacement is permitted only if Core can still retract
311 // this exact unsent user message. A runtime note or rewrite
312 // cannot be silently replayed as the original task.
313 if let Some(mark) = turn.unanswered_user_message.clone()
314 && self.can_retract_unanswered_user_message(&mark)
315 {
316 match self.admit_child_first_request_replacement(&e).await {
317 Ok(true) => match self.retract_child_unsent_message(mark).await {
318 Ok(true) => {
319 turn.unanswered_user_message = None;
320 self.emit_session_updated().await;
321 return PhaseResult::Return((
322 TurnOutcomeStatus::Failed,
323 Some(codewhale_config::persistence::redact_secrets(&format!(
324 "{e:#}; approved captured replacement queued"
325 ))),
326 ));
327 }
328 Ok(false) => {
329 self.clear_child_pending_route();
330 }
331 Err(error) => {
332 return PhaseResult::Return((
333 TurnOutcomeStatus::Failed,
334 Some(codewhale_config::persistence::redact_secrets(&format!(
335 "{e:#}; unsent child checkpoint failed: {error:#}"
336 ))),
337 ));
338 }
339 },
340 Err(error) => {
341 return PhaseResult::Return((
342 TurnOutcomeStatus::Failed,
343 Some(codewhale_config::persistence::redact_secrets(&format!(
344 "{e:#}; {error:#}"
345 ))),
346 ));
347 }
348 Ok(false) => {}
349 }
350 }
351 let body_size_rejection = matches!(
352 e.downcast_ref::<LlmError>(),
353 Some(LlmError::InvalidRequest { status: 413, .. })
354 );
355 let refusal_proven =
356 crate::tools::subagent::engine::provider_request_refusal_proven(&e);
357 if refusal_proven
358 && !body_size_rejection
359 && self.rlm_host.is_none()
360 && let Some(rejection) =
361 crate::llm_client::image_count_rejection(&format!("{e:#}").to_lowercase())
362 && let Some(result) = self
363 .recover_image_count_rejection(progress, &stream_request, rejection, &e)
364 .await
365 {
366 return result;
367 }
368 if let Some(waited) = crate::client::stream_open_header_timeout(&e) {
369 let waited = waited.as_secs();
370 if self.rlm_host.is_none()
371 && !self.cancel_token.is_cancelled()
372 && child_job
373 .as_ref()
374 .is_none_or(|job| !job.authority.runtime.cancel_token.is_cancelled())
375 && let Some(attempt) = progress.stream_open_timeout_retry_budget.authorize()
376 {
377 turn.stop_diagnostics.stream_resumes =
378 turn.stop_diagnostics.stream_resumes.saturating_add(1);
379 let limit = progress.stream_open_timeout_retry_budget.limit();
380 let _ = self
381 .send_retry_status(format!(
382 "Retry attempt: stream-open-timeout {attempt}/{limit}; provider sent no response headers in {waited}s; sending the request again"
383 ))
384 .await;
385 codewhale_runtime::logging::warn(format!(
386 "No response headers after {waited}s (retry {attempt}/{limit}); sending the request again"
387 ));
388 return PhaseResult::Retry;
389 }
390 let retried = progress.stream_open_timeout_retry_budget.spent();
391 if retried > 0 {
392 if let Some(LlmError::HeaderTimeout {
393 retried: marked, ..
394 }) = e.downcast_mut::<LlmError>()
395 {
396 *marked = retried;
397 }
398 let _ = self
399 .send_retry_status(format!(
400 "Retry exhaustion: stream-open-timeout stopped after {retried} retries; provider sent no response headers in {waited}s"
401 ))
402 .await;
403 }
404 }
405 if let Some(recovery) = self.recover_child_request(progress, &e).await {
406 return recovery;
407 }
408 // Recovery/classification keeps its existing input. Expanding
409 // diagnostics must not introduce another model request.
410 let message = self.decorate_auth_error_message(e.to_string());
411 if refusal_proven
412 && !body_size_rejection
413 && self.rlm_host.is_none()
414 && is_context_length_error_message(&message)
415 && progress.context_recovery_attempts < MAX_CONTEXT_RECOVERY_ATTEMPTS
416 && self
417 .recover_context_overflow(
418 client.as_ref(),
419 stream_request.tools.as_deref(),
420 "provider context-length rejection",
421 turn,
422 )
423 .await
424 {
425 progress.context_recovery_attempts =
426 progress.context_recovery_attempts.saturating_add(1);
427 return PhaseResult::Retry;
428 }
429 if self.cancel_token.is_cancelled() {
430 return PhaseResult::Return((TurnOutcomeStatus::Interrupted, None));
431 }
432 if let Some(message) = self.report_context_recovery_failure(turn).await {
433 return PhaseResult::Return((TurnOutcomeStatus::Failed, Some(message)));
434 }
435 if refusal_proven
436 && !body_size_rejection
437 && self.rlm_host.is_none()
438 && is_image_input_rejection_message(&message)
439 && self.active_route_capabilities.image_input != CapabilityState::Unsupported
440 && !progress.image_rejection_recovered
441 && codewhale_models::image_window::count_request_images(
442 &stream_request.messages,
443 ) > 0
444 {
445 return self.resend_without_images(progress).await;
446 }
447 let display_message = self.decorate_auth_error_message(
448 initial_stream_error_user_message(&self.config.locale_tag, &e),
449 );
450 // Classified from the error's types across its whole
451 // context chain, before `e` moves into the envelope: an
452 // adapter's outer context must not hide a connect error,
453 // and a provider's HTTP rejection must not pass for one
454 // because its body text mentions a timeout (#6711).
455 let open_transport_failure = crate::client::is_stream_open_transport_failure(&e);
456 let unknown_outcome_open_reason =
457 super::streaming::unknown_outcome_open_retry_reason(&e, &message);
458 // #6889: read the upstream status before `e` moves, so a 5xx
459 // that keeps repeating on this model can be told apart from
460 // a transient one below.
461 let upstream_status =
462 e.chain()
463 .find_map(|cause| match cause.downcast_ref::<LlmError>() {
464 Some(LlmError::ServerError { status, .. }) => Some(*status),
465 _ => None,
466 });
467 let mut envelope =
468 crate::llm_error_envelope::envelope_for_llm_error(e, message.clone());
469 if self.rlm_host.is_none()
470 && open_transport_failure
471 && !self.cancel_token.is_cancelled()
472 && let Some(attempt) = progress.stream_retry_budget.authorize()
473 {
474 turn.stop_diagnostics.stream_resumes =
475 turn.stop_diagnostics.stream_resumes.saturating_add(1);
476 let _ = self.send_retry_status(format!(
477 "Retry attempt: stream-open {attempt}/{}; connection failed before request dispatch",
478 progress.stream_retry_budget.limit()
479 )).await;
480 codewhale_runtime::logging::warn(format!(
481 "Stream failed to open (attempt {attempt}/{}); retrying request: {message}",
482 progress.stream_retry_budget.limit()
483 ));
484 return PhaseResult::Retry;
485 }
486 if open_transport_failure && progress.stream_retry_budget.spent() > 0 {
487 let _ = self.send_retry_status(format!(
488 "Retry exhaustion: stream-open stopped after {} retries; connection failed before request dispatch",
489 progress.stream_retry_budget.spent()
490 )).await;
491 }
492 if self.rlm_host.is_none()
493 && self.child_host.is_none()
494 && !self.cancel_token.is_cancelled()
495 && let Some(reason) = unknown_outcome_open_reason
496 {
497 if let Some(attempt) = progress.stream_unknown_outcome_retry_budget.authorize()
498 {
499 turn.stop_diagnostics.stream_resumes =
500 turn.stop_diagnostics.stream_resumes.saturating_add(1);
501 let limit = progress.stream_unknown_outcome_retry_budget.limit();
502 let _ = self
503 .send_retry_status(format!(
504 "Retry attempt: stream-unknown-outcome {attempt}/{limit}; {reason}; sending the request again"
505 ))
506 .await;
507 codewhale_runtime::logging::warn(format!(
508 "Stream request failed with unknown outcome (attempt {attempt}/{limit}); {reason}; retrying request: {message}"
509 ));
510 return PhaseResult::Retry;
511 }
512 let retried = progress.stream_unknown_outcome_retry_budget.spent();
513 if retried > 0 {
514 let _ = self
515 .send_retry_status(format!(
516 "Retry exhaustion: stream-unknown-outcome stopped after {retried} retries; {reason}"
517 ))
518 .await;
519 }
520 }
521 // #6889: this request is not being re-issued. When the same
522 // model has now failed the same way more than once, say so
523 // and name the way out; the provider's own text stays first.
524 let display_message = match upstream_status {
525 Some(status) => match super::streaming::note_upstream_failure(
526 &mut self.repeated_upstream_failure,
527 &stream_request.model,
528 status,
529 ) {
530 Some(notice) => format!("{display_message}\n{notice}"),
531 None => display_message,
532 },
533 None => {
534 self.repeated_upstream_failure = None;
535 display_message
536 }
537 };
538 envelope.message = display_message.clone();
539 // #6566: no model saw the question. Take it back out of
540 // the session before reporting, so the next request does
541 // not send it twice and a resumed session does not show
542 // it twice; the code tells the host to hand the text back.
543 if envelope.category == ErrorCategory::Authentication
544 && let Some(mark) = turn.unanswered_user_message.take()
545 {
546 match self.retract_child_unsent_message(mark).await {
547 Ok(true) => {
548 envelope.code =
549 codewhale_error_taxonomy::CREDENTIAL_REJECTED_UNSENT_CODE
550 .to_string();
551 self.emit_session_updated().await;
552 }
553 Ok(false) => {}
554 Err(error) => {
555 return PhaseResult::Return((
556 TurnOutcomeStatus::Failed,
557 Some(format!(
558 "{display_message}; unsent child checkpoint failed: {error:#}"
559 )),
560 ));
561 }
562 }
563 }
564 progress.turn_error = Some(display_message);
565 if envelope.severity == codewhale_error_taxonomy::ErrorSeverity::Warning {
566 envelope.severity = codewhale_error_taxonomy::ErrorSeverity::Error;
567 }
568 let _ = self.send_event(Event::error(envelope)).await;
569 return PhaseResult::Return((
570 TurnOutcomeStatus::Failed,
571 progress.turn_error.take(),
572 ));
573 }
574 };
575 let StreamOutcome {
576 current_text_raw,
577 current_text_visible,
578 current_thinking,
579 current_thinking_signature,
580 current_thinking_state,
581 mut completed_thinking,
582 server_blocks,
583 mut tool_uses,
584 usage,
585 usage_reported,
586 accounting,
587 stop_reason,
588 refusal_text,
589 pending_message_complete,
590 last_text_index,
591 stream_errors,
592 steer_preempted,
593 pending_steers,
594 stream_start,
595 first_token_at,
596 request_dispatched_at,
597 stream_error,
598 deferred_unknown_outcome_error,
599 } = self
600 .process_stream(
601 stream,
602 &stream_request,
603 request_dispatched_at,
604 request_receipt,
605 )
606 .await;
607 self.turn_heartbeat.enter(
608 super::turn_heartbeat::TurnPhase::Preparing,
609 None,
610 Some(super::turn_heartbeat::PREPARING_PHASE_BOUND),
611 );
612 if let Some(dispatch) = rlm_dispatch.as_mut() {
613 dispatch
614 .settle(
615 &usage,
616 !steer_preempted && stream_error.is_none() && stream_errors == 0,
617 )
618 .await;
619 }
620 if let Some((envelope, reason)) = deferred_unknown_outcome_error {
621 if !steer_preempted
622 && self.rlm_host.is_none()
623 && self.child_host.is_none()
624 && !self.cancel_token.is_cancelled()
625 && let Some(attempt) = progress.stream_unknown_outcome_retry_budget.authorize()
626 {
627 turn.stop_diagnostics.stream_resumes =
628 turn.stop_diagnostics.stream_resumes.saturating_add(1);
629 let limit = progress.stream_unknown_outcome_retry_budget.limit();
630 let _ = self
631 .send_retry_status(format!(
632 "Retry attempt: stream-unknown-outcome {attempt}/{limit}; {reason}; sending the request again"
633 ))
634 .await;
635 codewhale_runtime::logging::warn(format!(
636 "Provider stream failed before any output (attempt {attempt}/{limit}); {reason}; retrying request"
637 ));
638 return PhaseResult::Retry;
639 }
640 let retried = progress.stream_unknown_outcome_retry_budget.spent();
641 if !steer_preempted
642 && !self.cancel_token.is_cancelled()
643 && self.rlm_host.is_none()
644 && self.child_host.is_none()
645 && retried > 0
646 {
647 let _ = self
648 .send_retry_status(format!(
649 "Retry exhaustion: stream-unknown-outcome stopped after {retried} retries; {reason}"
650 ))
651 .await;
652 }
653 let _ = self.send_stream_event(Event::error(envelope)).await;
654 }
655 let response_stream_failed = steer_preempted || stream_error.is_some();
656 progress.turn_error = progress.turn_error.take().or(stream_error.clone());
657 turn.stop_diagnostics
658 .observe_provider_response(stop_reason.as_deref(), tool_uses.len());
659 // Counts and terminal metadata only: never log messages, tool
660 // arguments, credentials, or raw provider bodies.
661 tracing::debug!(
662 target: "provider_response_diagnostics",
663 model_request = turn.stop_diagnostics.model_requests_started,
664 prepared_output_limit_tokens = stream_request.max_tokens,
665 finish_reason = ?turn.stop_diagnostics.last_provider_finish_reason,
666 reported_usage = usage_reported,
667 input_tokens = usage.input_tokens,
668 output_tokens = usage.output_tokens,
669 cached_input_tokens = ?usage.prompt_cache_hit_tokens,
670 reasoning_tokens = ?usage.reasoning_tokens,
671 decoded_tool_calls = tool_uses.len(),
672 visible_text_chars = current_text_visible.chars().count(),
673 "parent model response settled"
674 );
675 // #6889: a Chat Completions `stop` whose own usage equals the output
676 // ceiling this request asked for was cut at that ceiling. From here
677 // on it is the `length` stop it should have been, so it takes the
678 // one output-limit path below (continue from the partial answer, or
679 // fail by name when there is none) instead of passing for a finished
680 // answer or being re-requested unchanged. The diagnostics above keep
681 // the reason the provider sent.
682 let provider_finish_reason = stop_reason.clone();
683 let stop_reason = if stop_contradicts_output_ceiling(
684 stop_reason.as_deref(),
685 usage_reported.then_some(usage.output_tokens),
686 stream_request.max_tokens,
687 ) {
688 codewhale_runtime::logging::warn(format!(
689 "Provider reported stop reason `stop`, but its usage shows the whole requested output allowance was used ({} tokens, reasoning tokens: {:?}); treating the response as cut at the output limit.",
690 usage.output_tokens, usage.reasoning_tokens
691 ));
692 Some(OUTPUT_CEILING_STOP_REASON.to_string())
693 } else {
694 stop_reason
695 };
696 if let Some(job) = self.child_job() {
697 job.record_activation_provider_stop(stop_reason.as_deref(), response_stream_failed);
698 }
699 // These belong to post-stream response assembly, not stream
700 // consumption: blocks are built from the completed stream state,
701 // and truncation is derived from its terminal stop reason below.
702 let mut content_blocks: Vec<ContentBlock> = Vec::new();
703 let mut output_limit_truncated: Option<String> = None;
704
705 // Account for every provider response before deciding whether to
706 // retry or accept it. A terminal stop reason followed by a
707 // transport error is still a billed, incomplete response; it must
708 // not be discarded and re-issued.
709 if let Some(dispatch) = child_dispatch.as_mut() {
710 dispatch
711 .settle(
712 &usage,
713 !response_stream_failed && !self.cancel_token.is_cancelled(),
714 )
715 .await;
716 }
717 drop(child_dispatch.take());
718 if let Some(job) = child_job.as_ref() {
719 job.response_settled(!response_stream_failed);
720 }
721 turn.add_parent_usage(&usage);
722 turn.note_parent_prompt_len(
723 self.session.messages.len(),
724 crate::compaction::estimate_request_input_tokens(
725 &stream_request.messages,
726 stream_request.system.as_ref(),
727 stream_request.tools.as_deref(),
728 ),
729 );
730 self.session.latest_parent_input_tokens = turn.latest_parent_input_tokens;
731 if usage_reported {
732 let _ = self
733 .send_event(Event::TurnUsage {
734 accounting,
735 max_output_tokens: turn.max_output_tokens.map(|_| stream_request.max_tokens),
736 usage: usage.clone(),
737 duration_ms: u64::try_from(stream_start.elapsed().as_millis())
738 .unwrap_or(u64::MAX),
739 first_token_ms: first_token_at.map(|at| {
740 u64::try_from(
741 at.saturating_duration_since(request_dispatched_at)
742 .as_millis(),
743 )
744 .unwrap_or(u64::MAX)
745 }),
746 request_ms: Some(
747 u64::try_from(request_dispatched_at.elapsed().as_millis())
748 .unwrap_or(u64::MAX),
749 ),
750 finish_reason: provider_finish_reason,
751 })
752 .await;
753 }
754
755 if steer_preempted {
756 self.add_interrupted_assistant_text(&current_text_visible)
757 .await;
758 return self
759 .resume_after_model_steer(turn, progress, pending_steers, true)
760 .await;
761 }
762
763 if response_stream_failed && let Some(state) = self.child_host.as_mut() {
764 state.request_stop_reason = Some("request_outcome_unknown");
765 }
766
767 if let Some(state) = self.rlm_host.as_mut() {
768 state.usage.record_nested_event(serde_json::json!({"run_id": state.run_id, "depth_remaining": match state.mode { rlm_host::RlmMode::Completion => 0, rlm_host::RlmMode::Recursive { depth_remaining } => depth_remaining }, "kind":"code", "content":current_text_visible})).await;
769 if is_incomplete_stop_reason(stop_reason.as_deref())
770 || stream_error.is_some()
771 || stream_errors > 0
772 || !tool_uses.is_empty()
773 {
774 let error = if !tool_uses.is_empty() {
775 "RLM provider emitted a structured tool call outside its pure Python surface"
776 .to_string()
777 } else {
778 format!(
779 "Model response incomplete: {}",
780 stream_error
781 .as_deref()
782 .unwrap_or_else(|| stop_reason_detail(stop_reason.as_deref()))
783 )
784 };
785 self.add_interrupted_assistant_text(&current_text_visible)
786 .await;
787 return PhaseResult::Return((TurnOutcomeStatus::Failed, Some(error)));
788 }
789 // Rejected fragments remain in the interrupted Session/code receipt,
790 // but cannot replace the last admitted answer or execute FINAL/REPL.
791 state.last_response = current_text_visible.clone();
792 }
793 if !response_stream_failed {
794 progress.child_request_retries = Default::default();
795 }
796
797 // The injected Child transport owns its response grammar, including
798 // an explicitly configured Custom wire or an approved replacement.
799 let protocol = self
800 .child_request_protocol()
801 .or_else(|| {
802 self.active_route_endpoint
803 .as_ref()
804 .map(|endpoint| endpoint.protocol)
805 })
806 .unwrap_or(codewhale_config::provider::WireFormat::ChatCompletions);
807 // No tool observation or replayable tool history is published before
808 // this whole-response admission. Usage and visible text remain real.
809 if let Err(error) = crate::client::validate_tool_call_ids_for_protocol(
810 protocol,
811 tool_uses.iter().map(|tool| tool.id.as_str()),
812 ) {
813 self.add_interrupted_assistant_text(&current_text_visible)
814 .await;
815 return PhaseResult::Return((TurnOutcomeStatus::Failed, Some(error.to_string())));
816 }
817
818 if self.cancel_token.is_cancelled() {
819 let _ = self.send_event(Event::status("Request cancelled")).await;
820 self.add_interrupted_assistant_text(&current_text_visible)
821 .await;
822 return PhaseResult::Return((TurnOutcomeStatus::Interrupted, None));
823 }
824
825 let retry_empty_child_output = self.child_host.is_some()
826 && self.config.reasoning_only_on_output_limit
827 && is_output_limit_stop_reason(stop_reason.as_deref())
828 && current_text_visible.trim().is_empty()
829 && stream_errors == 0
830 && progress.reasoning_only_reprompts < self.config.reasoning_only_max_reprompts
831 && should_fail_no_sendable_content(
832 tool_uses.is_empty(),
833 progress.turn_error.is_none(),
834 self.cancel_token.is_cancelled(),
835 !pending_steers.is_empty(),
836 false,
837 );
838 if is_incomplete_stop_reason(stop_reason.as_deref()) && !retry_empty_child_output {
839 let reason = stop_reason_detail(stop_reason.as_deref());
840 if self.child_host.is_none()
841 && is_output_limit_stop_reason(stop_reason.as_deref())
842 && stream_errors == 0
843 {
844 // Degrade, don't kill the turn — but only when the stream
845 // finished cleanly. A `max_tokens` stop followed by a
846 // transport error is a billed incomplete response: charge
847 // it and fail closed instead of continuing into a second
848 // request. A generation limit on a complete stream is a
849 // normal provider outcome, not an unrecoverable error:
850 // accept whatever complete tool call or content was
851 // produced and continue. The truncation is surfaced as a
852 // bounded observation after the partial assistant message
853 // is committed (and, for a tool-call response, after the
854 // tool result is appended) so the transcript stays
855 // well-formed.
856 codewhale_runtime::logging::warn(format!(
857 "Model output truncated: provider stop reason `{reason}`; accepting partial response and continuing the turn."
858 ));
859 output_limit_truncated = Some(reason.to_string());
860 // Fall through to the normal content/tool dispatch below.
861 } else {
862 self.settle_unadmitted_tool_calls(&tool_uses, &incomplete_tool_result(reason))
863 .await;
864 if codewhale_models::is_refusal_stop_reason(stop_reason.as_deref()) {
865 let _ = self
866 .send_event(Event::ContentFilterRefusal {
867 reason: reason.to_string(),
868 refusal: refusal_text.clone(),
869 })
870 .await;
871 } else {
872 self.add_interrupted_assistant_text(&current_text_visible)
873 .await;
874 }
875 let error = if self.child_host.is_some() {
876 crate::tools::subagent::incomplete_subagent_response_failure(
877 stop_reason.as_deref(),
878 )
879 } else {
880 format!(
881 "Model response incomplete: provider stop reason `{reason}`; no complete response or tool call was accepted."
882 )
883 };
884 codewhale_runtime::logging::warn(&error);
885 return PhaseResult::Return((TurnOutcomeStatus::Failed, Some(error)));
886 }
887 }
888
889 if stream_errors == 0 {
890 progress.stream_retry_budget.reset();
891 let unknown_outcome_retries = progress.stream_unknown_outcome_retry_budget.spent();
892 if unknown_outcome_retries > 0 {
893 progress.stream_unknown_outcome_retry_budget.reset();
894 let _ = self
895 .send_retry_status(format!(
896 "Retry recovery: stream-unknown-outcome recovered after {unknown_outcome_retries} retries"
897 ))
898 .await;
899 }
900 }
901
902 let mut final_text = current_text_visible.clone();
903 if tool_uses.is_empty() && tool_parser::has_tool_call_markers(&current_text_raw) {
904 let parsed = tool_parser::parse_tool_calls(&current_text_raw);
905 if parsed.tool_calls.len() > super::streaming::MAX_TOOL_CALLS_PER_RESPONSE {
906 let envelope = super::streaming::tool_call_limit_error();
907 let error = envelope.message.clone();
908 turn.stop_diagnostics.last_response_tool_calls_suppressed =
909 Some(parsed.tool_calls.len());
910 let _ = self.send_stream_event(Event::error(envelope)).await;
911 self.add_interrupted_assistant_text(&current_text_visible)
912 .await;
913 return PhaseResult::Return((TurnOutcomeStatus::Failed, Some(error)));
914 }
915 final_text = parsed.clean_text;
916 for call in parsed.tool_calls {
917 tool_uses.push(ToolUseState {
918 execution_id: self.new_tool_execution_id(),
919 id: call.id,
920 name: call.name,
921 input: call.args,
922 caller: None,
923 thought_signature: None,
924 input_buffer: String::new(),
925 input_parse_error: None,
926 });
927 }
928 if let Err(error) = crate::client::validate_tool_call_ids_for_protocol(
929 protocol,
930 tool_uses.iter().map(|tool| tool.id.as_str()),
931 ) {
932 self.add_interrupted_assistant_text(&current_text_visible)
933 .await;
934 return PhaseResult::Return((TurnOutcomeStatus::Failed, Some(error.to_string())));
935 }
936 }
937
938 // C02-05: the one admission authority for a failed stream. Calls
939 // collected before the failure are announced with an explicit
940 // not-executed result and never reach planning, approval or a
941 // handler; the visible text is kept as an interrupted fragment
942 // and no tool_use enters history, so the transcript stays paired.
943 if response_stream_failed && !tool_uses.is_empty() {
944 let error = progress
945 .turn_error
946 .clone()
947 .unwrap_or_else(|| "provider stream failed".to_string());
948 self.settle_unadmitted_tool_calls(
949 &tool_uses,
950 &stream_failed_tool_result(&summarize_text(&error, 200)),
951 )
952 .await;
953 self.add_interrupted_assistant_text(&current_text_visible)
954 .await;
955 turn.stop_diagnostics.last_response_tool_calls_suppressed = Some(tool_uses.len());
956 return PhaseResult::Return((TurnOutcomeStatus::Failed, Some(error)));
957 }
958
959 for tool in &tool_uses {
960 let _ = self
961 .send_event(Event::ToolCallStarted {
962 id: tool.execution_id.clone(),
963 model_call: Some(tool.model_call()),
964 name: tool.name.clone(),
965 input: final_tool_input(tool),
966 })
967 .await;
968 }
969
970 // Persist only reasoning the provider actually emitted. Some chat
971 // wires require a non-empty `reasoning_content` field when an
972 // assistant message carries tool calls; the route serializer adds
973 // that compatibility value to the outgoing JSON only. Persisting
974 // it here leaked an invented "(reasoning omitted)" block into the
975 // transcript and every provider-neutral session replay.
976 // `completed_thinking` holds every thinking/redacted block the
977 // stream already terminated, in wire order; the guard below keeps
978 // a trailing block whose stop event never arrived. Both must
979 // survive — Anthropic replays the whole thinking sequence
980 // unmodified.
981 content_blocks.append(&mut completed_thinking);
982 let thinking_is_placeholder_only =
983 crate::client::is_reasoning_replay_placeholder(&current_thinking);
984 if (!current_thinking.is_empty() && !thinking_is_placeholder_only)
985 || current_thinking_state.is_some()
986 {
987 content_blocks.push(ContentBlock::Thinking {
988 thinking: current_thinking.clone(),
989 signature: current_thinking_signature.clone(),
990 state: current_thinking_state.clone(),
991 redacted_data: None,
992 });
993 }
994
995 // A worker may cooperate with the strategy notice by immediately
996 // reporting its blocker. No intervening useful work means that
997 // report must not become a false Completed result.
998 let fleet_no_progress_report = fleet_report_response
999 || tool_uses.is_empty()
1000 && progress
1001 .fleet_denial_guard
1002 .as_ref()
1003 .is_some_and(FleetDenialGuard::awaiting_strategy_change);
1004
1005 // A protocol-level tool stop promises a call, unlike ordinary
1006 // text that merely describes an intended action. Keep that
1007 // distinction factual; never synthesize a tool or another request.
1008 if tool_uses.is_empty()
1009 && !fleet_no_progress_report
1010 && progress.turn_error.is_none()
1011 && matches!(stop_reason.as_deref(), Some("tool_calls" | "tool_use"))
1012 {
1013 turn.stop_diagnostics.reason = Some(TurnStopReason::ProviderToolCallMissing);
1014 turn.stop_diagnostics.last_response_tool_calls_suppressed = Some(0);
1015 self.add_interrupted_assistant_text(&current_text_visible)
1016 .await;
1017 let reason = stop_reason.as_deref().expect("matched tool stop");
1018 return PhaseResult::Return((
1019 TurnOutcomeStatus::Failed,
1020 Some(
1021 codewhale_localization::tr(
1022 codewhale_localization::resolve_locale(&self.config.locale_tag),
1023 codewhale_localization::MessageId::ProviderToolCallMissing,
1024 )
1025 .replace("{reason}", reason),
1026 ),
1027 ));
1028 }
1029
1030 for tool in &mut tool_uses {
1031 let Some(schema) = progress
1032 .tool_catalog
1033 .iter()
1034 .find(|candidate| candidate.name == tool.name)
1035 .map(|candidate| &candidate.input_schema)
1036 else {
1037 continue;
1038 };
1039 normalize_schema_json_containers(&mut tool.input, schema);
1040 }
1041
1042 // A zero-tool turn (plain `exec`) has no tool channel, yet a model
1043 // can still answer with nothing but a tool call written as text
1044 // (DeepSeek's DSML). The stream filter strips the markup and leaves
1045 // at most whitespace, which is not an answer: persisting it would
1046 // end the run "successfully" on a blank line, and re-requesting
1047 // only reproduces the call. It is failed once below, by name.
1048 let zero_tool_text_call = zero_tool_turn
1049 && tool_uses.is_empty()
1050 && final_text.trim().is_empty()
1051 && contains_fake_tool_wrapper(&current_text_raw);
1052 if !final_text.is_empty() && !zero_tool_text_call {
1053 content_blocks.push(ContentBlock::Text {
1054 text: final_text,
1055 cache_control: None,
1056 });
1057 }
1058 content_blocks.extend(server_blocks);
1059 for tool in &tool_uses {
1060 content_blocks.push(ContentBlock::ToolUse {
1061 execution_id: Some(tool.execution_id.clone()),
1062 id: tool.id.clone(),
1063 name: tool.name.clone(),
1064 input: tool.input.clone(),
1065 caller: tool.caller.clone(),
1066 thought_signature: tool.thought_signature.clone(),
1067 });
1068 }
1069
1070 if pending_message_complete && !response_stream_failed {
1071 let index = last_text_index.unwrap_or(0);
1072 let _ = self.send_event(Event::MessageComplete { index }).await;
1073 }
1074
1075 // RLM is a structured tool call (`rlm_query`) handled by the
1076 // normal tool dispatch path; a ```repl fence in prose is never
1077 // executed outside an RLM host turn.
1078 // DeepSeek chat API rejects assistant messages that contain only
1079 // Keep thinking for UI stream events, but persist only sendable
1080 // assistant turns in the conversation state.
1081 let has_sendable_assistant_content = content_blocks.iter().any(|block| match block {
1082 ContentBlock::Text { text, .. } => !text.trim().is_empty(),
1083 ContentBlock::ToolUse { .. } => true,
1084 _ => false,
1085 });
1086 let has_provider_reasoning = content_blocks.iter().any(|block| {
1087 matches!(
1088 block,
1089 ContentBlock::Thinking {
1090 thinking,
1091 state,
1092 redacted_data,
1093 ..
1094 } if !thinking.trim().is_empty() || state.is_some() || redacted_data.is_some()
1095 )
1096 });
1097
1098 // Issue #1727: did this turn produce ONLY a reasoning/thinking
1099 // block — empty content, no tool calls (e.g. gpt-oss via ollama's
1100 // harmony→OpenAI shim mapping to `reasoning_content`)? We do NOT
1101 // surface anything here: after this point the same turn can still
1102 // CONTINUE for pending steers (~below) or sub-agent completions,
1103 // and emitting now would show a spurious "turn ended" notice right
1104 // before the turn resumes. Capture the fact and decide later, at
1105 // the point the turn is certain to be finishing with no sendable
1106 // content (see the `tool_uses.is_empty()` tail).
1107 let no_sendable_assistant_content = !has_sendable_assistant_content;
1108
1109 // Add assistant message to session
1110 if has_sendable_assistant_content {
1111 self.add_session_message(Message {
1112 role: if response_stream_failed {
1113 Role::InterruptedAssistant
1114 } else {
1115 Role::Assistant
1116 },
1117 content: content_blocks,
1118 })
1119 .await;
1120 }
1121
1122 // C02-05: a failed stream that carried no tool call keeps its text
1123 // (above) and ends the turn with the stream's error. It never
1124 // runs a ```repl fence from the failed text, and never authorizes
1125 // another request for an output-limit continuation, a steer, a
1126 // sub-agent completion or a goal continuation.
1127 if response_stream_failed {
1128 return PhaseResult::Break;
1129 }
1130
1131 PhaseResult::Ready(AcceptedModelStep {
1132 current_text_visible,
1133 tool_uses,
1134 pending_steers,
1135 output_limit_truncated,
1136 zero_tool_turn,
1137 zero_tool_text_call,
1138 fleet_report_response,
1139 fleet_no_progress_report,
1140 has_sendable_assistant_content,
1141 has_provider_reasoning,
1142 no_sendable_assistant_content,
1143 stop_reason,
1144 stream_errors,
1145 prepared_output_tokens: stream_request.max_tokens,
1146 })
1147 }
1148 async fn resume_after_model_steer(
1149 &mut self,
1150 turn: &mut TurnContext,
1151 progress: &mut TurnLoopProgress,
1152 mut pending_steers: Vec<handle::PendingSteer>,
1153 request_started: bool,
1154 ) -> PhaseResult<AcceptedModelStep> {
1155 while let Some(pending) = self.next_turn_steer() {
1156 if pending.content.trim().is_empty() {
1157 continue;
1158 }
1159 if pending.replace_pending {
1160 pending_steers.clear();
1161 }
1162 pending_steers.push(pending);
1163 }
1164 if self.cancel_token.is_cancelled() {
1165 return PhaseResult::Return((TurnOutcomeStatus::Interrupted, None));
1166 }
1167 for pending in pending_steers {
1168 if self.cancel_token.is_cancelled() {
1169 return PhaseResult::Return((TurnOutcomeStatus::Interrupted, None));
1170 }
1171 let steer = pending.content.trim().to_string();
1172 self.session
1173 .working_set
1174 .observe_user_message(&steer, &self.session.workspace);
1175 self.add_session_message(self.user_text_message_with_turn_metadata(steer))
1176 .await;
1177 let (_text, person_text) = self.commit_pending_steer_with_intent(pending);
1178 if let Some(person_text) = person_text {
1179 let index = self.session.messages.len().saturating_sub(1);
1180 self.session.record_person_message(person_text, Some(index));
1181 }
1182 }
1183 if let Some(guard) = progress.fleet_denial_guard.as_mut() {
1184 guard.reset();
1185 turn.stop_diagnostics
1186 .permission_denial_rounds_without_progress = 0;
1187 }
1188 progress.turn_error = None;
1189 let _ = self
1190 .send_event(Event::status("Continuing — queued steer input"))
1191 .await;
1192 if request_started {
1193 turn.next_step();
1194 }
1195 PhaseResult::Retry
1196 }
1197
1198 async fn resend_without_images(
1199 &mut self,
1200 progress: &mut TurnLoopProgress,
1201 ) -> PhaseResult<AcceptedModelStep> {
1202 progress.image_rejection_recovered = true;
1203 // This path tells the user itself; the resend must
1204 // not announce the same omission a second time.
1205 progress.image_omission_notified = true;
1206 self.active_route_capabilities.image_input = CapabilityState::Unsupported;
1207 codewhale_runtime::logging::warn(format!(
1208 "model {} rejected image content; resending with images replaced by text",
1209 self.session.model
1210 ));
1211 let status = codewhale_localization::tr(
1212 codewhale_localization::resolve_locale(&self.config.locale_tag),
1213 codewhale_localization::MessageId::ImageInputRejectedResent,
1214 )
1215 .replace("{model}", &self.session.model);
1216 let _ = self.send_event(Event::status(status)).await;
1217 PhaseResult::Retry
1218 }
1219
1220 async fn recover_image_count_rejection(
1221 &mut self,
1222 progress: &mut TurnLoopProgress,
1223 request: &codewhale_models::MessageRequest,
1224 rejection: crate::llm_client::ImageCountRejection,
1225 error: &anyhow::Error,
1226 ) -> Option<PhaseResult<AcceptedModelStep>> {
1227 let sent = codewhale_models::image_window::count_request_images(&request.messages);
1228 let model = self.session.model.clone();
1229 let cap = self.learn_image_cap(&model, sent, rejection)?;
1230 if cap == 0 {
1231 if self.active_route_capabilities.image_input != CapabilityState::Unsupported
1232 && !progress.image_rejection_recovered
1233 {
1234 return Some(self.resend_without_images(progress).await);
1235 }
1236 } else if progress.image_count_recoveries < MAX_IMAGE_COUNT_RECOVERIES {
1237 progress.image_count_recoveries = progress.image_count_recoveries.saturating_add(1);
1238 return Some(PhaseResult::Retry);
1239 }
1240 let hint = codewhale_localization::tr(
1241 codewhale_localization::resolve_locale(&self.config.locale_tag),
1242 codewhale_localization::MessageId::ImageCountRejected,
1243 )
1244 .replace("{model}", &model)
1245 .replace("{count}", &sent.to_string());
1246 let detail = self.decorate_auth_error_message(initial_stream_error_user_message(
1247 &self.config.locale_tag,
1248 error,
1249 ));
1250 let display_message = format!("{hint}\n{detail}");
1251 progress.turn_error = Some(display_message.clone());
1252 let _ = self
1253 .send_event(Event::error(
1254 codewhale_error_taxonomy::ErrorEnvelope::image_count_exceeded(display_message),
1255 ))
1256 .await;
1257 Some(PhaseResult::Return((
1258 TurnOutcomeStatus::Failed,
1259 progress.turn_error.take(),
1260 )))
1261 }
1262
1263 async fn recover_child_request(
1264 &mut self,
1265 progress: &mut TurnLoopProgress,
1266 error: &anyhow::Error,
1267 ) -> Option<PhaseResult<AcceptedModelStep>> {
1268 use crate::tools::subagent::engine::ChildRequestRecovery;
1269 let job = self.child_job()?;
1270 let decision = progress
1271 .child_request_retries
1272 .decide(&job.authority.runtime, error)?;
1273 match decision {
1274 ChildRequestRecovery::Interrupted {
1275 checkpoint_reason,
1276 message,
1277 } => {
1278 self.child_host
1279 .as_mut()
1280 .expect("captured child recovery")
1281 .request_stop_reason = Some(checkpoint_reason);
1282 Some(PhaseResult::Return((
1283 TurnOutcomeStatus::Interrupted,
1284 Some(
1285 job.authority
1286 .runtime
1287 .client
1288 .redact_model_bound_text(&message),
1289 ),
1290 )))
1291 }
1292 ChildRequestRecovery::Retry { delay, note } => {
1293 let _ = self
1294 .send_event(Event::status(
1295 job.authority.runtime.client.redact_model_bound_text(&note),
1296 ))
1297 .await;
1298 tokio::select! {
1299 biased;
1300 () = self.cancel_token.cancelled() => Some(PhaseResult::Return((TurnOutcomeStatus::Interrupted, None))),
1301 () = job.authority.runtime.cancel_token.cancelled() => Some(PhaseResult::Return((TurnOutcomeStatus::Interrupted, None))),
1302 () = tokio::time::sleep(delay) => {
1303 progress.turn_error = None;
1304 Some(PhaseResult::Retry)
1305 }
1306 }
1307 }
1308 }
1309 }
1310 }
1311
1311 lines RUST