fetchium-core 1.0.0

Fetchium core library — search, extract, rank, validate, cache
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! Query Expansion Engine (QXE) — automatic synonym, acronym, and perspective expansion.
//!
//! Two expansion modes:
//! 1. **Lexical** (`expand_query`): Synonym/acronym substitution for technical terms.
//!    "JS frameworks" → "JavaScript frameworks", "k8s" → "kubernetes"
//! 2. **Perspective** (`ai_perspective_expand`): AI-generated domain-specific sub-queries.
//!    "who created the world" → ["Big Bang cosmology universe origin", "religious creation myths", ...]
//!
//! Perspective expansion is the high-impact path for ambiguous/multi-domain queries.
//! It ensures all relevant angles (scientific, religious, philosophical, historical) are covered.

use crate::ai::provider_client::chat_with_fallback;
use crate::ai::types::{AiConfig, ChatMessage};

/// An expanded query with its variants.
#[derive(Debug, Clone)]
pub struct ExpandedQuery {
    /// The original query, unchanged.
    pub original: String,
    /// Expanded variants to also search for.
    pub expansions: Vec<QueryVariant>,
}

/// A single query variant produced by expansion.
#[derive(Debug, Clone)]
pub struct QueryVariant {
    /// The expanded query text.
    pub text: String,
    /// Confidence that this expansion is relevant (0.0-1.0).
    pub confidence: f64,
    /// What type of expansion produced this variant.
    pub expansion_type: ExpansionType,
}

/// Types of query expansion.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExpansionType {
    /// Acronym → full form ("JS" → "JavaScript")
    AcronymExpansion,
    /// Full form → acronym ("JavaScript" → "JS")
    AcronymContraction,
    /// Synonym substitution ("fast" → "quick")
    Synonym,
    /// Related term addition
    Related,
}

/// Acronym dictionary — maps abbreviations to full forms.
const ACRONYMS: &[(&str, &str)] = &[
    ("js", "javascript"),
    ("ts", "typescript"),
    ("py", "python"),
    ("rb", "ruby"),
    ("rs", "rust"),
    ("ml", "machine learning"),
    ("ai", "artificial intelligence"),
    ("dl", "deep learning"),
    ("nlp", "natural language processing"),
    ("cv", "computer vision"),
    ("llm", "large language model"),
    ("gpt", "generative pre-trained transformer"),
    ("rl", "reinforcement learning"),
    ("nn", "neural network"),
    ("cnn", "convolutional neural network"),
    ("rnn", "recurrent neural network"),
    ("api", "application programming interface"),
    ("sdk", "software development kit"),
    ("cli", "command line interface"),
    ("gui", "graphical user interface"),
    ("db", "database"),
    ("sql", "structured query language"),
    ("nosql", "not only sql"),
    ("orm", "object relational mapping"),
    ("css", "cascading style sheets"),
    ("html", "hypertext markup language"),
    ("http", "hypertext transfer protocol"),
    ("rest", "representational state transfer"),
    ("grpc", "remote procedure call"),
    ("ci", "continuous integration"),
    ("cd", "continuous deployment"),
    ("k8s", "kubernetes"),
    ("tf", "terraform"),
    ("aws", "amazon web services"),
    ("gcp", "google cloud platform"),
    ("vm", "virtual machine"),
    ("os", "operating system"),
    ("cpu", "central processing unit"),
    ("gpu", "graphics processing unit"),
    ("ram", "random access memory"),
    ("ssd", "solid state drive"),
    ("ux", "user experience"),
    ("ui", "user interface"),
    ("seo", "search engine optimization"),
    ("mvp", "minimum viable product"),
    ("saas", "software as a service"),
    ("iot", "internet of things"),
    ("tls", "transport layer security"),
    ("jwt", "json web token"),
    ("oauth", "open authorization"),
    ("xss", "cross site scripting"),
    ("dos", "denial of service"),
    ("wasm", "webassembly"),
    ("ssr", "server side rendering"),
    ("csr", "client side rendering"),
    ("ssg", "static site generation"),
];

/// Synonym pairs — bidirectional substitutions.
const SYNONYMS: &[(&str, &str)] = &[
    ("fast", "quick"),
    ("error", "bug"),
    ("fix", "resolve"),
    ("issue", "problem"),
    ("tutorial", "guide"),
    ("library", "package"),
    ("framework", "library"),
    ("install", "setup"),
    ("config", "configuration"),
    ("deploy", "deployment"),
    ("auth", "authentication"),
    ("async", "asynchronous"),
    ("sync", "synchronous"),
    ("perf", "performance"),
    ("benchmark", "performance test"),
    ("regex", "regular expression"),
];

