1use std::time::{Duration, SystemTime, UNIX_EPOCH};
43
44#[derive(Debug, Clone)]
50pub struct TemporalDecayConfig {
51 pub decay_rate: f32,
53
54 pub half_life_secs: f64,
56
57 pub semantic_weight: f32,
59
60 pub min_decay: f32,
62
63 pub apply_stage: DecayStage,
65}
66
67impl Default for TemporalDecayConfig {
68 fn default() -> Self {
69 Self {
70 decay_rate: 0.5,
71 half_life_secs: 3600.0 * 24.0, semantic_weight: 0.7,
73 min_decay: 0.01,
74 apply_stage: DecayStage::PostRetrieval,
75 }
76 }
77}
78
79impl TemporalDecayConfig {
80 pub fn short_term() -> Self {
82 Self {
83 decay_rate: 0.5,
84 half_life_secs: 3600.0, semantic_weight: 0.5,
86 min_decay: 0.01,
87 apply_stage: DecayStage::PostRetrieval,
88 }
89 }
90
91 pub fn long_term() -> Self {
93 Self {
94 decay_rate: 0.5,
95 half_life_secs: 3600.0 * 24.0 * 7.0, semantic_weight: 0.85,
97 min_decay: 0.05,
98 apply_stage: DecayStage::PostRetrieval,
99 }
100 }
101
102 pub fn working_memory() -> Self {
104 Self {
105 decay_rate: 0.5,
106 half_life_secs: 300.0, semantic_weight: 0.3,
108 min_decay: 0.0,
109 apply_stage: DecayStage::PostRetrieval,
110 }
111 }
112
113 pub fn with_half_life(half_life_secs: f64, semantic_weight: f32) -> Self {
115 Self {
116 half_life_secs,
117 semantic_weight,
118 ..Default::default()
119 }
120 }
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub enum DecayStage {
126 DuringSearch,
128 PostRetrieval,
130 Final,
132}
133
134#[derive(Debug, Clone)]
140pub struct TemporalScorer {
141 config: TemporalDecayConfig,
142 reference_time: f64,
144}
145
146impl TemporalScorer {
147 pub fn new(config: TemporalDecayConfig) -> Self {
149 let reference_time = SystemTime::now()
150 .duration_since(UNIX_EPOCH)
151 .unwrap_or_default()
152 .as_secs_f64();
153
154 Self {
155 config,
156 reference_time,
157 }
158 }
159
160 pub fn with_reference_time(config: TemporalDecayConfig, reference_time: f64) -> Self {
162 Self {
163 config,
164 reference_time,
165 }
166 }
167
168 pub fn default_scorer() -> Self {
170 Self::new(TemporalDecayConfig::default())
171 }
172
173 pub fn decay_score(&self, timestamp_secs: f64) -> f32 {
177 let delta_t = (self.reference_time - timestamp_secs).max(0.0);
178
179 let exponent = delta_t / self.config.half_life_secs;
181 let decay = self.config.decay_rate.powf(exponent as f32);
182
183 decay.max(self.config.min_decay)
184 }
185
186 pub fn decay_score_duration(&self, age: Duration) -> f32 {
188 let delta_t = age.as_secs_f64();
189 let exponent = delta_t / self.config.half_life_secs;
190 let decay = self.config.decay_rate.powf(exponent as f32);
191
192 decay.max(self.config.min_decay)
193 }
194
195 pub fn blend_scores(&self, semantic_score: f32, decay_score: f32) -> f32 {
199 let alpha = self.config.semantic_weight;
200 alpha * semantic_score + (1.0 - alpha) * decay_score
201 }
202
203 pub fn final_score(&self, semantic_score: f32, timestamp_secs: f64) -> f32 {
205 let decay = self.decay_score(timestamp_secs);
206 self.blend_scores(semantic_score, decay)
207 }
208
209 pub fn apply_decay<I>(&self, results: I) -> Vec<(String, f32)>
214 where
215 I: IntoIterator<Item = (String, f32, f64)>,
216 {
217 let mut scored: Vec<_> = results
218 .into_iter()
219 .map(|(id, semantic, timestamp)| {
220 let final_score = self.final_score(semantic, timestamp);
221 (id, final_score)
222 })
223 .collect();
224
225 scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
227
228 scored
229 }
230
231 pub fn apply_decay_typed<T, F>(
233 &self,
234 results: &mut [T],
235 get_score: impl Fn(&T) -> f32,
236 get_timestamp: impl Fn(&T) -> f64,
237 set_score: F,
238 ) where
239 F: Fn(&mut T, f32),
240 {
241 for result in results.iter_mut() {
242 let semantic = get_score(result);
243 let timestamp = get_timestamp(result);
244 let final_score = self.final_score(semantic, timestamp);
245 set_score(result, final_score);
246 }
247 }
248
249 pub fn half_life_display(&self) -> String {
251 let secs = self.config.half_life_secs;
252
253 if secs < 60.0 {
254 format!("{:.0} seconds", secs)
255 } else if secs < 3600.0 {
256 format!("{:.1} minutes", secs / 60.0)
257 } else if secs < 86400.0 {
258 format!("{:.1} hours", secs / 3600.0)
259 } else {
260 format!("{:.1} days", secs / 86400.0)
261 }
262 }
263}
264
265#[derive(Debug, Clone)]
271pub struct TemporallyDecayedResult {
272 pub id: String,
274
275 pub semantic_score: f32,
277
278 pub decay_factor: f32,
280
281 pub final_score: f32,
283
284 pub timestamp: f64,
286
287 pub age_secs: f64,
289}
290
291impl TemporallyDecayedResult {
292 pub fn new(id: String, semantic_score: f32, timestamp: f64, scorer: &TemporalScorer) -> Self {
294 let decay_factor = scorer.decay_score(timestamp);
295 let final_score = scorer.blend_scores(semantic_score, decay_factor);
296 let age_secs = scorer.reference_time - timestamp;
297
298 Self {
299 id,
300 semantic_score,
301 decay_factor,
302 final_score,
303 timestamp,
304 age_secs,
305 }
306 }
307
308 pub fn age_display(&self) -> String {
310 let age = self.age_secs;
311
312 if age < 60.0 {
313 format!("{:.0}s ago", age)
314 } else if age < 3600.0 {
315 format!("{:.0}m ago", age / 60.0)
316 } else if age < 86400.0 {
317 format!("{:.1}h ago", age / 3600.0)
318 } else {
319 format!("{:.1}d ago", age / 86400.0)
320 }
321 }
322}
323
324#[derive(Debug, Clone)]
330pub struct DecayCurve {
331 pub points: Vec<(f64, f32)>,
333
334 pub half_life: f64,
336
337 pub config: TemporalDecayConfig,
339}
340
341impl DecayCurve {
342 pub fn generate(config: &TemporalDecayConfig, max_age_secs: f64, num_points: usize) -> Self {
344 let scorer = TemporalScorer::with_reference_time(config.clone(), max_age_secs);
345
346 let mut points = Vec::with_capacity(num_points);
347 for i in 0..num_points {
348 let age = (i as f64) * max_age_secs / (num_points as f64);
349 let timestamp = max_age_secs - age;
350 let score = scorer.decay_score(timestamp);
351 points.push((age, score));
352 }
353
354 Self {
355 points,
356 half_life: config.half_life_secs,
357 config: config.clone(),
358 }
359 }
360
361 pub fn age_at_threshold(&self, threshold: f32) -> Option<f64> {
363 for (age, score) in &self.points {
364 if *score <= threshold {
365 return Some(*age);
366 }
367 }
368 None
369 }
370
371 pub fn ascii_chart(&self, width: usize, height: usize) -> String {
373 let mut chart = vec![vec![' '; width]; height];
374
375 for (age, score) in &self.points {
376 let x = ((age / self.points.last().unwrap().0) * (width - 1) as f64) as usize;
377 let y = ((1.0 - *score) * (height - 1) as f32) as usize;
378
379 if x < width && y < height {
380 chart[y][x] = '█';
381 }
382 }
383
384 for row in &mut chart {
386 row[0] = '│';
387 }
388 chart[height - 1] = vec!['─'; width];
389 chart[height - 1][0] = '└';
390
391 chart
392 .iter()
393 .map(|row| row.iter().collect::<String>())
394 .collect::<Vec<_>>()
395 .join("\n")
396 }
397}
398
399pub trait TemporalDecayExt {
405 fn with_temporal_decay(self, scorer: &TemporalScorer) -> Vec<TemporallyDecayedResult>;
407}
408
409impl<I> TemporalDecayExt for I
410where
411 I: IntoIterator<Item = (String, f32, f64)>,
412{
413 fn with_temporal_decay(self, scorer: &TemporalScorer) -> Vec<TemporallyDecayedResult> {
414 let mut results: Vec<_> = self
415 .into_iter()
416 .map(|(id, semantic_score, timestamp)| {
417 TemporallyDecayedResult::new(id, semantic_score, timestamp, scorer)
418 })
419 .collect();
420
421 results.sort_by(|a, b| {
423 b.final_score
424 .partial_cmp(&a.final_score)
425 .unwrap_or(std::cmp::Ordering::Equal)
426 });
427
428 results
429 }
430}
431
432pub fn quick_decay(age_secs: f64) -> f32 {
438 let scorer = TemporalScorer::new(TemporalDecayConfig::default());
439 scorer.decay_score_duration(Duration::from_secs_f64(age_secs))
440}
441
442pub fn quick_temporal_score(semantic_score: f32, age_secs: f64) -> f32 {
444 let scorer = TemporalScorer::new(TemporalDecayConfig::default());
445 let decay = scorer.decay_score_duration(Duration::from_secs_f64(age_secs));
446 scorer.blend_scores(semantic_score, decay)
447}
448
449pub fn apply_default_decay<I>(results: I) -> Vec<(String, f32)>
451where
452 I: IntoIterator<Item = (String, f32, f64)>,
453{
454 let scorer = TemporalScorer::new(TemporalDecayConfig::default());
455 scorer.apply_decay(results)
456}
457
458#[cfg(test)]
463mod tests {
464 use super::*;
465
466 #[test]
467 fn test_decay_at_half_life() {
468 let config = TemporalDecayConfig {
469 decay_rate: 0.5,
470 half_life_secs: 3600.0, semantic_weight: 0.5,
472 min_decay: 0.0,
473 apply_stage: DecayStage::PostRetrieval,
474 };
475
476 let scorer = TemporalScorer::with_reference_time(config, 3600.0);
477
478 let decay_now = scorer.decay_score(3600.0);
480 assert!((decay_now - 1.0).abs() < 0.01);
481
482 let decay_half = scorer.decay_score(0.0);
484 assert!((decay_half - 0.5).abs() < 0.01);
485 }
486
487 #[test]
488 fn test_decay_double_half_life() {
489 let config = TemporalDecayConfig {
490 decay_rate: 0.5,
491 half_life_secs: 3600.0,
492 semantic_weight: 0.5,
493 min_decay: 0.0,
494 apply_stage: DecayStage::PostRetrieval,
495 };
496
497 let scorer = TemporalScorer::with_reference_time(config, 7200.0);
498
499 let decay = scorer.decay_score(0.0);
501 assert!((decay - 0.25).abs() < 0.01);
502 }
503
504 #[test]
505 fn test_blend_scores() {
506 let config = TemporalDecayConfig {
507 semantic_weight: 0.7,
508 ..Default::default()
509 };
510
511 let scorer = TemporalScorer::new(config);
512
513 let final_score = scorer.blend_scores(0.8, 0.5);
516 assert!((final_score - 0.71).abs() < 0.01);
517 }
518
519 #[test]
520 fn test_min_decay_floor() {
521 let config = TemporalDecayConfig {
522 decay_rate: 0.5,
523 half_life_secs: 1.0, min_decay: 0.1,
525 semantic_weight: 0.5,
526 apply_stage: DecayStage::PostRetrieval,
527 };
528
529 let scorer = TemporalScorer::with_reference_time(config, 1000.0);
530
531 let decay = scorer.decay_score(0.0);
533 assert!((decay - 0.1).abs() < 0.01);
534 }
535
536 #[test]
537 fn test_apply_decay_reorders() {
538 let config = TemporalDecayConfig {
539 decay_rate: 0.5,
540 half_life_secs: 100.0,
541 semantic_weight: 0.5,
542 min_decay: 0.0,
543 apply_stage: DecayStage::PostRetrieval,
544 };
545
546 let scorer = TemporalScorer::with_reference_time(config, 200.0);
547
548 let results = vec![
550 ("old_high".to_string(), 0.9, 0.0), ("new_low".to_string(), 0.6, 190.0), ];
553
554 let decayed = scorer.apply_decay(results);
555
556 assert_eq!(decayed[0].0, "new_low");
558 }
559
560 #[test]
561 fn test_decay_curve_generation() {
562 let config = TemporalDecayConfig::default();
563 let curve = DecayCurve::generate(&config, 86400.0 * 7.0, 100);
564
565 assert_eq!(curve.points.len(), 100);
566
567 assert!(curve.points[0].1 > 0.9);
569
570 assert!(curve.points.last().unwrap().1 < curve.points[0].1);
572 }
573
574 #[test]
575 fn test_temporally_decayed_result() {
576 let config = TemporalDecayConfig::short_term();
577 let scorer = TemporalScorer::with_reference_time(config, 7200.0);
578
579 let result = TemporallyDecayedResult::new(
580 "doc1".to_string(),
581 0.85,
582 3600.0, &scorer,
584 );
585
586 assert_eq!(result.id, "doc1");
587 assert!((result.semantic_score - 0.85).abs() < 0.01);
588 assert!(result.decay_factor < 1.0);
589 assert!(result.age_secs > 0.0);
590 }
591
592 #[test]
593 fn test_half_life_display() {
594 let config = TemporalDecayConfig {
595 half_life_secs: 7200.0, ..Default::default()
597 };
598
599 let scorer = TemporalScorer::new(config);
600 let display = scorer.half_life_display();
601
602 assert!(display.contains("hours") || display.contains("2.0"));
603 }
604}