fetchium_core/rank/
temporal.rs1use crate::rank::fusion::QueryIntent;
18use crate::types::ResultItem;
19
20#[derive(Debug, Clone)]
22pub struct TemporalConfig {
23 pub default_half_life_days: f64,
25 pub freshness_boost: f64,
27 pub decay_floor: f64,
29}
30
31impl Default for TemporalConfig {
32 fn default() -> Self {
33 Self {
34 default_half_life_days: 90.0,
35 freshness_boost: 1.15,
36 decay_floor: 0.3,
37 }
38 }
39}
40
41fn half_life_for_intent(intent: &QueryIntent) -> f64 {
43 match intent {
44 QueryIntent::CurrentEvents => 7.0,
45 QueryIntent::Code => 120.0,
46 QueryIntent::Academic => 365.0,
47 QueryIntent::Data => 180.0,
48 QueryIntent::Factual => 365.0,
49 QueryIntent::HowTo => 730.0,
50 QueryIntent::Comparison => 180.0,
51 QueryIntent::Verification => 90.0,
52 QueryIntent::DeepAnalysis => 180.0,
53 QueryIntent::Opinion => 30.0,
54 QueryIntent::Informational => 365.0, QueryIntent::Casual => 180.0, }
57}
58
59pub fn apply_temporal_decay(
64 results: &mut [ResultItem],
65 intent: &QueryIntent,
66 config: &TemporalConfig,
67) {
68 let half_life = half_life_for_intent(intent);
69 let now = chrono::Utc::now();
70
71 for item in results.iter_mut() {
72 let Some(ref date_str) = item.published_date else {
73 continue;
75 };
76
77 let age_days = parse_age_days(date_str, &now);
78
79 let decay = compute_decay(age_days, half_life, config);
80
81 if let Some(score) = item.score.as_mut() {
82 *score *= decay;
83 }
84 }
85}
86
87fn compute_decay(age_days: f64, half_life: f64, config: &TemporalConfig) -> f64 {
92 if age_days <= 0.0 {
93 return config.freshness_boost;
95 }
96
97 let raw_decay = (2.0f64).powf(-age_days / half_life);
99
100 if age_days < 1.0 {
102 config.freshness_boost
103 } else {
104 raw_decay.max(config.decay_floor)
105 }
106}
107
108fn parse_age_days(date_str: &str, now: &chrono::DateTime<chrono::Utc>) -> f64 {
110 if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(date_str) {
112 return (*now - dt.with_timezone(&chrono::Utc)).num_hours() as f64 / 24.0;
113 }
114
115 if let Ok(dt) = chrono::NaiveDate::parse_from_str(date_str, "%Y-%m-%d") {
117 let dt_utc = dt.and_hms_opt(0, 0, 0).unwrap_or_default();
118 let dt_utc =
119 chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(dt_utc, chrono::Utc);
120 return (*now - dt_utc).num_hours() as f64 / 24.0;
121 }
122
123 if let Ok(dt) = chrono::NaiveDate::parse_from_str(date_str, "%B %d, %Y") {
125 let dt_utc = dt.and_hms_opt(0, 0, 0).unwrap_or_default();
126 let dt_utc =
127 chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(dt_utc, chrono::Utc);
128 return (*now - dt_utc).num_hours() as f64 / 24.0;
129 }
130
131 0.0
133}
134
135pub fn decay_factor(age_days: f64, intent: &QueryIntent) -> f64 {
137 let half_life = half_life_for_intent(intent);
138 compute_decay(age_days, half_life, &TemporalConfig::default())
139}
140
141#[cfg(test)]
142mod tests {
143 use super::*;
144 use crate::types::BackendId;
145
146 fn make_result(score: f64, date: Option<&str>) -> ResultItem {
147 ResultItem {
148 title: "Test".into(),
149 url: "https://test.com".into(),
150 snippet: "Test content".into(),
151 rank: 1,
152 backend: BackendId::DuckDuckGo,
153 score: Some(score),
154 published_date: date.map(|d| d.to_string()),
155 }
156 }
157
158 #[test]
159 fn fresh_content_boosted() {
160 let config = TemporalConfig::default();
161 let factor = compute_decay(0.5, 90.0, &config);
162 assert!(factor > 1.0, "Fresh content should be boosted: {factor}");
163 }
164
165 #[test]
166 fn old_content_decayed() {
167 let config = TemporalConfig::default();
168 let factor = compute_decay(365.0, 90.0, &config);
169 assert!(factor < 1.0, "Old content should be decayed: {factor}");
170 assert!(
171 factor >= config.decay_floor,
172 "Should not go below floor: {factor}"
173 );
174 }
175
176 #[test]
177 fn news_decays_fast() {
178 let news_30d = decay_factor(30.0, &QueryIntent::CurrentEvents);
179 let academic_30d = decay_factor(30.0, &QueryIntent::Academic);
180 assert!(
181 news_30d < academic_30d,
182 "30-day-old news should decay more than academic: news={news_30d} academic={academic_30d}"
183 );
184 }
185
186 #[test]
187 fn decay_floor_prevents_zero() {
188 let config = TemporalConfig {
189 decay_floor: 0.2,
190 ..Default::default()
191 };
192 let factor = compute_decay(10000.0, 7.0, &config);
193 assert!(factor >= 0.2, "Should not go below floor: {factor}");
194 }
195
196 #[test]
197 fn apply_decay_modifies_scores() {
198 let mut results = vec![
199 make_result(0.9, Some("2020-01-01")),
200 make_result(0.9, None), ];
202
203 apply_temporal_decay(
204 &mut results,
205 &QueryIntent::CurrentEvents,
206 &TemporalConfig::default(),
207 );
208
209 assert!(
211 results[0].score.unwrap() < results[1].score.unwrap(),
212 "Old news should score lower: dated={} undated={}",
213 results[0].score.unwrap(),
214 results[1].score.unwrap()
215 );
216 }
217
218 #[test]
219 fn half_life_varies_by_intent() {
220 let news_hl = half_life_for_intent(&QueryIntent::CurrentEvents);
221 let academic_hl = half_life_for_intent(&QueryIntent::Academic);
222 assert!(news_hl < academic_hl, "News half-life should be shorter");
223 }
224
225 #[test]
226 fn parse_iso_date() {
227 let now = chrono::Utc::now();
228 let yesterday = (now - chrono::Duration::hours(24))
229 .format("%Y-%m-%d")
230 .to_string();
231 let age = parse_age_days(&yesterday, &now);
232 assert!(
234 (0.5..=2.5).contains(&age),
235 "Yesterday should be ~1-2 days old: {age}"
236 );
237 }
238}