返回 CodeWhale
turn_route_plan.rs
根目录 / crates / engine / src / turn_route_plan.rs
1 //! The single shared turn-route planner (#1004).
2 //!
3 //! One function decides which provider, model, route identity, client, limits,
4 //! compaction policy, and reasoning tier a turn will use.
5 //! `spawned_dispatch_inner` calls it to *send* a turn; `/preview-request`
6 //! calls it with a hypothetical prompt to *describe* one. Because there is a
7 //! single implementation, a preview cannot report a route different from the
8 //! one dispatch would pick for the same prompt — which is the whole point of
9 //! previewing a route before spending anything on it.
10 //!
11 //! It lives outside the TUI module so the engine-side preview tests can drive
12 //! the same planner the UI drives, provider-free.
13 //!
14 //! The planner mutates no engine or session state. Its one outbound call is
15 //! the auto-router classifier, which only runs when auto model routing is on.
16 //! Production may use the deterministic response cache for that call;
17 //! `/preview-request` explicitly bypasses it so inspection does not perturb
18 //! later routing.
19
20 use crate::compaction::CompactionConfig;
21 use crate::reasoning_preference::ReasoningEffort;
22 use crate::route_runtime::{ResolvedRuntimeRoute, resolve_runtime_route_for_identity};
23 use codewhale_config::AppMode;
24 use codewhale_config::ProviderKind;
25 use codewhale_runtime::config::{Config, ProviderIdentity};
26
27 /// Everything the shared turn-route planner needs.
28 ///
29 /// Borrowed rather than owned so the dispatch path can pass its already
30 /// captured `UserDispatchPrepare` fields and `/preview-request` can pass a
31 /// hypothetical prompt, without either one duplicating the other's logic.
32 pub struct TurnRoutePlanRequest<'a> {
33 pub accounting_origin: Option<crate::cost_status::NativeUsageOrigin>,
34 pub route_config: &'a Config,
35 pub app_route_identity: &'a ProviderIdentity,
36 pub api_provider: ProviderKind,
37 pub app_model: &'a str,
38 pub auto_model: bool,
39 pub reasoning_effort: ReasoningEffort,
40 pub mode: AppMode,
41 /// Model-facing content of the next user message (file mentions and skill
42 /// wrapping already resolved). This is what the auto router classifies.
43 pub content: &'a str,
44 pub auto_router_context: &'a str,
45 pub should_auto_resolve: bool,
46 /// Production dispatch may use the deterministic response cache for the
47 /// auxiliary Auto classifier. Read-only previews must set this to false.
48 pub allow_auto_router_response_cache: bool,
49 pub preflight_required: bool,
50 pub auto_compact_user_configured: bool,
51 pub auto_compact: bool,
52 pub auto_compact_threshold_percent: f64,
53 }
54
55 /// The exact route, limits, compaction policy, and reasoning normalization one
56 /// turn would use.
57 pub struct PlannedTurnRoute {
58 pub route: ResolvedRuntimeRoute,
59 pub compaction: CompactionConfig,
60 pub effective_provider: ProviderKind,
61 pub effective_model: String,
62 pub effective_provider_identity: String,
63 pub effective_provider_label: String,
64 pub selected_reasoning_effort: Option<ReasoningEffort>,
65 /// Normalized api value for the resolved route — the string that reaches
66 /// the wire.
67 pub effective_reasoning_effort: Option<String>,
68 pub auto_controls_reasoning: bool,
69 pub auto_selection: Option<crate::model_routing::AutoRouteSelection>,
70 /// Bounded auxiliary classifier usage that must enter the accepted turn
71 /// under its own frozen routes. It is moved out of `auto_selection` so a
72 /// UI-only receipt consumer cannot accidentally become the accounting
73 /// owner or price it under the parent route.
74 pub initial_routed_usage: crate::cost_status::RuntimeUsageBatch,
75 /// Why this concrete route was selected. This is captured by the planner,
76 /// not inferred later from the resulting provider/model pair.
77 pub routing_source: TurnRoutingSource,
78 }
79
80 /// Durable provenance for the route selected for one turn.
81 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
82 pub enum TurnRoutingSource {
83 /// The active fixed route was used unchanged. This intentionally does not
84 /// guess whether an earlier UI action or persisted config installed it.
85 ActiveFixedRoute,
86 /// Auto model routing used its provider-backed classifier.
87 AutoProviderClassifier,
88 /// Auto model routing fell back to the local declared default (no
89 /// classifier signal; request wording never inspected).
90 AutoLocalFallback,
91 }
92
93 impl TurnRoutingSource {
94 pub const fn label(self) -> &'static str {
95 match self {
96 Self::ActiveFixedRoute => "active-fixed-route",
97 Self::AutoProviderClassifier => "auto-provider-classifier",
98 Self::AutoLocalFallback => "auto-local-fallback",
99 }
100 }
101 }
102
103 fn reasoning_effort_for_route_selection(
104 auto_model: bool,
105 provider: ProviderKind,
106 effort: ReasoningEffort,
107 ) -> &'static str {
108 if auto_model {
109 effort.as_setting()
110 } else {
111 effort.as_setting_for_provider(provider)
112 }
113 }
114
115 /// Settle the classifier usage of a turn whose route then failed, into the
116 /// cost scope that was current when the classifier call was made. A fresh
117 /// token taken here would bill it to whatever session is current by now:
118 /// after a `/new` or session load during the call, a different one.
119 fn settle_failed_parent_route(
120 cost_scope: crate::cost_status::CostScopeToken,
121 error: String,
122 initial_routed_usage: &crate::cost_status::RuntimeUsageBatch,
123 ) -> String {
124 crate::cost_status::record_runtime_usage_batch(cost_scope, None, initial_routed_usage);
125 error
126 }
127
128 /// Resolve the route for one turn.
129 ///
130 /// This is *the* route planner (#1004). `spawned_dispatch_inner` calls it to
131 /// send a turn; `/preview-request` calls it with a hypothetical prompt to
132 /// describe one. Because there is a single implementation, a preview cannot
133 /// report a provider, model, route identity, client, reasoning tier, limit,
134 /// tool budget, billing basis, or endpoint different from the one dispatch
135 /// would pick for the same prompt.
136 ///
137 /// It mutates no engine or session state: it reads config, resolves a route,
138 /// and returns a value. Its one outbound call is the auto-router classifier,
139 /// which is the same auxiliary call a real turn makes and only runs when auto
140 /// model routing is on. The caller chooses whether that auxiliary call may
141 /// touch the process-global deterministic response cache.
142 pub async fn plan_turn_route(
143 request: TurnRoutePlanRequest<'_>,
144 ) -> Result<PlannedTurnRoute, String> {
145 // Taken before the classifier call so its usage settles into the scope
146 // it was spent in, not the one current when a failure is noticed.
147 let cost_scope = crate::cost_status::scope_token();
148 let mut auto_selection = if request.should_auto_resolve {
149 Some(
150 crate::model_routing::resolve_auto_route_with_inventory_for_session_and_cache_policy(
151 request.route_config,
152 request.content,
153 request.auto_router_context,
154 request.mode.as_setting(),
155 if request.auto_model { "auto" } else { "fixed" },
156 reasoning_effort_for_route_selection(
157 request.auto_model,
158 request.api_provider,
159 request.reasoning_effort,
160 ),
161 request.allow_auto_router_response_cache,
162 request.accounting_origin.clone().map(|origin| {
163 crate::cost_status::NativeUsageSource::capture_with_origin(
164 format!("auto-router:{}", uuid::Uuid::new_v4()),
165 crate::cost_status::UsageSpendOwner::Auxiliary,
166 Some(origin),
167 )
168 }),
169 )
170 .await
171 .map_err(|err| err.to_string())?,
172 )
173 } else {
174 None
175 };
176
177 // Move classifier accounting out immediately. Every later parent-route
178 // failure must settle this already-incurred auxiliary call instead of
179 // returning an error that silently drops its exact quote/usage.
180 let initial_routed_usage = auto_selection
181 .as_mut()
182 .map(|selection| crate::cost_status::RuntimeUsageBatch {
183 decisions: Vec::new(),
184 records: std::mem::take(&mut selection.routed_usage),
185 drop_records: std::mem::take(&mut selection.routed_usage_drop_records),
186 dropped_records: std::mem::take(&mut selection.routed_usage_dropped_records),
187 })
188 .unwrap_or_default();
189
190 let selected_identity = auto_selection
191 .as_ref()
192 .map_or(request.app_route_identity, |selection| &selection.provider);
193 let effective_provider = selected_identity.provider;
194
195 // Without an Auto selection there is no per-request signal, so the
196 // route is the configured model — the same declared default the local
197 // fallback uses. Request wording is never inspected (#6290 rework).
198 let selected_model = if request.auto_model {
199 auto_selection
200 .as_ref()
201 .map(|selection| selection.model.clone())
202 .unwrap_or_else(|| request.app_model.to_string())
203 } else {
204 request.app_model.to_string()
205 };
206
207 let turn_route = resolve_runtime_route_for_identity(
208 request.route_config,
209 selected_identity,
210 Some(&selected_model),
211 );
212
213 let turn_route = match turn_route {
214 Ok(route) => route,
215 Err(err) => {
216 return Err(settle_failed_parent_route(
217 cost_scope,
218 err.to_string(),
219 &initial_routed_usage,
220 ));
221 }
222 };
223 let turn_route = if request.preflight_required {
224 match turn_route.preflight_async().await {
225 Ok(route) => route,
226 Err(err) => {
227 return Err(settle_failed_parent_route(
228 cost_scope,
229 err,
230 &initial_routed_usage,
231 ));
232 }
233 }
234 } else {
235 turn_route
236 };
237
238 let turn_route_limits = crate::route_budget::known_route_limits(turn_route.candidate.limits());
239 let effective_provider_identity = turn_route.identity.key.to_string();
240 let effective_provider_label = if effective_provider == ProviderKind::Custom {
241 effective_provider_identity.clone()
242 } else {
243 turn_route
244 .identity
245 .compatibility()
246 .map_or(effective_provider.as_str(), |row| row.label)
247 .to_string()
248 };
249
250 let turn_compaction = CompactionConfig {
251 enabled: if request.auto_compact_user_configured {
252 request.auto_compact
253 } else {
254 crate::route_budget::auto_compact_default_for_route(
255 turn_route.identity.provider,
256 &turn_route.model,
257 turn_route_limits,
258 )
259 },
260 token_threshold: crate::route_budget::compaction_threshold_for_route_at_percent_with_window(
261 turn_route.identity.provider,
262 &turn_route.model,
263 turn_route_limits,
264 Some(turn_route.context_window.tokens),
265 request.auto_compact_threshold_percent,
266 ),
267 model: turn_route.model.clone(),
268 image_input: turn_route.candidate.capabilities().image_input,
269 effective_context_window: Some(turn_route.context_window.tokens),
270 summary_instructions: request.route_config.compaction_summary_instructions(),
271 retained_user_message_tokens: request
272 .route_config
273 .compaction_retained_user_message_tokens(),
274 ..Default::default()
275 };
276
277 // Model selection and reasoning selection are independent. A fixed
278 // reasoning preference survives auto model routing and is normalized
279 // against the concrete route below; only an explicit `auto` delegates the
280 // tier to the classifier/declared fallback.
281 let auto_controls_reasoning = request.reasoning_effort == ReasoningEffort::Auto;
282 let selected_reasoning_effort = if auto_controls_reasoning {
283 Some(
284 auto_selection
285 .as_ref()
286 .and_then(|selection| selection.reasoning_effort)
287 .unwrap_or_else(crate::auto_reasoning::select),
288 )
289 } else {
290 None
291 };
292
293 let effective_reasoning_effort = selected_reasoning_effort
294 .unwrap_or(request.reasoning_effort)
295 .normalize_for_route_identity(
296 effective_provider,
297 turn_route.identity.key.as_str(),
298 &turn_route.candidate.endpoint().base_url,
299 &turn_route.model,
300 )
301 .api_value_for_provider(effective_provider)
302 .map(str::to_string);
303
304 let routing_source = if !request.auto_model {
305 TurnRoutingSource::ActiveFixedRoute
306 } else if auto_selection.is_some() {
307 TurnRoutingSource::AutoProviderClassifier
308 } else {
309 TurnRoutingSource::AutoLocalFallback
310 };
311
312 Ok(PlannedTurnRoute {
313 effective_model: turn_route.model.clone(),
314 route: turn_route,
315 compaction: turn_compaction,
316 effective_provider,
317 effective_provider_identity,
318 effective_provider_label,
319 selected_reasoning_effort,
320 effective_reasoning_effort,
321 auto_controls_reasoning,
322 auto_selection,
323 initial_routed_usage,
324 routing_source,
325 })
326 }
327
328 #[cfg(test)]
329 mod tests {
330 use super::*;
331 use codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL;
332
333 fn deepseek_identity() -> ProviderIdentity {
334 codewhale_runtime::config::Config::default()
335 .builtin_provider_identity(ProviderKind::Deepseek)
336 .unwrap()
337 }
338
339 #[test]
340 fn failed_parent_route_settles_classifier_batch_once() {
341 let _cost_scope = crate::cost_status::test_scope();
342 let route = crate::cost_status::EffectiveRouteEnvelope::capture(
343 None,
344 ProviderKind::Deepseek,
345 "deepseek",
346 "classifier-model",
347 Some(ProviderKind::Deepseek.provider().default_base_url()),
348 chrono::Utc::now(),
349 );
350 let batch = crate::cost_status::RuntimeUsageBatch {
351 decisions: Vec::new(),
352 records: vec![crate::cost_status::RuntimeUsageRecord::legacy(
353 "auto-router:plan-usage".to_string(),
354 crate::cost_status::EffectiveRouteUsage {
355 route: route.clone(),
356 usage: codewhale_models::Usage {
357 input_tokens: 4,
358 output_tokens: 2,
359 ..Default::default()
360 },
361 },
362 )],
363 drop_records: vec![crate::cost_status::RuntimeUsageDropRecord {
364 reason: crate::cost_status::RuntimeUsageMissingReason::default(),
365 source_id: "auto-router:plan-drop".to_string(),
366 route,
367 }],
368 dropped_records: 1,
369 };
370
371 let scope = crate::cost_status::scope_token();
372 assert_eq!(
373 settle_failed_parent_route(scope, "route failed".to_string(), &batch),
374 "route failed"
375 );
376 settle_failed_parent_route(scope, "route failed".to_string(), &batch);
377 let pending = crate::cost_status::drain();
378 assert_eq!(
379 pending.usage_source_fingerprints.len(),
380 2,
381 "both exact classifier outcomes persist, and replay is idempotent"
382 );
383
384 // The classifier ran in one session; `/new` closed it before the
385 // route failed. Its cost belongs to the closed session, never the new.
386 let spent_in = crate::cost_status::scope_token();
387 let _closed = crate::cost_status::close_current_scope();
388 let batch = crate::cost_status::RuntimeUsageBatch {
389 decisions: Vec::new(),
390 records: batch
391 .records
392 .iter()
393 .cloned()
394 .map(|mut record| {
395 record.source_id = "auto-router:plan-usage-after-new".to_string();
396 record
397 })
398 .collect(),
399 drop_records: Vec::new(),
400 dropped_records: 0,
401 };
402 settle_failed_parent_route(spent_in, "route failed".to_string(), &batch);
403 assert!(
404 crate::cost_status::drain()
405 .usage_source_fingerprints
406 .is_empty(),
407 "classifier cost leaked into the session opened after it was spent"
408 );
409 }
410
411 #[test]
412 fn auto_model_route_selection_keeps_raw_reasoning_preference() {
413 assert_eq!(
414 reasoning_effort_for_route_selection(
415 true,
416 ProviderKind::OpenaiCodex,
417 ReasoningEffort::Off,
418 ),
419 "off"
420 );
421 assert_eq!(
422 reasoning_effort_for_route_selection(
423 false,
424 ProviderKind::OpenaiCodex,
425 ReasoningEffort::Off,
426 ),
427 "low"
428 );
429 }
430
431 #[tokio::test]
432 async fn auto_model_route_respects_fixed_reasoning_preference() {
433 let config = Config::default();
434 let identity = deepseek_identity();
435
436 let planned = plan_turn_route(TurnRoutePlanRequest {
437 accounting_origin: None,
438 route_config: &config,
439 app_route_identity: &identity,
440 api_provider: ProviderKind::Deepseek,
441 app_model: DEFAULT_TEXT_MODEL,
442 auto_model: true,
443 reasoning_effort: ReasoningEffort::Low,
444 mode: AppMode::Agent,
445 content: "explain this function",
446 auto_router_context: "",
447 should_auto_resolve: false,
448 allow_auto_router_response_cache: false,
449 preflight_required: false,
450 auto_compact_user_configured: false,
451 auto_compact: true,
452 auto_compact_threshold_percent: 80.0,
453 })
454 .await
455 .expect("plan auto-model turn");
456
457 assert_eq!(planned.routing_source, TurnRoutingSource::AutoLocalFallback);
458 assert!(!planned.auto_controls_reasoning);
459 assert_eq!(planned.selected_reasoning_effort, None);
460 // First-party DeepSeek routes carry low as the real wire tier
461 // (`reasoning_effort` low/high/max are documented); the App keeps the
462 // unresolved preference as Low either way.
463 assert_eq!(planned.effective_reasoning_effort.as_deref(), Some("low"));
464 }
465 }
466
466 lines RUST