use std::collections::{HashMap, HashSet};
use crate::engines;
use crate::models::{RawSearchResult, SourceResult};
const MIN_CHUNK_CHARS: usize = 80;
const MAX_CHUNK_CHARS: usize = 600; const CHUNK_OVERLAP_RATIO: f64 = 0.15; const BM25_K1: f64 = 1.2;
const BM25_B: f64 = 0.75;
const BM25_DELTA: f64 = 1.0; const RRF_K: f64 = 60.0; const MMR_LAMBDA: f64 = 0.7; const MAX_CHUNKS_PER_URL_IN_TOP_K: usize = 3; const FRESHNESS_HALF_LIFE_NEWS: f64 = 7.0;
const FRESHNESS_HALF_LIFE_PERSON: f64 = 180.0;
const FRESHNESS_HALF_LIFE_DEFAULT: f64 = 60.0;
const FRESHNESS_FLOOR: f64 = 0.60;
const MMR_WINDOW_FACTOR: usize = 5;
const STOPWORDS: &[&str] = &[
"a",
"about",
"above",
"after",
"again",
"against",
"all",
"am",
"an",
"and",
"any",
"are",
"aren't",
"as",
"at",
"be",
"because",
"been",
"before",
"being",
"below",
"between",
"both",
"but",
"by",
"can",
"can't",
"cannot",
"could",
"couldn't",
"did",
"didn't",
"do",
"does",
"doesn't",
"doing",
"don't",
"down",
"during",
"each",
"few",
"for",
"from",
"further",
"get",
"got",
"had",
"hadn't",
"has",
"hasn't",
"have",
"haven't",
"having",
"he",
"her",
"here",
"hers",
"herself",
"him",
"himself",
"his",
"how",
"i",
"if",
"in",
"into",
"is",
"isn't",
"it",
"its",
"itself",
"just",
"let",
"like",
"ll",
"me",
"might",
"more",
"most",
"must",
"mustn't",
"my",
"myself",
"no",
"nor",
"not",
"of",
"off",
"on",
"once",
"only",
"or",
"other",
"our",
"ours",
"ourselves",
"out",
"over",
"own",
"re",
"s",
"same",
"shall",
"shan't",
"she",
"should",
"shouldn't",
"so",
"some",
"such",
"t",
"than",
"that",
"the",
"their",
"theirs",
"them",
"themselves",
"then",
"there",
"these",
"they",
"this",
"those",
"through",
"to",
"too",
"under",
"until",
"up",
"ve",
"very",
"was",
"wasn't",
"we",
"were",
"weren't",
"what",
"when",
"where",
"which",
"while",
"who",
"whom",
"why",
"will",
"with",
"won't",
"would",
"wouldn't",
"you",
"your",
"yours",
"yourself",
"yourselves",
];
use std::sync::LazyLock;
static STOPWORD_SET: LazyLock<HashSet<&'static str>> =
LazyLock::new(|| STOPWORDS.iter().copied().collect());
#[derive(Clone)]
struct ChunkCandidate {
url: String,
title: String,
engine: String,
text: String,
rrf_score: f64,
extraction_confidence: f64,
published: Option<chrono::DateTime<chrono::Utc>>,
language: Option<String>,
byline: Option<String>,
site_name: Option<String>,
extractor: &'static str,
}
pub fn compute_rrf_scores(results: &[RawSearchResult]) -> HashMap<String, f64> {
let mut best_rank: HashMap<(String, &'static str), usize> = HashMap::new();
for result in results {
let key = crate::url_utils::canonical_key(&result.url);
let family = engines::engine_family(&result.engine);
let rank = result.rank_position.max(1);
best_rank
.entry((key, family))
.and_modify(|cur| {
if rank < *cur {
*cur = rank;
}
})
.or_insert(rank);
}
let mut scores: HashMap<String, f64> = HashMap::new();
for ((key, family), rank) in best_rank {
let weight = engines::family_weight(family) as f64;
*scores.entry(key).or_insert(0.0) += weight / (RRF_K + rank as f64);
}
scores
}
pub fn family_agreement(results: &[RawSearchResult]) -> HashMap<String, Vec<&'static str>> {
let mut map: HashMap<String, Vec<&'static str>> = HashMap::new();
for result in results {
let key = crate::url_utils::canonical_key(&result.url);
let family = engines::engine_family(&result.engine);
let entry = map.entry(key).or_default();
if !entry.contains(&family) {
entry.push(family);
}
}
map
}
pub fn rank_top_chunks(query: &str, sources: &[SourceResult], top_k: usize) -> Vec<SourceResult> {
rank_top_chunks_with_rrf(query, sources, top_k, None)
}
pub fn freshness_multiplier(
published: Option<chrono::DateTime<chrono::Utc>>,
is_time_sensitive: bool,
intent: &crate::query_intel::QueryIntent,
) -> f64 {
use crate::query_intel::QueryIntent;
if !is_time_sensitive {
return 1.0;
}
let Some(p) = published else {
return 0.92;
};
let days = (chrono::Utc::now() - p).num_days().max(0) as f64;
let half_life = match intent {
QueryIntent::Temporal => FRESHNESS_HALF_LIFE_NEWS,
QueryIntent::Person => FRESHNESS_HALF_LIFE_PERSON,
_ => FRESHNESS_HALF_LIFE_DEFAULT,
};
FRESHNESS_FLOOR + (1.0 - FRESHNESS_FLOOR) * 0.5_f64.powf(days / half_life)
}
pub fn rank_top_chunks_with_rrf(
query: &str,
sources: &[SourceResult],
top_k: usize,
rrf_scores: Option<&HashMap<String, f64>>,
) -> Vec<SourceResult> {
rank_top_chunks_with_signals(query, sources, top_k, rrf_scores, None)
}
#[derive(Debug, Clone, Copy)]
pub struct RankOptions {
pub max_chunks_per_url: usize,
pub freshness: bool,
pub mode: crate::modes::Mode,
pub domain: crate::modes::Domain,
}
impl Default for RankOptions {
fn default() -> Self {
Self {
max_chunks_per_url: MAX_CHUNKS_PER_URL_IN_TOP_K,
freshness: true,
mode: crate::modes::Mode::Auto,
domain: crate::modes::Domain::General,
}
}
}
impl RankOptions {
pub fn from_profile(p: &crate::modes::ModeProfile) -> Self {
Self {
max_chunks_per_url: p.max_chunks_per_url.max(1),
freshness: p.freshness,
mode: p.mode,
domain: p.domain,
}
}
}
pub fn rank_top_chunks_with_signals(
query: &str,
sources: &[SourceResult],
top_k: usize,
rrf_scores: Option<&HashMap<String, f64>>,
intel: Option<&crate::query_intel::QueryIntelligence>,
) -> Vec<SourceResult> {
rank_with_options(
query,
sources,
top_k,
rrf_scores,
intel,
&RankOptions::default(),
)
}
pub fn rank_with_options(
query: &str,
sources: &[SourceResult],
top_k: usize,
rrf_scores: Option<&HashMap<String, f64>>,
intel: Option<&crate::query_intel::QueryIntelligence>,
opts: &RankOptions,
) -> Vec<SourceResult> {
if sources.is_empty() || top_k == 0 {
return Vec::new();
}
let max_rrf = rrf_scores
.map(|s| s.values().cloned().fold(0.0_f64, f64::max))
.unwrap_or(1.0)
.max(1e-9);
let mut candidates = Vec::new();
for source in sources {
let url_rrf = rrf_scores
.and_then(|s| {
s.get(&crate::url_utils::canonical_key(&source.url))
.copied()
})
.unwrap_or(0.0);
for chunk in paragraph_chunks(&source.extracted_text) {
if chunk.trim().is_empty() {
continue;
}
let inline_date = extract_chunk_inline_date(&chunk);
let (effective_published, annotated_text) = match (inline_date, source.published) {
(Some(d_inline), Some(d_page)) if (d_page - d_inline).num_days() > 7 => {
let prefix = format!(
"[Entry Date: {} | Page Modified: {}] ",
d_inline.format("%Y-%m-%d"),
d_page.format("%Y-%m-%d")
);
let tagged = if chunk.starts_with("[Entry Date:") {
chunk
} else {
format!("{prefix}{chunk}")
};
(Some(d_inline), tagged)
}
(Some(d_inline), None) => (Some(d_inline), chunk),
(_, page_pub) => (page_pub, chunk),
};
candidates.push(ChunkCandidate {
url: source.url.clone(),
title: source.title.clone(),
engine: source.engine.clone(),
text: annotated_text,
rrf_score: url_rrf,
extraction_confidence: if source.confidence > 0.0 {
source.confidence
} else {
0.7
},
published: effective_published,
language: source.language.clone(),
byline: source.byline.clone(),
site_name: source.site_name.clone(),
extractor: source.extractor,
});
}
}
if candidates.is_empty() {
return Vec::new();
}
let query_terms = unique_tokens_filtered(query);
if query_terms.is_empty() {
return candidates
.into_iter()
.take(top_k)
.map(|c| SourceResult {
url: c.url,
title: c.title,
engine: c.engine,
char_count: crate::util::char_len(&c.text),
extracted_text: c.text,
published: c.published,
language: c.language,
byline: c.byline,
site_name: c.site_name,
confidence: c.extraction_confidence,
extractor: c.extractor,
})
.collect();
}
let tokenized_docs: Vec<Vec<String>> = candidates
.iter()
.map(|c| tokenize_filtered(&c.text))
.collect();
let doc_count = tokenized_docs.len() as f64;
let avg_doc_len = {
let total: usize = tokenized_docs.iter().map(|d| d.len()).sum();
(total.max(1) as f64) / doc_count.max(1.0)
};
let mut doc_freq: HashMap<String, usize> = HashMap::new();
for tokens in &tokenized_docs {
let mut seen = HashSet::new();
for token in tokens {
if seen.insert(token.clone()) {
*doc_freq.entry(token.clone()).or_insert(0) += 1;
}
}
}
let has_official_in_pool = match intel {
Some(it) if !it.key_entities.is_empty() => candidates.iter().any(|c| {
crate::llm::url_matches_query_entities(&c.url, c.site_name.as_deref(), &it.key_entities)
.0
> 0
}),
_ => false,
};
let entity_token_set: HashSet<String> = intel
.map(|it| {
it.key_entities
.iter()
.flat_map(|e| e.split_whitespace())
.map(|t| {
t.trim_matches(|c: char| !crate::util::is_word_char(c))
.to_lowercase()
})
.filter(|t| t.chars().count() >= 3)
.collect()
})
.unwrap_or_default();
let subtopic_query_terms: Vec<&str> = query_terms
.iter()
.map(|s| s.as_str())
.filter(|t| !entity_token_set.contains(*t))
.collect();
let query_phrase = query.trim().to_lowercase();
let mut scored: Vec<(usize, f64)> = Vec::with_capacity(candidates.len());
for (idx, tokens) in tokenized_docs.iter().enumerate() {
let mut tf: HashMap<&str, usize> = HashMap::new();
for token in tokens {
*tf.entry(token.as_str()).or_insert(0) += 1;
}
let dl = tokens.len().max(1) as f64;
let mut score = 0.0;
for term in &query_terms {
let term_tf = tf.get(term.as_str()).copied().unwrap_or(0) as f64;
if term_tf <= 0.0 {
continue;
}
let df = doc_freq.get(term).copied().unwrap_or(0) as f64;
let idf = ((doc_count - df + 0.5) / (df + 0.5) + 1.0).ln();
let numerator = term_tf * (BM25_K1 + 1.0);
let denominator = term_tf + BM25_K1 * (1.0 - BM25_B + BM25_B * (dl / avg_doc_len));
let bm25_base = idf * (numerator / denominator.max(1e-9));
score += bm25_base + BM25_DELTA * idf;
}
if !query_phrase.is_empty() && candidates[idx].text.to_lowercase().contains(&query_phrase) {
score += 1.25;
}
let title_lower = candidates[idx].title.to_lowercase();
let title_match_count = query_terms
.iter()
.filter(|qt| title_lower.contains(qt.as_str()))
.count();
if title_match_count > 0 {
score += (title_match_count as f64) * 0.5;
}
if !entity_token_set.is_empty() && !subtopic_query_terms.is_empty() {
let has_entity = entity_token_set
.iter()
.any(|et| tf.contains_key(et.as_str()) || title_lower.contains(et.as_str()));
let subtopic_matches = subtopic_query_terms
.iter()
.filter(|&&st| tf.contains_key(st))
.count();
if has_entity && subtopic_matches > 0 {
score *= 1.0 + 0.18 * (subtopic_matches.min(3) as f64);
} else if subtopic_matches == 0
&& crate::llm::is_encyclopedia_url(
&candidates[idx].url,
candidates[idx].site_name.as_deref(),
)
{
score *= 0.80;
}
}
let rrf_normalized = candidates[idx].rrf_score / max_rrf;
score *= 1.0 + (rrf_normalized * 0.5);
score *= 0.80 + 0.20 * candidates[idx].extraction_confidence.clamp(0.0, 1.0);
score *= crate::llm::dynamic_authority_score(
&candidates[idx].url,
candidates[idx].site_name.as_deref(),
&candidates[idx].title,
intel,
opts.mode,
has_official_in_pool,
);
score *= crate::modes::source_boost(&candidates[idx].url, opts.mode, opts.domain);
if let (true, Some(it)) = (opts.freshness, intel) {
let effective_intent = if it.is_time_sensitive
&& matches!(
it.semantic_category,
crate::query_intel::SemanticCategory::LiveNews
| crate::query_intel::SemanticCategory::ProductOrg
) {
&crate::query_intel::QueryIntent::Temporal
} else {
&it.intent
};
score *= freshness_multiplier(
candidates[idx].published,
it.is_time_sensitive,
effective_intent,
);
}
scored.push((idx, score));
}
scored.sort_by(|a, b| {
b.1.partial_cmp(&a.1)
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| {
let a_len = candidates[a.0].text.chars().count();
let b_len = candidates[b.0].text.chars().count();
b_len.cmp(&a_len)
})
});
let selected = mmr_rerank(
&candidates,
&scored,
top_k,
&tokenized_docs,
opts.max_chunks_per_url.max(1),
);
selected
.into_iter()
.map(|idx| {
let chunk = &candidates[idx];
SourceResult {
url: chunk.url.clone(),
title: chunk.title.clone(),
engine: chunk.engine.clone(),
char_count: crate::util::char_len(&chunk.text),
extracted_text: chunk.text.clone(),
published: chunk.published,
language: chunk.language.clone(),
byline: chunk.byline.clone(),
site_name: chunk.site_name.clone(),
confidence: chunk.extraction_confidence,
extractor: chunk.extractor,
}
})
.collect()
}
fn token_signature(tokens: &[String]) -> Vec<u64> {
use std::hash::{Hash, Hasher};
let mut v: Vec<u64> = tokens
.iter()
.map(|t| {
let mut h = std::collections::hash_map::DefaultHasher::new();
t.hash(&mut h);
h.finish()
})
.collect();
v.sort_unstable();
v.dedup();
v
}
fn jaccard_sorted(a: &[u64], b: &[u64]) -> f64 {
if a.is_empty() && b.is_empty() {
return 1.0;
}
let (mut i, mut j, mut inter) = (0usize, 0usize, 0usize);
while i < a.len() && j < b.len() {
match a[i].cmp(&b[j]) {
std::cmp::Ordering::Equal => {
inter += 1;
i += 1;
j += 1;
}
std::cmp::Ordering::Less => i += 1,
std::cmp::Ordering::Greater => j += 1,
}
}
let union = a.len() + b.len() - inter;
if union == 0 {
0.0
} else {
inter as f64 / union as f64
}
}
fn mmr_rerank(
candidates: &[ChunkCandidate],
scored: &[(usize, f64)],
top_k: usize,
tokenized: &[Vec<String>],
max_per_url: usize,
) -> Vec<usize> {
if scored.is_empty() || top_k == 0 {
return Vec::new();
}
let max_score = scored
.iter()
.map(|(_, s)| *s)
.fold(0.0_f64, f64::max)
.max(1e-9);
let window = top_k.saturating_mul(MMR_WINDOW_FACTOR).min(scored.len());
struct Cand {
idx: usize,
rel: f64,
sig: Vec<u64>,
url_key: String,
max_sim: f64,
taken: bool,
}
let mut pool: Vec<Cand> = scored[..window]
.iter()
.map(|&(idx, rel)| Cand {
idx,
rel: rel / max_score,
sig: token_signature(tokenized.get(idx).map(|v| v.as_slice()).unwrap_or(&[])),
url_key: crate::url_utils::canonical_key(&candidates[idx].url),
max_sim: 0.0,
taken: false,
})
.collect();
let mut selected: Vec<usize> = Vec::with_capacity(top_k);
let mut url_counts: HashMap<String, usize> = HashMap::new();
while selected.len() < top_k {
let mut best: Option<(usize, f64)> = None; let mut any_eligible = false;
for (pos, c) in pool.iter().enumerate() {
if c.taken {
continue;
}
if url_counts.get(&c.url_key).copied().unwrap_or(0) >= max_per_url {
continue;
}
any_eligible = true;
let mmr = MMR_LAMBDA * c.rel - (1.0 - MMR_LAMBDA) * c.max_sim;
if best.is_none_or(|(_, b)| mmr > b) {
best = Some((pos, mmr));
}
}
let Some((pos, _)) = best else {
if !any_eligible {
break;
}
break;
};
pool[pos].taken = true;
let chosen_idx = pool[pos].idx;
*url_counts.entry(pool[pos].url_key.clone()).or_insert(0) += 1;
selected.push(chosen_idx);
let (left, right) = pool.split_at_mut(pos);
let (chosen, right) = right.split_first_mut().expect("pos is in range");
for c in left.iter_mut().chain(right.iter_mut()) {
if c.taken {
continue;
}
let sim = jaccard_sorted(&c.sig, &chosen.sig);
if sim > c.max_sim {
c.max_sim = sim;
}
}
}
selected
}
fn paragraph_chunks(text: &str) -> Vec<String> {
let normalized = text.replace('\r', "");
let mut paragraphs = normalized
.split("\n\n")
.map(str::trim)
.filter(|p| !p.is_empty())
.collect::<Vec<_>>();
if paragraphs.is_empty() {
let compact = normalized.trim();
if compact.is_empty() {
return Vec::new();
}
paragraphs.push(compact);
}
let mut chunks: Vec<String> = Vec::new();
let mut current = String::new();
for paragraph in paragraphs {
if current.is_empty() {
current.push_str(paragraph);
continue;
}
let projected_len = current.chars().count() + 2 + paragraph.chars().count();
let current_len = current.chars().count();
if projected_len <= MAX_CHUNK_CHARS || current_len < MIN_CHUNK_CHARS {
current.push_str("\n\n");
current.push_str(paragraph);
} else {
let trimmed = current.trim().to_string();
if trimmed.chars().count() > MAX_CHUNK_CHARS {
let sub_chunks = split_at_sentence_boundaries(&trimmed);
chunks.extend(sub_chunks);
} else {
chunks.push(trimmed);
}
current.clear();
current.push_str(paragraph);
}
}
if !current.trim().is_empty() {
let trimmed = current.trim().to_string();
if trimmed.chars().count() > MAX_CHUNK_CHARS {
let sub_chunks = split_at_sentence_boundaries(&trimmed);
chunks.extend(sub_chunks);
} else {
chunks.push(trimmed);
}
}
if chunks.len() > 1 {
apply_chunk_overlap(&mut chunks);
}
chunks
}
const SENTENCE_TERMINATORS: &[char] = &[
'.', '!', '?', '\u{0964}', '\u{0965}', '\u{06D4}', '\u{3002}', '\u{FF01}', '\u{FF1F}', '\u{0589}', '\u{104A}', '\u{104B}', '\u{1362}', '\u{17D4}', '\u{0E2F}', ];
fn script_has_case(c: char) -> bool {
c.is_uppercase() || c.is_lowercase()
}
fn is_sentence_boundary(chars: &[char], i: usize) -> bool {
if !SENTENCE_TERMINATORS.contains(&chars[i]) {
return false;
}
let Some(&next) = chars.get(i + 1) else {
return true;
};
if !next.is_whitespace() {
return matches!(
chars[i],
'\u{0964}' | '\u{0965}' | '\u{3002}' | '\u{FF01}' | '\u{FF1F}'
);
}
match chars.get(i + 2) {
None => true,
Some(&after) if script_has_case(after) => after.is_uppercase(),
Some(_) => true,
}
}
fn split_at_sentence_boundaries(text: &str) -> Vec<String> {
let chars: Vec<char> = text.chars().collect();
let mut chunks: Vec<String> = Vec::new();
let mut current = String::new();
let mut current_chars = 0usize;
let mut i = 0usize;
while i < chars.len() {
current.push(chars[i]);
current_chars += 1;
if current_chars >= MIN_CHUNK_CHARS && is_sentence_boundary(&chars, i) {
chunks.push(current.trim().to_string());
current.clear();
current_chars = 0;
i += 1;
while i < chars.len() && chars[i].is_whitespace() {
i += 1;
}
continue;
}
if current_chars >= MAX_CHUNK_CHARS * 2 {
chunks.push(current.trim().to_string());
current.clear();
current_chars = 0;
}
i += 1;
}
if !current.trim().is_empty() {
if current_chars < MIN_CHUNK_CHARS && !chunks.is_empty() {
let last = chunks.last_mut().unwrap();
last.push(' ');
last.push_str(current.trim());
} else {
chunks.push(current.trim().to_string());
}
}
if chunks.is_empty() {
chunks.push(text.to_string());
}
chunks
}
fn apply_chunk_overlap(chunks: &mut Vec<String>) {
if chunks.len() <= 1 {
return;
}
let mut overlapped = Vec::with_capacity(chunks.len());
overlapped.push(chunks[0].clone());
for i in 1..chunks.len() {
let prev = &chunks[i - 1];
let overlap_chars = (prev.chars().count() as f64 * CHUNK_OVERLAP_RATIO) as usize;
if overlap_chars > 10 {
let prev_suffix: String = prev
.chars()
.rev()
.take(overlap_chars)
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect();
let word_start = prev_suffix.find(' ').unwrap_or(0);
let clean_overlap = prev_suffix[word_start..].trim();
if !clean_overlap.is_empty() {
overlapped.push(format!("{}… {}", clean_overlap, chunks[i]));
} else {
overlapped.push(chunks[i].clone());
}
} else {
overlapped.push(chunks[i].clone());
}
}
*chunks = overlapped;
}
fn tokenize_filtered(text: &str) -> Vec<String> {
text.split(|c: char| !crate::util::is_word_char(c))
.filter_map(|raw| {
let t = raw.trim().to_lowercase();
if t.len() < 2 {
return None;
}
if STOPWORD_SET.contains(t.as_str()) {
return None;
}
Some(t)
})
.collect()
}
pub(crate) fn query_terms(text: &str) -> Vec<String> {
unique_tokens_filtered(text)
}
fn unique_tokens_filtered(text: &str) -> Vec<String> {
let mut out = Vec::new();
let mut seen = HashSet::new();
for token in tokenize_filtered(text) {
if seen.insert(token.clone()) {
out.push(token);
}
}
out
}
pub fn cross_query_scores(
query_results: &[(String, Vec<RawSearchResult>)],
original_query: &str,
) -> HashMap<String, f64> {
const ORIGINAL_WEIGHT: f64 = 2.0;
const SUB_WEIGHT: f64 = 1.0;
let mut scores: HashMap<String, f64> = HashMap::new();
let mut sub_query_count: HashMap<String, HashSet<&str>> = HashMap::new();
for (sub_query, results) in query_results {
let weight = if sub_query.eq_ignore_ascii_case(original_query) {
ORIGINAL_WEIGHT
} else {
SUB_WEIGHT
};
for (key, score) in compute_rrf_scores(results) {
*scores.entry(key.clone()).or_insert(0.0) += weight * score;
sub_query_count
.entry(key)
.or_default()
.insert(sub_query.as_str());
}
}
let total_queries = query_results.len().max(1) as f64;
for (key, qs) in &sub_query_count {
if qs.len() > 1 {
if let Some(s) = scores.get_mut(key) {
*s *= 1.0 + 0.15 * (qs.len() as f64 / total_queries);
}
}
}
scores
}
#[cfg(test)]
mod tests {
use super::*;
use crate::models::RawSearchResult;
fn hit(url: &str, engine: &str, rank: usize) -> RawSearchResult {
RawSearchResult {
url: url.to_string(),
title: "t".into(),
snippet: String::new(),
engine: engine.to_string(),
rank_position: rank,
published: None,
full_text: None,
}
}
#[test]
fn rrf_counts_bing_aliases_once() {
let aliases = [
"bing", "bing_us", "bing_uk", "bing_in", "bing_de", "bing_fr", "bing_es", "bing_it",
"bing_jp", "bing_ca", "bing_au", "bing_nl", "bing_se", "bing_no", "bing_fi",
];
let many: Vec<RawSearchResult> = aliases
.iter()
.map(|e| hit("https://a.test/x", e, 1))
.collect();
let one = vec![hit("https://a.test/x", "bing", 1)];
let s_many = compute_rrf_scores(&many);
let s_one = compute_rrf_scores(&one);
let k = crate::url_utils::canonical_key("https://a.test/x");
assert!(
(s_many[&k] - s_one[&k]).abs() < 1e-12,
"15 Bing aliases scored {} vs one alias {} — aliases are inflating consensus",
s_many[&k],
s_one[&k]
);
}
#[test]
fn rrf_treats_bing_derived_engines_as_one_family() {
let derived = vec![
hit("https://a.test/x", "bing", 1),
hit("https://a.test/x", "yahoo", 1),
hit("https://a.test/x", "duckduckgo", 1),
];
let single = vec![hit("https://a.test/x", "bing", 1)];
let k = crate::url_utils::canonical_key("https://a.test/x");
assert!((compute_rrf_scores(&derived)[&k] - compute_rrf_scores(&single)[&k]).abs() < 1e-12);
let google_family = vec![
hit("https://a.test/x", "google", 1),
hit("https://a.test/x", "startpage", 1),
hit("https://a.test/x", "ecosia", 1),
];
assert!(
(compute_rrf_scores(&google_family)[&k] - compute_rrf_scores(&single)[&k]).abs() < 1e-9
);
}
#[test]
fn genuinely_independent_engines_do_accumulate() {
let independent = vec![
hit("https://a.test/x", "bing", 1),
hit("https://a.test/x", "google", 1),
hit("https://a.test/x", "brave", 1),
hit("https://a.test/x", "yandex", 1),
hit("https://a.test/x", "marginalia_api", 1),
];
let single = vec![hit("https://a.test/x", "bing", 1)];
let k = crate::url_utils::canonical_key("https://a.test/x");
let multi = compute_rrf_scores(&independent)[&k];
let one = compute_rrf_scores(&single)[&k];
assert!(
multi > one * 3.0,
"5 independent families scored {multi} vs {one}"
);
}
#[test]
fn rrf_uses_the_best_rank_within_a_family() {
let mixed = vec![
hit("https://a.test/x", "bing", 9),
hit("https://a.test/x", "bing_uk", 2),
];
let best_only = vec![hit("https://a.test/x", "bing", 2)];
let k = crate::url_utils::canonical_key("https://a.test/x");
assert!(
(compute_rrf_scores(&mixed)[&k] - compute_rrf_scores(&best_only)[&k]).abs() < 1e-12
);
}
#[test]
fn rrf_unifies_url_spellings_of_one_page() {
let spellings = vec![
hit("https://example.com/story", "bing", 1),
hit("https://www.example.com/story/", "bing", 1),
hit("https://m.example.com/story?utm_source=x", "bing", 1),
];
let scores = compute_rrf_scores(&spellings);
assert_eq!(
scores.len(),
1,
"expected one canonical key, got {scores:?}"
);
}
#[test]
fn higher_rank_scores_higher() {
let a = compute_rrf_scores(&[hit("https://a.test/1", "bing", 1)]);
let b = compute_rrf_scores(&[hit("https://a.test/1", "bing", 20)]);
let k = crate::url_utils::canonical_key("https://a.test/1");
assert!(a[&k] > b[&k], "rank 1 must beat rank 20");
}
#[test]
fn family_agreement_reports_independent_families() {
let results = vec![
hit("https://a.test/x", "bing", 1),
hit("https://a.test/x", "bing_uk", 3),
hit("https://a.test/x", "yahoo", 2), hit("https://a.test/x", "brave", 1), hit("https://a.test/x", "marginalia_api", 5),
];
let agree = family_agreement(&results);
let k = crate::url_utils::canonical_key("https://a.test/x");
let fams = &agree[&k];
assert_eq!(
fams.len(),
3,
"expected bing+brave+marginalia, got {fams:?}"
);
assert!(fams.contains(&"bing") && fams.contains(&"brave") && fams.contains(&"marginalia"));
}
#[test]
fn hindi_article_splits_on_danda_not_one_blob() {
let sentence = "भारत और पाकिस्तान के बीच मुकाबला दस अक्टूबर को खेला जाएगा।";
let article = std::iter::repeat_n(sentence, 12)
.collect::<Vec<_>>()
.join(" ");
let chunks = paragraph_chunks(&article);
assert!(
chunks.len() >= 3,
"Hindi article produced {} chunk(s) — danda boundaries not detected",
chunks.len()
);
assert!(chunks.iter().all(|c| c.contains('\u{0915}')
|| c.contains('\u{092E}')
|| c.contains('\u{092C}')
|| c.contains('\u{0926}')));
}
#[test]
fn cjk_text_splits_on_ideographic_full_stop() {
let s = "这是一个句子。这是另一个句子。还有第三个句子。";
let article = std::iter::repeat_n(s, 40).collect::<Vec<_>>().join("");
assert!(
article.chars().count() > MAX_CHUNK_CHARS,
"test input too short"
);
let chunks = paragraph_chunks(&article);
assert!(chunks.len() >= 2, "CJK produced {} chunk(s)", chunks.len());
assert!(chunks
.iter()
.all(|c| c.chars().count() <= MAX_CHUNK_CHARS * 2));
}
#[test]
fn short_text_correctly_stays_one_chunk() {
let s = "这是一个句子。".repeat(10);
assert!(s.chars().count() < MAX_CHUNK_CHARS);
assert_eq!(paragraph_chunks(&s).len(), 1);
}
#[test]
fn english_sentences_still_split_correctly() {
let s = "This is the first sentence of the document. Here is a second one that continues. \
And a third sentence follows after it. Then a fourth appears here as well.";
let article = std::iter::repeat_n(s, 6).collect::<Vec<_>>().join(" ");
let chunks = paragraph_chunks(&article);
assert!(
chunks.len() >= 2,
"English produced {} chunk(s)",
chunks.len()
);
}
#[test]
fn decimals_and_abbreviations_do_not_split_english() {
let chars: Vec<char> = "pi is 3.14 exactly".chars().collect();
let dot = chars.iter().position(|c| *c == '.').unwrap();
assert!(!is_sentence_boundary(&chars, dot), "split inside a decimal");
}
#[test]
fn terminator_free_text_still_gets_chunked() {
let blob = "x".repeat(MAX_CHUNK_CHARS * 6);
let chunks = paragraph_chunks(&blob);
assert!(
chunks.len() >= 3,
"terminator-free blob produced {} chunk(s)",
chunks.len()
);
}
#[test]
fn script_case_detection() {
assert!(script_has_case('A') && script_has_case('z'));
assert!(!script_has_case('\u{0915}'));
assert!(!script_has_case('\u{0627}'));
assert!(!script_has_case('\u{4E2D}'));
assert!(!script_has_case('\u{0E01}'));
}
#[test]
fn chunking_is_utf8_safe_on_mixed_scripts() {
let mixed = "Hello world. नमस्ते दुनिया। 你好世界。مرحبا بالعالم؟ Done.".repeat(20);
let chunks = paragraph_chunks(&mixed);
assert!(!chunks.is_empty());
assert!(chunks.iter().all(|c| !c.contains('\u{FFFD}')));
}
#[test]
fn freshness_is_neutral_for_evergreen_queries() {
use crate::query_intel::QueryIntent;
let old = Some(chrono::Utc::now() - chrono::Duration::days(3000));
assert_eq!(freshness_multiplier(old, false, &QueryIntent::HowTo), 1.0);
assert_eq!(
freshness_multiplier(None, false, &QueryIntent::Factual),
1.0
);
}
#[test]
fn fresh_news_outranks_stale_news_on_temporal_queries() {
use crate::query_intel::QueryIntent;
let today = Some(chrono::Utc::now());
let month_old = Some(chrono::Utc::now() - chrono::Duration::days(30));
let year_old = Some(chrono::Utc::now() - chrono::Duration::days(365));
let f_today = freshness_multiplier(today, true, &QueryIntent::Temporal);
let f_month = freshness_multiplier(month_old, true, &QueryIntent::Temporal);
let f_year = freshness_multiplier(year_old, true, &QueryIntent::Temporal);
assert!(
f_today > f_month && f_month > f_year,
"{f_today} {f_month} {f_year}"
);
assert!(f_today > 0.99, "today should be ~1.0, got {f_today}");
}
#[test]
fn freshness_never_erases_an_old_authoritative_source() {
use crate::query_intel::QueryIntent;
let ancient = Some(chrono::Utc::now() - chrono::Duration::days(10_000));
let f = freshness_multiplier(ancient, true, &QueryIntent::Temporal);
assert!(f >= FRESHNESS_FLOOR, "floor breached: {f}");
assert!(f > 0.0);
}
#[test]
fn person_queries_decay_more_slowly_than_news() {
use crate::query_intel::QueryIntent;
let d = Some(chrono::Utc::now() - chrono::Duration::days(60));
let news = freshness_multiplier(d, true, &QueryIntent::Temporal);
let person = freshness_multiplier(d, true, &QueryIntent::Person);
assert!(
person > news,
"person {person} should decay slower than news {news}"
);
}
#[test]
fn undated_sources_get_a_mild_penalty_not_a_veto() {
use crate::query_intel::QueryIntent;
let f = freshness_multiplier(None, true, &QueryIntent::Temporal);
assert!(f > 0.85 && f < 1.0, "got {f}");
}
#[test]
fn future_dates_do_not_produce_a_bonus_above_one() {
use crate::query_intel::QueryIntent;
let future = Some(chrono::Utc::now() + chrono::Duration::days(500));
let f = freshness_multiplier(future, true, &QueryIntent::Temporal);
assert!(f <= 1.0, "clock-skewed future date gave {f}");
}
fn fused_order(groups: &[(String, Vec<RawSearchResult>)], orig: &str) -> Vec<String> {
let mut v: Vec<(String, f64)> = cross_query_scores(groups, orig).into_iter().collect();
v.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
v.into_iter().map(|(k, _)| k).collect()
}
#[test]
fn original_query_outweighs_sub_queries() {
let orig = "cricket world cup 2027";
let groups = vec![
(
orig.to_string(),
vec![hit("https://a.test/from-original", "bing", 1)],
),
(
"cricket".to_string(),
vec![hit("https://b.test/from-sub", "bing", 1)],
),
];
let order = fused_order(&groups, orig);
assert_eq!(order.len(), 2);
assert!(
order[0].contains("from-original"),
"the original query's hit must rank first, got {order:?}"
);
}
#[test]
fn pages_found_by_multiple_sub_queries_get_a_bonus() {
let orig = "postgres vs mysql";
let shared = "https://both.test/compare";
let only_one = "https://one.test/page";
let groups = vec![
(
orig.to_string(),
vec![hit(shared, "bing", 5), hit(only_one, "bing", 1)],
),
("postgres".to_string(), vec![hit(shared, "brave", 5)]),
("mysql".to_string(), vec![hit(shared, "yandex", 5)]),
];
let s = cross_query_scores(&groups, orig);
let k = |u: &str| crate::url_utils::canonical_key(u);
assert!(
s[&k(shared)] > s[&k(only_one)],
"a page confirmed by 3 sub-queries and 3 families should beat a \
single-query rank-1 hit"
);
}
#[test]
fn fusion_keeps_cross_engine_consensus_within_a_sub_query() {
let orig = "capital of France";
let agreed = "https://en.wikipedia.org/wiki/Paris";
let single = "https://odd.test/page";
let groups = vec![
(
orig.to_string(),
vec![
hit(single, "bing", 1),
hit(agreed, "wikipedia", 2),
hit(agreed, "duckduckgo", 2),
],
),
("capital of France history".to_string(), vec![]),
];
let order = fused_order(&groups, orig);
assert_eq!(
order[0],
crate::url_utils::canonical_key(agreed),
"{order:?}"
);
}
#[test]
fn fusion_matches_plain_rrf_for_a_single_query() {
let orig = "q";
let results = vec![
hit("https://a.test/1", "bing", 1),
hit("https://a.test/1", "brave", 3),
hit("https://b.test/2", "bing", 2),
];
let fused = cross_query_scores(&[(orig.to_string(), results.clone())], orig);
let plain = compute_rrf_scores(&results);
for (k, v) in &plain {
assert!(
(fused[k] - 2.0 * v).abs() < 1e-12,
"only the original-query weight should differ"
);
}
}
#[test]
fn fusion_collapses_url_spellings_and_aliases() {
let orig = "q";
let groups = vec![(
orig.to_string(),
vec![
hit("https://example.com/story", "bing", 1),
hit("https://www.example.com/story/", "bing_uk", 1),
hit("https://m.example.com/story?utm_source=x", "bing_de", 1),
],
)];
let s = cross_query_scores(&groups, orig);
assert_eq!(s.len(), 1, "one page, three spellings: {s:?}");
}
#[test]
fn fusion_handles_empty_groups() {
assert!(cross_query_scores(&[], "q").is_empty());
assert!(cross_query_scores(&[("q".into(), vec![])], "q").is_empty());
}
#[test]
fn ranking_fewer_chunks_than_top_k_does_not_panic() {
let sources: Vec<SourceResult> = (0..3)
.map(|i| SourceResult {
url: format!("https://t{i}.test/a"),
title: format!("Title {i}"),
extracted_text: format!(
"Short source {i} about rust ownership and borrowing rules."
),
char_count: 60,
engine: "test".into(),
confidence: 1.0,
..Default::default()
})
.collect();
for top_k in [1, 3, 25, 500] {
let out = rank_top_chunks_with_signals("rust ownership", &sources, top_k, None, None);
assert!(out.len() <= top_k.clamp(1, 3) || out.len() <= 3);
}
assert!(rank_top_chunks_with_signals("rust", &[], 25, None, None).is_empty());
}
#[test]
fn empty_input_is_handled() {
assert!(compute_rrf_scores(&[]).is_empty());
assert!(family_agreement(&[]).is_empty());
}
}
fn parse_month_token(tok: &str) -> Option<u32> {
let clean = tok
.trim_matches(|c: char| !c.is_ascii_alphabetic())
.to_ascii_lowercase();
match clean.as_str() {
"jan" | "january" => Some(1),
"feb" | "february" => Some(2),
"mar" | "march" => Some(3),
"apr" | "april" => Some(4),
"may" => Some(5),
"jun" | "june" => Some(6),
"jul" | "july" => Some(7),
"aug" | "august" => Some(8),
"sep" | "sept" | "september" => Some(9),
"oct" | "october" => Some(10),
"nov" | "november" => Some(11),
"dec" | "december" => Some(12),
_ => None,
}
}
fn parse_day_token(tok: &str) -> Option<u32> {
let clean = tok
.trim_matches(|c: char| !c.is_ascii_alphanumeric())
.to_ascii_lowercase();
let digits = clean
.strip_suffix("st")
.or_else(|| clean.strip_suffix("nd"))
.or_else(|| clean.strip_suffix("rd"))
.or_else(|| clean.strip_suffix("th"))
.unwrap_or(&clean);
if digits.is_empty() || digits.len() > 2 || !digits.chars().all(|c| c.is_ascii_digit()) {
return None;
}
digits
.parse::<u32>()
.ok()
.filter(|&d| (1..=31).contains(&d))
}
fn parse_year_token(tok: &str, max_year: i32) -> Option<i32> {
let clean = tok.trim_matches(|c: char| !c.is_ascii_alphanumeric());
if clean.len() != 4 || !clean.chars().all(|c| c.is_ascii_digit()) {
return None;
}
clean
.parse::<i32>()
.ok()
.filter(|&y| (1995..=max_year).contains(&y))
}
pub fn extract_chunk_inline_date(text: &str) -> Option<chrono::DateTime<chrono::Utc>> {
use chrono::{Datelike, TimeZone, Utc};
let now = Utc::now();
let max_year = now.year() + 1;
let max_valid_dt = now + chrono::Duration::days(2);
let mut day_precision_dates: Vec<chrono::DateTime<Utc>> = Vec::new();
let mut month_precision_dates: Vec<chrono::DateTime<Utc>> = Vec::new();
let tokens: Vec<&str> = text.split_whitespace().collect();
for raw_tok in &tokens {
let clean =
raw_tok.trim_matches(|c: char| !c.is_ascii_alphanumeric() && c != '-' && c != '/');
if let Some(head) = clean.get(..10) {
if head.is_ascii() {
let bytes = head.as_bytes();
let sep = bytes[4];
if (sep == b'-' || sep == b'/') && bytes[7] == sep {
if let (Ok(y), Ok(m), Ok(d)) = (
head[0..4].parse::<i32>(),
head[5..7].parse::<u32>(),
head[8..10].parse::<u32>(),
) {
if (1995..=max_year).contains(&y) {
if let Some(dt) = Utc.with_ymd_and_hms(y, m, d, 0, 0, 0).single() {
if dt <= max_valid_dt {
day_precision_dates.push(dt);
}
}
}
}
}
}
}
}
let mut i = 0;
while i < tokens.len() {
if let Some(m) = parse_month_token(tokens[i]) {
if i + 2 < tokens.len() {
if let (Some(d), Some(y)) = (
parse_day_token(tokens[i + 1]),
parse_year_token(tokens[i + 2], max_year),
) {
if let Some(dt) = Utc.with_ymd_and_hms(y, m, d, 0, 0, 0).single() {
if dt <= max_valid_dt {
day_precision_dates.push(dt);
i += 3;
continue;
}
}
}
}
if i + 1 < tokens.len() {
if let Some(y) = parse_year_token(tokens[i + 1], max_year) {
if let Some(dt) = Utc.with_ymd_and_hms(y, m, 15, 0, 0, 0).single() {
if dt <= max_valid_dt {
month_precision_dates.push(dt);
i += 2;
continue;
}
}
}
}
} else if let Some(d) = parse_day_token(tokens[i]) {
if i + 2 < tokens.len() {
if let (Some(m), Some(y)) = (
parse_month_token(tokens[i + 1]),
parse_year_token(tokens[i + 2], max_year),
) {
if let Some(dt) = Utc.with_ymd_and_hms(y, m, d, 0, 0, 0).single() {
if dt <= max_valid_dt {
day_precision_dates.push(dt);
i += 3;
continue;
}
}
}
}
}
i += 1;
}
if !day_precision_dates.is_empty() {
day_precision_dates.into_iter().max()
} else {
month_precision_dates.into_iter().max()
}
}
#[cfg(test)]
mod stage2_tests {
use super::*;
use chrono::{Datelike, Utc};
#[test]
fn extract_chunk_inline_date_parses_iso_and_month_formats() {
assert!(
extract_chunk_inline_date("Anthropic’s latest model release and केप्लर टेलिस्कोप")
.is_none()
);
let current_year = Utc::now().year();
let past_year = current_year - 1;
let iso_chunk = format!("Release v1.20.0 shipped on {past_year}-02-19 with new features.");
let d1 = extract_chunk_inline_date(&iso_chunk).expect("should parse ISO date");
assert_eq!((d1.year(), d1.month(), d1.day()), (past_year, 2, 19));
let named_chunk = format!("Feb 19, {past_year} — Added sidebar workspace controls.");
let d2 = extract_chunk_inline_date(&named_chunk).expect("should parse Month DD, YYYY");
assert_eq!((d2.year(), d2.month(), d2.day()), (past_year, 2, 19));
let dmy_chunk = format!("Published 25 March {past_year} by the release team.");
let d3 = extract_chunk_inline_date(&dmy_chunk).expect("should parse DD Month YYYY");
assert_eq!((d3.year(), d3.month(), d3.day()), (past_year, 3, 25));
}
#[test]
fn older_changelog_chunk_on_recently_modified_page_gets_its_own_inline_date() {
let now = Utc::now();
let recent_page_modified = now - chrono::Duration::days(1);
let old_entry_dt = now - chrono::Duration::days(60);
let recent_entry_dt = now - chrono::Duration::days(2);
let old_iso = old_entry_dt.format("%Y-%m-%d").to_string();
let recent_iso = recent_entry_dt.format("%Y-%m-%d").to_string();
let rolling_changelog = SourceResult {
url: "https://clickup.com/changelog".to_string(),
title: "ClickUp Changelog".to_string(),
extracted_text: format!(
"{old_iso} — ClickUp release update: legacy sidebar polish and old bug fixes. {}\n\n\
{recent_iso} — ClickUp release update: brand new AI autopilot workflows and API v3. {}",
"Details about the older release update. ".repeat(15),
"Details about the newest release update. ".repeat(15)
),
char_count: 1400,
engine: "brave".to_string(),
published: Some(recent_page_modified),
language: Some("en".to_string()),
byline: None,
site_name: Some("ClickUp".to_string()),
confidence: 0.95,
extractor: "dom_smoothie",
};
let mut intel = crate::query_intel::analyze_query("ClickUp latest release update");
intel.is_time_sensitive = true;
intel.intent = crate::query_intel::QueryIntent::Temporal;
intel.semantic_category = crate::query_intel::SemanticCategory::ProductOrg;
intel.key_entities = vec!["ClickUp".to_string()];
let ranked = rank_with_options(
"ClickUp latest release update",
&[rolling_changelog],
2,
None,
Some(&intel),
&RankOptions::default(),
);
assert_eq!(ranked.len(), 2);
assert!(
ranked[0].extracted_text.contains(&recent_iso),
"newest changelog chunk should rank #1, got: {}",
ranked[0].extracted_text
);
assert!(
ranked[1].extracted_text.contains("[Entry Date:"),
"older chunk on modified page should carry [Entry Date:] provenance tag: {}",
ranked[1].extracted_text
);
}
#[test]
fn official_entity_domain_outranks_wikipedia_and_third_party_aggregators_dynamically() {
let now = Utc::now();
let mut intel = crate::query_intel::analyze_query("Google Antigravity latest update");
intel.is_time_sensitive = true;
intel.intent = crate::query_intel::QueryIntent::Temporal;
intel.semantic_category = crate::query_intel::SemanticCategory::ProductOrg;
intel.key_entities = vec!["Google Antigravity".to_string()];
let official_score = crate::llm::dynamic_authority_score(
"https://antigravity.google/changelog",
Some("Google Antigravity"),
"Google Antigravity Changelog",
Some(&intel),
crate::modes::Mode::Auto,
true,
);
let aggregator_score = crate::llm::dynamic_authority_score(
"https://releasebot.io/updates/google/antigravity",
Some("Releasebot"),
"Google Antigravity Release Notes",
Some(&intel),
crate::modes::Mode::Auto,
true,
);
let wiki_score = crate::llm::dynamic_authority_score(
"https://en.wikipedia.org/wiki/Google_Play",
Some("Wikipedia"),
"Google Play - Wikipedia",
Some(&intel),
crate::modes::Mode::Auto,
true,
);
assert!(
official_score >= 1.65,
"official entity domain should get primary boost: {official_score}"
);
assert!(
aggregator_score < 0.85,
"third-party aggregator should be demoted when official domain exists: {aggregator_score}"
);
assert!(
wiki_score <= 1.0,
"Wikipedia must stay secondary/demoted on live product queries: {wiki_score}"
);
assert!(official_score > aggregator_score * 2.0);
assert!(official_score > wiki_score * 1.6);
let mut stripe_intel =
crate::query_intel::analyze_query("Stripe webhook signature verification");
stripe_intel.key_entities = vec!["Stripe".to_string()];
let stripe_official = crate::llm::dynamic_authority_score(
"https://docs.stripe.com/webhooks/signatures",
Some("Stripe Docs"),
"Verify webhook signatures",
Some(&stripe_intel),
crate::modes::Mode::Auto,
true,
);
assert!(
stripe_official >= 1.65,
"docs.stripe.com should match entity 'Stripe': {stripe_official}"
);
let _ = now;
}
}