| 1 | use codewhale_config::route::RouteLimits; |
| 2 | |
| 3 | use crate::provider_lake::provider_capability; |
| 4 | use crate::reasoning_preference::ReasoningEffort; |
| 5 | use codewhale_config::ProviderKind; |
| 6 | use codewhale_models::{DEFAULT_COMPACTION_TOKEN_THRESHOLD, context_window_for_model}; |
| 7 | use codewhale_runtime::context_budget::ContextBudget; |
| 8 | |
| 9 | /// Safe ordinary API request cap across provider routes. |
| 10 | const API_MAX_OUTPUT_TOKENS: u32 = 65_536; |
| 11 | pub const MIN_REQUEST_OUTPUT_TOKENS: u64 = 128; |
| 12 | |
| 13 | /// Automatic request cap on a first-party DeepSeek route at max reasoning |
| 14 | /// effort, where DeepSeek documents 128K instead of the 64K thinking-mode |
| 15 | /// default (allowed range 1..=393216). |
| 16 | const DEEPSEEK_MAX_EFFORT_MAX_OUTPUT_TOKENS: u32 = 131_072; |
| 17 | |
| 18 | /// Preserve only route limits that came from a concrete offering. |
| 19 | #[must_use] |
| 20 | pub fn known_route_limits(limits: RouteLimits) -> Option<RouteLimits> { |
| 21 | limits.has_known_limit().then_some(limits) |
| 22 | } |
| 23 | |
| 24 | /// Whether this exact transport can represent an explicit output allowance. |
| 25 | /// Codex OAuth Responses rejects the field; other supported dialects carry it. |
| 26 | pub fn route_supports_output_token_limit( |
| 27 | provider: ProviderKind, |
| 28 | protocol: codewhale_config::route::RequestProtocol, |
| 29 | ) -> bool { |
| 30 | !(provider == ProviderKind::OpenaiCodex |
| 31 | && protocol == codewhale_config::route::RequestProtocol::Responses) |
| 32 | } |
| 33 | |
| 34 | pub fn effective_max_output_tokens_for_turn( |
| 35 | provider: ProviderKind, |
| 36 | model: &str, |
| 37 | route_limits: Option<RouteLimits>, |
| 38 | allowance: Option<std::num::NonZeroU32>, |
| 39 | reasoning_effort: Option<&str>, |
| 40 | ) -> u32 { |
| 41 | effective_max_output_tokens_for_turn_with_window( |
| 42 | provider, |
| 43 | model, |
| 44 | route_limits, |
| 45 | None, |
| 46 | allowance, |
| 47 | reasoning_effort, |
| 48 | ) |
| 49 | } |
| 50 | |
| 51 | pub fn effective_max_output_tokens_for_turn_with_window( |
| 52 | provider: ProviderKind, |
| 53 | model: &str, |
| 54 | route_limits: Option<RouteLimits>, |
| 55 | effective_window: Option<u32>, |
| 56 | allowance: Option<std::num::NonZeroU32>, |
| 57 | reasoning_effort: Option<&str>, |
| 58 | ) -> u32 { |
| 59 | let ceiling = effective_max_output_tokens_for_route_with_cap( |
| 60 | provider, |
| 61 | model, |
| 62 | route_limits, |
| 63 | effective_window, |
| 64 | automatic_max_output_tokens(provider, reasoning_effort), |
| 65 | ); |
| 66 | allowance.map_or(ceiling, |allowance| ceiling.min(allowance.get())) |
| 67 | } |
| 68 | |
| 69 | fn automatic_max_output_tokens(provider: ProviderKind, reasoning_effort: Option<&str>) -> u32 { |
| 70 | let max_effort = reasoning_effort.is_some_and(|raw| { |
| 71 | ReasoningEffort::parse_strict(raw) |
| 72 | .is_ok_and(|effort| matches!(effort, ReasoningEffort::Max | ReasoningEffort::Ultra)) |
| 73 | }); |
| 74 | if provider == ProviderKind::Deepseek && max_effort { |
| 75 | DEEPSEEK_MAX_EFFORT_MAX_OUTPUT_TOKENS |
| 76 | } else { |
| 77 | API_MAX_OUTPUT_TOKENS |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | /// Context window for a resolved runtime route. |
| 82 | /// |
| 83 | /// Route/offering facts win when known; otherwise this falls back to the |
| 84 | /// existing provider+model capability matrix so startup and custom/local |
| 85 | /// routes keep their previous conservative behavior. |
| 86 | #[must_use] |
| 87 | pub fn route_context_window_tokens( |
| 88 | provider: ProviderKind, |
| 89 | model: &str, |
| 90 | route_limits: Option<RouteLimits>, |
| 91 | ) -> u32 { |
| 92 | route_limits |
| 93 | .and_then(|limits| limits.context_tokens) |
| 94 | .and_then(|tokens| u32::try_from(tokens).ok()) |
| 95 | .filter(|tokens| *tokens > 0) |
| 96 | .unwrap_or_else(|| provider_capability(provider, model).context_window) |
| 97 | } |
| 98 | |
| 99 | /// Share of the route's context window (in estimated characters) one tool |
| 100 | /// result may occupy inline. |
| 101 | const TOOL_OUTPUT_INLINE_WINDOW_PERCENT: u64 = 3; |
| 102 | /// Inline ceiling for one tool result when the route is unknown, and the cap |
| 103 | /// for every route unless the operator opted into a larger budget. |
| 104 | const TOOL_OUTPUT_INLINE_MAX_CHARS: usize = 100_000; |
| 105 | /// Hard ceiling on an operator-raised inline tool-result budget (#5367). |
| 106 | const TOOL_OUTPUT_INLINE_OPT_IN_MAX_CHARS: usize = 2 * 1024 * 1024; |
| 107 | |
| 108 | /// The one budget for how much of a tool result the model sees inline (#6508). |
| 109 | /// |
| 110 | /// Every tool result is measured against this number: 3% of the route's |
| 111 | /// context window (at about 4 characters per token), capped at 100,000 |
| 112 | /// characters, or the full cap when the window is unknown. An opt-in |
| 113 | /// `tool_result_max_bytes` workshop setting may raise it, up to 2 MiB. |
| 114 | /// Anything past it is cut only after the raw output has been saved as a |
| 115 | /// session artifact that `retrieve_tool_result` can read back. |
| 116 | #[must_use] |
| 117 | pub fn route_inline_char_budget(window_tokens: Option<u32>) -> usize { |
| 118 | route_inline_char_budget_with_raise( |
| 119 | window_tokens, |
| 120 | codewhale_runtime::active_workshop::active_tool_result_max_bytes(), |
| 121 | ) |
| 122 | } |
| 123 | |
| 124 | #[must_use] |
| 125 | fn route_inline_char_budget_with_raise(window_tokens: Option<u32>, raise: Option<usize>) -> usize { |
| 126 | let base = window_tokens |
| 127 | .filter(|tokens| *tokens > 0) |
| 128 | .map(|tokens| { |
| 129 | let chars = u64::from(tokens) |
| 130 | .saturating_mul(4) |
| 131 | .saturating_mul(TOOL_OUTPUT_INLINE_WINDOW_PERCENT) |
| 132 | / 100; |
| 133 | usize::try_from(chars).unwrap_or(TOOL_OUTPUT_INLINE_MAX_CHARS) |
| 134 | }) |
| 135 | .unwrap_or(TOOL_OUTPUT_INLINE_MAX_CHARS) |
| 136 | .clamp(1, TOOL_OUTPUT_INLINE_MAX_CHARS); |
| 137 | match raise { |
| 138 | Some(bytes) if bytes > base => bytes.min(TOOL_OUTPUT_INLINE_OPT_IN_MAX_CHARS), |
| 139 | _ => base, |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | /// [`route_inline_char_budget`] for a resolved provider/model route. |
| 144 | #[cfg(any(test, feature = "test-support"))] |
| 145 | #[must_use] |
| 146 | pub fn route_inline_char_budget_for_route( |
| 147 | provider: ProviderKind, |
| 148 | model: &str, |
| 149 | route_limits: Option<RouteLimits>, |
| 150 | ) -> usize { |
| 151 | route_inline_char_budget(Some(route_context_window_tokens( |
| 152 | provider, |
| 153 | model, |
| 154 | route_limits, |
| 155 | ))) |
| 156 | } |
| 157 | |
| 158 | /// Provider/offering output cap, when the resolved route reports one. |
| 159 | #[must_use] |
| 160 | pub fn route_output_limit_tokens(route_limits: Option<RouteLimits>) -> Option<u32> { |
| 161 | route_limits |
| 162 | .and_then(|limits| limits.output_tokens) |
| 163 | .and_then(|tokens| u32::try_from(tokens).ok()) |
| 164 | .filter(|tokens| *tokens > 0) |
| 165 | } |
| 166 | |
| 167 | /// Provider/offering input cap, when the resolved route reports one. |
| 168 | #[must_use] |
| 169 | pub fn route_input_limit_tokens(route_limits: Option<RouteLimits>) -> Option<u32> { |
| 170 | route_limits |
| 171 | .and_then(|limits| limits.input_tokens) |
| 172 | .and_then(|tokens| u32::try_from(tokens).ok()) |
| 173 | .filter(|tokens| *tokens > 0) |
| 174 | } |
| 175 | |
| 176 | /// Explicit operator request cap, when configured. |
| 177 | /// |
| 178 | /// Keep this separate from catalogue/default resolution: a published maximum |
| 179 | /// is a ceiling, while these environment variables are an actual request from |
| 180 | /// the operator. Route/window validation still clamps the value before it is |
| 181 | /// sent. |
| 182 | #[must_use] |
| 183 | fn explicit_max_output_tokens_override() -> Option<u32> { |
| 184 | match std::env::var("CODEWHALE_MAX_OUTPUT_TOKENS") { |
| 185 | Ok(raw) if !raw.trim().is_empty() => { |
| 186 | // A non-blank canonical value is authoritative. Invalid/zero |
| 187 | // values deliberately fall back to the safe automatic default; |
| 188 | // they must not silently activate a stale legacy setting. |
| 189 | return raw.trim().parse::<u32>().ok().filter(|tokens| *tokens > 0); |
| 190 | } |
| 191 | Ok(_) | Err(_) => {} |
| 192 | } |
| 193 | std::env::var("DEEPSEEK_MAX_OUTPUT_TOKENS") |
| 194 | .ok() |
| 195 | .and_then(|raw| raw.trim().parse::<u32>().ok()) |
| 196 | .filter(|tokens| *tokens > 0) |
| 197 | } |
| 198 | |
| 199 | /// Effective `max_tokens` for a model before provider/route caps are applied. |
| 200 | #[cfg(any(test, feature = "test-support"))] |
| 201 | #[must_use] |
| 202 | pub fn effective_max_output_tokens(model: &str) -> u32 { |
| 203 | effective_max_output_tokens_with_cap(model, API_MAX_OUTPUT_TOKENS) |
| 204 | } |
| 205 | |
| 206 | fn effective_max_output_tokens_with_cap(model: &str, automatic_cap: u32) -> u32 { |
| 207 | if let Some(tokens) = explicit_max_output_tokens_override() { |
| 208 | return tokens; |
| 209 | } |
| 210 | |
| 211 | // A documented catalogue value is a capability ceiling, not necessarily a |
| 212 | // sensible default request size. In particular, DeepSeek V4 advertises a |
| 213 | // 384K maximum. Treating that maximum as the default made Codewhale ask a |
| 214 | // 262K/327K self-hosted route for almost its whole context as output before |
| 215 | // it had counted a single input token (#5516/#5518). Keep documented |
| 216 | // ceilings through the normal compatibility intersection, but automatic |
| 217 | // requests start at the ordinary cap — 64K, or DeepSeek's documented 128K |
| 218 | // at max effort — unless the operator explicitly overrides it. A maximum |
| 219 | // describes what a provider may allow, not what every response should |
| 220 | // reserve by default. |
| 221 | // |
| 222 | // Provenance for the ceiling (deepseek-v4-flash/pro: 384_000 output): |
| 223 | // - models_dev.bundled.json documents limit.output = 384000. |
| 224 | // - The DS4 provider contract corroborates 384K |
| 225 | // (crates/config/src/model_reference.rs pins max_output 384_000 / "384K"). |
| 226 | // - Official DeepSeek API docs publish the output allowance: 64K by |
| 227 | // default in thinking mode, 128K at `reasoning_effort: max`, in the |
| 228 | // range 1..=393216 (#5373). |
| 229 | if let Some(documented) = codewhale_models::max_output_tokens_for_model(model) { |
| 230 | return documented.min(automatic_cap); |
| 231 | } |
| 232 | |
| 233 | let window = context_window_for_model(model).unwrap_or(128_000); |
| 234 | (window / 2).min(automatic_cap) |
| 235 | } |
| 236 | |
| 237 | /// Automatic allowance when an exact remote model has no output metadata. |
| 238 | /// This is policy, not a discovered provider limit. Reasoning and tool arguments |
| 239 | /// share this allowance; an 8K fallback truncated ordinary file writes after |
| 240 | /// reasoning consumed most of the response. Known route limits still constrain |
| 241 | /// requests, and an explicit operator setting may replace this fallback. |
| 242 | const UNCATALOGUED_COMPAT_MAX_OUTPUT_TOKENS: u32 = API_MAX_OUTPUT_TOKENS; |
| 243 | |
| 244 | /// Assumed output ceiling for an Anthropic-family model the catalogue does |
| 245 | /// not describe (#5440). The 64K Messages floor is real, but applying it to |
| 246 | /// an unknown model is an assumption about that model, not a documented |
| 247 | /// fact, so it clamps under an `unverified` label. |
| 248 | const ANTHROPIC_UNKNOWN_MAX_OUTPUT_TOKENS: u32 = 64_000; |
| 249 | |
| 250 | /// Assumed output ceiling for the ChatGPT/Codex OAuth route, which publishes |
| 251 | /// no output ceiling of its own (#5440). Same clamp as the long-standing 4K |
| 252 | /// policy — relabeled, not revalued. |
| 253 | const CODEX_OAUTH_MAX_OUTPUT_TOKENS: u32 = 4_096; |
| 254 | |
| 255 | /// Why a route's compatibility output ceiling has the value it does. |
| 256 | /// |
| 257 | /// Carried so a clamp is always attributable: "unknown" is only allowed to |
| 258 | /// mean "no clamp" when a route *truthfully publishes no ceiling*, never when |
| 259 | /// the catalogue simply has no row for the model. |
| 260 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 261 | pub enum OutputCeilingSource { |
| 262 | /// The static catalogue publishes an exact/conservative ceiling. |
| 263 | Documented(u32), |
| 264 | /// The route is known to publish no output maximum we can stand behind |
| 265 | /// (Kimi Code membership ids, operator-owned self-hosted engines). Unknown |
| 266 | /// stays unknown and nothing is clamped. |
| 267 | RouteDeclaredUnknown, |
| 268 | /// The catalogue has no row for this model. Fail closed to a conservative |
| 269 | /// ceiling rather than treating absence as permission. |
| 270 | Uncatalogued(u32), |
| 271 | /// The route publishes no ceiling we can stand behind, but a defensible |
| 272 | /// floor is still applied: an Anthropic-family model the catalogue does |
| 273 | /// not describe (64K Messages floor) or the Codex OAuth route (4K |
| 274 | /// policy). Clamping trades late provider failure for early truncation; |
| 275 | /// lying about why is not part of that trade, so receipts and pickers |
| 276 | /// must render this as an assumption, never as "documented" (#5440). |
| 277 | Unverified(u32), |
| 278 | } |
| 279 | |
| 280 | impl OutputCeilingSource { |
| 281 | /// The ceiling to intersect a requested cap with, if any. |
| 282 | #[must_use] |
| 283 | pub const fn clamp_tokens(self) -> Option<u32> { |
| 284 | match self { |
| 285 | Self::Documented(tokens) | Self::Uncatalogued(tokens) | Self::Unverified(tokens) => { |
| 286 | Some(tokens) |
| 287 | } |
| 288 | Self::RouteDeclaredUnknown => None, |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | /// Stable provenance label, surfaced in exec stream metadata so a wrong |
| 293 | /// ceiling is visible in a receipt rather than requiring packet capture. |
| 294 | #[must_use] |
| 295 | pub const fn as_str(self) -> &'static str { |
| 296 | match self { |
| 297 | Self::Documented(_) => "documented", |
| 298 | Self::Uncatalogued(_) => "uncatalogued", |
| 299 | Self::RouteDeclaredUnknown => "route-declared", |
| 300 | Self::Unverified(_) => "unverified", |
| 301 | } |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | #[must_use] |
| 306 | fn route_declares_unknown_output_ceiling(provider: ProviderKind, model: &str) -> bool { |
| 307 | if codewhale_config::provider::credential_help(provider).acquisition |
| 308 | == codewhale_config::provider::CredentialAcquisition::LocalOptional |
| 309 | { |
| 310 | return true; |
| 311 | } |
| 312 | if codewhale_config::route::ProviderDescriptor::for_kind(provider).family() == "moonshot" { |
| 313 | let resolved = codewhale_config::route::resolve_model(provider, model, None) |
| 314 | .ok() |
| 315 | .filter(|row| !row.is_auto); |
| 316 | let wire_id = resolved |
| 317 | .as_ref() |
| 318 | .map_or_else(|| model.trim(), |row| row.wire_id.as_str()); |
| 319 | return codewhale_runtime::config::is_kimi_code_membership_model(wire_id); |
| 320 | } |
| 321 | false |
| 322 | } |
| 323 | |
| 324 | #[must_use] |
| 325 | pub fn output_ceiling_source(provider: ProviderKind, model: &str) -> OutputCeilingSource { |
| 326 | if provider == ProviderKind::Custom { |
| 327 | return OutputCeilingSource::RouteDeclaredUnknown; |
| 328 | } |
| 329 | if provider == ProviderKind::OpenaiCodex { |
| 330 | return OutputCeilingSource::Unverified(CODEX_OAUTH_MAX_OUTPUT_TOKENS); |
| 331 | } |
| 332 | if crate::provider_lake::provider_uses_anthropic_messages_floor(provider) |
| 333 | && crate::provider_lake::catalog_max_output_for_route(provider, model).is_none() |
| 334 | { |
| 335 | return OutputCeilingSource::Unverified(ANTHROPIC_UNKNOWN_MAX_OUTPUT_TOKENS); |
| 336 | } |
| 337 | provider_capability(provider, model).max_output.map_or_else( |
| 338 | || { |
| 339 | if route_declares_unknown_output_ceiling(provider, model) { |
| 340 | OutputCeilingSource::RouteDeclaredUnknown |
| 341 | } else { |
| 342 | OutputCeilingSource::Uncatalogued(UNCATALOGUED_COMPAT_MAX_OUTPUT_TOKENS) |
| 343 | } |
| 344 | }, |
| 345 | OutputCeilingSource::Documented, |
| 346 | ) |
| 347 | } |
| 348 | |
| 349 | /// Effective request output cap for a fully resolved provider/model route. |
| 350 | #[must_use] |
| 351 | pub fn effective_max_output_tokens_for_route( |
| 352 | provider: ProviderKind, |
| 353 | model: &str, |
| 354 | route_limits: Option<RouteLimits>, |
| 355 | ) -> u32 { |
| 356 | effective_max_output_tokens_for_route_with_cap( |
| 357 | provider, |
| 358 | model, |
| 359 | route_limits, |
| 360 | None, |
| 361 | API_MAX_OUTPUT_TOKENS, |
| 362 | ) |
| 363 | } |
| 364 | |
| 365 | fn effective_max_output_tokens_for_route_with_cap( |
| 366 | provider: ProviderKind, |
| 367 | model: &str, |
| 368 | route_limits: Option<RouteLimits>, |
| 369 | effective_window: Option<u32>, |
| 370 | automatic_cap: u32, |
| 371 | ) -> u32 { |
| 372 | let window = effective_window |
| 373 | .filter(|tokens| *tokens > 0) |
| 374 | .unwrap_or_else(|| route_context_window_tokens(provider, model, route_limits)); |
| 375 | let compatibility_source = output_ceiling_source(provider, model); |
| 376 | let compatibility_cap = compatibility_source.clamp_tokens(); |
| 377 | let route_cap = route_output_limit_tokens(route_limits); |
| 378 | // With a known route window and no published output limit, reserve a |
| 379 | // conservative part of that window. The model-only fallback reserved 64K even |
| 380 | // for a configured 32K Ollama route, leaving just 1K for input (#5820). |
| 381 | // The same squeeze hit the capability *fallback* window: an unknown local |
| 382 | // Ollama tag resolves to an 8K window with no route limits, the model-only |
| 383 | // 64K request clamped to 6K, and the input budget collapsed to 1K — every |
| 384 | // turn tripped emergency compaction before its first request (#6540). So a |
| 385 | // model-only request larger than half of whatever window is in force also |
| 386 | // yields to the window-relative reservation. |
| 387 | // Explicit requests and documented ceilings retain their existing rules. |
| 388 | let model_only_cap = if provider == ProviderKind::Custom { |
| 389 | explicit_max_output_tokens_override().unwrap_or_else(|| { |
| 390 | codewhale_models::generation_default_for_model(model) |
| 391 | .unwrap_or(window / 2) |
| 392 | .min(automatic_cap) |
| 393 | }) |
| 394 | } else { |
| 395 | effective_max_output_tokens_with_cap(model, automatic_cap) |
| 396 | }; |
| 397 | let window_known = route_limits |
| 398 | .and_then(|limits| limits.context_tokens) |
| 399 | .is_some_and(|tokens| (1..=u64::from(u32::MAX)).contains(&tokens)); |
| 400 | let requested_cap = if explicit_max_output_tokens_override().is_none() |
| 401 | && codewhale_models::max_output_tokens_for_model(model).is_none() |
| 402 | && route_cap.is_none() |
| 403 | && matches!( |
| 404 | compatibility_source, |
| 405 | OutputCeilingSource::RouteDeclaredUnknown | OutputCeilingSource::Uncatalogued(_) |
| 406 | ) |
| 407 | && (window_known || model_only_cap > window / 2) |
| 408 | { |
| 409 | (window / 4).clamp(1, UNCATALOGUED_COMPAT_MAX_OUTPUT_TOKENS) |
| 410 | } else { |
| 411 | model_only_cap |
| 412 | }; |
| 413 | // Unknown means unknown only where a route *declares* it: membership ids |
| 414 | // such as the `kimi-for-coding` family, and operator-owned self-hosted |
| 415 | // engines. For those there is nothing to clamp against and the requested |
| 416 | // cap stands. A model the catalogue simply has no row for is not the same |
| 417 | // fact — absence keeps a labeled automatic allowance |
| 418 | // (see `output_ceiling_source`). A concrete route/offering maximum is the |
| 419 | // missing evidence for that exact route and may replace only the generic |
| 420 | // uncatalogued guess on a routed offering. An |
| 421 | // explicit request may also rise past a compatibility cap to a maximum |
| 422 | // the operator declared for this exact model and endpoint. Otherwise known |
| 423 | // compatibility caps stay authoritative and are still intersected with |
| 424 | // any route maximum. |
| 425 | let declared_route_override = explicit_max_output_tokens_override().is_some() |
| 426 | && route_limits.is_some_and(|limits| limits.output_declared); |
| 427 | let cap = match (compatibility_source, route_cap) { |
| 428 | // A concrete route/offering maximum is evidence about this exact |
| 429 | // route. It therefore outranks the generic fallback that exists only |
| 430 | // because the static catalogue has no row for the wire id. With no |
| 431 | // route fact the conservative guess still applies, and the route fact |
| 432 | // can never raise the caller's requested cap. |
| 433 | (OutputCeilingSource::Uncatalogued(_), Some(route_cap)) => requested_cap.min(route_cap), |
| 434 | (_, Some(route_cap)) if declared_route_override => requested_cap.min(route_cap), |
| 435 | (OutputCeilingSource::Uncatalogued(_), None) |
| 436 | if explicit_max_output_tokens_override().is_some() => |
| 437 | { |
| 438 | requested_cap |
| 439 | } |
| 440 | _ => { |
| 441 | let cap = compatibility_cap.map_or(requested_cap, |compat| requested_cap.min(compat)); |
| 442 | route_cap.map_or(cap, |route_cap| cap.min(route_cap)) |
| 443 | } |
| 444 | }; |
| 445 | // Clamp against the effective route window even when it came from the |
| 446 | // capability fallback rather than an explicit offering. This keeps a |
| 447 | // suffix/config/catalog-derived small window from ever receiving a request |
| 448 | // cap larger than the window itself. |
| 449 | u32::try_from(ContextBudget::new(u64::from(window), 0, u64::from(cap)).output_cap_tokens) |
| 450 | .unwrap_or(cap) |
| 451 | .max(1) |
| 452 | } |
| 453 | |
| 454 | /// Share of one output allowance a single review pass must keep for visible |
| 455 | /// text, as a percentage. |
| 456 | /// |
| 457 | /// A reasoning route shares one `max_tokens` allowance between hidden |
| 458 | /// reasoning and visible text, and Codewhale has no wire-level separation |
| 459 | /// (`thinking.budget_tokens` is not plumbed), so "reserving" means two things |
| 460 | /// together: state the reserve, and cap the reasoning level that may consume |
| 461 | /// it (`review::bounded_review_reasoning_effort`). |
| 462 | /// |
| 463 | /// The share is sized from the model's reasoning behaviour rather than a flat |
| 464 | /// constant: |
| 465 | /// |
| 466 | /// * `Some(false)` — nothing to reserve; the whole allowance is visible text. |
| 467 | /// * `Some(true)` in the summarized-reasoning families whose reasoning is |
| 468 | /// counted as ordinary output tokens |
| 469 | /// ([`codewhale_models::model_is_openai_reasoning_family`]) — half. These are |
| 470 | /// the models observed consuming an entire 64K allowance on reasoning and |
| 471 | /// returning zero visible text with stop reason `length` (#6285). |
| 472 | /// * `Some(true)` otherwise, and `None` (no catalogue row) — a quarter. A |
| 473 | /// review pass needs only enough text for its structured findings, and an |
| 474 | /// unknown model is not evidence that it does not reason (#6032). |
| 475 | #[must_use] |
| 476 | pub fn review_visible_text_reserve_percent(model: &str) -> u32 { |
| 477 | review_reserve_percent_for( |
| 478 | codewhale_models::model_reasoning_capability(model), |
| 479 | codewhale_models::model_is_openai_reasoning_family(model), |
| 480 | ) |
| 481 | } |
| 482 | |
| 483 | /// Pure core of [`review_visible_text_reserve_percent`]: the mapping from a |
| 484 | /// model's reasoning classification to the reserved share. Split out so the |
| 485 | /// mapping is testable without the process-global model catalog. |
| 486 | fn review_reserve_percent_for(capability: Option<bool>, openai_reasoning_family: bool) -> u32 { |
| 487 | match capability { |
| 488 | // Nothing to reserve; the whole allowance is visible text. |
| 489 | Some(false) => 0, |
| 490 | Some(true) if openai_reasoning_family => 50, |
| 491 | Some(true) | None => 25, |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | /// Visible-text reserve in tokens for one review pass on this exact model and |
| 496 | /// resolved output allowance. |
| 497 | #[must_use] |
| 498 | pub fn review_visible_text_reserve_tokens(model: &str, allowance: u32) -> u32 { |
| 499 | allowance.saturating_mul(review_visible_text_reserve_percent(model)) / 100 |
| 500 | } |
| 501 | |
| 502 | /// Output reservation used by the internal input budget for a route. |
| 503 | #[cfg(any(test, feature = "test-support"))] |
| 504 | #[must_use] |
| 505 | pub fn route_output_reservation( |
| 506 | provider: ProviderKind, |
| 507 | model: &str, |
| 508 | route_limits: Option<RouteLimits>, |
| 509 | ) -> u32 { |
| 510 | route_output_reservation_with_window(provider, model, route_limits, None) |
| 511 | } |
| 512 | |
| 513 | pub fn route_output_reservation_with_window( |
| 514 | provider: ProviderKind, |
| 515 | model: &str, |
| 516 | route_limits: Option<RouteLimits>, |
| 517 | effective_window: Option<u32>, |
| 518 | ) -> u32 { |
| 519 | // Use exactly the value that can reach the wire on every window size, |
| 520 | // except on a route whose published output limit is more than half its |
| 521 | // window: there the limit is the shared window itself, so a quarter of the |
| 522 | // window (at most 64K) is reserved and each request's wire cap is sized |
| 523 | // from what its input leaves (`request_output_cap_for_input`). The previous split |
| 524 | // reserved 65K for a possible 325K wire request below 500K, then jumped to |
| 525 | // an unrequested 262K reservation at 500K. Both directions made preflight |
| 526 | // disagree with the actual request. Reasoning effort is a request control, |
| 527 | // not separately metered non-wire output, so it does not justify a second |
| 528 | // hidden context reservation. |
| 529 | let window = effective_window |
| 530 | .filter(|tokens| *tokens > 0) |
| 531 | .unwrap_or_else(|| route_context_window_tokens(provider, model, route_limits)); |
| 532 | let ceiling = effective_max_output_tokens_for_route_with_cap( |
| 533 | provider, |
| 534 | model, |
| 535 | route_limits, |
| 536 | Some(window), |
| 537 | API_MAX_OUTPUT_TOKENS, |
| 538 | ); |
| 539 | if shares_context_window(route_limits, window) { |
| 540 | ceiling.min((window / 4).clamp(1, UNCATALOGUED_COMPAT_MAX_OUTPUT_TOKENS)) |
| 541 | } else { |
| 542 | ceiling |
| 543 | } |
| 544 | } |
| 545 | |
| 546 | fn shares_context_window(route_limits: Option<RouteLimits>, window: u32) -> bool { |
| 547 | route_limits |
| 548 | .and_then(|limits| limits.context_tokens) |
| 549 | .is_some_and(|tokens| (1..=u64::from(u32::MAX)).contains(&tokens)) |
| 550 | && explicit_max_output_tokens_override().is_none() |
| 551 | && route_output_limit_tokens(route_limits).is_some_and(|cap| cap > window / 2) |
| 552 | } |
| 553 | |
| 554 | pub fn route_admission_input_ceiling_with_window( |
| 555 | provider: ProviderKind, |
| 556 | model: &str, |
| 557 | route_limits: Option<RouteLimits>, |
| 558 | effective_window: Option<u32>, |
| 559 | ) -> Option<u64> { |
| 560 | let window = effective_window |
| 561 | .filter(|tokens| *tokens > 0) |
| 562 | .unwrap_or_else(|| route_context_window_tokens(provider, model, route_limits)); |
| 563 | shares_context_window(route_limits, window).then(|| { |
| 564 | ContextBudget::new_with_input_limit( |
| 565 | u64::from(window), |
| 566 | 0, |
| 567 | MIN_REQUEST_OUTPUT_TOKENS, |
| 568 | route_input_limit_tokens(route_limits).map(u64::from), |
| 569 | ) |
| 570 | .input_budget_ceiling |
| 571 | }) |
| 572 | } |
| 573 | |
| 574 | #[must_use] |
| 575 | pub fn request_output_cap_for_input( |
| 576 | provider: ProviderKind, |
| 577 | model: &str, |
| 578 | route_limits: Option<RouteLimits>, |
| 579 | ceiling: u32, |
| 580 | estimated_input_tokens: u64, |
| 581 | ) -> Option<u32> { |
| 582 | request_output_cap_for_input_with_window( |
| 583 | provider, |
| 584 | model, |
| 585 | route_limits, |
| 586 | None, |
| 587 | ceiling, |
| 588 | estimated_input_tokens, |
| 589 | ) |
| 590 | } |
| 591 | |
| 592 | pub fn request_output_cap_for_input_with_window( |
| 593 | provider: ProviderKind, |
| 594 | model: &str, |
| 595 | route_limits: Option<RouteLimits>, |
| 596 | effective_window: Option<u32>, |
| 597 | ceiling: u32, |
| 598 | estimated_input_tokens: u64, |
| 599 | ) -> Option<u32> { |
| 600 | let window = effective_window |
| 601 | .filter(|tokens| *tokens > 0) |
| 602 | .unwrap_or_else(|| route_context_window_tokens(provider, model, route_limits)); |
| 603 | if !shares_context_window(route_limits, window) { |
| 604 | return Some(ceiling); |
| 605 | } |
| 606 | let remaining = u64::from(window) |
| 607 | .saturating_sub(estimated_input_tokens) |
| 608 | .saturating_sub(codewhale_runtime::context_budget::CONTEXT_HEADROOM_TOKENS); |
| 609 | u32::try_from(remaining.min(u64::from(ceiling))) |
| 610 | .ok() |
| 611 | .filter(|cap| *cap > 0) |
| 612 | } |
| 613 | |
| 614 | #[must_use] |
| 615 | pub fn route_context_budget( |
| 616 | provider: ProviderKind, |
| 617 | model: &str, |
| 618 | route_limits: Option<RouteLimits>, |
| 619 | input_tokens: usize, |
| 620 | ) -> Option<ContextBudget> { |
| 621 | route_context_budget_with_window(provider, model, route_limits, None, input_tokens) |
| 622 | } |
| 623 | |
| 624 | pub fn route_context_budget_with_window( |
| 625 | provider: ProviderKind, |
| 626 | model: &str, |
| 627 | route_limits: Option<RouteLimits>, |
| 628 | effective_window: Option<u32>, |
| 629 | input_tokens: usize, |
| 630 | ) -> Option<ContextBudget> { |
| 631 | let window = effective_window |
| 632 | .filter(|tokens| *tokens > 0) |
| 633 | .unwrap_or_else(|| route_context_window_tokens(provider, model, route_limits)); |
| 634 | let output_cap = |
| 635 | route_output_reservation_with_window(provider, model, route_limits, Some(window)); |
| 636 | Some(ContextBudget::new_with_input_limit( |
| 637 | u64::from(window), |
| 638 | u64::try_from(input_tokens).ok()?, |
| 639 | u64::from(output_cap), |
| 640 | route_input_limit_tokens(route_limits).map(u64::from), |
| 641 | )) |
| 642 | } |
| 643 | |
| 644 | #[cfg(any(test, feature = "test-support"))] |
| 645 | #[must_use] |
| 646 | pub fn compaction_threshold_for_route_at_percent( |
| 647 | provider: ProviderKind, |
| 648 | model: &str, |
| 649 | route_limits: Option<RouteLimits>, |
| 650 | percent: f64, |
| 651 | ) -> usize { |
| 652 | compaction_threshold_for_route_at_percent_with_window( |
| 653 | provider, |
| 654 | model, |
| 655 | route_limits, |
| 656 | None, |
| 657 | percent, |
| 658 | ) |
| 659 | } |
| 660 | |
| 661 | pub fn compaction_threshold_for_route_at_percent_with_window( |
| 662 | provider: ProviderKind, |
| 663 | model: &str, |
| 664 | route_limits: Option<RouteLimits>, |
| 665 | effective_window: Option<u32>, |
| 666 | percent: f64, |
| 667 | ) -> usize { |
| 668 | route_context_budget_with_window(provider, model, route_limits, effective_window, 0) |
| 669 | .and_then(|budget| { |
| 670 | usize::try_from(budget.compaction_trigger_for_percent(percent.clamp(10.0, 100.0))).ok() |
| 671 | }) |
| 672 | .unwrap_or(DEFAULT_COMPACTION_TOKEN_THRESHOLD) |
| 673 | } |
| 674 | |
| 675 | #[must_use] |
| 676 | pub fn auto_compact_default_for_route( |
| 677 | provider: ProviderKind, |
| 678 | model: &str, |
| 679 | route_limits: Option<RouteLimits>, |
| 680 | ) -> bool { |
| 681 | // Every resolved route has either concrete offering limits or a |
| 682 | // conservative provider/model fallback. Large windows need continuity too; |
| 683 | // their size is not a reason to disable compaction entirely. |
| 684 | route_context_window_tokens(provider, model, route_limits) > 0 |
| 685 | } |
| 686 | |
| 687 | #[cfg(test)] |
| 688 | mod tests { |
| 689 | #[test] |
| 690 | fn route_inline_char_budget_is_three_percent_of_the_window_capped() { |
| 691 | use super::route_inline_char_budget_with_raise as budget; |
| 692 | assert_eq!(budget(Some(128_000), None), 15_360); |
| 693 | assert_eq!(budget(Some(10_000), None), 1_200); |
| 694 | assert_eq!(budget(None, None), 100_000); |
| 695 | assert_eq!(budget(Some(0), None), 100_000); |
| 696 | assert_eq!(budget(Some(1_000_000), None), 100_000); |
| 697 | // An operator opt-in raises the budget, never lowers it, and stops at 2 MiB. |
| 698 | assert_eq!(budget(Some(128_000), Some(80_000)), 80_000); |
| 699 | assert_eq!(budget(Some(128_000), Some(1_000)), 15_360); |
| 700 | assert_eq!( |
| 701 | budget(Some(128_000), Some(64 * 1024 * 1024)), |
| 702 | 2 * 1024 * 1024 |
| 703 | ); |
| 704 | } |
| 705 | |
| 706 | use super::*; |
| 707 | |
| 708 | #[test] |
| 709 | fn provider_regression_5820_small_unknown_windows_keep_room_for_input() { |
| 710 | let _lock = crate::test_support::lock_test_env(); |
| 711 | let _canonical = crate::test_support::EnvVarGuard::remove("CODEWHALE_MAX_OUTPUT_TOKENS"); |
| 712 | let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MAX_OUTPUT_TOKENS"); |
| 713 | let model = "qwen2.5:7b"; |
| 714 | assert!(codewhale_models::max_output_tokens_for_model(model).is_none()); |
| 715 | for provider in [ |
| 716 | ProviderKind::Ollama, |
| 717 | ProviderKind::Sglang, |
| 718 | ProviderKind::Vllm, |
| 719 | ProviderKind::Custom, |
| 720 | ] { |
| 721 | for (window, expected_output) in [ |
| 722 | (16_384, 4_096), |
| 723 | (32_768, 8_192), |
| 724 | (65_536, 16_384), |
| 725 | (262_144, 65_536), |
| 726 | ] { |
| 727 | let limits = Some(RouteLimits { |
| 728 | context_tokens: Some(window), |
| 729 | ..RouteLimits::default() |
| 730 | }); |
| 731 | let wire_cap = effective_max_output_tokens_for_route(provider, model, limits); |
| 732 | let budget = route_context_budget(provider, model, limits, 6_225).unwrap(); |
| 733 | assert_eq!(wire_cap, expected_output, "{provider:?}, window={window}"); |
| 734 | assert_eq!(budget.output_cap_tokens, u64::from(wire_cap)); |
| 735 | assert_eq!( |
| 736 | budget.input_budget_ceiling, |
| 737 | window - u64::from(wire_cap) - 1_024 |
| 738 | ); |
| 739 | assert!( |
| 740 | budget.input_tokens < budget.input_budget_ceiling, |
| 741 | "{budget:?}" |
| 742 | ); |
| 743 | assert!(!budget.should_compact(), "{budget:?}"); |
| 744 | } |
| 745 | } |
| 746 | let _explicit = |
| 747 | crate::test_support::EnvVarGuard::set("CODEWHALE_MAX_OUTPUT_TOKENS", "16384"); |
| 748 | let limits = RouteLimits { |
| 749 | context_tokens: Some(32_768), |
| 750 | ..RouteLimits::default() |
| 751 | }; |
| 752 | assert_eq!( |
| 753 | effective_max_output_tokens_for_route(ProviderKind::Ollama, model, Some(limits)), |
| 754 | 16_384 |
| 755 | ); |
| 756 | assert_eq!( |
| 757 | effective_max_output_tokens_for_route( |
| 758 | ProviderKind::Ollama, |
| 759 | model, |
| 760 | Some(RouteLimits { |
| 761 | output_tokens: Some(4_096), |
| 762 | ..limits |
| 763 | }) |
| 764 | ), |
| 765 | 4_096 |
| 766 | ); |
| 767 | } |
| 768 | |
| 769 | /// #6540: the runtime store's 15 failed compactions were all emergency |
| 770 | /// passes on an unknown local Ollama tag (`qwen3:4b`) with no route |
| 771 | /// limits: the capability fallback window (8K) minus a 6K output |
| 772 | /// reservation left a ~1K input budget, so every first request of a turn |
| 773 | /// tripped preflight recovery. The fallback window must keep the same |
| 774 | /// input room a configured window of that size gets. |
| 775 | #[test] |
| 776 | fn provider_regression_6540_fallback_window_keeps_room_for_input() { |
| 777 | let _lock = crate::test_support::lock_test_env(); |
| 778 | let _canonical = crate::test_support::EnvVarGuard::remove("CODEWHALE_MAX_OUTPUT_TOKENS"); |
| 779 | let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MAX_OUTPUT_TOKENS"); |
| 780 | let model = "qwen3:4b"; |
| 781 | assert!(codewhale_models::max_output_tokens_for_model(model).is_none()); |
| 782 | let window = route_context_window_tokens(ProviderKind::Ollama, model, None); |
| 783 | assert_eq!( |
| 784 | window, 8_192, |
| 785 | "unknown local tags keep the conservative window" |
| 786 | ); |
| 787 | |
| 788 | let wire_cap = effective_max_output_tokens_for_route(ProviderKind::Ollama, model, None); |
| 789 | assert_eq!(wire_cap, 2_048); |
| 790 | let budget = route_context_budget(ProviderKind::Ollama, model, None, 0).unwrap(); |
| 791 | assert_eq!(budget.output_cap_tokens, u64::from(wire_cap)); |
| 792 | assert_eq!(budget.input_budget_ceiling, 8_192 - 2_048 - 1_024); |
| 793 | // The recorded first-request estimates (~1.9K–3.9K) now fit. |
| 794 | assert!(budget.input_budget_ceiling > 3_900, "{budget:?}"); |
| 795 | |
| 796 | // Same answer as the explicitly configured 8K window (#5820). |
| 797 | let configured = Some(RouteLimits { |
| 798 | context_tokens: Some(8_192), |
| 799 | ..RouteLimits::default() |
| 800 | }); |
| 801 | assert_eq!( |
| 802 | effective_max_output_tokens_for_route(ProviderKind::Ollama, model, configured), |
| 803 | wire_cap |
| 804 | ); |
| 805 | } |
| 806 | |
| 807 | /// Absence of a catalogue row is not evidence of a large ceiling. An |
| 808 | /// unrecognized wire alias on a remote OpenAI-compatible route keeps the |
| 809 | /// conservative compatibility ceiling, with an attributable source. |
| 810 | #[test] |
| 811 | fn uncatalogued_remote_model_keeps_a_conservative_ceiling() { |
| 812 | let _lock = crate::test_support::lock_test_env(); |
| 813 | let _canonical = crate::test_support::EnvVarGuard::remove("CODEWHALE_MAX_OUTPUT_TOKENS"); |
| 814 | let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MAX_OUTPUT_TOKENS"); |
| 815 | let source = output_ceiling_source(ProviderKind::Openai, "totally-unknown-alias-v9"); |
| 816 | assert_eq!( |
| 817 | source, |
| 818 | OutputCeilingSource::Uncatalogued(UNCATALOGUED_COMPAT_MAX_OUTPUT_TOKENS) |
| 819 | ); |
| 820 | assert_eq!( |
| 821 | source.clamp_tokens(), |
| 822 | Some(UNCATALOGUED_COMPAT_MAX_OUTPUT_TOKENS) |
| 823 | ); |
| 824 | assert!( |
| 825 | effective_max_output_tokens_for_route( |
| 826 | ProviderKind::Openai, |
| 827 | "totally-unknown-alias-v9", |
| 828 | None |
| 829 | ) <= UNCATALOGUED_COMPAT_MAX_OUTPUT_TOKENS |
| 830 | ); |
| 831 | } |
| 832 | |
| 833 | /// #5460: absence is not permission, but a positive output maximum on the |
| 834 | /// resolved route is permission for that exact route. The concrete fact |
| 835 | /// replaces only the catalogue-absence guess; it never raises the caller's |
| 836 | /// requested cap, and an undeclared fact never raises a documented model |
| 837 | /// ceiling. |
| 838 | #[test] |
| 839 | fn concrete_route_output_limit_outranks_uncatalogued_guess() { |
| 840 | let _lock = crate::test_support::lock_test_env(); |
| 841 | let _codewhale = crate::test_support::EnvVarGuard::remove("CODEWHALE_MAX_OUTPUT_TOKENS"); |
| 842 | let _deepseek = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MAX_OUTPUT_TOKENS"); |
| 843 | let model = "totally-unknown-alias-v9"; |
| 844 | |
| 845 | assert_eq!(effective_max_output_tokens(model), 64_000); |
| 846 | for provider in [ProviderKind::Openai, ProviderKind::Custom] { |
| 847 | assert_eq!( |
| 848 | output_ceiling_source(provider, model), |
| 849 | if provider == ProviderKind::Custom { |
| 850 | OutputCeilingSource::RouteDeclaredUnknown |
| 851 | } else { |
| 852 | OutputCeilingSource::Uncatalogued(UNCATALOGUED_COMPAT_MAX_OUTPUT_TOKENS) |
| 853 | } |
| 854 | ); |
| 855 | assert_eq!( |
| 856 | effective_max_output_tokens_for_route(provider, model, None), |
| 857 | 64_000, |
| 858 | "{provider:?}: no route fact must preserve the labeled automatic allowance" |
| 859 | ); |
| 860 | for route_cap in [24_576, 64_000] { |
| 861 | assert_eq!( |
| 862 | effective_max_output_tokens_for_route( |
| 863 | provider, |
| 864 | model, |
| 865 | Some(RouteLimits { |
| 866 | output_tokens: Some(route_cap), |
| 867 | ..RouteLimits::default() |
| 868 | }), |
| 869 | ), |
| 870 | u32::try_from(route_cap).unwrap(), |
| 871 | "{provider:?}: the exact route fact must replace the catalogue-absence guess" |
| 872 | ); |
| 873 | } |
| 874 | assert_eq!( |
| 875 | effective_max_output_tokens_for_route( |
| 876 | provider, |
| 877 | model, |
| 878 | Some(RouteLimits { |
| 879 | output_tokens: Some(65_536), |
| 880 | ..RouteLimits::default() |
| 881 | }), |
| 882 | ), |
| 883 | 64_000, |
| 884 | "{provider:?}: a route fact must not raise the requested cap" |
| 885 | ); |
| 886 | } |
| 887 | |
| 888 | assert_eq!( |
| 889 | effective_max_output_tokens_for_route( |
| 890 | ProviderKind::Moonshot, |
| 891 | "kimi-k2.7-code", |
| 892 | Some(RouteLimits { |
| 893 | output_tokens: Some(64_000), |
| 894 | ..RouteLimits::default() |
| 895 | }), |
| 896 | ), |
| 897 | 32_768, |
| 898 | "a route fact must not raise a documented model ceiling" |
| 899 | ); |
| 900 | } |
| 901 | |
| 902 | /// Routes that *declare* an unknown ceiling still avoid the clamp. |
| 903 | #[test] |
| 904 | fn route_declared_unknown_ceilings_are_not_clamped() { |
| 905 | for (provider, model) in [ |
| 906 | (ProviderKind::Moonshot, "kimi-for-coding"), |
| 907 | (ProviderKind::Moonshot, "kimi-for-coding-highspeed"), |
| 908 | (ProviderKind::Ollama, "some-local-build"), |
| 909 | (ProviderKind::Custom, "alibaba/qwen3.8-27b"), |
| 910 | ] { |
| 911 | assert_eq!( |
| 912 | output_ceiling_source(provider, model), |
| 913 | OutputCeilingSource::RouteDeclaredUnknown, |
| 914 | "{provider:?}/{model} must declare its unknown ceiling" |
| 915 | ); |
| 916 | assert_eq!(output_ceiling_source(provider, model).clamp_tokens(), None); |
| 917 | } |
| 918 | // Bare `k3` is a membership id, but unlike the `kimi-for-coding` |
| 919 | // family the K3 quickstart documents its output maximum, and the model |
| 920 | // catalogue carries it. A documented ceiling is authoritative — the |
| 921 | // membership allowlist only covers ids the catalogue has nothing to |
| 922 | // say about, and must not turn a real fact back into an unknown. |
| 923 | assert_eq!( |
| 924 | output_ceiling_source(ProviderKind::Moonshot, "k3"), |
| 925 | OutputCeilingSource::Documented(131_072) |
| 926 | ); |
| 927 | assert_eq!( |
| 928 | output_ceiling_source(ProviderKind::OllamaCloud, "some-cloud-build"), |
| 929 | OutputCeilingSource::Uncatalogued(UNCATALOGUED_COMPAT_MAX_OUTPUT_TOKENS), |
| 930 | "hosted Ollama Cloud must not inherit the local runtime's unbounded output semantics" |
| 931 | ); |
| 932 | } |
| 933 | |
| 934 | /// #5440: an Anthropic-family model the catalogue does not describe keeps |
| 935 | /// the 64K Messages floor as its clamp, but the floor is an assumption |
| 936 | /// about that model — never a "documented" ceiling. |
| 937 | #[test] |
| 938 | fn anthropic_unknown_model_ceiling_is_an_unverified_assumed_floor() { |
| 939 | let source = output_ceiling_source(ProviderKind::Anthropic, "claude-future-99"); |
| 940 | assert_eq!(source, OutputCeilingSource::Unverified(64_000)); |
| 941 | assert_eq!(source.as_str(), "unverified"); |
| 942 | assert_eq!(source.clamp_tokens(), Some(64_000)); |
| 943 | // Same honesty on the compatibility dialects of the same family. |
| 944 | assert_eq!( |
| 945 | output_ceiling_source(ProviderKind::MinimaxAnthropic, "claude-future-99"), |
| 946 | OutputCeilingSource::Unverified(64_000) |
| 947 | ); |
| 948 | assert_eq!( |
| 949 | output_ceiling_source(ProviderKind::Openmodel, "claude-future-99"), |
| 950 | OutputCeilingSource::Unverified(64_000) |
| 951 | ); |
| 952 | } |
| 953 | |
| 954 | /// #5440: a model the catalogue does describe keeps its documented |
| 955 | /// ceiling and its documented label — the unverified rung must not |
| 956 | /// swallow real facts. |
| 957 | #[test] |
| 958 | fn anthropic_documented_model_ceiling_stays_documented() { |
| 959 | let source = output_ceiling_source(ProviderKind::Anthropic, "claude-sonnet-4-6"); |
| 960 | assert_eq!(source, OutputCeilingSource::Documented(128_000)); |
| 961 | assert_eq!(source.as_str(), "documented"); |
| 962 | assert_eq!(source.clamp_tokens(), Some(128_000)); |
| 963 | } |
| 964 | |
| 965 | /// #5440: the Codex OAuth route clamps every response to 4K by policy, |
| 966 | /// because the OAuth cache publishes no ceiling. The clamp stands; the |
| 967 | /// receipt must call the number what it is. |
| 968 | #[test] |
| 969 | fn codex_oauth_ceiling_clamps_but_never_claims_documented() { |
| 970 | let source = output_ceiling_source(ProviderKind::OpenaiCodex, "gpt-5.5"); |
| 971 | assert_eq!(source, OutputCeilingSource::Unverified(4_096)); |
| 972 | assert_eq!(source.as_str(), "unverified"); |
| 973 | assert_eq!(source.clamp_tokens(), Some(4_096)); |
| 974 | assert_eq!( |
| 975 | effective_max_output_tokens_for_route(ProviderKind::OpenaiCodex, "gpt-5.5", None), |
| 976 | 4_096, |
| 977 | "the honesty relabel must not revalue the long-standing clamp" |
| 978 | ); |
| 979 | } |
| 980 | |
| 981 | #[test] |
| 982 | fn codex_missing_route_metadata_uses_provider_context_floor() { |
| 983 | assert_eq!( |
| 984 | route_context_window_tokens(ProviderKind::OpenaiCodex, "gpt-5.5", None), |
| 985 | 128_000 |
| 986 | ); |
| 987 | // 80% of the 128K window (102_400) fits under the input ceiling. |
| 988 | assert_eq!( |
| 989 | compaction_threshold_for_route_at_percent( |
| 990 | ProviderKind::OpenaiCodex, |
| 991 | "gpt-5.5", |
| 992 | None, |
| 993 | 80.0, |
| 994 | ), |
| 995 | 102_400 |
| 996 | ); |
| 997 | assert!(auto_compact_default_for_route( |
| 998 | ProviderKind::OpenaiCodex, |
| 999 | "gpt-5.5", |
| 1000 | None, |
| 1001 | )); |
| 1002 | } |
| 1003 | |
| 1004 | /// The assertion values here depend on `explicit_max_output_tokens_override` |
| 1005 | /// seeing no ambient env override, and sibling tests in this binary |
| 1006 | /// (this module, `client`, `vision/tools`, `core/engine`) set |
| 1007 | /// `CODEWHALE_MAX_OUTPUT_TOKENS`/`DEEPSEEK_MAX_OUTPUT_TOKENS` while holding |
| 1008 | /// `lock_test_env`. Without the lock and guards this test could read a |
| 1009 | /// concurrent writer's value mid-assertion (process-global env, parallel |
| 1010 | /// threads), which is the order-dependent flake this guards against. |
| 1011 | #[test] |
| 1012 | fn v4_trigger_uses_window_percent_when_it_fits_spendable_input() { |
| 1013 | let _lock = crate::test_support::lock_test_env(); |
| 1014 | let _codewhale = crate::test_support::EnvVarGuard::remove("CODEWHALE_MAX_OUTPUT_TOKENS"); |
| 1015 | let _deepseek = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MAX_OUTPUT_TOKENS"); |
| 1016 | |
| 1017 | let budget = route_context_budget(ProviderKind::Deepseek, "deepseek-v4-pro", None, 0) |
| 1018 | .expect("V4 route budget"); |
| 1019 | |
| 1020 | assert_eq!(budget.window_tokens, 1_000_000); |
| 1021 | assert_eq!(budget.output_cap_tokens, u64::from(API_MAX_OUTPUT_TOKENS)); |
| 1022 | assert_eq!(budget.input_budget_ceiling, 933_440); |
| 1023 | // 80% of the 1M window fits below the spendable input ceiling. |
| 1024 | assert_eq!( |
| 1025 | compaction_threshold_for_route_at_percent( |
| 1026 | ProviderKind::Deepseek, |
| 1027 | "deepseek-v4-pro", |
| 1028 | None, |
| 1029 | 80.0, |
| 1030 | ), |
| 1031 | 800_000 |
| 1032 | ); |
| 1033 | } |
| 1034 | |
| 1035 | #[test] |
| 1036 | fn kimi_k3_defaults_auto_compaction_on() { |
| 1037 | assert!(auto_compact_default_for_route( |
| 1038 | ProviderKind::Moonshot, |
| 1039 | "kimi-k3", |
| 1040 | None, |
| 1041 | )); |
| 1042 | } |
| 1043 | |
| 1044 | #[test] |
| 1045 | fn kimi_catalog_output_ceiling_preserves_input_budget() { |
| 1046 | let _lock = crate::test_support::lock_test_env(); |
| 1047 | let _max_output = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MAX_OUTPUT_TOKENS"); |
| 1048 | // #4368/#4378: Models.dev may report Kimi's full 262K context as both |
| 1049 | // context and output ceilings. Reserve the route-effective 32K request |
| 1050 | // cap rather than treating that catalog maximum as the amount every |
| 1051 | // turn will emit. |
| 1052 | let limits = RouteLimits { |
| 1053 | context_tokens: Some(262_144), |
| 1054 | output_tokens: Some(262_144), |
| 1055 | ..RouteLimits::default() |
| 1056 | }; |
| 1057 | let budget = |
| 1058 | route_context_budget(ProviderKind::Moonshot, "kimi-k2.7-code", Some(limits), 0) |
| 1059 | .expect("Kimi route budget"); |
| 1060 | let trigger = compaction_threshold_for_route_at_percent( |
| 1061 | ProviderKind::Moonshot, |
| 1062 | "kimi-k2.7-code", |
| 1063 | Some(limits), |
| 1064 | 80.0, |
| 1065 | ); |
| 1066 | |
| 1067 | assert_eq!(budget.output_cap_tokens, 32_768); |
| 1068 | assert_eq!(budget.input_budget_ceiling, 228_352); |
| 1069 | // 80% of the 262_144 window; fits under the 228_352 ceiling because |
| 1070 | // the output reservation is the route-effective 32K request cap. |
| 1071 | assert_eq!(trigger, 209_715); |
| 1072 | assert!(trigger as u64 <= budget.input_budget_ceiling); |
| 1073 | } |
| 1074 | |
| 1075 | #[test] |
| 1076 | fn explicit_route_output_limit_beats_unknown_model_name_fallback() { |
| 1077 | let _lock = crate::test_support::lock_test_env(); |
| 1078 | let _max_output = |
| 1079 | crate::test_support::EnvVarGuard::set("CODEWHALE_MAX_OUTPUT_TOKENS", "65536"); |
| 1080 | let limits = RouteLimits { |
| 1081 | context_tokens: Some(262_144), |
| 1082 | output_tokens: Some(24_576), |
| 1083 | ..RouteLimits::default() |
| 1084 | }; |
| 1085 | |
| 1086 | assert_eq!( |
| 1087 | effective_max_output_tokens_for_route( |
| 1088 | ProviderKind::Vllm, |
| 1089 | "arbitrary-local-wire-alias", |
| 1090 | Some(limits), |
| 1091 | ), |
| 1092 | 24_576 |
| 1093 | ); |
| 1094 | assert_eq!( |
| 1095 | effective_max_output_tokens_for_route( |
| 1096 | ProviderKind::Vllm, |
| 1097 | "arbitrary-local-wire-alias", |
| 1098 | None, |
| 1099 | ), |
| 1100 | 65_536, |
| 1101 | "an unknown compatibility cap must not clamp; only the requested cap applies" |
| 1102 | ); |
| 1103 | assert_eq!( |
| 1104 | effective_max_output_tokens_for_route( |
| 1105 | ProviderKind::Vllm, |
| 1106 | "kimi-k2.7-code", |
| 1107 | Some(RouteLimits { |
| 1108 | output_tokens: Some(262_144), |
| 1109 | ..RouteLimits::default() |
| 1110 | }), |
| 1111 | ), |
| 1112 | 32_768, |
| 1113 | "known model caps must remain authoritative on self-hosted routes" |
| 1114 | ); |
| 1115 | } |
| 1116 | |
| 1117 | /// #4368 follow-up: the Kimi Code membership ids deliberately have no |
| 1118 | /// static output cap (the membership catalog owns their limits). The old |
| 1119 | /// generic `unwrap_or(4096)` in `provider_capability` turned that unknown |
| 1120 | /// into a hard 4K clamp here, silently truncating every offline membership |
| 1121 | /// turn. Unknown must mean "no compatibility clamp". |
| 1122 | #[test] |
| 1123 | fn kimi_membership_unknown_output_cap_does_not_clamp_to_4k() { |
| 1124 | let _lock = crate::test_support::lock_test_env(); |
| 1125 | let _codewhale = crate::test_support::EnvVarGuard::remove("CODEWHALE_MAX_OUTPUT_TOKENS"); |
| 1126 | let _deepseek = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MAX_OUTPUT_TOKENS"); |
| 1127 | |
| 1128 | for model in ["kimi-for-coding", "kimi-for-coding-highspeed"] { |
| 1129 | assert_eq!( |
| 1130 | provider_capability(ProviderKind::Moonshot, model).max_output, |
| 1131 | None, |
| 1132 | "{model}: membership output ceiling must stay unknown, not a placeholder" |
| 1133 | ); |
| 1134 | |
| 1135 | let cap = effective_max_output_tokens_for_route(ProviderKind::Moonshot, model, None); |
| 1136 | assert_eq!( |
| 1137 | cap, |
| 1138 | effective_max_output_tokens(model), |
| 1139 | "{model}: unknown compatibility cap must leave the requested cap intact" |
| 1140 | ); |
| 1141 | assert_ne!(cap, 4_096, "{model}: must not inherit the old 4K fallback"); |
| 1142 | // No invented sentinel ceiling either. |
| 1143 | assert_ne!(cap, u32::MAX); |
| 1144 | assert_ne!(cap, 32_768); |
| 1145 | } |
| 1146 | } |
| 1147 | |
| 1148 | /// A concrete membership offering limit is still authoritative — "unknown |
| 1149 | /// means no clamp" must not become "never clamp". |
| 1150 | #[test] |
| 1151 | fn kimi_membership_route_limit_still_caps_output() { |
| 1152 | let _lock = crate::test_support::lock_test_env(); |
| 1153 | let _codewhale = crate::test_support::EnvVarGuard::remove("CODEWHALE_MAX_OUTPUT_TOKENS"); |
| 1154 | let _deepseek = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MAX_OUTPUT_TOKENS"); |
| 1155 | |
| 1156 | let limits = RouteLimits { |
| 1157 | context_tokens: Some(262_144), |
| 1158 | output_tokens: Some(16_384), |
| 1159 | ..RouteLimits::default() |
| 1160 | }; |
| 1161 | assert_eq!( |
| 1162 | effective_max_output_tokens_for_route( |
| 1163 | ProviderKind::Moonshot, |
| 1164 | "kimi-for-coding", |
| 1165 | Some(limits), |
| 1166 | ), |
| 1167 | 16_384 |
| 1168 | ); |
| 1169 | } |
| 1170 | |
| 1171 | /// GLM and MiniMax publish real output ceilings; those stay authoritative |
| 1172 | /// so relaxing the unknown case cannot leak into known routes. |
| 1173 | #[test] |
| 1174 | fn known_glm_and_minimax_output_caps_remain_authoritative() { |
| 1175 | let _lock = crate::test_support::lock_test_env(); |
| 1176 | let _codewhale = crate::test_support::EnvVarGuard::remove("CODEWHALE_MAX_OUTPUT_TOKENS"); |
| 1177 | let _deepseek = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MAX_OUTPUT_TOKENS"); |
| 1178 | |
| 1179 | // GLM 5.2: 1M window, documented 131K output. The capability remains |
| 1180 | // known even though the safe automatic request starts at 64K. |
| 1181 | let glm = provider_capability(ProviderKind::Zai, "glm-5.2"); |
| 1182 | assert_eq!(glm.max_output, Some(131_072)); |
| 1183 | |
| 1184 | let minimax = provider_capability(ProviderKind::Minimax, "minimax-m3"); |
| 1185 | assert_eq!(minimax.max_output, Some(524_288)); |
| 1186 | |
| 1187 | // A known cap below the requested cap must still clamp. |
| 1188 | assert_eq!( |
| 1189 | effective_max_output_tokens_for_route(ProviderKind::Moonshot, "kimi-k2.7-code", None), |
| 1190 | 32_768, |
| 1191 | ); |
| 1192 | } |
| 1193 | |
| 1194 | /// A documented capability maximum is not itself a sane default request |
| 1195 | /// size. The capability remains documented and available as an explicit |
| 1196 | /// override; only the automatic request is bounded. |
| 1197 | #[test] |
| 1198 | fn documented_ceiling_is_a_bound_not_an_unbounded_default_request() { |
| 1199 | let _lock = crate::test_support::lock_test_env(); |
| 1200 | let _codewhale = crate::test_support::EnvVarGuard::remove("CODEWHALE_MAX_OUTPUT_TOKENS"); |
| 1201 | let _deepseek = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MAX_OUTPUT_TOKENS"); |
| 1202 | |
| 1203 | for model in [ |
| 1204 | "deepseek-v4-flash", |
| 1205 | "deepseek-v4-pro", |
| 1206 | "deepseek-v4flash", |
| 1207 | "deepseek-ai/deepseek-v4-pro", |
| 1208 | "deepseek-chat", |
| 1209 | "deepseek-reasoner", |
| 1210 | ] { |
| 1211 | assert_eq!( |
| 1212 | output_ceiling_source(ProviderKind::Deepseek, model), |
| 1213 | OutputCeilingSource::Documented(384_000), |
| 1214 | "{model}" |
| 1215 | ); |
| 1216 | } |
| 1217 | assert_eq!( |
| 1218 | effective_max_output_tokens("deepseek-v4-flash"), |
| 1219 | API_MAX_OUTPUT_TOKENS, |
| 1220 | "a 384K capability maximum must not become the no-config request size" |
| 1221 | ); |
| 1222 | assert_eq!( |
| 1223 | effective_max_output_tokens("glm-5.2"), |
| 1224 | API_MAX_OUTPUT_TOKENS, |
| 1225 | "a 131K capability maximum must also remain a ceiling, not a default" |
| 1226 | ); |
| 1227 | } |
| 1228 | |
| 1229 | #[test] |
| 1230 | fn uncatalogued_deepseek_variants_require_exact_output_metadata() { |
| 1231 | let _env_lock = crate::test_support::lock_test_env(); |
| 1232 | let _codewhale = crate::test_support::EnvVarGuard::remove("CODEWHALE_MAX_OUTPUT_TOKENS"); |
| 1233 | let _deepseek = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MAX_OUTPUT_TOKENS"); |
| 1234 | |
| 1235 | for provider in [ |
| 1236 | ProviderKind::Deepseek, |
| 1237 | ProviderKind::Deepseek, |
| 1238 | ProviderKind::DeepseekAnthropic, |
| 1239 | ProviderKind::Custom, |
| 1240 | ] { |
| 1241 | for model in [ |
| 1242 | "deepseek-v4.1-flash-expires-on-0910", |
| 1243 | "deepseek-v4-flash-vendor", |
| 1244 | ] { |
| 1245 | assert_eq!(provider_capability(provider, model).max_output, None); |
| 1246 | let source = output_ceiling_source(provider, model); |
| 1247 | if provider == ProviderKind::Custom { |
| 1248 | assert_eq!(source, OutputCeilingSource::RouteDeclaredUnknown); |
| 1249 | assert_eq!(source.as_str(), "route-declared"); |
| 1250 | } else { |
| 1251 | assert_eq!(source, OutputCeilingSource::Uncatalogued(65_536)); |
| 1252 | assert_eq!(source.as_str(), "uncatalogued"); |
| 1253 | } |
| 1254 | assert_eq!( |
| 1255 | effective_max_output_tokens_for_route(provider, model, None), |
| 1256 | 64_000, |
| 1257 | "{provider:?}: {model}" |
| 1258 | ); |
| 1259 | } |
| 1260 | } |
| 1261 | |
| 1262 | assert_eq!( |
| 1263 | output_ceiling_source(ProviderKind::Deepseek, "deepseek-v4.1-flash"), |
| 1264 | OutputCeilingSource::Documented(384_000) |
| 1265 | ); |
| 1266 | |
| 1267 | // Exact route output facts supply a ceiling only for that request. |
| 1268 | let limits = RouteLimits { |
| 1269 | context_tokens: Some(128_000), |
| 1270 | output_tokens: Some(24_576), |
| 1271 | ..RouteLimits::default() |
| 1272 | }; |
| 1273 | assert_eq!( |
| 1274 | effective_max_output_tokens_for_route( |
| 1275 | ProviderKind::Deepseek, |
| 1276 | "deepseek-v4.1-flash-expires-on-0910", |
| 1277 | Some(limits) |
| 1278 | ), |
| 1279 | 24_576 |
| 1280 | ); |
| 1281 | assert_eq!( |
| 1282 | codewhale_models::max_output_tokens_for_model("deepseek-v4.1-flash-expires-on-0910"), |
| 1283 | None |
| 1284 | ); |
| 1285 | } |
| 1286 | |
| 1287 | #[test] |
| 1288 | fn deepseek_v4_explicit_mid_windows_share_one_safe_no_config_budget() { |
| 1289 | let _lock = crate::test_support::lock_test_env(); |
| 1290 | let _codewhale = crate::test_support::EnvVarGuard::remove("CODEWHALE_MAX_OUTPUT_TOKENS"); |
| 1291 | let _deepseek = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MAX_OUTPUT_TOKENS"); |
| 1292 | |
| 1293 | for window in [262_144, 327_680, 393_216] { |
| 1294 | let limits = RouteLimits { |
| 1295 | context_tokens: Some(window), |
| 1296 | ..RouteLimits::default() |
| 1297 | }; |
| 1298 | let cap = effective_max_output_tokens_for_route( |
| 1299 | ProviderKind::Vllm, |
| 1300 | "DeepSeek-V4-Flash", |
| 1301 | Some(limits), |
| 1302 | ); |
| 1303 | let reservation = |
| 1304 | route_output_reservation(ProviderKind::Vllm, "DeepSeek-V4-Flash", Some(limits)); |
| 1305 | let budget = route_context_budget( |
| 1306 | ProviderKind::Vllm, |
| 1307 | "DeepSeek-V4-Flash", |
| 1308 | Some(limits), |
| 1309 | 105_000, |
| 1310 | ) |
| 1311 | .expect("explicit vLLM route budget"); |
| 1312 | |
| 1313 | assert_eq!(cap, API_MAX_OUTPUT_TOKENS, "window={window}"); |
| 1314 | assert_eq!(reservation, cap, "window={window}"); |
| 1315 | assert_eq!( |
| 1316 | budget.input_budget_ceiling, |
| 1317 | window - u64::from(API_MAX_OUTPUT_TOKENS) - 1_024, |
| 1318 | "window={window}" |
| 1319 | ); |
| 1320 | assert!( |
| 1321 | 105_000 < budget.input_budget_ceiling, |
| 1322 | "ordinary 85K-105K inputs must not trigger emergency compaction: {budget:?}" |
| 1323 | ); |
| 1324 | assert!(budget.available_input_tokens > 0, "window={window}"); |
| 1325 | } |
| 1326 | } |
| 1327 | |
| 1328 | #[test] |
| 1329 | fn explicit_output_override_is_preserved_and_reserved_on_mid_windows() { |
| 1330 | let _lock = crate::test_support::lock_test_env(); |
| 1331 | let _codewhale = |
| 1332 | crate::test_support::EnvVarGuard::set("CODEWHALE_MAX_OUTPUT_TOKENS", "100000"); |
| 1333 | let _deepseek = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MAX_OUTPUT_TOKENS"); |
| 1334 | let limits = RouteLimits { |
| 1335 | context_tokens: Some(327_680), |
| 1336 | ..RouteLimits::default() |
| 1337 | }; |
| 1338 | |
| 1339 | let cap = effective_max_output_tokens_for_route( |
| 1340 | ProviderKind::Vllm, |
| 1341 | "DeepSeek-V4-Flash", |
| 1342 | Some(limits), |
| 1343 | ); |
| 1344 | assert_eq!(cap, 100_000); |
| 1345 | assert_eq!( |
| 1346 | route_output_reservation(ProviderKind::Vllm, "DeepSeek-V4-Flash", Some(limits),), |
| 1347 | cap |
| 1348 | ); |
| 1349 | let budget = route_context_budget( |
| 1350 | ProviderKind::Vllm, |
| 1351 | "DeepSeek-V4-Flash", |
| 1352 | Some(limits), |
| 1353 | 105_000, |
| 1354 | ) |
| 1355 | .expect("override route budget"); |
| 1356 | assert_eq!(budget.input_budget_ceiling, 226_656); |
| 1357 | assert!(budget.available_input_tokens > 0); |
| 1358 | } |
| 1359 | |
| 1360 | #[test] |
| 1361 | fn explicit_uncatalogued_allowance_respects_route_and_context_limits() { |
| 1362 | let _lock = crate::test_support::lock_test_env(); |
| 1363 | let _canonical = |
| 1364 | crate::test_support::EnvVarGuard::set("CODEWHALE_MAX_OUTPUT_TOKENS", "100000"); |
| 1365 | let _legacy = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MAX_OUTPUT_TOKENS"); |
| 1366 | let model = "uncatalogued-preview-for-output-test"; |
| 1367 | let limits = RouteLimits { |
| 1368 | context_tokens: Some(327_680), |
| 1369 | ..RouteLimits::default() |
| 1370 | }; |
| 1371 | assert_eq!( |
| 1372 | effective_max_output_tokens_for_route(ProviderKind::Custom, model, Some(limits)), |
| 1373 | 100_000 |
| 1374 | ); |
| 1375 | assert_eq!( |
| 1376 | effective_max_output_tokens_for_route( |
| 1377 | ProviderKind::Custom, |
| 1378 | model, |
| 1379 | Some(RouteLimits { |
| 1380 | output_tokens: Some(32_768), |
| 1381 | ..limits |
| 1382 | }) |
| 1383 | ), |
| 1384 | 32_768 |
| 1385 | ); |
| 1386 | let small = RouteLimits { |
| 1387 | context_tokens: Some(32_768), |
| 1388 | ..RouteLimits::default() |
| 1389 | }; |
| 1390 | let cap = effective_max_output_tokens_for_route(ProviderKind::Custom, model, Some(small)); |
| 1391 | assert_eq!(cap, 30_720); |
| 1392 | assert_eq!( |
| 1393 | route_output_reservation(ProviderKind::Custom, model, Some(small)), |
| 1394 | cap |
| 1395 | ); |
| 1396 | } |
| 1397 | |
| 1398 | #[test] |
| 1399 | fn oversized_explicit_override_is_clamped_and_reserved_to_the_route_window() { |
| 1400 | let _lock = crate::test_support::lock_test_env(); |
| 1401 | let _codewhale = |
| 1402 | crate::test_support::EnvVarGuard::set("CODEWHALE_MAX_OUTPUT_TOKENS", "384000"); |
| 1403 | let _deepseek = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MAX_OUTPUT_TOKENS"); |
| 1404 | let limits = RouteLimits { |
| 1405 | context_tokens: Some(327_680), |
| 1406 | ..RouteLimits::default() |
| 1407 | }; |
| 1408 | |
| 1409 | let cap = effective_max_output_tokens_for_route( |
| 1410 | ProviderKind::Vllm, |
| 1411 | "DeepSeek-V4-Flash", |
| 1412 | Some(limits), |
| 1413 | ); |
| 1414 | assert_eq!(cap, 325_632); |
| 1415 | assert_eq!( |
| 1416 | route_output_reservation(ProviderKind::Vllm, "DeepSeek-V4-Flash", Some(limits),), |
| 1417 | cap, |
| 1418 | "preflight must reserve every token the explicit override can put on the wire" |
| 1419 | ); |
| 1420 | let budget = route_context_budget(ProviderKind::Vllm, "DeepSeek-V4-Flash", Some(limits), 0) |
| 1421 | .expect("oversized override route budget"); |
| 1422 | assert_eq!(budget.input_budget_ceiling, 1_024); |
| 1423 | } |
| 1424 | |
| 1425 | #[test] |
| 1426 | fn explicit_override_on_large_window_stays_unified() { |
| 1427 | let _lock = crate::test_support::lock_test_env(); |
| 1428 | let _codewhale = |
| 1429 | crate::test_support::EnvVarGuard::set("CODEWHALE_MAX_OUTPUT_TOKENS", "384000"); |
| 1430 | let _deepseek = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MAX_OUTPUT_TOKENS"); |
| 1431 | let limits = RouteLimits { |
| 1432 | context_tokens: Some(1_000_000), |
| 1433 | ..RouteLimits::default() |
| 1434 | }; |
| 1435 | |
| 1436 | let cap = effective_max_output_tokens_for_route( |
| 1437 | ProviderKind::Vllm, |
| 1438 | "DeepSeek-V4-Flash", |
| 1439 | Some(limits), |
| 1440 | ); |
| 1441 | let reservation = |
| 1442 | route_output_reservation(ProviderKind::Vllm, "DeepSeek-V4-Flash", Some(limits)); |
| 1443 | let budget = route_context_budget(ProviderKind::Vllm, "DeepSeek-V4-Flash", Some(limits), 0) |
| 1444 | .expect("large explicit route budget"); |
| 1445 | |
| 1446 | assert_eq!(cap, 384_000); |
| 1447 | assert_eq!(reservation, cap); |
| 1448 | assert_eq!(budget.output_cap_tokens, u64::from(cap)); |
| 1449 | assert_eq!(budget.input_budget_ceiling, 614_976); |
| 1450 | } |
| 1451 | |
| 1452 | #[test] |
| 1453 | fn automatic_wire_cap_and_reservation_have_no_large_window_cliff() { |
| 1454 | let _lock = crate::test_support::lock_test_env(); |
| 1455 | let _codewhale = crate::test_support::EnvVarGuard::remove("CODEWHALE_MAX_OUTPUT_TOKENS"); |
| 1456 | let _deepseek = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MAX_OUTPUT_TOKENS"); |
| 1457 | |
| 1458 | for window in [499_999, 500_000, 1_000_000] { |
| 1459 | let limits = RouteLimits { |
| 1460 | context_tokens: Some(window), |
| 1461 | ..RouteLimits::default() |
| 1462 | }; |
| 1463 | let wire = effective_max_output_tokens_for_route( |
| 1464 | ProviderKind::Vllm, |
| 1465 | "DeepSeek-V4-Flash", |
| 1466 | Some(limits), |
| 1467 | ); |
| 1468 | let reservation = |
| 1469 | route_output_reservation(ProviderKind::Vllm, "DeepSeek-V4-Flash", Some(limits)); |
| 1470 | assert_eq!(wire, API_MAX_OUTPUT_TOKENS, "window={window}"); |
| 1471 | assert_eq!(reservation, wire, "window={window}"); |
| 1472 | } |
| 1473 | } |
| 1474 | |
| 1475 | #[test] |
| 1476 | fn concrete_route_input_limit_clamps_preflight_and_compaction() { |
| 1477 | let _lock = crate::test_support::lock_test_env(); |
| 1478 | let _codewhale = crate::test_support::EnvVarGuard::remove("CODEWHALE_MAX_OUTPUT_TOKENS"); |
| 1479 | let _deepseek = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MAX_OUTPUT_TOKENS"); |
| 1480 | let limits = RouteLimits { |
| 1481 | context_tokens: Some(1_000_000), |
| 1482 | input_tokens: Some(128_000), |
| 1483 | output_tokens: Some(64_000), |
| 1484 | output_declared: false, |
| 1485 | }; |
| 1486 | |
| 1487 | let budget = route_context_budget( |
| 1488 | ProviderKind::Vllm, |
| 1489 | "DeepSeek-V4-Flash", |
| 1490 | Some(limits), |
| 1491 | 200_000, |
| 1492 | ) |
| 1493 | .expect("route budget"); |
| 1494 | assert_eq!(route_input_limit_tokens(Some(limits)), Some(128_000)); |
| 1495 | assert_eq!(budget.input_budget_ceiling, 128_000); |
| 1496 | assert_eq!(budget.available_input_tokens, 0); |
| 1497 | assert_eq!(budget.compaction_trigger_for_percent(80.0), 128_000); |
| 1498 | } |
| 1499 | |
| 1500 | #[test] |
| 1501 | fn canonical_output_override_blank_falls_through_but_invalid_is_authoritative() { |
| 1502 | let _lock = crate::test_support::lock_test_env(); |
| 1503 | let _legacy = crate::test_support::EnvVarGuard::set("DEEPSEEK_MAX_OUTPUT_TOKENS", "100000"); |
| 1504 | |
| 1505 | { |
| 1506 | let _canonical = |
| 1507 | crate::test_support::EnvVarGuard::set("CODEWHALE_MAX_OUTPUT_TOKENS", " "); |
| 1508 | assert_eq!(explicit_max_output_tokens_override(), Some(100_000)); |
| 1509 | } |
| 1510 | for invalid in ["not-a-number", "0"] { |
| 1511 | let _canonical = |
| 1512 | crate::test_support::EnvVarGuard::set("CODEWHALE_MAX_OUTPUT_TOKENS", invalid); |
| 1513 | assert_eq!(explicit_max_output_tokens_override(), None, "{invalid}"); |
| 1514 | assert_eq!( |
| 1515 | effective_max_output_tokens("deepseek-v4-pro"), |
| 1516 | API_MAX_OUTPUT_TOKENS |
| 1517 | ); |
| 1518 | } |
| 1519 | } |
| 1520 | |
| 1521 | #[test] |
| 1522 | fn mid_window_internal_reservation_stays_on_the_ordinary_request_floor() { |
| 1523 | let _lock = crate::test_support::lock_test_env(); |
| 1524 | let _codewhale = crate::test_support::EnvVarGuard::remove("CODEWHALE_MAX_OUTPUT_TOKENS"); |
| 1525 | let _deepseek = crate::test_support::EnvVarGuard::remove("DEEPSEEK_MAX_OUTPUT_TOKENS"); |
| 1526 | let reservation = |
| 1527 | route_output_reservation(ProviderKind::Arcee, "trinity-large-thinking", None); |
| 1528 | assert_eq!(reservation, API_MAX_OUTPUT_TOKENS); |
| 1529 | let budget = route_context_budget(ProviderKind::Arcee, "trinity-large-thinking", None, 0) |
| 1530 | .expect("trinity route budget"); |
| 1531 | assert_eq!(budget.compaction_trigger_for_percent(80.0), 195_584); |
| 1532 | } |
| 1533 | |
| 1534 | #[test] |
| 1535 | fn review_reserve_is_sized_from_reasoning_classification() { |
| 1536 | // Mapping core (#6285): every classification arm. |
| 1537 | assert_eq!(review_reserve_percent_for(Some(false), false), 0); |
| 1538 | assert_eq!(review_reserve_percent_for(Some(false), true), 0); |
| 1539 | assert_eq!(review_reserve_percent_for(Some(true), false), 25); |
| 1540 | assert_eq!(review_reserve_percent_for(Some(true), true), 50); |
| 1541 | // Unknown (no catalogue row) is not evidence of no reasoning (#6032). |
| 1542 | assert_eq!(review_reserve_percent_for(None, false), 25); |
| 1543 | assert_eq!(review_reserve_percent_for(None, true), 25); |
| 1544 | } |
| 1545 | |
| 1546 | #[test] |
| 1547 | fn review_reserve_tokens_follow_the_model_classification() { |
| 1548 | // A model no catalogue row resolves for: a quarter of the allowance is |
| 1549 | // reserved as visible text, and the token math scales off the exact |
| 1550 | // resolved allowance. |
| 1551 | let unknown = "not-a-catalogue-model-6285"; |
| 1552 | assert_eq!(review_visible_text_reserve_percent(unknown), 25); |
| 1553 | assert_eq!(review_visible_text_reserve_tokens(unknown, 65_536), 16_384); |
| 1554 | assert_eq!(review_visible_text_reserve_tokens(unknown, 0), 0); |
| 1555 | } |
| 1556 | } |
| 1557 |