Skip to main content

vector_core/
emoji_usage.rs

1//! Per-account emoji "frecency" (most-used) tracker — SQL-backed.
2//!
3//! One row per distinct emoji in `emoji_usage` (PK `(kind,id)`); a reuse is an
4//! in-place UPSERT, so the table holds at most one row per emoji and never grows
5//! on repeat use. It's also pruned to the top `MAX_ENTRIES` by score.
6//!
7//! ## The log-space score (why writes and reads are both O(log n))
8//!
9//! Each use at time `t` adds `2^((t - EPOCH)/half_life)` points to the emoji's
10//! `score`. To rank "right now" you'd multiply every score by the same factor
11//! `2^(-(now - EPOCH)/half_life)` — but a uniform factor doesn't change order,
12//! so ranking is just `ORDER BY score DESC` off an index — no per-row decay math
13//! at read time. Newer uses are worth exponentially more, so old favourites fade
14//! automatically as tastes change.
15//!
16//! A soft cap (`score = MIN(score + inc, CAP·inc)`, enforced in the UPSERT) stops
17//! a one-off burst from pinning an emoji forever: a burst saturates at the cap,
18//! and a newer use — worth more per point — overtakes it within a half-life or
19//! two. `ranked()` converts the stored log-space score back to a normalised
20//! 0..CAP "effective" value for the UI.
21//!
22//! The row shape (kind, id, url, score, last_used) is also the cross-device sync
23//! payload: log-space scores from two devices are directly additive (sum =
24//! combined usage). Sync itself is future work.
25
26use serde::{Deserialize, Serialize};
27
28/// Compact, indexable kind discriminant.
29const KIND_UNICODE: i64 = 0;
30const KIND_CUSTOM: i64 = 1;
31
32/// Half-life: an emoji unused for this long loses half its standing.
33const HALF_LIFE_SECS: f64 = 21.0 * 24.0 * 3600.0; // 21 days
34/// Reference epoch (2025-01-01 UTC) keeps the log-space exponent small. It grows
35/// ~17/year and f64 overflows near 2^1024, so this is safe for ~50 years before
36/// a rebase would ever be needed; `bump` guards against a non-finite increment.
37const EPOCH_SECS: f64 = 1_735_689_600.0;
38/// Effective-score ceiling — a burst saturates here instead of running away.
39const SCORE_CAP: f64 = 25.0;
40/// Keep the table bounded; pruned to the top-N by score after writes.
41const MAX_ENTRIES: i64 = 256;
42
43/// A ranked usage row handed to the frontend. `score` is the normalised
44/// effective (decayed-to-now) value in `0..=SCORE_CAP`, not the raw log-space
45/// store — so the UI can treat it as a plain 0..25 weight.
46#[derive(Serialize, Deserialize, Clone, Debug)]
47pub struct EmojiUsageEntry {
48    pub kind: String,
49    pub id: String,
50    #[serde(skip_serializing_if = "Option::is_none", default)]
51    pub url: Option<String>,
52    pub score: f64,
53}
54
55/// One use to record (a sent message's distinct emojis, or a reaction).
56#[derive(Serialize, Deserialize, Clone, Debug)]
57pub struct EmojiUse {
58    pub kind: String,
59    pub id: String,
60    #[serde(default)]
61    pub url: Option<String>,
62}
63
64fn now_secs() -> f64 {
65    crate::clock::now_secs() as f64
66}
67
68fn kind_code(kind: &str) -> i64 {
69    if kind == "custom" { KIND_CUSTOM } else { KIND_UNICODE }
70}
71
72fn kind_label(code: i64) -> &'static str {
73    if code == KIND_CUSTOM { "custom" } else { "unicode" }
74}
75
76/// Log-space points one use contributes at `now`: `2^((now - EPOCH)/half_life)`.
77fn use_increment(now: f64) -> f64 {
78    ((now - EPOCH_SECS) / HALF_LIFE_SECS).exp2()
79}
80
81/// Factor that converts a stored log-space score to its effective value at `now`.
82fn decay_to_now(now: f64) -> f64 {
83    (-(now - EPOCH_SECS) / HALF_LIFE_SECS).exp2()
84}
85
86// ============================================================================
87// Writes
88// ============================================================================
89
90/// Record several uses in one transaction (one sent message → one DB write).
91pub fn bump_batch(uses: &[EmojiUse]) -> Result<(), String> {
92    if uses.is_empty() {
93        return Ok(());
94    }
95    let now = now_secs();
96    let inc = use_increment(now);
97    // Decades-out overflow guard: never write a non-finite score.
98    if !inc.is_finite() {
99        return Ok(());
100    }
101    let cap = SCORE_CAP * inc;
102    let now_i = now as i64;
103
104    let conn = crate::db::get_write_connection_guard_static()?;
105    let tx = conn
106        .unchecked_transaction()
107        .map_err(|e| format!("emoji_usage tx: {e}"))?;
108    {
109        let mut up = tx
110            .prepare_cached(
111                "INSERT INTO emoji_usage (kind, id, url, score, last_used)
112                 VALUES (?1, ?2, ?3, ?4, ?5)
113                 ON CONFLICT(kind, id) DO UPDATE SET
114                     score     = MIN(score + ?4, ?6),
115                     last_used = ?5,
116                     url       = COALESCE(?3, url)",
117            )
118            .map_err(|e| e.to_string())?;
119        for u in uses {
120            if u.id.is_empty() {
121                continue;
122            }
123            up.execute(rusqlite::params![kind_code(&u.kind), u.id, u.url, inc, now_i, cap])
124                .map_err(|e| format!("emoji_usage upsert: {e}"))?;
125        }
126        // Bound the table: drop everything outside the top-N by score. Cheap —
127        // the score index orders the subquery and a small table makes it a no-op
128        // until the cap is actually exceeded.
129        tx.execute(
130            "DELETE FROM emoji_usage
131             WHERE (kind, id) NOT IN (
132                 SELECT kind, id FROM emoji_usage ORDER BY score DESC LIMIT ?1
133             )",
134            rusqlite::params![MAX_ENTRIES],
135        )
136        .map_err(|e| format!("emoji_usage prune: {e}"))?;
137    }
138    tx.commit().map_err(|e| format!("emoji_usage commit: {e}"))?;
139    Ok(())
140}
141
142/// Record one use (reactions; single emoji).
143pub fn bump(kind: &str, id: &str, url: Option<&str>) -> Result<(), String> {
144    if id.is_empty() {
145        return Ok(());
146    }
147    bump_batch(&[EmojiUse {
148        kind: kind.to_string(),
149        id: id.to_string(),
150        url: url.map(|s| s.to_string()),
151    }])
152}
153
154// ============================================================================
155// Reads
156// ============================================================================
157
158/// Ranked usage, highest frecency first. `limit` caps the set (`None` = all).
159pub fn ranked(limit: Option<usize>) -> Vec<EmojiUsageEntry> {
160    let now = now_secs();
161    let decay = decay_to_now(now);
162    let lim: i64 = limit.map(|l| l as i64).unwrap_or(-1); // SQLite: LIMIT -1 = no cap
163
164    let conn = match crate::db::get_db_connection_guard_static() {
165        Ok(c) => c,
166        Err(_) => return Vec::new(),
167    };
168    let mut stmt = match conn
169        .prepare_cached("SELECT kind, id, url, score FROM emoji_usage ORDER BY score DESC LIMIT ?1")
170    {
171        Ok(s) => s,
172        Err(_) => return Vec::new(),
173    };
174    let rows = stmt.query_map(rusqlite::params![lim], |row| {
175        let kind_c: i64 = row.get(0)?;
176        let id: String = row.get(1)?;
177        let url: Option<String> = row.get(2)?;
178        let raw: f64 = row.get(3)?;
179        Ok(EmojiUsageEntry {
180            kind: kind_label(kind_c).to_string(),
181            id,
182            url,
183            score: raw * decay, // normalise log-space → effective 0..=CAP
184        })
185    });
186    match rows {
187        Ok(iter) => iter.filter_map(|r| r.ok()).collect(),
188        Err(_) => Vec::new(),
189    }
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195
196    const DAY: f64 = 24.0 * 3600.0;
197    const T0: f64 = EPOCH_SECS + 365.0 * DAY; // ~1 year past the epoch
198
199    /// Pure simulation of the stored log-space score for a sequence of use
200    /// times (applies the per-write soft cap), so the algorithm is testable
201    /// without a DB. Ranking compares these at a common `now`, and the uniform
202    /// decay factor cancels — so comparing raw scores IS the ranking.
203    fn simulate(times: &[f64]) -> f64 {
204        let mut score = 0.0f64;
205        for &t in times {
206            let inc = use_increment(t);
207            score = (score + inc).min(SCORE_CAP * inc);
208        }
209        score
210    }
211
212    #[test]
213    fn kind_code_label_round_trip() {
214        assert_eq!(kind_code("unicode"), KIND_UNICODE);
215        assert_eq!(kind_code("custom"), KIND_CUSTOM);
216        assert_eq!(kind_label(KIND_UNICODE), "unicode");
217        assert_eq!(kind_label(KIND_CUSTOM), "custom");
218        // Unknown kinds default to unicode rather than panicking.
219        assert_eq!(kind_code("???"), KIND_UNICODE);
220    }
221
222    #[test]
223    fn increment_is_finite_and_monotonic_this_era() {
224        let a = use_increment(T0);
225        let b = use_increment(T0 + 30.0 * DAY);
226        assert!(a.is_finite() && b.is_finite());
227        assert!(b > a, "a later use must be worth more in log-space");
228    }
229
230    #[test]
231    fn effective_of_one_use_is_one() {
232        // A single use, decayed back to its own time, is worth exactly 1.
233        let s = simulate(&[T0]);
234        let eff = s * decay_to_now(T0);
235        assert!((eff - 1.0).abs() < 1e-9, "got {eff}");
236    }
237
238    #[test]
239    fn burst_saturates_at_cap() {
240        let s = simulate(&[T0; 1000]);
241        let eff = s * decay_to_now(T0);
242        assert!((eff - SCORE_CAP).abs() < 1e-6, "burst effective {eff} should hit the cap");
243    }
244
245    #[test]
246    fn a_burst_does_not_pin_forever_new_favourite_overtakes() {
247        // The user's worry: paste one emoji 1000× — does everything else need
248        // 1000 uses to win? No. The burst caps; a newer steady habit overtakes.
249        let burst = simulate(&[T0; 1000]);
250        let mut new_times = Vec::new();
251        for d in 0..14 {
252            new_times.push(T0 + (30.0 + d as f64) * DAY);
253        }
254        let fresh = simulate(&new_times);
255        // Compared at a common instant the decay factor cancels, so raw score
256        // order IS the rank: the 14-use recent favourite beats the 1000× burst.
257        assert!(fresh > burst, "fresh {fresh} should outrank burst {burst}");
258    }
259
260    #[test]
261    fn recent_use_outranks_an_equal_older_one() {
262        let older = simulate(&[T0, T0 + DAY, T0 + 2.0 * DAY]);
263        let newer = simulate(&[T0 + 10.0 * DAY, T0 + 11.0 * DAY, T0 + 12.0 * DAY]);
264        assert!(newer > older, "same use count, more recent should rank higher");
265    }
266}