返回 CodeWhale
backend.rs
根目录 / crates / engine / src / tools / web / backend.rs
1 //! Search backend selection and the shared async adapter contract.
2
3 use std::time::{Duration, Instant};
4
5 use async_trait::async_trait;
6 use futures_util::StreamExt;
7
8 use super::adapter::{self, AdapterFailure, AdapterResult};
9 use super::contract::{BackendId, BackendSearch, DegradedReason, QueryCapabilities, SearchQuery};
10 use super::contract::{CapabilityState as QueryCapabilityState, SearchResult};
11 use crate::client::ProviderNativeSearchRequest;
12 use crate::tools::spec::{ToolContext, ToolError};
13 use codewhale_net::network_policy::Decision;
14 use codewhale_runtime::config::SearchProvider;
15
16 const SEARCH_BACKEND_CONFIGURATION_HINT: &str = concat!(
17 "Check network access, or configure `[search] provider` and `[search] api_key` in ",
18 "config.toml. Keyed providers include tavily, bocha, metaso, baidu, volcengine, serply, deepseek, ",
19 "searchapi, and sofya; metaso also accepts METASO_API_KEY, tavily accepts TAVILY_API_KEY, baidu ",
20 "accepts BAIDU_SEARCH_API_KEY, volcengine accepts VOLCENGINE_API_KEY / ",
21 "VOLCENGINE_ARK_API_KEY / ARK_API_KEY, serply accepts SERPLY_API_KEY, deepseek accepts ",
22 "DEEPSEEK_API_KEY, searchapi accepts SEARCHAPI_API_KEY, and sofya ",
23 "accepts SOFYA_API_KEY. SearXNG needs a trusted self-hosted `[search] base_url`. For a ",
24 "keyless route, use the default `[search] provider = \"firecrawl\"` or ",
25 "`[search] provider = \"bing\"`."
26 );
27
28 const LINK_CHECK_TIMEOUT: Duration = Duration::from_secs(5);
29 const LINK_CHECK_CONCURRENCY: usize = 4;
30 const LINK_CHECK_RESERVE: Duration = Duration::from_millis(250);
31
32 #[async_trait]
33 pub trait SearchBackend: Send + Sync {
34 fn id(&self) -> BackendId;
35 fn capabilities(&self) -> QueryCapabilities;
36 async fn search(&self, query: &SearchQuery, deadline: Instant) -> AdapterResult<BackendSearch>;
37 }
38
39 #[derive(Clone, Copy)]
40 pub struct BackendContext<'a> {
41 tool_context: &'a ToolContext,
42 }
43
44 pub enum ConfiguredSearchBackend<'a> {
45 Bing(BackendContext<'a>),
46 DuckDuckGo(BackendContext<'a>),
47 Firecrawl(BackendContext<'a>),
48 Tavily(BackendContext<'a>),
49 Bocha(BackendContext<'a>),
50 Metaso(BackendContext<'a>),
51 Searxng(BackendContext<'a>),
52 Baidu(BackendContext<'a>),
53 Volcengine(BackendContext<'a>),
54 Sofya(BackendContext<'a>),
55 Serply(BackendContext<'a>),
56 DeepSeek(BackendContext<'a>),
57 SearchApi(BackendContext<'a>),
58 }
59
60 #[derive(Clone, Copy)]
61 struct ProviderNativeSearchBackend<'a> {
62 context: &'a ToolContext,
63 }
64
65 impl<'a> ConfiguredSearchBackend<'a> {
66 #[must_use]
67 pub fn from_provider(context: &'a ToolContext, provider: SearchProvider) -> Self {
68 let backend = BackendContext {
69 tool_context: context,
70 };
71 match provider {
72 SearchProvider::Bing => Self::Bing(backend),
73 SearchProvider::DuckDuckGo => Self::DuckDuckGo(backend),
74 SearchProvider::Firecrawl => Self::Firecrawl(backend),
75 SearchProvider::Tavily => Self::Tavily(backend),
76 SearchProvider::Bocha => Self::Bocha(backend),
77 SearchProvider::Metaso => Self::Metaso(backend),
78 SearchProvider::Searxng => Self::Searxng(backend),
79 SearchProvider::Baidu => Self::Baidu(backend),
80 SearchProvider::Volcengine => Self::Volcengine(backend),
81 SearchProvider::Sofya => Self::Sofya(backend),
82 SearchProvider::Serply => Self::Serply(backend),
83 SearchProvider::DeepSeek => Self::DeepSeek(backend),
84 SearchProvider::SearchApi => Self::SearchApi(backend),
85 }
86 }
87
88 const fn provider(&self) -> SearchProvider {
89 match self {
90 Self::Bing(_) => SearchProvider::Bing,
91 Self::DuckDuckGo(_) => SearchProvider::DuckDuckGo,
92 Self::Firecrawl(_) => SearchProvider::Firecrawl,
93 Self::Tavily(_) => SearchProvider::Tavily,
94 Self::Bocha(_) => SearchProvider::Bocha,
95 Self::Metaso(_) => SearchProvider::Metaso,
96 Self::Searxng(_) => SearchProvider::Searxng,
97 Self::Baidu(_) => SearchProvider::Baidu,
98 Self::Volcengine(_) => SearchProvider::Volcengine,
99 Self::Sofya(_) => SearchProvider::Sofya,
100 Self::Serply(_) => SearchProvider::Serply,
101 Self::DeepSeek(_) => SearchProvider::DeepSeek,
102 Self::SearchApi(_) => SearchProvider::SearchApi,
103 }
104 }
105
106 const fn context(&self) -> &BackendContext<'a> {
107 match self {
108 Self::Bing(context)
109 | Self::DuckDuckGo(context)
110 | Self::Firecrawl(context)
111 | Self::Tavily(context)
112 | Self::Bocha(context)
113 | Self::Metaso(context)
114 | Self::Searxng(context)
115 | Self::Baidu(context)
116 | Self::Volcengine(context)
117 | Self::Sofya(context)
118 | Self::Serply(context)
119 | Self::DeepSeek(context)
120 | Self::SearchApi(context) => context,
121 }
122 }
123 }
124
125 pub struct SearchBackendChain<'a> {
126 backends: Vec<Box<dyn SearchBackend + 'a>>,
127 }
128
129 #[derive(Debug)]
130 pub struct ChainedSearch {
131 pub raw: BackendSearch,
132 pub capabilities: QueryCapabilities,
133 }
134
135 impl<'a> SearchBackendChain<'a> {
136 #[must_use]
137 pub fn from_context(context: &'a ToolContext) -> Self {
138 let selected = context.search_provider;
139 let third_party_allowed = context.third_party_search.get().allows_third_party();
140 let admitted = |provider: SearchProvider| {
141 third_party_allowed || !super::consent::backend_is_third_party(context, provider)
142 };
143 let mut backends: Vec<Box<dyn SearchBackend + 'a>> = Vec::new();
144 if provider_native_leads(context) {
145 backends.push(Box::new(ProviderNativeSearchBackend { context }));
146 }
147 if admitted(selected) {
148 backends.push(Box::new(ConfiguredSearchBackend::from_provider(
149 context, selected,
150 )));
151 }
152 if !matches!(selected, SearchProvider::Bing | SearchProvider::DuckDuckGo)
153 && admitted(SearchProvider::DuckDuckGo)
154 {
155 backends.push(Box::new(ConfiguredSearchBackend::from_provider(
156 context,
157 SearchProvider::DuckDuckGo,
158 )));
159 }
160 Self { backends }
161 }
162
163 #[must_use]
164 pub fn initial_backend(&self) -> Option<BackendId> {
165 self.backends.first().map(|backend| backend.id())
166 }
167
168 pub async fn search(
169 &self,
170 query: &SearchQuery,
171 deadline: Instant,
172 first_attempt_budget: Option<Duration>,
173 fallback_budget_after_first: Option<Duration>,
174 ) -> AdapterResult<ChainedSearch> {
175 let backends = self
176 .backends
177 .iter()
178 .map(|backend| backend.as_ref())
179 .collect::<Vec<_>>();
180 run_backend_chain(
181 &backends,
182 query,
183 deadline,
184 first_attempt_budget,
185 fallback_budget_after_first,
186 )
187 .await
188 }
189 }
190
191 pub fn provider_native_leads(context: &ToolContext) -> bool {
192 provider_native_is_available(
193 context
194 .route_capabilities
195 .server_side_web_search
196 .is_supported(),
197 context.provider_native_search.is_some(),
198 )
199 }
200
201 const fn provider_native_is_available(capability_supported: bool, client_present: bool) -> bool {
202 capability_supported && client_present
203 }
204
205 async fn run_backend_chain(
206 backends: &[&dyn SearchBackend],
207 query: &SearchQuery,
208 mut deadline: Instant,
209 first_attempt_budget: Option<Duration>,
210 fallback_budget_after_first: Option<Duration>,
211 ) -> AdapterResult<ChainedSearch> {
212 let mut degraded = Vec::new();
213 let mut last_empty = None;
214 let mut attempted = Vec::new();
215
216 for (index, backend) in backends.iter().enumerate() {
217 if index == 1
218 && let Some(fallback_budget) = fallback_budget_after_first
219 {
220 deadline = Instant::now() + fallback_budget.max(Duration::from_millis(1));
221 }
222 let remaining = deadline.saturating_duration_since(Instant::now());
223 if remaining.is_zero() {
224 break;
225 }
226 let backend_id = backend.id();
227 if let Some(previous) = attempted.last() {
228 degraded.push(DegradedReason::BackendFallback {
229 from: *previous,
230 to: backend_id,
231 });
232 }
233 attempted.push(backend_id);
234
235 let attempts_left = u32::try_from(backends.len() - index).unwrap_or(u32::MAX);
236 let fair_share = remaining / attempts_left;
237 let attempt_budget = if index == 0 {
238 first_attempt_budget
239 .map(|budget| budget.min(remaining))
240 .unwrap_or(fair_share)
241 } else {
242 fair_share
243 }
244 .max(Duration::from_millis(1));
245 let attempt_deadline = Instant::now() + attempt_budget;
246
247 let pending_host = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
248 let result = tokio::time::timeout(
249 attempt_budget,
250 adapter::HOST_PENDING.scope(
251 std::sync::Arc::clone(&pending_host),
252 backend.search(query, attempt_deadline),
253 ),
254 )
255 .await
256 .map_err(|_| {
257 let error = ToolError::Timeout {
258 seconds: u64::try_from(attempt_budget.as_millis())
259 .unwrap_or(u64::MAX)
260 .div_ceil(1_000),
261 };
262 if pending_host.load(std::sync::atomic::Ordering::SeqCst) {
263 AdapterFailure::host(error)
264 } else {
265 error.into()
266 }
267 })
268 .and_then(std::convert::identity);
269
270 match result {
271 Ok(mut raw) => {
272 let capabilities = backend.capabilities();
273 crate::tools::web_search::apply_domain_constraints(query, capabilities, &mut raw);
274 if !raw.results.is_empty() {
275 degraded.append(&mut raw.degraded);
276 raw.degraded = degraded;
277 return Ok(ChainedSearch { raw, capabilities });
278 }
279 degraded.push(DegradedReason::NoUsableResults {
280 backend: backend_id,
281 });
282 degraded.append(&mut raw.degraded);
283 last_empty = Some((raw, capabilities));
284 }
285 Err(error) if !error.content() || is_fail_closed(&error.error) => return Err(error),
286 Err(error) if backends.len() == 1 => return Err(error),
287 Err(_) => degraded.push(DegradedReason::BackendUnavailable {
288 backend: backend_id,
289 }),
290 }
291 }
292
293 if let Some((mut raw, capabilities)) = last_empty {
294 raw.degraded = degraded;
295 return Ok(ChainedSearch { raw, capabilities });
296 }
297
298 if attempted.is_empty() {
299 return Err((ToolError::Timeout { seconds: 1 }).into());
300 }
301
302 let backend_ids = attempted
303 .into_iter()
304 .map(BackendId::as_str)
305 .collect::<Vec<_>>()
306 .join(", ");
307 Err((ToolError::not_available(format!(
308 "web search backends unavailable: {backend_ids}. {SEARCH_BACKEND_CONFIGURATION_HINT}"
309 )))
310 .into())
311 }
312
313 const fn is_fail_closed(error: &ToolError) -> bool {
314 matches!(
315 error,
316 ToolError::InvalidInput { .. }
317 | ToolError::MissingField { .. }
318 | ToolError::PathEscape { .. }
319 | ToolError::Cancelled { .. }
320 | ToolError::Timeout { seconds: 0 }
321 | ToolError::PermissionDenied { .. }
322 )
323 }
324
325 #[async_trait]
326 impl SearchBackend for ConfiguredSearchBackend<'_> {
327 fn id(&self) -> BackendId {
328 match self.provider() {
329 SearchProvider::Bing => BackendId::Bing,
330 SearchProvider::DuckDuckGo => BackendId::DuckDuckGo,
331 SearchProvider::Firecrawl => BackendId::Firecrawl,
332 SearchProvider::Tavily => BackendId::Tavily,
333 SearchProvider::Bocha => BackendId::Bocha,
334 SearchProvider::Metaso => BackendId::Metaso,
335 SearchProvider::Searxng => BackendId::Searxng,
336 SearchProvider::Baidu => BackendId::Baidu,
337 SearchProvider::Volcengine => BackendId::Volcengine,
338 SearchProvider::Sofya => BackendId::Sofya,
339 SearchProvider::Serply => BackendId::Serply,
340 SearchProvider::DeepSeek => BackendId::DeepSeek,
341 SearchProvider::SearchApi => BackendId::SearchApi,
342 }
343 }
344
345 fn capabilities(&self) -> QueryCapabilities {
346 // All current adapters enforce result count. Recency and locale are
347 // forwarded where the backend's API takes them (see `QueryFilters` in
348 // `web_search.rs`) — and the keyless Bing and DuckDuckGo scrapes
349 // honor `locale` directly in the request (Bing mkt/setlang,
350 // DuckDuckGo kl, plus a matching Accept-Language); every other knob
351 // is post-filtered by the shared harness or reported as not honored.
352 let (recency, locale) = match self.provider() {
353 SearchProvider::Firecrawl | SearchProvider::Searxng | SearchProvider::SearchApi => {
354 (true, true)
355 }
356 SearchProvider::Tavily => (true, false),
357 SearchProvider::Serply => (false, true),
358 SearchProvider::Bing | SearchProvider::DuckDuckGo => (false, true),
359 _ => (false, false),
360 };
361 let state = |supported: bool| {
362 if supported {
363 QueryCapabilityState::Supported
364 } else {
365 QueryCapabilityState::Unsupported
366 }
367 };
368 QueryCapabilities {
369 recency: state(recency),
370 locale: state(locale),
371 ..QueryCapabilities::count_only()
372 }
373 }
374
375 async fn search(&self, query: &SearchQuery, deadline: Instant) -> AdapterResult<BackendSearch> {
376 crate::tools::web_search::run_backend_search(
377 self.provider(),
378 query,
379 deadline,
380 self.context().tool_context,
381 )
382 .await
383 }
384 }
385
386 #[async_trait]
387 impl SearchBackend for ProviderNativeSearchBackend<'_> {
388 fn id(&self) -> BackendId {
389 BackendId::ProviderNative
390 }
391
392 fn capabilities(&self) -> QueryCapabilities {
393 QueryCapabilities {
394 max_results: QueryCapabilityState::Supported,
395 recency: QueryCapabilityState::Unsupported,
396 domains: QueryCapabilityState::Supported,
397 locale: QueryCapabilityState::Unsupported,
398 published_date: QueryCapabilityState::Unknown,
399 }
400 }
401
402 async fn search(&self, query: &SearchQuery, deadline: Instant) -> AdapterResult<BackendSearch> {
403 if !self
404 .context
405 .route_capabilities
406 .server_side_web_search
407 .is_supported()
408 {
409 return Err((ToolError::not_available(
410 "active route does not report provider-native web search",
411 ))
412 .into());
413 }
414 let client = self
415 .context
416 .provider_native_search
417 .as_ref()
418 .ok_or_else(|| ToolError::not_available("provider-native search client unavailable"))?;
419 // Moonshot/Kimi, Z.AI, MiMo, and the Responses-dialect routes cannot
420 // express domain filters in their native wire contracts. Declining
421 // here must not fail the whole search: report this backend unavailable
422 // so the chain falls back to the configured provider or DuckDuckGo,
423 // which honor domains natively or through post-filtering.
424 let domain_limit = client.maximum_domain_count();
425 if !query.domains.is_empty() && domain_limit == Some(0) {
426 return Err((ToolError::not_available(format!(
427 "{} native web search cannot honor domain filters",
428 client.provider().as_str()
429 )))
430 .into());
431 }
432 if let Some(maximum) = domain_limit
433 && query.domains.len() > maximum
434 {
435 return Err((ToolError::invalid_input(format!(
436 "{} native web search accepts at most {maximum} domains",
437 client.provider().as_str()
438 )))
439 .into());
440 }
441 if query.recency.is_some() {
442 return Err((ToolError::not_available(format!(
443 "{} native web search cannot enforce a recency window",
444 client.provider().as_str()
445 )))
446 .into());
447 }
448 let host = client.host().ok_or_else(|| {
449 ToolError::execution_failed("provider-native search endpoint has no valid host")
450 })?;
451 crate::tools::web_search::check_policy(
452 self.context.network_policy.as_ref(),
453 host.as_str(),
454 )?;
455 let response = client
456 .search(&ProviderNativeSearchRequest {
457 query: query.query.clone(),
458 max_results: query.max_results,
459 domains: query.domains.clone(),
460 })
461 .await
462 .map_err(|error| {
463 ToolError::execution_failed(format!(
464 "{} provider-native web search failed: {error}",
465 client.provider().as_str()
466 ))
467 })?;
468 let entries = response
469 .citations
470 .into_iter()
471 .map(|citation| super::contract::CapturedSearchEntry {
472 title: citation.title,
473 url: citation.url,
474 snippet: citation.snippet,
475 published: citation.published,
476 })
477 .collect();
478 let results = crate::tools::web_search::normalize_captured_entries(
479 entries,
480 self.context,
481 deadline.saturating_duration_since(Instant::now()),
482 )
483 .await?
484 .into_iter()
485 .enumerate()
486 .map(|(index, entry)| {
487 SearchResult::new(
488 index + 1,
489 entry.title,
490 entry.url,
491 entry.snippet,
492 entry.published,
493 )
494 })
495 .collect();
496 let mut raw = BackendSearch {
497 backend: BackendId::ProviderNative,
498 source: format!(
499 "provider-native/{}/{}",
500 client.provider().as_str(),
501 client.model()
502 ),
503 backend_detail: Some(host),
504 results,
505 degraded: if response.truncated {
506 vec![DegradedReason::AnswerCutByProvider]
507 } else {
508 Vec::new()
509 },
510 note: response.answer,
511 };
512 crate::tools::web_search::apply_domain_constraints(query, self.capabilities(), &mut raw);
513 let (results, unverified) = verify_citations(
514 std::mem::take(&mut raw.results),
515 &query.query,
516 self.context,
517 deadline,
518 )
519 .await;
520 raw.results = results;
521 raw.degraded.extend(unverified);
522 Ok(raw)
523 }
524 }
525
526 async fn verify_citations(
527 results: Vec<SearchResult>,
528 query: &str,
529 context: &ToolContext,
530 deadline: Instant,
531 ) -> (Vec<SearchResult>, Vec<DegradedReason>) {
532 let needle = query
533 .split_whitespace()
534 .collect::<Vec<_>>()
535 .join(" ")
536 .to_lowercase();
537 let needle = needle.as_str();
538 let checks = futures_util::stream::iter(results)
539 .map(|result| async move {
540 let budget = deadline
541 .saturating_duration_since(Instant::now())
542 .saturating_sub(LINK_CHECK_RESERVE)
543 .min(LINK_CHECK_TIMEOUT);
544 let outcome = match super::citations::normalize_http_url(&result.url) {
545 Some(url) if repeats_query(&url, needle) => LinkCheck::Failed(
546 "the address repeats the search query, so it was not requested".to_string(),
547 ),
548 Some(_) if budget.is_zero() => LinkCheck::Deadline,
549 Some(url) => match host_needing_approval(&url, context) {
550 Some(host) => LinkCheck::NeedsApproval(host),
551 None => {
552 match super::fetch::reachable_status(&url, budget, context, "web_search")
553 .await
554 {
555 Ok(status) => LinkCheck::Status(status),
556 Err(
557 ToolError::PermissionDenied { message }
558 | ToolError::InvalidInput { message },
559 ) => LinkCheck::Failed(message),
560 Err(_) => LinkCheck::Failed("no usable response".to_string()),
561 }
562 }
563 },
564 None => LinkCheck::Failed("not an http(s) address with a host".to_string()),
565 };
566 (result, outcome)
567 })
568 .buffered(LINK_CHECK_CONCURRENCY)
569 .collect::<Vec<_>>()
570 .await;
571 let mut kept = Vec::new();
572 let mut unverified = Vec::new();
573 for (result, outcome) in checks {
574 let reason = match outcome {
575 LinkCheck::Status(status) if (200..300).contains(&status) => {
576 kept.push(result);
577 continue;
578 }
579 LinkCheck::Status(status) => format!("HTTP {status}"),
580 LinkCheck::Failed(message) => message,
581 LinkCheck::Deadline => "not checked before the search deadline".to_string(),
582 LinkCheck::NeedsApproval(host) => {
583 unverified.push(DegradedReason::CitationUnchecked {
584 url: citation_label(&result.url),
585 reason: format!(
586 "the [network] policy needs approval for {host}; run `/network allow {host}` to have it checked"
587 ),
588 });
589 kept.push(result);
590 continue;
591 }
592 };
593 unverified.push(DegradedReason::CitationUnverified {
594 url: citation_label(&result.url),
595 reason,
596 });
597 }
598 (kept, unverified)
599 }
600
601 enum LinkCheck {
602 Status(u16),
603 Failed(String),
604 Deadline,
605 NeedsApproval(String),
606 }
607
608 fn host_needing_approval(url: &str, context: &ToolContext) -> Option<String> {
609 let decider = context.network_policy.as_ref()?;
610 let host = reqwest::Url::parse(url).ok()?.host_str()?.to_string();
611 matches!(decider.evaluate(&host, "web_search"), Decision::Prompt).then_some(host)
612 }
613
614 fn repeats_query(url: &str, needle: &str) -> bool {
615 !needle.is_empty()
616 && reqwest::Url::parse(url).is_ok_and(|url| {
617 url.query_pairs().any(|(_, value)| {
618 value
619 .split_whitespace()
620 .collect::<Vec<_>>()
621 .join(" ")
622 .to_lowercase()
623 .contains(needle)
624 })
625 })
626 }
627
628 fn citation_label(url: &str) -> String {
629 reqwest::Url::parse(url)
630 .map(|mut url| {
631 let _ = url.set_username("");
632 let _ = url.set_password(None);
633 url.set_query(None);
634 url.set_fragment(None);
635 url.to_string()
636 })
637 .unwrap_or_default()
638 }
639
640 #[cfg(test)]
641 mod tests {
642 use std::sync::{Arc, Mutex};
643
644 use super::*;
645
646 struct FakeBackend {
647 id: BackendId,
648 result: Result<Vec<super::super::contract::SearchResult>, ToolError>,
649 }
650
651 struct DeadlineBackend {
652 id: BackendId,
653 observed_budget: Arc<Mutex<Option<Duration>>>,
654 delay: Duration,
655 }
656
657 #[async_trait]
658 impl SearchBackend for FakeBackend {
659 fn id(&self) -> BackendId {
660 self.id
661 }
662
663 fn capabilities(&self) -> QueryCapabilities {
664 QueryCapabilities::count_only()
665 }
666
667 async fn search(
668 &self,
669 _query: &SearchQuery,
670 _deadline: Instant,
671 ) -> AdapterResult<BackendSearch> {
672 Ok(BackendSearch {
673 backend: self.id,
674 source: self.id.as_str().to_string(),
675 backend_detail: None,
676 results: self.result.clone()?,
677 degraded: Vec::new(),
678 note: None,
679 })
680 }
681 }
682
683 #[async_trait]
684 impl SearchBackend for DeadlineBackend {
685 fn id(&self) -> BackendId {
686 self.id
687 }
688
689 fn capabilities(&self) -> QueryCapabilities {
690 QueryCapabilities::count_only()
691 }
692
693 async fn search(
694 &self,
695 _query: &SearchQuery,
696 deadline: Instant,
697 ) -> AdapterResult<BackendSearch> {
698 *self.observed_budget.lock().expect("budget lock") =
699 Some(deadline.saturating_duration_since(Instant::now()));
700 tokio::time::sleep(self.delay).await;
701 Ok(BackendSearch {
702 backend: self.id,
703 source: self.id.as_str().to_string(),
704 backend_detail: None,
705 results: vec![result()],
706 degraded: Vec::new(),
707 note: None,
708 })
709 }
710 }
711
712 fn query() -> SearchQuery {
713 SearchQuery::new("bounded chain".to_string(), 5, None, Vec::new(), None)
714 }
715
716 fn result() -> super::super::contract::SearchResult {
717 super::super::contract::SearchResult::new(
718 1,
719 "Fallback result".to_string(),
720 "https://example.com/result".to_string(),
721 None,
722 None,
723 )
724 }
725
726 #[test]
727 fn every_configured_provider_maps_to_one_explicit_backend_adapter() {
728 let cases = [
729 (SearchProvider::Bing, BackendId::Bing),
730 (SearchProvider::DuckDuckGo, BackendId::DuckDuckGo),
731 (SearchProvider::Firecrawl, BackendId::Firecrawl),
732 (SearchProvider::Tavily, BackendId::Tavily),
733 (SearchProvider::Bocha, BackendId::Bocha),
734 (SearchProvider::Metaso, BackendId::Metaso),
735 (SearchProvider::Searxng, BackendId::Searxng),
736 (SearchProvider::Baidu, BackendId::Baidu),
737 (SearchProvider::Volcengine, BackendId::Volcengine),
738 (SearchProvider::Sofya, BackendId::Sofya),
739 (SearchProvider::Serply, BackendId::Serply),
740 (SearchProvider::DeepSeek, BackendId::DeepSeek),
741 (SearchProvider::SearchApi, BackendId::SearchApi),
742 ];
743
744 for (provider, expected) in cases {
745 let mut context = ToolContext::new(std::path::PathBuf::from("."));
746 context.search_provider = provider;
747 let backend = ConfiguredSearchBackend::from_provider(&context, provider);
748 assert_eq!(backend.id(), expected);
749 assert_eq!(
750 backend.capabilities().max_results,
751 super::super::contract::CapabilityState::Supported
752 );
753 }
754 }
755
756 #[test]
757 fn keyless_scrape_backends_declare_locale_support() {
758 // The keyless Bing and DuckDuckGo scrapes honor the locale knob in
759 // their scrape requests; every other configured adapter must keep
760 // reporting locale per its own API so the receipt does not overclaim.
761 let cases = [
762 (SearchProvider::Bing, QueryCapabilityState::Supported),
763 (SearchProvider::DuckDuckGo, QueryCapabilityState::Supported),
764 (SearchProvider::Firecrawl, QueryCapabilityState::Supported),
765 (SearchProvider::Searxng, QueryCapabilityState::Supported),
766 (SearchProvider::Serply, QueryCapabilityState::Supported),
767 (SearchProvider::Tavily, QueryCapabilityState::Unsupported),
768 (SearchProvider::Bocha, QueryCapabilityState::Unsupported),
769 (SearchProvider::Metaso, QueryCapabilityState::Unsupported),
770 (SearchProvider::Baidu, QueryCapabilityState::Unsupported),
771 (
772 SearchProvider::Volcengine,
773 QueryCapabilityState::Unsupported,
774 ),
775 (SearchProvider::Sofya, QueryCapabilityState::Unsupported),
776 (SearchProvider::DeepSeek, QueryCapabilityState::Unsupported),
777 (SearchProvider::SearchApi, QueryCapabilityState::Supported),
778 ];
779 for (provider, expected_locale) in cases {
780 let mut context = ToolContext::new(std::path::PathBuf::from("."));
781 context.search_provider = provider;
782 let backend = ConfiguredSearchBackend::from_provider(&context, provider);
783 assert_eq!(
784 backend.capabilities().locale,
785 expected_locale,
786 "{provider:?}"
787 );
788 }
789 }
790
791 #[test]
792 fn provider_native_is_fail_closed_without_both_fact_and_client() {
793 assert!(!provider_native_is_available(false, false));
794 assert!(!provider_native_is_available(true, false));
795 assert!(!provider_native_is_available(false, true));
796 assert!(provider_native_is_available(true, true));
797 }
798
799 #[tokio::test]
800 async fn unavailable_api_falls_back_with_explicit_receipts() {
801 let api = FakeBackend {
802 id: BackendId::Tavily,
803 result: Err(ToolError::execution_failed(
804 "provider detail must stay private",
805 )),
806 };
807 let scrape = FakeBackend {
808 id: BackendId::DuckDuckGo,
809 result: Ok(vec![result()]),
810 };
811 let response = run_backend_chain(
812 &[&api, &scrape],
813 &query(),
814 Instant::now() + Duration::from_secs(1),
815 None,
816 None,
817 )
818 .await
819 .expect("fallback should succeed");
820
821 assert_eq!(response.raw.backend, BackendId::DuckDuckGo);
822 assert_eq!(
823 response.raw.degraded,
824 vec![
825 DegradedReason::BackendUnavailable {
826 backend: BackendId::Tavily,
827 },
828 DegradedReason::BackendFallback {
829 from: BackendId::Tavily,
830 to: BackendId::DuckDuckGo,
831 },
832 ]
833 );
834 }
835
836 #[tokio::test]
837 async fn provider_native_to_api_to_scrape_records_every_transition() {
838 let native = FakeBackend {
839 id: BackendId::ProviderNative,
840 result: Err(ToolError::execution_failed("native unavailable")),
841 };
842 let api = FakeBackend {
843 id: BackendId::Tavily,
844 result: Err(ToolError::execution_failed("API unavailable")),
845 };
846 let scrape = FakeBackend {
847 id: BackendId::DuckDuckGo,
848 result: Ok(vec![result()]),
849 };
850
851 let response = run_backend_chain(
852 &[&native, &api, &scrape],
853 &query(),
854 Instant::now() + Duration::from_secs(1),
855 None,
856 None,
857 )
858 .await
859 .expect("final scrape fallback should succeed");
860
861 assert_eq!(response.raw.backend, BackendId::DuckDuckGo);
862 assert_eq!(
863 response.raw.degraded,
864 vec![
865 DegradedReason::BackendUnavailable {
866 backend: BackendId::ProviderNative,
867 },
868 DegradedReason::BackendFallback {
869 from: BackendId::ProviderNative,
870 to: BackendId::Tavily,
871 },
872 DegradedReason::BackendUnavailable {
873 backend: BackendId::Tavily,
874 },
875 DegradedReason::BackendFallback {
876 from: BackendId::Tavily,
877 to: BackendId::DuckDuckGo,
878 },
879 ]
880 );
881 }
882
883 #[tokio::test]
884 async fn zero_domain_native_providers_decline_without_failing_the_chain() {
885 use codewhale_runtime::config::{Config, ProviderConfig, ProvidersConfig};
886
887 let moonshot_config = {
888 let __cw_config_init_0_0 = Some("moonshot".to_string());
889 let __cw_config_init_0_1 = Some(ProvidersConfig {
890 moonshot: ProviderConfig {
891 api_key: Some("moonshot-test-key".to_string()),
892 base_url: Some("https://api.moonshot.ai/v1".to_string()),
893 model: Some("kimi-k3".to_string()),
894 ..ProviderConfig::default()
895 },
896 ..ProvidersConfig::default()
897 });
898 let mut __cw_config_init_0_value: Config = Config::default();
899 __cw_config_init_0_value.provider = __cw_config_init_0_0;
900 __cw_config_init_0_value.providers = __cw_config_init_0_1;
901 __cw_config_init_0_value
902 };
903 let tmp = tempfile::tempdir().expect("tempdir");
904 let mut context = ToolContext::new(tmp.path().to_path_buf());
905 context.route_capabilities.server_side_web_search =
906 codewhale_config::route::CapabilityState::Supported;
907 context.provider_native_search = Some(
908 crate::client::ProviderNativeSearchClient::new(
909 crate::client::CodewhaleClient::new(&moonshot_config)
910 .expect("test Moonshot client"),
911 )
912 .expect("Moonshot native adapter"),
913 );
914 let backend = ProviderNativeSearchBackend { context: &context };
915
916 let domain_query = SearchQuery::new(
917 "bounded chain".to_string(),
918 5,
919 None,
920 vec!["example.com".to_string()],
921 None,
922 );
923 let error = backend
924 .search(&domain_query, Instant::now() + Duration::from_secs(1))
925 .await
926 .expect_err("Moonshot native search must decline domain-filtered queries");
927 assert!(
928 matches!(error.error, ToolError::NotAvailable { .. }),
929 "declining must stay fallback-shaped, not fail-closed: {error:?}"
930 );
931
932 let xai_config = {
933 let __cw_config_init_1_0 = Some("xai".to_string());
934 let __cw_config_init_1_1 = Some(ProvidersConfig {
935 xai: ProviderConfig {
936 api_key: Some("xai-test-key".to_string()),
937 base_url: Some("https://api.x.ai/v1".to_string()),
938 model: Some("grok-4.5".to_string()),
939 ..ProviderConfig::default()
940 },
941 ..ProvidersConfig::default()
942 });
943 let mut __cw_config_init_1_value: Config = Config::default();
944 __cw_config_init_1_value.provider = __cw_config_init_1_0;
945 __cw_config_init_1_value.providers = __cw_config_init_1_1;
946 __cw_config_init_1_value
947 };
948 let mut xai_context = ToolContext::new(tmp.path().to_path_buf());
949 xai_context.route_capabilities.server_side_web_search =
950 codewhale_config::route::CapabilityState::Supported;
951 xai_context.provider_native_search = Some(
952 crate::client::ProviderNativeSearchClient::new(
953 crate::client::CodewhaleClient::new(&xai_config).expect("test xAI client"),
954 )
955 .expect("xAI native adapter"),
956 );
957 let oversized_domain_query = SearchQuery::new(
958 "bounded chain".to_string(),
959 5,
960 None,
961 [
962 "a.example",
963 "b.example",
964 "c.example",
965 "d.example",
966 "e.example",
967 "f.example",
968 ]
969 .iter()
970 .map(|domain| domain.to_string())
971 .collect(),
972 None,
973 );
974 let error = ProviderNativeSearchBackend {
975 context: &xai_context,
976 }
977 .search(
978 &oversized_domain_query,
979 Instant::now() + Duration::from_secs(1),
980 )
981 .await
982 .expect_err("too many domains stays a typed user error");
983 assert!(
984 matches!(error.error, ToolError::InvalidInput { .. }),
985 "over the provider limit must stay fail-closed: {error:?}"
986 );
987 }
988
989 #[tokio::test]
990 async fn first_attempt_budget_overrides_the_default_fair_share() {
991 let observed_budget = Arc::new(Mutex::new(None));
992 let volcengine = DeadlineBackend {
993 id: BackendId::Volcengine,
994 observed_budget: Arc::clone(&observed_budget),
995 delay: Duration::ZERO,
996 };
997 let fallback = FakeBackend {
998 id: BackendId::DuckDuckGo,
999 result: Ok(vec![result()]),
1000 };
1001 let first_attempt_budget = Duration::from_millis(1_500);
1002 let response = run_backend_chain(
1003 &[&volcengine, &fallback],
1004 &query(),
1005 Instant::now() + Duration::from_secs(2),
1006 Some(first_attempt_budget),
1007 None,
1008 )
1009 .await
1010 .expect("the first backend should complete inside its dedicated budget");
1011
1012 assert_eq!(response.raw.backend, BackendId::Volcengine);
1013 let observed = observed_budget
1014 .lock()
1015 .expect("budget lock")
1016 .expect("first backend must observe a deadline");
1017 assert!(
1018 observed > Duration::from_millis(1_250),
1019 "dedicated first-attempt budget should exceed the default one-second fair share: {observed:?}"
1020 );
1021 assert!(observed <= first_attempt_budget);
1022 }
1023
1024 #[tokio::test]
1025 async fn provider_native_unused_budget_does_not_extend_fallback_deadline() {
1026 let native = FakeBackend {
1027 id: BackendId::ProviderNative,
1028 result: Err(ToolError::execution_failed("native unavailable")),
1029 };
1030 let observed_budget = Arc::new(Mutex::new(None));
1031 let fallback = DeadlineBackend {
1032 id: BackendId::DuckDuckGo,
1033 observed_budget: Arc::clone(&observed_budget),
1034 delay: Duration::from_millis(200),
1035 };
1036 let fallback_budget = Duration::from_millis(30);
1037 let error = run_backend_chain(
1038 &[&native, &fallback],
1039 &query(),
1040 Instant::now() + Duration::from_millis(500),
1041 Some(Duration::from_millis(500)),
1042 Some(fallback_budget),
1043 )
1044 .await
1045 .expect_err("blocking fallback must stop at its own budget");
1046
1047 assert!(matches!(error.error, ToolError::NotAvailable { .. }));
1048 let observed = observed_budget
1049 .lock()
1050 .expect("budget lock")
1051 .expect("fallback must observe a deadline");
1052 assert!(observed <= fallback_budget);
1053 }
1054
1055 #[tokio::test]
1056 async fn all_unavailable_returns_actionable_error_without_private_details() {
1057 let private_error = "secret provider response";
1058 let api = FakeBackend {
1059 id: BackendId::Bocha,
1060 result: Err(ToolError::execution_failed(private_error)),
1061 };
1062 let scrape = FakeBackend {
1063 id: BackendId::DuckDuckGo,
1064 result: Err(ToolError::execution_failed("different private response")),
1065 };
1066 let error = run_backend_chain(
1067 &[&api, &scrape],
1068 &query(),
1069 Instant::now() + Duration::from_secs(1),
1070 None,
1071 None,
1072 )
1073 .await
1074 .expect_err("all-down chain must fail");
1075 let message = error.to_string();
1076
1077 assert!(matches!(error.error, ToolError::NotAvailable { .. }));
1078 assert!(message.contains("bocha, duckduckgo"));
1079 for provider in [
1080 "tavily",
1081 "bocha",
1082 "metaso",
1083 "baidu",
1084 "volcengine",
1085 "serply",
1086 "deepseek",
1087 "searchapi",
1088 "sofya",
1089 ] {
1090 assert!(
1091 message.contains(provider),
1092 "configuration hint must name {provider}: `{message}`"
1093 );
1094 }
1095 assert!(message.contains("[search] provider"));
1096 assert!(message.contains("[search] api_key"));
1097 assert!(message.contains("config.toml"));
1098 assert!(message.contains("METASO_API_KEY"));
1099 assert!(message.contains("TAVILY_API_KEY"));
1100 assert!(message.contains("BAIDU_SEARCH_API_KEY"));
1101 assert!(message.contains("VOLCENGINE_API_KEY"));
1102 assert!(message.contains("VOLCENGINE_ARK_API_KEY"));
1103 assert!(message.contains("ARK_API_KEY"));
1104 assert!(message.contains("SERPLY_API_KEY"));
1105 assert!(message.contains("DEEPSEEK_API_KEY"));
1106 assert!(message.contains("SEARCHAPI_API_KEY"));
1107 assert!(message.contains("SOFYA_API_KEY"));
1108 assert!(message.contains("[search] base_url"));
1109 assert!(message.contains("provider = \"firecrawl\""));
1110 assert!(message.contains("provider = \"bing\""));
1111 assert!(!message.contains(private_error));
1112 assert!(!message.contains("different private response"));
1113 }
1114
1115 #[tokio::test]
1116 async fn policy_failure_does_not_leak_query_to_fallback() {
1117 struct CountingBackend {
1118 calls: Arc<std::sync::atomic::AtomicUsize>,
1119 }
1120 #[async_trait]
1121 impl SearchBackend for CountingBackend {
1122 fn id(&self) -> BackendId {
1123 BackendId::DuckDuckGo
1124 }
1125
1126 fn capabilities(&self) -> QueryCapabilities {
1127 QueryCapabilities::count_only()
1128 }
1129
1130 async fn search(
1131 &self,
1132 _query: &SearchQuery,
1133 _deadline: Instant,
1134 ) -> AdapterResult<BackendSearch> {
1135 self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1136 Err(ToolError::execution_failed("unexpected fallback").into())
1137 }
1138 }
1139
1140 let api = FakeBackend {
1141 id: BackendId::Searxng,
1142 result: Err(ToolError::permission_denied("policy blocked")),
1143 };
1144 let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1145 let scrape = CountingBackend {
1146 calls: Arc::clone(&calls),
1147 };
1148 let error = run_backend_chain(
1149 &[&api, &scrape],
1150 &query(),
1151 Instant::now() + Duration::from_secs(1),
1152 None,
1153 None,
1154 )
1155 .await
1156 .expect_err("policy error must fail closed");
1157
1158 assert!(matches!(error.error, ToolError::PermissionDenied { .. }));
1159 assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0);
1160 }
1161
1162 #[tokio::test]
1163 async fn empty_api_falls_back_and_records_no_usable_results() {
1164 let api = FakeBackend {
1165 id: BackendId::Metaso,
1166 result: Ok(Vec::new()),
1167 };
1168 let scrape = FakeBackend {
1169 id: BackendId::DuckDuckGo,
1170 result: Ok(vec![result()]),
1171 };
1172 let response = run_backend_chain(
1173 &[&api, &scrape],
1174 &query(),
1175 Instant::now() + Duration::from_secs(1),
1176 None,
1177 None,
1178 )
1179 .await
1180 .expect("empty API response should fall back");
1181
1182 assert_eq!(
1183 response.raw.degraded,
1184 vec![
1185 DegradedReason::NoUsableResults {
1186 backend: BackendId::Metaso,
1187 },
1188 DegradedReason::BackendFallback {
1189 from: BackendId::Metaso,
1190 to: BackendId::DuckDuckGo,
1191 },
1192 ]
1193 );
1194 }
1195
1196 #[tokio::test]
1197 async fn domain_filtered_results_fall_back_before_chain_success() {
1198 let native = FakeBackend {
1199 id: BackendId::ProviderNative,
1200 result: Ok(vec![SearchResult::new(
1201 1,
1202 "Outside source".to_string(),
1203 "https://outside.test/result".to_string(),
1204 None,
1205 None,
1206 )]),
1207 };
1208 let configured = FakeBackend {
1209 id: BackendId::Searxng,
1210 result: Ok(vec![SearchResult::new(
1211 1,
1212 "Matching source".to_string(),
1213 "https://docs.rs/example/latest/example/".to_string(),
1214 None,
1215 None,
1216 )]),
1217 };
1218 let constrained = SearchQuery::new(
1219 "example docs".to_string(),
1220 5,
1221 None,
1222 vec!["docs.rs".to_string()],
1223 None,
1224 );
1225
1226 let response = run_backend_chain(
1227 &[&native, &configured],
1228 &constrained,
1229 Instant::now() + Duration::from_secs(1),
1230 None,
1231 None,
1232 )
1233 .await
1234 .expect("configured backend should satisfy the domain constraint");
1235
1236 assert_eq!(response.raw.backend, BackendId::Searxng);
1237 assert_eq!(response.raw.results.len(), 1);
1238 assert!(response.raw.degraded.iter().any(|reason| matches!(
1239 reason,
1240 DegradedReason::NoUsableResults {
1241 backend: BackendId::ProviderNative
1242 }
1243 )));
1244 assert!(response.raw.degraded.iter().any(|reason| matches!(
1245 reason,
1246 DegradedReason::BackendFallback {
1247 from: BackendId::ProviderNative,
1248 to: BackendId::Searxng
1249 }
1250 )));
1251 }
1252 #[tokio::test]
1253 async fn adapter_origins_and_selected_host_timeout_stop_backend_fallback() {
1254 use super::super::adapter::FailureOrigin;
1255 struct Refusal {
1256 origin: FailureOrigin,
1257 delay: bool,
1258 }
1259 #[async_trait]
1260 impl SearchBackend for Refusal {
1261 fn id(&self) -> BackendId {
1262 BackendId::Tavily
1263 }
1264 fn capabilities(&self) -> QueryCapabilities {
1265 QueryCapabilities::count_only()
1266 }
1267 async fn search(
1268 &self,
1269 _query: &SearchQuery,
1270 _deadline: Instant,
1271 ) -> AdapterResult<BackendSearch> {
1272 if self.delay {
1273 if self.origin == FailureOrigin::Host {
1274 let _ = adapter::HOST_PENDING.try_with(|pending| {
1275 pending.store(true, std::sync::atomic::Ordering::SeqCst)
1276 });
1277 }
1278 tokio::time::sleep(Duration::from_secs(10)).await;
1279 }
1280 Err(AdapterFailure {
1281 origin: self.origin,
1282 error: ToolError::execution_failed(
1283 "No readable page content was found at fixture",
1284 ),
1285 })
1286 }
1287 }
1288 struct Count(std::sync::atomic::AtomicUsize);
1289 #[async_trait]
1290 impl SearchBackend for Count {
1291 fn id(&self) -> BackendId {
1292 BackendId::Bing
1293 }
1294 fn capabilities(&self) -> QueryCapabilities {
1295 QueryCapabilities::count_only()
1296 }
1297 async fn search(
1298 &self,
1299 _query: &SearchQuery,
1300 _deadline: Instant,
1301 ) -> AdapterResult<BackendSearch> {
1302 self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1303 Ok(BackendSearch {
1304 backend: BackendId::Bing,
1305 source: "bing".into(),
1306 backend_detail: None,
1307 results: vec![result()],
1308 degraded: vec![],
1309 note: None,
1310 })
1311 }
1312 }
1313 let query = SearchQuery::new("authorized".into(), 5, None, vec![], None);
1314 for (origin, delay) in [
1315 (FailureOrigin::Host, false),
1316 (FailureOrigin::CaptureGuard, false),
1317 (FailureOrigin::Host, true),
1318 (FailureOrigin::ContentOrProvider, false),
1319 (FailureOrigin::ContentOrProvider, true),
1320 ] {
1321 let first = Refusal { origin, delay };
1322 let second = Count(std::sync::atomic::AtomicUsize::new(0));
1323 let response = run_backend_chain(
1324 &[&first, &second],
1325 &query,
1326 Instant::now() + Duration::from_millis(100),
1327 None,
1328 None,
1329 )
1330 .await;
1331 assert_eq!(response.is_ok(), origin == FailureOrigin::ContentOrProvider);
1332 assert_eq!(
1333 second.0.load(std::sync::atomic::Ordering::SeqCst),
1334 usize::from(origin == FailureOrigin::ContentOrProvider)
1335 );
1336 }
1337 }
1338 }
1339
1339 lines RUST