返回 CodeWhale
superfast.rs
根目录 / crates / engine / src / superfast.rs
1 //! Superfast Decision Gate — a small, off-by-default "System One" front-door
2 //! classifier that rides the decision router's request (#6603).
3 //!
4 //! Every user message normally wakes a large, slow, expensive model just to
5 //! decide intent and whether a tool is needed. The Decision Gate asks a small,
6 //! fast decision model (a Jev-compatible System One endpoint) those routine
7 //! questions in one non-generating pass, and derives a conservative routing
8 //! recommendation. A later, validated step could send each turn to the cheapest
9 //! correct path; this increment only measures and logs.
10 //!
11 //! Design contract:
12 //! - Off by default. Nothing is asked unless `[auto.router]` has
13 //! `kind = "decision"` and `shadow_gate = true`.
14 //! - One call. The gate's three questions are appended to the decision
15 //! router's own System One request (`model_routing`): same route, key,
16 //! model, `timeout_secs`, redacted state and usage record. There is no
17 //! second request, client, deadline or configuration surface.
18 //! - Shadow mode. The gate logs a typed [`ShadowOutcome`] through `tracing`
19 //! (target `superfast`) and publishes one shadow decision receipt, but
20 //! never changes routing and never alters any user-visible behavior.
21 //! - Fail open. A router failure of any class is the gate's failure class
22 //! and the turn continues exactly as the router's fallback decides.
23 //!
24 //! Known limits (written down so nobody assumes them):
25 //! - Shadow only: the recommendation is logged, never acted on.
26 //! - The gate runs only when the decision router runs: Auto model mode with
27 //! a runnable strong/fast pair. It no longer fires on every turn.
28 //! - The transport validates every offered question, so a decision server
29 //! that cannot answer the gate's questions fails the router's answer too
30 //! and the turn takes the router's local fallback.
31 //! - The router's state (bounded recent context plus the latest request,
32 //! truncated to 4,000 characters and redacted of configured secrets) is
33 //! what the gate's questions are asked over. No prompt text is logged;
34 //! the log carries the route, failure class and latency.
35 //! - The `SUPERFAST_*` environment variables are no longer read. Setting
36 //! any of them logs one warning per process that names the config key.
37 //!
38 //! The Decision Gate concept and the reference implementation are by Andrea
39 //! Bruno, released under Creative Commons Attribution 4.0 (CC BY 4.0); see
40 //! <https://github.com/Andrea-Bruno/harness-superfast>. The decision models
41 //! (Von, OpenJev, Laya) are third-party open models; only the integration
42 //! architecture and the routing method here are covered by that attribution.
43
44 use serde_json::{Map, Value, json};
45
46 use crate::client::system_one::SystemOneResponse;
47 use crate::cost_status::{
48 EffectiveRouteEnvelope, NativeUsageSource, RuntimeDecisionReceipt, RuntimeUsageBatch,
49 };
50 use crate::model_routing::AutoRouterFailure;
51
52 const REMOVED_ENV_VARS: [&str; 5] = [
53 "SUPERFAST_ENABLED",
54 "SUPERFAST_PROVIDER",
55 "SUPERFAST_BASE_URL",
56 "SUPERFAST_MODEL",
57 "SUPERFAST_TIMEOUT_MS",
58 ];
59
60 const INTENT_OPTIONS: [&str; 5] = ["code_change", "code_question", "command", "chat", "other"];
61 const GATE_QUESTIONS: [&str; 3] = ["intent", "needs_tool", "answerable_from_context"];
62
63 /// Conservative routing recommendation derived from a turn's answers. Only a
64 /// decisive set of numbers produces a fast route; anything else is `Unknown`,
65 /// which means "fall back to the full model exactly as today".
66 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
67 pub enum Route {
68 NeedsTool,
69 AnswerFromContext,
70 PlainChat,
71 Unknown,
72 }
73
74 impl Route {
75 fn as_str(self) -> &'static str {
76 match self {
77 Route::NeedsTool => "needs_tool",
78 Route::AnswerFromContext => "answer_from_context",
79 Route::PlainChat => "plain_chat",
80 Route::Unknown => "unknown",
81 }
82 }
83 }
84
85 /// Everything one shadow evaluation can end in. Bounded by construction: a
86 /// route or a non-secret failure class, plus the measured latency. Provider
87 /// bodies and prompt text never enter this type.
88 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
89 pub enum ShadowOutcome {
90 /// The decision model answered; `route` is the derived recommendation.
91 Recommendation { route: Route, latency_ms: u64 },
92 /// Fail open: the router's call gave the gate nothing to read.
93 /// `NotRunnable` means the route could not be built (no key, bad URL)
94 /// and nothing was sent.
95 Failed {
96 failure: AutoRouterFailure,
97 latency_ms: u64,
98 },
99 }
100
101 /// One line naming the replacement key when a removed `SUPERFAST_*` variable
102 /// is still set, or `None` when none is.
103 pub fn removed_env_notice(lookup: impl Fn(&str) -> Option<String>) -> Option<String> {
104 let set: Vec<&str> = REMOVED_ENV_VARS
105 .into_iter()
106 .filter(|name| lookup(name).is_some_and(|value| !value.trim().is_empty()))
107 .collect();
108 (!set.is_empty()).then(|| {
109 format!(
110 "ignoring {}: the shadow Decision Gate is now `shadow_gate = true` under `[auto.router]` with `kind = \"decision\"`",
111 set.join(", ")
112 )
113 })
114 }
115
116 /// Log [`removed_env_notice`] once per process.
117 pub fn warn_on_removed_env() {
118 static WARNED: std::sync::Once = std::sync::Once::new();
119 WARNED.call_once(|| {
120 if let Some(notice) = removed_env_notice(|name| std::env::var(name).ok()) {
121 tracing::warn!(target: "superfast", "{notice}");
122 }
123 });
124 }
125
126 /// The gate's two `noul` questions and one `choice`, appended to the decision
127 /// router's request when `[auto.router] shadow_gate = true`.
128 pub(crate) fn gate_questions() -> Map<String, Value> {
129 match json!({
130 "needs_tool": {
131 "type": "noul",
132 "instructions": "Does answering this request require taking an action with a tool (reading, writing, running, searching), rather than replying from what is already known?"
133 },
134 "answerable_from_context": {
135 "type": "noul",
136 "instructions": "Can this request be answered from information already present in the conversation, without any new investigation?"
137 },
138 "intent": {
139 "type": "choice",
140 "instructions": "Classify the primary intent of the user request.",
141 "criteria": {
142 "code_change": "Create, edit, or delete code or files.",
143 "code_question": "Explain or reason about code without changing it.",
144 "command": "Run a command or operation.",
145 "chat": "Casual conversation or a question needing no tools.",
146 "other": "None of the above."
147 }
148 }
149 }) {
150 Value::Object(questions) => questions,
151 _ => Map::new(),
152 }
153 }
154
155 /// Record that the router's call produced no answer for the gate to read.
156 pub(crate) fn record_shadow_failure(failure: AutoRouterFailure, latency_ms: u64) -> ShadowOutcome {
157 let outcome = ShadowOutcome::Failed {
158 failure,
159 latency_ms,
160 };
161 log_outcome(outcome);
162 outcome
163 }
164
165 /// Derive, log and receipt the shadow recommendation from the router's own
166 /// response. Usage is settled by the router's record; this adds evidence only.
167 pub(crate) async fn record_shadow_response(
168 response: &SystemOneResponse,
169 latency_ms: u64,
170 request_route: &EffectiveRouteEnvelope,
171 source: &NativeUsageSource,
172 ) -> ShadowOutcome {
173 let intent =
174 crate::model_routing::validated_choice(response.answers.get("intent"), &INTENT_OPTIONS);
175 let receipt = RuntimeDecisionReceipt {
176 source_id: source.source_id(),
177 route: request_route.sanitized_for_persistence(),
178 usage: response.usage.as_ref().map(|u| codewhale_models::Usage {
179 input_tokens: u.input_tokens,
180 output_tokens: u.output_tokens,
181 ..Default::default()
182 }),
183 usage_complete: response
184 .usage
185 .as_ref()
186 .is_some_and(|u| u.complete && (u.input_tokens > 0 || u.output_tokens > 0)),
187 shadow: true,
188 valid_answers: response.answers_validated != Some(false),
189 evidence: codewhale_models::auto_route_evidence::AutoRouteDecisionEvidence {
190 choice: intent
191 .as_ref()
192 .map_or_else(|| "invalid".to_string(), |v| v.choice.clone()),
193 probabilities_bp: intent
194 .as_ref()
195 .map_or_else(Default::default, |v| v.probabilities_bp.clone()),
196 confidence_bp: intent.as_ref().map_or(0, |v| v.confidence_bp),
197 min_confidence_bp: 5_000,
198 abstained_questions: response.abstained_questions(&GATE_QUESTIONS),
199 cost_saving_kept_fast: false,
200 thinking: None,
201 provider_reported_cost_usd: response.usage.as_ref().and_then(|u| u.reported_cost()),
202 latency_ms,
203 response_model: response
204 .model
205 .as_deref()
206 .map(|model| model.chars().take(128).collect()),
207 },
208 };
209 report_receipt(source, receipt).await;
210 let outcome = if response.answers_validated == Some(false) {
211 ShadowOutcome::Failed {
212 failure: AutoRouterFailure::InvalidAnswer,
213 latency_ms,
214 }
215 } else {
216 ShadowOutcome::Recommendation {
217 route: derive_route(response),
218 latency_ms,
219 }
220 };
221 log_outcome(outcome);
222 outcome
223 }
224
225 async fn report_receipt(source: &NativeUsageSource, receipt: RuntimeDecisionReceipt) {
226 let origin = source.origin().cloned();
227 let scope = origin.as_ref().map_or_else(
228 crate::cost_status::scope_token,
229 crate::cost_status::NativeUsageOrigin::scope,
230 );
231 #[cfg(any(test, feature = "test-support"))]
232 let test_origin = crate::cost_status::test_cost_scope_id();
233 let settled = codewhale_runtime::runtime_control::owner_work(move || {
234 #[cfg(any(test, feature = "test-support"))]
235 let _origin = crate::cost_status::bind_test_cost_scope(test_origin);
236 crate::cost_status::record_runtime_usage_batch(
237 scope,
238 origin.as_ref(),
239 &RuntimeUsageBatch {
240 decisions: vec![receipt],
241 ..Default::default()
242 },
243 );
244 Ok(())
245 })
246 .await;
247 if settled.is_err() {
248 tracing::warn!(target: "superfast", "decision receipt settlement worker failed");
249 }
250 }
251
252 fn log_outcome(outcome: ShadowOutcome) {
253 match outcome {
254 ShadowOutcome::Recommendation { route, latency_ms } => tracing::info!(
255 target: "superfast",
256 route = route.as_str(),
257 latency_ms,
258 "decision gate (shadow) recommendation"
259 ),
260 ShadowOutcome::Failed {
261 failure: AutoRouterFailure::NotRunnable,
262 ..
263 } => tracing::warn!(
264 target: "superfast",
265 "decision gate (shadow) not run: route not runnable (check the router key and [auto.router])"
266 ),
267 ShadowOutcome::Failed {
268 failure,
269 latency_ms,
270 } => tracing::debug!(
271 target: "superfast",
272 failure = %failure.label(),
273 latency_ms,
274 "decision gate (shadow) no opinion (fail-open)"
275 ),
276 }
277 }
278
279 /// A finite probability in [0, 1], or `None` ("no evidence").
280 fn unit_interval(value: Option<f64>) -> Option<f64> {
281 value.filter(|value| value.is_finite() && (0.0..=1.0).contains(value))
282 }
283
284 /// Read a `noul` answer only when it is typed as one and its value is a real
285 /// probability. Anything else (absent, wrong type, out of range) is "no
286 /// evidence", so a mis-scaled or missing answer can never produce a decisive
287 /// fast route.
288 fn read_noul(response: &SystemOneResponse, key: &str) -> Option<f64> {
289 let answer = response.answers.get(key)?;
290 (answer.kind == "noul" && !answer.abstained)
291 .then_some(answer.noul)
292 .and_then(unit_interval)
293 }
294
295 /// Derive a conservative route. The gate only recommends a fast route when the
296 /// relevant numbers are decisive; otherwise it says `Unknown` so the caller
297 /// falls back to the normal path.
298 fn derive_route(response: &SystemOneResponse) -> Route {
299 let needs_tool = read_noul(response, "needs_tool");
300 let from_context = read_noul(response, "answerable_from_context");
301
302 // Decisive "needs a tool" wins first — the harness must not skip work.
303 if needs_tool.is_some_and(|nt| nt >= 0.85) {
304 return Route::NeedsTool;
305 }
306
307 // Strongly answerable from context, with a present and low tool-need signal.
308 if from_context.is_some_and(|fc| fc >= 0.85) && needs_tool.is_some_and(|nt| nt <= 0.3) {
309 return Route::AnswerFromContext;
310 }
311
312 // Clearly chat, with a calibrated intent and a present, low tool-need signal.
313 let intent_is_calibrated_chat =
314 crate::model_routing::validated_choice(response.answers.get("intent"), &INTENT_OPTIONS)
315 .is_some_and(|intent| {
316 !intent.abstained && intent.choice == "chat" && intent.confidence_bp >= 5_000
317 });
318 if intent_is_calibrated_chat && needs_tool.is_some_and(|nt| nt <= 0.2) {
319 return Route::PlainChat;
320 }
321
322 Route::Unknown
323 }
324
325 #[cfg(test)]
326 mod tests {
327 use super::*;
328
329 #[test]
330 fn explicit_abstention_never_authorizes_a_shadow_route() {
331 let mut value = json!({"answers":{
332 "intent":{"type":"choice","choice":"chat","confidence":0.9,
333 "probabilities":{"chat":0.9,"code_change":0.1,"code_question":0.0,"command":0.0,"other":0.0}},
334 "needs_tool":{"type":"noul","noul":0.1},
335 "answerable_from_context":{"type":"noul","noul":0.1}}});
336 let decoded =
337 |value: Value| serde_json::from_value::<SystemOneResponse>(value).expect("response");
338 assert_eq!(derive_route(&decoded(value.clone())), Route::PlainChat);
339 value["answers"]["intent"]["abstained"] = true.into();
340 assert_eq!(derive_route(&decoded(value.clone())), Route::Unknown);
341 value["answers"]["needs_tool"]["noul"] = 0.95.into();
342 value["answers"]["needs_tool"]["abstained"] = true.into();
343 assert_eq!(derive_route(&decoded(value)), Route::Unknown);
344 }
345
346 fn noul_body(needs_tool: f64, from_context: f64) -> Value {
347 json!({
348 "id": "sf-1",
349 "model": "jev-latest",
350 "usage": { "input_tokens": 121, "output_tokens": 8 },
351 "answers": {
352 "needs_tool": { "type": "noul", "noul": needs_tool },
353 "answerable_from_context": { "type": "noul", "noul": from_context },
354 "intent": {
355 "type": "choice",
356 "choice": "code_change",
357 "probabilities": {
358 "code_change": 0.9, "code_question": 0.04, "command": 0.03,
359 "chat": 0.02, "other": 0.01
360 },
361 "confidence": 0.8
362 }
363 }
364 })
365 }
366
367 fn response(answers: Value) -> SystemOneResponse {
368 serde_json::from_value(json!({ "answers": answers })).expect("response")
369 }
370
371 #[test]
372 fn only_decisive_typed_answers_route_fast() {
373 let cases = [
374 (
375 json!({ "needs_tool": { "type": "noul", "noul": 0.9 } }),
376 Route::NeedsTool,
377 ),
378 (
379 json!({
380 "needs_tool": { "type": "noul", "noul": 0.1 },
381 "answerable_from_context": { "type": "noul", "noul": 0.9 }
382 }),
383 Route::AnswerFromContext,
384 ),
385 (
386 json!({
387 "needs_tool": { "type": "noul", "noul": 0.05 },
388 "intent": { "type": "choice", "choice": "chat", "confidence": 0.8,
389 "probabilities": { "chat": 0.9, "code_change": 0.04, "code_question": 0.03, "command": 0.02, "other": 0.01 } }
390 }),
391 Route::PlainChat,
392 ),
393 // Out of range, wrong type, or untyped answers are no evidence.
394 (
395 json!({
396 "needs_tool": { "type": "noul", "noul": 5.0 },
397 "answerable_from_context": { "type": "choice", "noul": 0.95 }
398 }),
399 Route::Unknown,
400 ),
401 (json!({ "needs_tool": { "noul": 0.95 } }), Route::Unknown),
402 // Chat without a present, low tool-need signal is not decisive.
403 (
404 json!({ "intent": { "type": "choice", "choice": "chat", "confidence": 0.9 } }),
405 Route::Unknown,
406 ),
407 (json!({}), Route::Unknown),
408 ];
409 for (answers, expected) in cases {
410 assert_eq!(
411 derive_route(&response(answers.clone())),
412 expected,
413 "{answers}"
414 );
415 }
416 }
417
418 #[test]
419 fn removed_environment_variables_name_the_router_key_in_one_line() {
420 assert_eq!(removed_env_notice(|_| None), None);
421 assert_eq!(
422 removed_env_notice(|name| (name == "SUPERFAST_MODEL").then(|| " ".to_string())),
423 None,
424 "a blank value is not a setting"
425 );
426 let notice = removed_env_notice(|name| {
427 matches!(name, "SUPERFAST_ENABLED" | "SUPERFAST_TIMEOUT_MS").then(|| "1".to_string())
428 })
429 .expect("notice");
430 assert!(
431 notice.contains("SUPERFAST_ENABLED, SUPERFAST_TIMEOUT_MS"),
432 "{notice}"
433 );
434 assert!(notice.contains("shadow_gate = true"), "{notice}");
435 assert!(notice.contains("[auto.router]"), "{notice}");
436 assert!(!notice.contains('\n'), "{notice}");
437 }
438
439 #[test]
440 fn gate_offers_its_three_typed_questions() {
441 let questions = gate_questions();
442 let names: Vec<&str> = questions.keys().map(String::as_str).collect();
443 assert_eq!(names, ["needs_tool", "answerable_from_context", "intent"]);
444 let intent: Vec<&str> = questions["intent"]["criteria"]
445 .as_object()
446 .expect("criteria")
447 .keys()
448 .map(String::as_str)
449 .collect();
450 assert_eq!(intent, INTENT_OPTIONS);
451 }
452
453 #[tokio::test]
454 async fn router_response_yields_one_shadow_receipt_and_keeps_rejected_cost() {
455 let decisions = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
456 let decision_sink = decisions.clone();
457 let origin = crate::cost_status::NativeUsageOrigin::captured_runtime_with_sinks(
458 crate::cost_status::scope_token(),
459 "superfast-owner".to_string(),
460 std::sync::Arc::new(|_record: crate::cost_status::RuntimeUsageRecord| true),
461 None,
462 Some(std::sync::Arc::new(
463 move |receipt: crate::cost_status::RuntimeDecisionReceipt| {
464 decision_sink.lock().expect("decision sink").push(receipt);
465 true
466 },
467 )),
468 );
469 let source = NativeUsageSource::capture_with_origin(
470 "auto-router:shadow-test",
471 crate::cost_status::UsageSpendOwner::Auxiliary,
472 Some(origin),
473 );
474 let route = crate::cost_status::decision_receipt_fixture("route").route;
475 let mut body = noul_body(0.93, 0.1);
476 body["usage"]["cost"] = 0.000012054.into();
477 let mut response: SystemOneResponse =
478 serde_json::from_str(&body.to_string()).expect("response");
479
480 assert_eq!(
481 record_shadow_response(&response, 42, &route, &source).await,
482 ShadowOutcome::Recommendation {
483 route: Route::NeedsTool,
484 latency_ms: 42
485 }
486 );
487 response.answers_validated = Some(false);
488 assert_eq!(
489 record_shadow_response(&response, 43, &route, &source).await,
490 ShadowOutcome::Failed {
491 failure: AutoRouterFailure::InvalidAnswer,
492 latency_ms: 43
493 }
494 );
495
496 let receipts = decisions.lock().expect("decision receipts");
497 assert_eq!(receipts.len(), 2);
498 assert!(receipts.iter().all(|receipt| receipt.shadow));
499 assert!(
500 receipts
501 .iter()
502 .all(|receipt| receipt.source_id == "auto-router:shadow-test")
503 );
504 assert!(receipts[0].valid_answers);
505 assert_eq!(receipts[0].evidence.choice, "code_change");
506 assert!(!receipts[1].valid_answers);
507 assert_eq!(
508 receipts[1].evidence.provider_reported_cost_usd.as_deref(),
509 Some("0.000012054")
510 );
511 }
512
513 #[test]
514 fn router_failure_is_the_gate_failure_class() {
515 assert_eq!(
516 record_shadow_failure(AutoRouterFailure::Timeout, 2_000),
517 ShadowOutcome::Failed {
518 failure: AutoRouterFailure::Timeout,
519 latency_ms: 2_000
520 }
521 );
522 }
523
524 #[tokio::test]
525 async fn ownerless_receipt_uses_the_existing_interactive_pool() {
526 let _scope = crate::cost_status::test_scope();
527 let source = NativeUsageSource::capture(
528 "auto-router:ownerless",
529 crate::cost_status::UsageSpendOwner::Auxiliary,
530 );
531 report_receipt(
532 &source,
533 crate::cost_status::decision_receipt_fixture("ownerless-fixture"),
534 )
535 .await;
536 let projected = crate::cost_status::drain();
537 assert!(
538 projected
539 .route_receipts
540 .iter()
541 .any(|r| r.contains("0.000012054"))
542 );
543 assert_eq!(
544 projected.unpriced_turns, 0,
545 "diagnostic receipts do not mint a new charge"
546 );
547 }
548 }
549
549 lines RUST