/// Expand a query with synonyms and acronyms.
///
/// Returns the original query plus expanded variants, each with a
/// confidence score. Higher confidence = more likely to be helpful.
pub fn expand_query(query: &str) -> ExpandedQuery {
    let original = query.to_string();
    let lower = query.to_lowercase();
    let tokens: Vec<&str> = lower.split_whitespace().collect();
    let mut expansions = Vec::new();

    // 1. Acronym expansion: replace abbreviations with full forms
    for (abbrev, full) in ACRONYMS {
        if tokens
            .iter()
            .any(|t| t.trim_matches(|c: char| c.is_ascii_punctuation()) == *abbrev)
        {
            let expanded = lower.replace(abbrev, full);
            if expanded != lower {
                expansions.push(QueryVariant {
                    text: expanded,
                    confidence: 0.9,
                    expansion_type: ExpansionType::AcronymExpansion,
                });
            }
        }
    }

    // 2. Reverse acronym: if query has full form, also try abbreviation
    for (abbrev, full) in ACRONYMS {
        if lower.contains(full) {
            let contracted = lower.replace(full, abbrev);
            if contracted != lower {
                expansions.push(QueryVariant {
                    text: contracted,
                    confidence: 0.7,
                    expansion_type: ExpansionType::AcronymContraction,
                });
            }
        }
    }

    // 3. Synonym substitution
    for (a, b) in SYNONYMS {
        if tokens
            .iter()
            .any(|t| t.trim_matches(|c: char| c.is_ascii_punctuation()) == *a)
        {
            let expanded = lower.replace(a, b);
            if expanded != lower {
                expansions.push(QueryVariant {
                    text: expanded,
                    confidence: 0.6,
                    expansion_type: ExpansionType::Synonym,
                });
            }
        }
        // Bidirectional
        if tokens
            .iter()
            .any(|t| t.trim_matches(|c: char| c.is_ascii_punctuation()) == *b)
        {
            let expanded = lower.replace(b, a);
            if expanded != lower {
                expansions.push(QueryVariant {
                    text: expanded,
                    confidence: 0.6,
                    expansion_type: ExpansionType::Synonym,
                });
            }
        }
    }

    // Deduplicate expansions
    let mut seen = std::collections::HashSet::new();
    seen.insert(lower.clone());
    expansions.retain(|v| seen.insert(v.text.clone()));

    // Sort by confidence descending
    expansions.sort_by(|a, b| {
        b.confidence
            .partial_cmp(&a.confidence)
            .unwrap_or(std::cmp::Ordering::Equal)
    });

    // Limit to top 3 expansions to prevent query drift
    expansions.truncate(3);

    ExpandedQuery {
        original,
        expansions,
    }
}

/// Check if a query would benefit from expansion.
///
/// Returns true if the query contains any known acronyms or synonyms.
pub fn should_expand(query: &str) -> bool {
    let lower = query.to_lowercase();
    let tokens: Vec<&str> = lower.split_whitespace().collect();

    // Check acronyms
    for (abbrev, _) in ACRONYMS {
        if tokens
            .iter()
            .any(|t| t.trim_matches(|c: char| c.is_ascii_punctuation()) == *abbrev)
        {
            return true;
        }
    }

    // Check synonyms
    for (a, b) in SYNONYMS {
        if tokens.iter().any(|t| {
            let clean = t.trim_matches(|c: char| c.is_ascii_punctuation());
            clean == *a || clean == *b
        }) {
            return true;
        }
    }

    false
}

