| 1 | //! Adaptive evidence routing for tool results (#4619) — explicit opt-in. |
| 2 | //! |
| 3 | //! Classic bounded spillover is the default: `tools/truncate.rs` keeps results |
| 4 | //! at or under its byte threshold fully inline and gives larger ones a |
| 5 | //! head/tail preview plus a session artifact. Set |
| 6 | //! `CODEWHALE_ADAPTIVE_OUTPUT_ROUTING` to enable the adaptive lane, which |
| 7 | //! classifies results as inline, hybrid, or handle-only by estimated tokens |
| 8 | //! and publishes non-inline results exactly once under their origin session |
| 9 | //! with immutable evidence metadata for bounded retrieval. |
| 10 | |
| 11 | use std::io; |
| 12 | use std::path::PathBuf; |
| 13 | |
| 14 | use serde::{Deserialize, Serialize}; |
| 15 | |
| 16 | use crate::tools::spec::ToolResult; |
| 17 | use codewhale_config::WorkshopConfig; |
| 18 | |
| 19 | // ── Constants ────────────────────────────────────────────────────────────────── |
| 20 | |
| 21 | /// Default token threshold separating hybrid from handle-only evidence. |
| 22 | /// |
| 23 | /// 32K tokens (≈96 KiB of text at the 3 chars/token estimate) keeps ordinary |
| 24 | /// tool results — file reads, test runs, build logs up to a few thousand |
| 25 | /// lines — fully inline. Only genuinely large outputs spill to evidence |
| 26 | /// artifacts, where the model-facing preview names the artifact path and how |
| 27 | /// to recover the omitted range. |
| 28 | pub const DEFAULT_LARGE_OUTPUT_THRESHOLD_TOKENS: usize = 32_768; |
| 29 | |
| 30 | /// Approximate characters-per-token ratio used for the heuristic estimate. |
| 31 | /// We intentionally choose a conservative value (3 chars/token) so we err |
| 32 | /// on the side of routing rather than dumping raw data into the parent. |
| 33 | const CHARS_PER_TOKEN_ESTIMATE: usize = 3; |
| 34 | |
| 35 | /// Resolve the effective threshold for the given tool name. |
| 36 | #[must_use] |
| 37 | pub fn workshop_threshold_for(config: &WorkshopConfig, tool_name: &str) -> usize { |
| 38 | if let Some(per_tool) = config.per_tool_thresholds.as_ref() |
| 39 | && let Some(&limit) = per_tool.get(tool_name) |
| 40 | { |
| 41 | return limit; |
| 42 | } |
| 43 | config |
| 44 | .large_output_threshold_tokens |
| 45 | .unwrap_or(DEFAULT_LARGE_OUTPUT_THRESHOLD_TOKENS) |
| 46 | } |
| 47 | |
| 48 | // ── Token estimation ────────────────────────────────────────────────────────── |
| 49 | |
| 50 | /// Estimate the number of tokens in `text` using a character-count heuristic. |
| 51 | /// |
| 52 | /// This avoids a real tokeniser dependency; the estimate is deliberately |
| 53 | /// conservative (under-counts tokens) so we route aggressively rather than |
| 54 | /// letting a 5K-token blob slip through. |
| 55 | #[must_use] |
| 56 | pub fn estimate_tokens(text: &str) -> usize { |
| 57 | let chars = text.chars().count(); |
| 58 | // Round up: partial last token still costs a token. |
| 59 | chars.div_ceil(CHARS_PER_TOKEN_ESTIMATE) |
| 60 | } |
| 61 | |
| 62 | // ── Router ──────────────────────────────────────────────────────────────────── |
| 63 | |
| 64 | /// Classifies tool results for adaptive evidence routing. |
| 65 | /// |
| 66 | /// This type is intentionally `Clone` and `Default` so it can be embedded |
| 67 | /// cheaply in [`ToolContext`](crate::tools::spec::ToolContext) without |
| 68 | /// requiring `Arc` wrappers. |
| 69 | #[derive(Debug, Clone, Default)] |
| 70 | pub struct LargeOutputRouter { |
| 71 | config: WorkshopConfig, |
| 72 | } |
| 73 | |
| 74 | impl LargeOutputRouter { |
| 75 | /// Construct a router from the resolved workshop config. |
| 76 | #[must_use] |
| 77 | pub fn new(config: WorkshopConfig) -> Self { |
| 78 | Self { config } |
| 79 | } |
| 80 | |
| 81 | #[must_use] |
| 82 | pub fn evidence_routing( |
| 83 | &self, |
| 84 | tool_name: &str, |
| 85 | result: &ToolResult, |
| 86 | ) -> (EvidenceRouting, usize, usize) { |
| 87 | let threshold = workshop_threshold_for(&self.config, tool_name); |
| 88 | let estimated_tokens = estimate_tokens(&result.content); |
| 89 | // There is no per-call bypass of the context bound: exact bytes stay |
| 90 | // available through the artifact handle. |
| 91 | let routing = EvidenceRouting::from_token_estimate(estimated_tokens, threshold); |
| 92 | (routing, estimated_tokens, threshold) |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | // ── Adaptive evidence routing (#4619) ───────────────────────────────────────── |
| 97 | |
| 98 | /// Routing policy for tool results: how much of the output stays inline in the |
| 99 | /// conversation vs. being stored as an external artifact. |
| 100 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 101 | #[serde(rename_all = "snake_case")] |
| 102 | pub enum EvidenceRouting { |
| 103 | /// Full result stays inline in the conversation context. |
| 104 | Inline, |
| 105 | /// A bounded observation (head/tail/summary) stays inline; the exact bytes |
| 106 | /// are stored as an artifact recoverable via handle. |
| 107 | Hybrid, |
| 108 | /// Only a handle/reference stays inline; the full result is artifact-only. |
| 109 | HandleOnly, |
| 110 | } |
| 111 | |
| 112 | impl EvidenceRouting { |
| 113 | /// Determine routing from estimated token count and threshold. |
| 114 | #[must_use] |
| 115 | pub fn from_token_estimate(estimated_tokens: usize, threshold: usize) -> Self { |
| 116 | if estimated_tokens <= threshold / 4 { |
| 117 | Self::Inline |
| 118 | } else if estimated_tokens <= threshold { |
| 119 | Self::Hybrid |
| 120 | } else { |
| 121 | Self::HandleOnly |
| 122 | } |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | /// Immutable metadata for a stored evidence artifact (#4619). |
| 127 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 128 | pub struct EvidenceArtifact { |
| 129 | pub handle: String, |
| 130 | pub digest: String, |
| 131 | pub size_bytes: u64, |
| 132 | pub content_type: String, |
| 133 | pub tool_name: String, |
| 134 | pub call_id: String, |
| 135 | pub origin_session: String, |
| 136 | pub generation: u32, |
| 137 | pub redacted: bool, |
| 138 | pub encoding: String, |
| 139 | pub retention_state: EvidenceRetentionState, |
| 140 | pub created_at_unix_ms: u64, |
| 141 | pub retain_until_unix_ms: u64, |
| 142 | pub storage_path: PathBuf, |
| 143 | } |
| 144 | |
| 145 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 146 | #[serde(rename_all = "snake_case")] |
| 147 | pub enum EvidenceRetentionState { |
| 148 | Live, |
| 149 | Expired, |
| 150 | } |
| 151 | |
| 152 | pub const EVIDENCE_RETENTION_SECS: u64 = 7 * 24 * 60 * 60; |
| 153 | |
| 154 | /// Whether adaptive evidence routing (#4619) is enabled for this process. |
| 155 | /// |
| 156 | /// Off by default — classic bounded spillover owns large results. Set |
| 157 | /// `CODEWHALE_ADAPTIVE_OUTPUT_ROUTING` to opt in. The retired rollback |
| 158 | /// variable is still honored in the negative, so |
| 159 | /// `CODEWHALE_CLASSIC_OUTPUT_ROUTING=0` also selects the adaptive lane. |
| 160 | #[must_use] |
| 161 | pub fn adaptive_output_routing_enabled() -> bool { |
| 162 | if let Ok(value) = std::env::var("CODEWHALE_ADAPTIVE_OUTPUT_ROUTING") { |
| 163 | return matches!(value.trim(), "1" | "true" | "yes" | "on"); |
| 164 | } |
| 165 | matches!( |
| 166 | std::env::var("CODEWHALE_CLASSIC_OUTPUT_ROUTING") |
| 167 | .ok() |
| 168 | .as_deref() |
| 169 | .map(str::trim), |
| 170 | Some("0" | "false" | "no" | "off") |
| 171 | ) |
| 172 | } |
| 173 | |
| 174 | #[must_use] |
| 175 | pub fn evidence_metadata_relative_path(handle: &str) -> PathBuf { |
| 176 | PathBuf::from(codewhale_runtime::artifacts::ARTIFACTS_DIR_NAME) |
| 177 | .join(format!("{handle}.evidence.json")) |
| 178 | } |
| 179 | |
| 180 | pub fn publish_evidence_metadata( |
| 181 | session_id: &str, |
| 182 | artifact: &EvidenceArtifact, |
| 183 | ) -> io::Result<PathBuf> { |
| 184 | let bytes = serde_json::to_vec_pretty(artifact) |
| 185 | .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?; |
| 186 | codewhale_runtime::artifacts::write_session_relative_immutable( |
| 187 | session_id, |
| 188 | &evidence_metadata_relative_path(&artifact.handle), |
| 189 | &bytes, |
| 190 | ) |
| 191 | } |
| 192 | |
| 193 | pub fn read_evidence_metadata(session_id: &str, handle: &str) -> io::Result<EvidenceArtifact> { |
| 194 | let relative = evidence_metadata_relative_path(handle); |
| 195 | let file = codewhale_runtime::artifacts::open_session_relative(session_id, &relative, false)?; |
| 196 | read_evidence_metadata_file(&file) |
| 197 | } |
| 198 | |
| 199 | /// Bounded, no-follow read shared by publication/replay and authenticated HTTP |
| 200 | /// retrieval. The caller chooses the existing session-root authority. |
| 201 | pub fn read_evidence_metadata_file( |
| 202 | file: &codewhale_util::files::WorkspaceFile, |
| 203 | ) -> io::Result<EvidenceArtifact> { |
| 204 | use std::io::Read; |
| 205 | const MAX_MANIFEST_BYTES: u64 = 64 * 1024; |
| 206 | let mut raw = Vec::new(); |
| 207 | file.open_file()? |
| 208 | .take(MAX_MANIFEST_BYTES + 1) |
| 209 | .read_to_end(&mut raw)?; |
| 210 | if raw.len() as u64 > MAX_MANIFEST_BYTES { |
| 211 | return Err(io::Error::new( |
| 212 | io::ErrorKind::InvalidData, |
| 213 | "evidence metadata exceeds limit", |
| 214 | )); |
| 215 | } |
| 216 | serde_json::from_slice(&raw).map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err)) |
| 217 | } |
| 218 | |
| 219 | #[must_use] |
| 220 | pub fn unix_millis_now() -> u64 { |
| 221 | std::time::SystemTime::now() |
| 222 | .duration_since(std::time::UNIX_EPOCH) |
| 223 | .unwrap_or_default() |
| 224 | .as_millis() |
| 225 | .try_into() |
| 226 | .unwrap_or(u64::MAX) |
| 227 | } |
| 228 | |
| 229 | #[must_use] |
| 230 | pub fn evidence_is_expired(artifact: &EvidenceArtifact, now_ms: u64) -> bool { |
| 231 | artifact.retention_state == EvidenceRetentionState::Expired |
| 232 | || now_ms > artifact.retain_until_unix_ms |
| 233 | } |
| 234 | |
| 235 | // ── Unit tests ──────────────────────────────────────────────────────────────── |
| 236 | |
| 237 | #[cfg(test)] |
| 238 | mod tests { |
| 239 | use super::*; |
| 240 | use std::collections::HashMap; |
| 241 | |
| 242 | fn make_result(content: &str) -> ToolResult { |
| 243 | ToolResult::success(content.to_string()) |
| 244 | } |
| 245 | |
| 246 | #[test] |
| 247 | fn default_threshold_is_32k_tokens() { |
| 248 | assert_eq!(DEFAULT_LARGE_OUTPUT_THRESHOLD_TOKENS, 32_768); |
| 249 | } |
| 250 | |
| 251 | #[test] |
| 252 | fn oversized_result_becomes_handle_only_evidence() { |
| 253 | let router = LargeOutputRouter::default(); |
| 254 | let big = make_result(&"a".repeat(100_000)); |
| 255 | let (routing, _, _) = router.evidence_routing("bash", &big); |
| 256 | assert_eq!(routing, EvidenceRouting::HandleOnly); |
| 257 | } |
| 258 | |
| 259 | #[test] |
| 260 | fn per_tool_threshold_override() { |
| 261 | let mut per_tool = HashMap::new(); |
| 262 | per_tool.insert("grep_files".to_string(), 100); // very low |
| 263 | let config = WorkshopConfig { |
| 264 | large_output_threshold_tokens: Some(4096), |
| 265 | per_tool_thresholds: Some(per_tool), |
| 266 | read_result_max_bytes: None, |
| 267 | tool_result_max_bytes: None, |
| 268 | }; |
| 269 | assert_eq!(workshop_threshold_for(&config, "grep_files"), 100); |
| 270 | assert_eq!(workshop_threshold_for(&config, "read_file"), 4096); |
| 271 | let default_config = WorkshopConfig::default(); |
| 272 | assert_eq!( |
| 273 | workshop_threshold_for(&default_config, "read_file"), |
| 274 | DEFAULT_LARGE_OUTPUT_THRESHOLD_TOKENS |
| 275 | ); |
| 276 | } |
| 277 | |
| 278 | #[test] |
| 279 | fn estimate_tokens_conservative() { |
| 280 | // 9 chars → ceil(9/3) = 3 tokens |
| 281 | assert_eq!(estimate_tokens("123456789"), 3); |
| 282 | // 10 chars → ceil(10/3) = 4 tokens |
| 283 | assert_eq!(estimate_tokens("1234567890"), 4); |
| 284 | // Empty string |
| 285 | assert_eq!(estimate_tokens(""), 0); |
| 286 | } |
| 287 | } |
| 288 |