/// Generate perspective-aware sub-queries using AI.
///
/// For ambiguous or multi-domain queries, generates 3-4 domain-specific sub-queries
/// that cover the main interpretive angles (scientific, religious, philosophical,
/// historical, technical, etc.). Returns the original query if AI is unavailable.
///
/// ## Example
/// Query: "who created the world"
/// Perspectives: ["Big Bang cosmology universe origin scientific",
///                "Earth geological formation history",
///                "religious creation myths major world religions",
///                "philosophical cosmological argument origin creation"]
pub async fn ai_perspective_expand(query: &str, ai_config: &AiConfig) -> Vec<String> {
    let system = "You are a search query expansion expert. Given a user query, output 3 specific sub-queries covering different perspectives or domains. Rules: each sub-query covers a DIFFERENT angle (scientific, religious, philosophical, technical, historical, etc.); use domain-specific terminology; output ONLY the sub-queries, one per line, no numbering or labels; do NOT repeat the original query; keep each under 10 words.";
    let messages = vec![
        ChatMessage {
            role: "system".into(),
            content: system.to_string(),
        },
        ChatMessage {
            role: "user".into(),
            content: format!("Query: {query}\nSub-queries:"),
        },
    ];

    let providers = ai_config.providers.clone();
    let ai_cfg = ai_config.clone();

    // Thread isolation: ai_config contains non-Send elements via dyn FnMut
    let (tx, rx) = tokio::sync::oneshot::channel::<Vec<String>>();
    std::thread::spawn(move || {
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();
        let result = rt.block_on(async move {
            let mut noop = |_: &str| {};
            match tokio::time::timeout(
                std::time::Duration::from_secs(6),
                chat_with_fallback(&messages, None, &ai_cfg, &providers, false, &mut noop),
            )
            .await
            {
                Ok(Ok(resp)) => resp
                    .content
                    .lines()
                    .map(|l| l.trim().to_string())
                    .filter(|l| !l.is_empty() && l.len() > 5)
                    .take(4)
                    .collect::<Vec<_>>(),
                _ => vec![],
            }
        });
        let _ = tx.send(result);
    });

    rx.await.unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn js_expands_to_javascript() {
        let expanded = expand_query("JS frameworks comparison");
        assert!(
            expanded
                .expansions
                .iter()
                .any(|v| v.text.contains("javascript")),
            "JS should expand to JavaScript, got: {:?}",
            expanded.expansions
        );
    }

    #[test]
    fn ml_expands_to_machine_learning() {
        let expanded = expand_query("ML models for text");
        assert!(
            expanded
                .expansions
                .iter()
                .any(|v| v.text.contains("machine learning")),
            "ML should expand to machine learning"
        );
    }

    #[test]
    fn k8s_expands_to_kubernetes() {
        let expanded = expand_query("k8s deployment guide");
        assert!(
            expanded
                .expansions
                .iter()
                .any(|v| v.text.contains("kubernetes")),
            "k8s should expand to kubernetes"
        );
    }

    #[test]
    fn synonym_expansion() {
        let expanded = expand_query("fast database library");
        let has_quick = expanded.expansions.iter().any(|v| v.text.contains("quick"));
        let has_package = expanded
            .expansions
            .iter()
            .any(|v| v.text.contains("package"));
        assert!(
            has_quick || has_package,
            "Should expand synonyms: {:?}",
            expanded.expansions
        );
    }

    #[test]
    fn no_expansion_for_unknown() {
        let expanded = expand_query("quantum entanglement theory");
        assert!(
            expanded.expansions.is_empty(),
            "Unknown terms should not expand"
        );
    }

    #[test]
    fn preserves_original() {
        let expanded = expand_query("JS tutorial");
        assert_eq!(expanded.original, "JS tutorial");
    }

    #[test]
    fn max_three_expansions() {
        let expanded = expand_query("fast ML api tutorial");
        assert!(
            expanded.expansions.len() <= 3,
            "Should limit to 3 expansions, got {}",
            expanded.expansions.len()
        );
    }

    #[test]
    fn should_expand_detects_acronyms() {
        assert!(should_expand("JS frameworks"));
        assert!(should_expand("deploy ML model"));
        assert!(!should_expand("quantum physics"));
    }

    #[test]
    fn deduplicates_expansions() {
        let expanded = expand_query("JS JS tutorial");
        let texts: Vec<&str> = expanded
            .expansions
            .iter()
            .map(|v| v.text.as_str())
            .collect();
        let unique: std::collections::HashSet<&&str> = texts.iter().collect();
        assert_eq!(
            texts.len(),
            unique.len(),
            "Should not have duplicate expansions"
        );
    }

    #[test]
    fn confidence_ordering() {
        let expanded = expand_query("fast JS api");
        for i in 1..expanded.expansions.len() {
            assert!(
                expanded.expansions[i - 1].confidence >= expanded.expansions[i].confidence,
                "Expansions should be sorted by confidence"
            );
        }
    }
}