Skip to main content

oomtop_core/
ranking.rs

1//! Ranking (UX §5.4) and frecency (UX §5.1).
2//!
3//! ```text
4//! score = w_s · salience        # share of memory/GPU/CPU weighted by mode; + anomaly z-score of change rate
5//!       + w_a · affinity         # frecency of this entity for this user (cold-start prior when unknown)
6//!       + w_x · actionability    # reclaimable bytes / idle cost
7//!       + w_q · query_match      # when a query is active, dominates
8//!       − w_n · noise            # muted, "show less", system-noise priors
9//!       + novelty                # small, decaying boost for entities the user hasn't met yet
10//!       − diversity              # MMR-style penalty for repeats of the same cluster
11//! ```
12//!
13//! Defaults `w_s=1.0, w_a=0.6, w_x=0.5, w_q=3.0, w_n=1.0` ([`RankWeights`]). Modes re-weight salience
14//! features (Pressure boosts memory and idle cost, Throttle boosts CPU/GPU, Working boosts busy servers).
15//!
16//! **Stability** ([`RankState`]): a row moves only after it has beaten the row above it by `margin` for
17//! [`MOVE_AFTER_REFRESHES`] consecutive refreshes; the selected row keeps its index; a moved row carries a
18//! one-refresh `moved` marker (rendered as `›`, no animation frames). At a 2 s refresh a row can therefore
19//! climb at most once every 4 s, and flip-flopping scores never move anything.
20//!
21//! **Frecency**: `Σ w(event) · 0.5^(age / half_life)`, half-life 7 days by default ([`DEFAULT_HALF_LIFE_S`]).
22
23use crate::headline::format_amount;
24use crate::headroom::is_reclaim_candidate;
25use crate::history::History;
26use crate::model::{Group, GroupKind, Snapshot};
27use crate::modes::Mode;
28use crate::query::{eval, EntityView, Understanding};
29use crate::units::{format_duration, UnitSystem};
30use serde::{Deserialize, Serialize};
31use std::collections::{HashMap, HashSet};
32
33/// Default frecency half-life: 7 days (UX §5.1, configurable as `personalization.half_life_days`).
34pub const DEFAULT_HALF_LIFE_S: f64 = 7.0 * 86_400.0;
35/// Default MMR diversity penalty per earlier pick of the same cluster.
36pub const DEFAULT_DIVERSITY_LAMBDA: f64 = 0.15;
37/// Default score margin a row must beat the row above by before it may move.
38pub const DEFAULT_MOVE_MARGIN: f64 = 0.05;
39/// Refreshes required before a row may move up.
40pub const MOVE_AFTER_REFRESHES: u32 = 2;
41/// Maximum novelty boost for an entity the user has never interacted with.
42pub const NOVELTY_MAX: f64 = 0.15;
43/// Novelty halves every 30 minutes of the entity's age.
44pub const NOVELTY_HALF_LIFE_S: f64 = 1_800.0;
45/// Affinity given to pinned entities.
46pub const PINNED_AFFINITY: f64 = 1.0;
47/// Weight of the same-mode context affinity added to the plain affinity.
48pub const CONTEXT_AFFINITY_WEIGHT: f64 = 0.3;
49
50#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
51#[serde(default)]
52pub struct RankWeights {
53    pub salience: f64,
54    pub affinity: f64,
55    pub actionability: f64,
56    pub query: f64,
57    pub noise: f64,
58}
59
60impl Default for RankWeights {
61    fn default() -> Self {
62        RankWeights {
63            salience: 1.0,
64            affinity: 0.6,
65            actionability: 0.5,
66            query: 3.0,
67            noise: 1.0,
68        }
69    }
70}
71
72/// Features of one candidate, each roughly 0..1.
73#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
74#[serde(default)]
75pub struct Candidate {
76    pub id: String,
77    pub salience: f64,
78    pub affinity: f64,
79    pub actionability: f64,
80    pub query_match: f64,
81    pub noise: f64,
82    /// Decaying boost for new entities (exploration).
83    pub novelty: f64,
84    /// Diversity key (e.g. kind + label); items sharing a key are penalized after the first.
85    pub cluster: Option<String>,
86    /// Cold-start prior (machine profile), used in place of affinity for entities without history;
87    /// weighted like affinity.
88    pub prior: f64,
89}
90
91/// Per-feature contributions (for "why ranked here"). `noise` and `diversity` are ≤ 0.
92#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
93#[serde(default)]
94pub struct ScoreParts {
95    pub salience: f64,
96    pub affinity: f64,
97    pub actionability: f64,
98    pub query: f64,
99    pub noise: f64,
100    pub novelty: f64,
101    pub total: f64,
102    /// MMR penalty applied by [`rank`] (≤ 0).
103    pub diversity: f64,
104    /// Cold-start prior contribution (weighted by `w_a`).
105    pub prior: f64,
106}
107
108fn finite(x: f64) -> f64 {
109    if x.is_finite() {
110        x
111    } else {
112        0.0
113    }
114}
115
116/// Weighted contributions and their total (before diversity).
117pub fn score(c: &Candidate, w: &RankWeights) -> ScoreParts {
118    let p = ScoreParts {
119        salience: finite(w.salience * c.salience),
120        affinity: finite(w.affinity * c.affinity),
121        actionability: finite(w.actionability * c.actionability),
122        query: finite(w.query * c.query_match),
123        noise: finite(-w.noise * c.noise),
124        novelty: finite(c.novelty),
125        total: 0.0,
126        diversity: 0.0,
127        prior: finite(w.affinity * c.prior),
128    };
129    ScoreParts {
130        total: p.salience + p.affinity + p.actionability + p.query + p.noise + p.novelty + p.prior,
131        ..p
132    }
133}
134
135/// Frecency: `Σ w(event) · 0.5^(age / half_life)` (zoxide/atuin style). `events` = (age_s, weight).
136/// Future events (negative age) count at full weight; non-finite inputs are ignored.
137pub fn frecency(events: &[(f64, f64)], half_life_s: f64) -> f64 {
138    if half_life_s.is_nan() || half_life_s <= 0.0 || half_life_s.is_infinite() {
139        return 0.0;
140    }
141    events
142        .iter()
143        .filter(|(age, w)| age.is_finite() && w.is_finite())
144        .map(|(age, w)| w * 0.5f64.powf(age.max(0.0) / half_life_s))
145        .sum()
146}
147
148/// Maps a raw frecency score to 0..1 affinity (`1 − e^(−f/5)`; f = 5 → 0.63, f = 15 → 0.95).
149pub fn affinity_from_frecency(f: f64) -> f64 {
150    if !f.is_finite() {
151        return 0.0;
152    }
153    1.0 - (-f.max(0.0) / 5.0).exp()
154}
155
156/// Novelty boost for an entity of age `age_s` that the user has affinity `affinity` (0..1) with:
157/// `NOVELTY_MAX · 0.5^(age / 30 min) · (1 − affinity)`.
158pub fn novelty_boost(age_s: f64, affinity: f64) -> f64 {
159    if !age_s.is_finite() {
160        return 0.0;
161    }
162    NOVELTY_MAX * 0.5f64.powf(age_s.max(0.0) / NOVELTY_HALF_LIFE_S) * (1.0 - affinity.clamp(0.0, 1.0))
163}
164
165/// Anomaly of the latest change in a footprint series (0..1): z-score of the last delta against the earlier
166/// deltas, counting growth only. Needs ≥ 6 points; the noise floor is 1 % of the mean level or 1 MiB.
167pub fn anomaly_score(series: &[u64]) -> f64 {
168    if series.len() < 6 {
169        return 0.0;
170    }
171    let deltas: Vec<f64> = series.windows(2).map(|w| w[1] as f64 - w[0] as f64).collect();
172    let Some((last, earlier)) = deltas.split_last() else {
173        return 0.0;
174    };
175    let n = earlier.len() as f64;
176    let mean = earlier.iter().sum::<f64>() / n;
177    let var = earlier.iter().map(|d| (d - mean).powi(2)).sum::<f64>() / n;
178    let level = series.iter().map(|v| *v as f64).sum::<f64>() / series.len() as f64;
179    let floor = (level * 0.01).max(1024.0 * 1024.0);
180    let z = (last - mean) / var.sqrt().max(floor);
181    if *last <= 0.0 {
182        return 0.0;
183    }
184    ((z - 2.0) / 4.0).clamp(0.0, 1.0)
185}
186
187/// [`anomaly_score`] of a group's history series. `History::group_series` reports 0 for samples in which
188/// the group did not exist yet, so the leading zeros are not measurements: without dropping them every
189/// group that has just appeared would look like a spike from 0 (being new is the *novelty* feature's job).
190pub fn group_anomaly_score(series: &[u64]) -> f64 {
191    let first = series.iter().position(|v| *v > 0).unwrap_or(series.len());
192    anomaly_score(&series[first..])
193}
194
195/// Cold-start priors from the machine profile (UX §5.4, §6): model servers and agent CLIs start with a
196/// boost on a machine where they are detected; everything else uses salience only.
197#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
198#[serde(default)]
199pub struct ColdStartPriors {
200    pub model_server: f64,
201    pub agent: f64,
202}
203
204impl Default for ColdStartPriors {
205    fn default() -> Self {
206        ColdStartPriors {
207            model_server: 0.3,
208            agent: 0.25,
209        }
210    }
211}
212
213impl ColdStartPriors {
214    /// Priors for the roles detected in this snapshot (`None` when neither role is present).
215    pub fn detect(s: &Snapshot) -> Option<ColdStartPriors> {
216        let d = ColdStartPriors::default();
217        let models = !s.model_servers.is_empty() || s.groups.iter().any(|g| g.kind == GroupKind::ModelServer);
218        let agents = s.groups.iter().any(|g| g.kind == GroupKind::AgentSession);
219        (models || agents).then_some(ColdStartPriors {
220            model_server: if models { d.model_server } else { 0.0 },
221            agent: if agents { d.agent } else { 0.0 },
222        })
223    }
224
225    pub fn for_kind(&self, kind: GroupKind) -> f64 {
226        match kind {
227            GroupKind::ModelServer => self.model_server,
228            GroupKind::AgentSession => self.agent,
229            _ => 0.0,
230        }
231    }
232}
233
234/// Everything the ranker can use beyond the snapshot. All maps are keyed by entity fingerprint except
235/// `query` (keyed by group id, see [`query_scores`]).
236#[derive(Debug, Clone, Copy, Default)]
237pub struct RankContext<'a> {
238    pub mode: Mode,
239    /// Affinity 0..1 (use [`affinity_from_frecency`]).
240    pub affinity: Option<&'a HashMap<String, f64>>,
241    pub muted: Option<&'a HashSet<String>>,
242    /// "Show less like this" (`-`): half the noise of a mute.
243    pub dismissed: Option<&'a HashSet<String>>,
244    pub pinned: Option<&'a HashSet<String>>,
245    /// First time the profile saw each entity (ms); falls back to the root process start time.
246    pub first_seen_ms: Option<&'a HashMap<String, u64>>,
247    /// Ring buffer for the anomaly feature.
248    pub history: Option<&'a History>,
249    /// Query match 0..1 per group id.
250    pub query: Option<&'a HashMap<String, f64>>,
251    /// Cold-start priors; `None` = salience only for unknown entities.
252    pub priors: Option<ColdStartPriors>,
253    /// Context match (UX §5.1 context counters, §5.4 "+ context match: same mode"): affinity 0..1 of each
254    /// entity *in the current mode* (e.g. "opened during Working mode"), keyed by fingerprint. Adds up to
255    /// [`CONTEXT_AFFINITY_WEIGHT`] on top of the plain affinity (capped at 1).
256    pub mode_affinity: Option<&'a HashMap<String, f64>>,
257}
258
259fn mem_total(s: &Snapshot) -> f64 {
260    s.memory.total.value.unwrap_or(s.host.mem_total).max(1) as f64
261}
262
263fn mode_weights(mode: Mode) -> (f64, f64, f64) {
264    // (memory, gpu, cpu)
265    match mode {
266        Mode::Pressure => (2.0, 1.0, 0.3),
267        Mode::Throttle => (0.6, 1.2, 1.8),
268        Mode::Working => (1.0, 1.5, 1.0),
269        Mode::Leftovers | Mode::Calm => (1.0, 1.0, 0.7),
270    }
271}
272
273/// Salience of a group: memory share (weighted by mode), GPU share, CPU share (of the whole machine).
274/// Unavailable values contribute nothing (they are unknown, not zero, but ranking must still order them).
275pub fn group_salience(g: &Group, s: &Snapshot, mode: Mode) -> f64 {
276    let total = mem_total(s);
277    let mem = g.totals.footprint.value.unwrap_or(0) as f64 / total;
278    let gpu_total = s
279        .accelerators
280        .iter()
281        .filter_map(|a| a.gpu_budget.value.or(a.mem_total.value))
282        .max()
283        .map(|b| b as f64)
284        .unwrap_or(total)
285        .max(1.0);
286    let gpu = g.totals.gpu.value.unwrap_or(0) as f64 / gpu_total;
287    let cores = s.host.cores_logical.max(1) as f64;
288    let cpu = g.totals.cpu_pct.value.unwrap_or(0.0).max(0.0) / (100.0 * cores);
289    let (wm, wg, wc) = mode_weights(mode);
290    let mut sal = (wm * mem + wg * gpu + wc * cpu) * 2.0;
291    if mode == Mode::Working
292        && s.model_servers
293            .iter()
294            .any(|m| m.group_id.as_deref() == Some(g.id.as_str()) && m.busy.value == Some(true))
295    {
296        sal += 0.5;
297    }
298    finite(sal).min(1.5)
299}
300
301/// Actionability: reclaimable bytes relative to RAM (idle cost), boosted in Pressure/Leftovers mode.
302pub fn group_actionability(g: &Group, s: &Snapshot, mode: Mode) -> f64 {
303    if !is_reclaim_candidate(g) {
304        return 0.0;
305    }
306    let gain = g.reclaim_gain.value.unwrap_or(0) as f64 / mem_total(s);
307    let boost = if matches!(mode, Mode::Pressure | Mode::Leftovers) {
308        2.0
309    } else {
310        1.0
311    };
312    finite(gain * 4.0 * boost).min(1.0)
313}
314
315/// System-noise prior: system groups and oomtop itself sink a little.
316pub fn group_noise(g: &Group) -> f64 {
317    let mut n = 0.0;
318    if g.kind == GroupKind::System {
319        n += 0.3;
320    }
321    if g.is_self {
322        n += 0.5;
323    }
324    n
325}
326
327/// Builds candidates for all groups (affinity 0..1 and mutes from the caller's profile maps, keyed by
328/// fingerprint). No history, query, novelty-by-profile or priors: see [`group_candidates_with`].
329pub fn group_candidates(
330    s: &Snapshot,
331    mode: Mode,
332    affinity: &HashMap<String, f64>,
333    muted: &HashSet<String>,
334) -> Vec<Candidate> {
335    group_candidates_with(
336        s,
337        &RankContext {
338            mode,
339            affinity: Some(affinity),
340            muted: Some(muted),
341            ..Default::default()
342        },
343    )
344}
345
346/// Diversity cluster of a group: same kind and label (e.g. four "Claude Code" sessions).
347pub fn group_cluster(g: &Group) -> String {
348    format!("{}:{}", g.kind.alias(), g.label.to_lowercase())
349}
350
351/// Builds candidates for all groups with the full context (UX §5.4).
352pub fn group_candidates_with(s: &Snapshot, ctx: &RankContext<'_>) -> Vec<Candidate> {
353    s.groups
354        .iter()
355        .map(|g| {
356            let fp = g.fingerprint.as_str();
357            let has_fp = !fp.is_empty();
358            let pinned = has_fp && ctx.pinned.map(|p| p.contains(fp)).unwrap_or(false);
359            let get = |m: Option<&HashMap<String, f64>>| {
360                if has_fp {
361                    m.and_then(|a| a.get(fp)).copied().map(finite)
362                } else {
363                    None
364                }
365            };
366            let in_mode = get(ctx.mode_affinity);
367            // Any learned signal (overall or in this mode) replaces the cold-start prior.
368            let learned = get(ctx.affinity).or(in_mode.map(|_| 0.0));
369            let affinity = if pinned {
370                PINNED_AFFINITY
371            } else {
372                (learned.unwrap_or(0.0).clamp(0.0, 1.0)
373                    + CONTEXT_AFFINITY_WEIGHT * in_mode.unwrap_or(0.0).clamp(0.0, 1.0))
374                .min(1.0)
375            };
376            let prior = match (learned, pinned, ctx.priors) {
377                (None, false, Some(p)) => p.for_kind(g.kind),
378                _ => 0.0,
379            };
380            let mut salience = group_salience(g, s, ctx.mode);
381            if let Some(h) = ctx.history {
382                salience = (salience + 0.5 * group_anomaly_score(&h.group_series(&g.id))).min(1.5);
383            }
384            let muted = has_fp && ctx.muted.map(|m| m.contains(fp)).unwrap_or(false);
385            let dismissed = has_fp && ctx.dismissed.map(|d| d.contains(fp)).unwrap_or(false);
386            let noise = group_noise(g) + if muted { 1.0 } else { 0.0 } + if dismissed { 0.5 } else { 0.0 };
387            let first_seen = ctx
388                .first_seen_ms
389                .and_then(|m| m.get(fp))
390                .copied()
391                .or_else(|| g.root.map(|r| r.start_time).filter(|t| *t > 0));
392            let novelty = match first_seen {
393                Some(t) if !muted && s.taken_at_ms > 0 => {
394                    novelty_boost(s.taken_at_ms.saturating_sub(t) as f64 / 1000.0, affinity)
395                }
396                _ => 0.0,
397            };
398            Candidate {
399                id: g.id.clone(),
400                salience,
401                affinity,
402                actionability: group_actionability(g, s, ctx.mode),
403                query_match: ctx.query.and_then(|q| q.get(&g.id)).copied().unwrap_or(0.0),
404                noise,
405                novelty,
406                cluster: Some(group_cluster(g)),
407                prior,
408            }
409        })
410        .collect()
411}
412
413/// Query match per group id (0..1) for an understood query: 1.0 when the filter matches, plus linked
414/// targets scaled relative to the best link (a `pid:N` target credits the group containing that pid).
415pub fn query_scores(u: &Understanding, s: &Snapshot) -> HashMap<String, f64> {
416    let mut out: HashMap<String, f64> = HashMap::new();
417    if let Some(f) = &u.filter {
418        for g in &s.groups {
419            if eval(f, &EntityView::from_group(g, s)) {
420                out.insert(g.id.clone(), 1.0);
421            }
422        }
423    }
424    let best = u.targets.first().map(|t| t.1).filter(|b| *b > 0.0);
425    if let Some(best) = best {
426        for (id, sc) in &u.targets {
427            let gid = if let Some(pid) = id.strip_prefix("pid:").and_then(|p| p.parse::<u32>().ok()) {
428                s.processes
429                    .iter()
430                    .find(|p| p.id.pid == pid)
431                    .and_then(|p| s.group_of(p.id))
432                    .map(|g| g.id.clone())
433            } else {
434                s.group(id).map(|g| g.id.clone())
435            };
436            if let Some(gid) = gid {
437                let v = (sc / best).clamp(0.0, 1.0);
438                // Groups sharing the entity fingerprint (e.g. four Claude Code sessions) are one entity.
439                let fp = s.group(&gid).map(|g| g.fingerprint.clone()).unwrap_or_default();
440                for g in &s.groups {
441                    if g.id == gid || (!fp.is_empty() && g.fingerprint == fp) {
442                        let e = out.entry(g.id.clone()).or_insert(0.0);
443                        *e = e.max(v);
444                    }
445                }
446            }
447        }
448    }
449    out
450}
451
452/// Scores candidates and orders them greedily with an MMR-style diversity penalty: each pick of a cluster
453/// costs later members of that cluster `λ` more (`λ = diversity_lambda`, 0 disables). Ties by id.
454pub fn rank(cands: &[Candidate], w: &RankWeights, diversity_lambda: f64) -> Vec<(String, ScoreParts)> {
455    let lambda = finite(diversity_lambda).max(0.0);
456    // Bucket by cluster (candidates without a cluster are singletons), each bucket sorted worst-first so
457    // `pop()`/`last()` is its best remaining member.
458    type Scored = (String, ScoreParts);
459    let mut buckets: Vec<Vec<Scored>> = Vec::new();
460    let mut index: HashMap<String, usize> = HashMap::new();
461    for c in cands {
462        let parts = score(c, w);
463        match &c.cluster {
464            Some(k) => {
465                let i = *index.entry(k.clone()).or_insert_with(|| {
466                    buckets.push(Vec::new());
467                    buckets.len() - 1
468                });
469                buckets[i].push((c.id.clone(), parts));
470            }
471            None => buckets.push(vec![(c.id.clone(), parts)]),
472        }
473    }
474    let cmp = |a: &Scored, b: &Scored| {
475        b.1.total
476            .partial_cmp(&a.1.total)
477            .unwrap_or(std::cmp::Ordering::Equal)
478            .then(a.0.cmp(&b.0))
479    };
480    for v in &mut buckets {
481        v.sort_by(cmp);
482        v.reverse();
483    }
484    let mut picked: Vec<u32> = vec![0; buckets.len()];
485    let mut out = Vec::with_capacity(cands.len());
486    loop {
487        let mut best: Option<(usize, f64, &str)> = None;
488        for (bi, v) in buckets.iter().enumerate() {
489            if let Some((id, p)) = v.last() {
490                let eff = p.total - lambda * picked[bi] as f64;
491                let better = match best {
492                    None => true,
493                    Some((_, oeff, oid)) => eff > oeff || (eff == oeff && id.as_str() < oid),
494                };
495                if better {
496                    best = Some((bi, eff, id.as_str()));
497                }
498            }
499        }
500        let Some((bi, _, _)) = best else { break };
501        let Some((id, mut p)) = buckets[bi].pop() else {
502            break;
503        };
504        p.diversity = -lambda * picked[bi] as f64;
505        p.total += p.diversity;
506        picked[bi] += 1;
507        out.push((id, p));
508    }
509    out
510}
511
512/// One row as served, with a one-refresh movement marker.
513#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
514pub struct RankedRow {
515    pub id: String,
516    pub score: f64,
517    /// Moved up this refresh (render `›` for one refresh).
518    pub moved: bool,
519}
520
521/// Stability state carried between refreshes.
522#[derive(Debug, Clone, Default, PartialEq)]
523pub struct RankState {
524    order: Vec<String>,
525    pending: HashMap<String, u32>,
526    /// Rows that appeared on the last refresh.
527    new_ids: HashSet<String>,
528}
529
530fn sane(x: f64) -> f64 {
531    if x.is_nan() {
532        f64::MIN
533    } else {
534        x
535    }
536}
537
538impl RankState {
539    pub fn new() -> Self {
540        Self::default()
541    }
542
543    /// The order served last refresh.
544    pub fn order(&self) -> &[String] {
545        &self.order
546    }
547
548    /// Rows that appeared on the last refresh (not counting the very first one).
549    pub fn new_ids(&self) -> &HashSet<String> {
550        &self.new_ids
551    }
552
553    /// Forgets the order (next [`apply`](Self::apply) sorts from scratch), e.g. after a view change.
554    pub fn reset(&mut self) {
555        self.order.clear();
556        self.pending.clear();
557        self.new_ids.clear();
558    }
559
560    /// Applies hysteresis to this refresh's scores:
561    /// - first call: plain score order (ties by id);
562    /// - rows that disappeared are dropped; new rows are inserted at their score position (see
563    ///   [`new_ids`](Self::new_ids));
564    /// - a row climbs only after beating the row directly above it by `margin` for
565    ///   [`MOVE_AFTER_REFRESHES`] consecutive refreshes; it then jumps above every row it beats by `margin`
566    ///   (not past a row that moved this refresh), and its counter restarts;
567    /// - `selected` keeps its index; rows arrange around it.
568    pub fn apply(&mut self, scored: &[(String, f64)], selected: Option<&str>, margin: f64) -> Vec<RankedRow> {
569        let margin = if margin.is_finite() { margin.max(0.0) } else { 0.0 };
570        let mut scores: HashMap<&str, f64> = HashMap::with_capacity(scored.len());
571        let mut ids: Vec<&str> = Vec::with_capacity(scored.len());
572        for (id, s) in scored {
573            if !scores.contains_key(id.as_str()) {
574                scores.insert(id.as_str(), sane(*s));
575                ids.push(id.as_str());
576            }
577        }
578        let sc = |id: &str| scores.get(id).copied().unwrap_or(f64::MIN);
579        let by_score = |a: &&str, b: &&str| {
580            sc(b)
581                .partial_cmp(&sc(a))
582                .unwrap_or(std::cmp::Ordering::Equal)
583                .then(a.cmp(b))
584        };
585        let prev: Vec<String> = self
586            .order
587            .iter()
588            .filter(|id| scores.contains_key(id.as_str()))
589            .cloned()
590            .collect();
591        if prev.is_empty() {
592            let mut order = ids.clone();
593            order.sort_by(by_score);
594            self.pending.clear();
595            self.new_ids.clear();
596            self.order = order.iter().map(|s| s.to_string()).collect();
597            return order
598                .into_iter()
599                .map(|id| RankedRow {
600                    id: id.to_string(),
601                    score: sc(id),
602                    moved: false,
603                })
604                .collect();
605        }
606        let prev_set: HashSet<&str> = prev.iter().map(String::as_str).collect();
607        let sel_idx = selected.and_then(|s| prev.iter().position(|x| x == s));
608        let sel_id = sel_idx.map(|i| prev[i].clone());
609        let mut work: Vec<String> = prev
610            .iter()
611            .filter(|x| Some(*x) != sel_id.as_ref())
612            .cloned()
613            .collect();
614        // New rows at their score position.
615        let mut new_ids: Vec<&str> = ids.iter().copied().filter(|id| !prev_set.contains(id)).collect();
616        new_ids.sort_by(by_score);
617        let new_set: HashSet<&str> = new_ids.iter().copied().collect();
618        for id in &new_ids {
619            let s = sc(id);
620            let pos = work.iter().position(|w| sc(w) < s).unwrap_or(work.len());
621            work.insert(pos, id.to_string());
622        }
623        // Streaks: consecutive refreshes beating the row directly above by the margin.
624        for i in 0..work.len() {
625            let id = &work[i];
626            if new_set.contains(id.as_str()) {
627                self.pending.remove(id);
628                continue;
629            }
630            let beats = i > 0 && sc(id) > sc(&work[i - 1]) + margin;
631            if beats {
632                *self.pending.entry(id.clone()).or_insert(0) += 1;
633            } else {
634                self.pending.remove(id);
635            }
636        }
637        // Moves, top to bottom.
638        let mut moved: HashSet<String> = HashSet::new();
639        let mut i = 1;
640        while i < work.len() {
641            let ready = self
642                .pending
643                .get(&work[i])
644                .map(|n| *n >= MOVE_AFTER_REFRESHES)
645                .unwrap_or(false);
646            if ready {
647                let s = sc(&work[i]);
648                let mut j = i;
649                while j > 0 && s > sc(&work[j - 1]) + margin && !moved.contains(&work[j - 1]) {
650                    j -= 1;
651                }
652                if j < i {
653                    let r = work.remove(i);
654                    self.pending.remove(&r);
655                    moved.insert(r.clone());
656                    work.insert(j, r);
657                }
658            }
659            i += 1;
660        }
661        if let (Some(idx), Some(id)) = (sel_idx, sel_id) {
662            self.pending.remove(&id);
663            let idx = idx.min(work.len());
664            work.insert(idx, id);
665        }
666        self.pending.retain(|id, _| scores.contains_key(id.as_str()));
667        self.new_ids = new_set.iter().map(|s| s.to_string()).collect();
668        self.order = work;
669        self.order
670            .iter()
671            .map(|id| RankedRow {
672                id: id.clone(),
673                score: sc(id),
674                moved: moved.contains(id),
675            })
676            .collect()
677    }
678}
679
680/// English ordinal: 1st, 2nd, 3rd, 4th, 11th, 12th, 13th, 21st, …
681pub fn ordinal(n: usize) -> String {
682    let suffix = match (n % 10, n % 100) {
683        (_, 11..=13) => "th",
684        (1, _) => "st",
685        (2, _) => "nd",
686        (3, _) => "rd",
687        _ => "th",
688    };
689    format!("{n}{suffix}")
690}
691
692/// Facts that turn score parts into plain words ("holds 2.8 GB", "you opened it 9× this week").
693#[derive(Debug, Clone, PartialEq, Default)]
694pub struct RankFacts {
695    pub footprint: Option<u64>,
696    pub gpu: Option<u64>,
697    pub cpu_pct: Option<f64>,
698    pub process_count: u32,
699    /// Selections in the last 7 days (from the profile).
700    pub opens_this_week: Option<u32>,
701    /// Selections while the current mode was active (context counter), e.g. (Pressure, 4).
702    pub opens_in_mode: Option<(Mode, u32)>,
703    pub reclaim_gain: Option<u64>,
704    pub idle_for_s: Option<u64>,
705    pub kind: GroupKind,
706    pub pinned: bool,
707    pub muted: bool,
708    pub dismissed: bool,
709    /// The active query text, when any.
710    pub query: Option<String>,
711    pub units: UnitSystem,
712}
713
714impl RankFacts {
715    pub fn from_group(g: &Group, opens_this_week: Option<u32>) -> Self {
716        RankFacts {
717            footprint: g.totals.footprint.value,
718            gpu: g.totals.gpu.value,
719            cpu_pct: g.totals.cpu_pct.value,
720            process_count: g.totals.process_count.max(g.members.len() as u32),
721            opens_this_week,
722            reclaim_gain: if is_reclaim_candidate(g) {
723                g.reclaim_gain.value
724            } else {
725                None
726            },
727            idle_for_s: if g.idle { g.idle_for_s } else { None },
728            kind: g.kind,
729            ..Default::default()
730        }
731    }
732}
733
734const EPS: f64 = 0.01;
735
736fn contributions(parts: &ScoreParts) -> Vec<(&'static str, f64)> {
737    let mut items: Vec<(&'static str, f64)> = vec![
738        ("query", parts.query),
739        ("salience", parts.salience),
740        ("affinity", parts.affinity),
741        ("prior", parts.prior),
742        ("actionability", parts.actionability),
743        ("novelty", parts.novelty),
744        ("noise", parts.noise),
745        ("diversity", parts.diversity),
746    ];
747    items.retain(|(_, v)| v.abs() > EPS);
748    // Stable sort: equal magnitudes keep the declared order.
749    items.sort_by(|a, b| {
750        b.1.abs()
751            .partial_cmp(&a.1.abs())
752            .unwrap_or(std::cmp::Ordering::Equal)
753    });
754    items
755}
756
757fn phrase(key: &str, f: Option<&RankFacts>) -> String {
758    let units = f.map(|f| f.units).unwrap_or_default();
759    let words = match (key, f) {
760        ("salience", Some(f)) => match (f.footprint, f.gpu, f.cpu_pct) {
761            (_, Some(g), _) if g > 0 && Some(g) >= f.footprint => {
762                format!("holds {} GPU memory", format_amount(g, units))
763            }
764            (Some(b), _, _) if b > 0 => format!("holds {}", format_amount(b, units)),
765            (_, _, Some(c)) if c >= 1.0 => format!("uses {c:.0}% CPU"),
766            _ => "large share of the machine".into(),
767        },
768        ("salience", None) => "large share of the machine".into(),
769        ("affinity", Some(f)) if f.pinned => "pinned by you".into(),
770        ("affinity", Some(f)) => {
771            let week = f.opens_this_week.filter(|n| *n > 0);
772            let ctx = f.opens_in_mode.filter(|(_, n)| *n > 0);
773            match (week, ctx) {
774                (Some(n), Some((m, k))) => {
775                    format!("you opened it {n}× this week, {k}× in {} mode", m.as_str())
776                }
777                (Some(n), None) => format!("you opened it {n}× this week"),
778                (None, Some((m, k))) => format!("you opened it {k}× in {} mode", m.as_str()),
779                (None, None) => "you use it often".into(),
780            }
781        }
782        ("affinity", None) => "you use it often".into(),
783        ("prior", Some(f)) => match f.kind {
784            GroupKind::ModelServer => "model servers start boosted on this machine".into(),
785            GroupKind::AgentSession => "agent sessions start boosted on this machine".into(),
786            _ => "machine-profile prior".into(),
787        },
788        ("prior", None) => "machine-profile prior".into(),
789        ("actionability", Some(f)) => match (f.idle_for_s, f.reclaim_gain) {
790            (Some(i), Some(g)) => format!(
791                "idle {}, could free {}",
792                format_duration(i),
793                format_amount(g, units)
794            ),
795            (None, Some(g)) => format!("could free {}", format_amount(g, units)),
796            _ => "reclaimable".into(),
797        },
798        ("actionability", None) => "reclaimable".into(),
799        ("query", Some(f)) => match &f.query {
800            Some(q) if !q.is_empty() => format!("matches \"{q}\""),
801            _ => "matches your query".into(),
802        },
803        ("query", None) => "matches your query".into(),
804        ("novelty", _) => "recently started".into(),
805        ("noise", Some(f)) if f.muted => "muted".into(),
806        ("noise", Some(f)) if f.dismissed => "you asked to see less of it".into(),
807        ("noise", Some(f)) if f.kind == GroupKind::System => "system process".into(),
808        ("noise", _) => "lowered as noise".into(),
809        ("diversity", _) => "similar to a row above".into(),
810        _ => key.to_string(),
811    };
812    format!("{words} ({key})")
813}
814
815fn explain_impl(position: usize, parts: &ScoreParts, facts: Option<&RankFacts>) -> String {
816    let mut body: Vec<String> = contributions(parts)
817        .iter()
818        .take(3)
819        .map(|(k, _)| phrase(k, facts))
820        .collect();
821    if let Some(f) = facts {
822        if f.process_count > 1 {
823            body.push(format!("{} processes grouped", f.process_count));
824        }
825    }
826    if body.is_empty() {
827        body.push("no strong signal (default order)".into());
828    }
829    format!("{}: {}.", ordinal(position.max(1)), body.join(" · "))
830}
831
832/// "Why ranked here" from score parts alone (top 3 contributions in plain words), e.g.
833/// `"3rd: large share of the machine (salience) · you use it often (affinity)."`.
834pub fn explain_rank(position: usize, parts: &ScoreParts) -> String {
835    explain_impl(position, parts, None)
836}
837
838/// "Why ranked here" with facts, e.g.
839/// `"3rd: holds 2.8 GB (salience) · you opened it 9× this week (affinity) · 14 processes grouped."`.
840pub fn explain_rank_for(position: usize, parts: &ScoreParts, facts: &RankFacts) -> String {
841    explain_impl(position, parts, Some(facts))
842}
843
844#[cfg(test)]
845mod tests {
846    use super::*;
847    use crate::model::{Measured, ProcId};
848    use crate::units::GIB;
849
850    #[test]
851    fn frecency_halves() {
852        let f = frecency(&[(0.0, 1.0), (7.0 * 86400.0, 1.0)], DEFAULT_HALF_LIFE_S);
853        assert!((f - 1.5).abs() < 1e-9);
854        assert_eq!(frecency(&[(1.0, 1.0)], 0.0), 0.0);
855        assert_eq!(frecency(&[(f64::NAN, 1.0), (0.0, 2.0)], 10.0), 2.0);
856        assert!((affinity_from_frecency(5.0) - 0.632).abs() < 1e-3);
857        assert_eq!(affinity_from_frecency(-3.0), 0.0);
858    }
859
860    #[test]
861    fn stability() {
862        let mut st = RankState::new();
863        let r = st.apply(&[("a".into(), 3.0), ("b".into(), 2.0)], None, 0.1);
864        assert_eq!(r.iter().map(|r| r.id.as_str()).collect::<Vec<_>>(), ["a", "b"]);
865        // b beats a: needs 2 refreshes.
866        let s2 = [("a".to_string(), 1.0), ("b".to_string(), 2.0)];
867        let r = st.apply(&s2, None, 0.1);
868        assert_eq!(r[0].id, "a");
869        let r = st.apply(&s2, None, 0.1);
870        assert_eq!(r[0].id, "b");
871        assert!(r[0].moved);
872        let r = st.apply(&s2, None, 0.1);
873        assert!(!r[0].moved, "marker lasts one refresh");
874        // Selected keeps its index.
875        let s3 = [("a".to_string(), 5.0), ("b".to_string(), 2.0)];
876        st.apply(&s3, Some("b"), 0.1);
877        let r = st.apply(&s3, Some("b"), 0.1);
878        assert_eq!(r[0].id, "b");
879        let r = st.apply(&s3, Some("a"), 0.1);
880        assert_eq!(r[1].id, "a", "selected a stays at index 1");
881        let r = st.apply(&s3, None, 0.1);
882        assert_eq!(r[0].id, "b", "streak restarted");
883        let r = st.apply(&s3, None, 0.1);
884        assert_eq!(r[0].id, "a");
885    }
886
887    #[test]
888    fn new_rows_insert_by_score_and_climbers_jump() {
889        let mut st = RankState::new();
890        st.apply(
891            &[("a".into(), 5.0), ("b".into(), 4.0), ("c".into(), 3.0)],
892            None,
893            0.1,
894        );
895        let r = st.apply(
896            &[
897                ("a".into(), 5.0),
898                ("b".into(), 4.0),
899                ("c".into(), 3.0),
900                ("n".into(), 4.5),
901            ],
902            None,
903            0.1,
904        );
905        assert_eq!(
906            r.iter().map(|r| r.id.as_str()).collect::<Vec<_>>(),
907            ["a", "n", "b", "c"]
908        );
909        assert!(st.new_ids().contains("n"));
910        // c jumps to the top after 2 refreshes.
911        let s = [
912            ("a".into(), 5.0),
913            ("b".into(), 4.0),
914            ("c".into(), 9.0),
915            ("n".into(), 4.5),
916        ];
917        st.apply(&s, None, 0.1);
918        let r = st.apply(&s, None, 0.1);
919        assert_eq!(r[0].id, "c");
920        assert!(r[0].moved);
921        // Removal.
922        let r = st.apply(&[("a".into(), 5.0), ("n".into(), 4.5)], None, 0.1);
923        assert_eq!(r.len(), 2);
924    }
925
926    #[test]
927    fn diversity_penalizes_repeats() {
928        let c = |id: &str, s: f64, cl: &str| Candidate {
929            id: id.into(),
930            salience: s,
931            cluster: Some(cl.into()),
932            ..Default::default()
933        };
934        let r = rank(
935            &[
936                c("x1", 1.0, "x"),
937                c("x2", 0.95, "x"),
938                c("y", 0.9, "y"),
939                c("x3", 0.94, "x"),
940            ],
941            &RankWeights::default(),
942            0.2,
943        );
944        assert_eq!(
945            r.iter().map(|r| r.0.as_str()).collect::<Vec<_>>(),
946            ["x1", "y", "x2", "x3"]
947        );
948        assert!((r[2].1.diversity + 0.2).abs() < 1e-9);
949        assert!((r[3].1.diversity + 0.4).abs() < 1e-9);
950        assert_eq!(
951            explain_rank(3, &r[2].1),
952            "3rd: large share of the machine (salience) · similar to a row above (diversity)."
953        );
954        // λ = 0: plain score order.
955        let r = rank(
956            &[c("x1", 1.0, "x"), c("x2", 0.95, "x"), c("y", 0.9, "y")],
957            &RankWeights::default(),
958            0.0,
959        );
960        assert_eq!(
961            r.iter().map(|r| r.0.as_str()).collect::<Vec<_>>(),
962            ["x1", "x2", "y"]
963        );
964    }
965
966    #[test]
967    fn novelty_and_priors() {
968        assert!((novelty_boost(0.0, 0.0) - NOVELTY_MAX).abs() < 1e-12);
969        assert!((novelty_boost(NOVELTY_HALF_LIFE_S, 0.0) - NOVELTY_MAX / 2.0).abs() < 1e-12);
970        assert_eq!(novelty_boost(0.0, 1.0), 0.0);
971        let mut s = Snapshot {
972            taken_at_ms: 10_000_000,
973            ..Default::default()
974        };
975        s.memory.total = Measured::exact(24 * GIB, "t");
976        s.groups.push(Group {
977            id: "model:sd".into(),
978            kind: GroupKind::ModelServer,
979            label: "sd-server".into(),
980            fingerprint: "fp-sd".into(),
981            root: Some(ProcId::new(10, 10_000_000)),
982            ..Default::default()
983        });
984        s.groups.push(Group {
985            id: "app:x".into(),
986            kind: GroupKind::App,
987            label: "X".into(),
988            fingerprint: "fp-x".into(),
989            ..Default::default()
990        });
991        let priors = ColdStartPriors::detect(&s).unwrap();
992        assert_eq!(priors.agent, 0.0);
993        let c = group_candidates_with(
994            &s,
995            &RankContext {
996                priors: Some(priors),
997                ..Default::default()
998            },
999        );
1000        assert!((c[0].prior - 0.3).abs() < 1e-12);
1001        assert!((c[0].novelty - NOVELTY_MAX).abs() < 1e-12, "just started");
1002        assert_eq!(c[1].prior, 0.0);
1003        // Learned affinity replaces the prior.
1004        let aff: HashMap<String, f64> = [("fp-sd".to_string(), 0.2)].into();
1005        let c = group_candidates_with(
1006            &s,
1007            &RankContext {
1008                priors: Some(priors),
1009                affinity: Some(&aff),
1010                ..Default::default()
1011            },
1012        );
1013        assert_eq!(c[0].prior, 0.0);
1014        assert_eq!(c[0].affinity, 0.2);
1015    }
1016
1017    #[test]
1018    fn anomaly() {
1019        let flat: Vec<u64> = vec![GIB; 10];
1020        assert_eq!(anomaly_score(&flat), 0.0);
1021        let mut jump = flat.clone();
1022        jump.push(3 * GIB);
1023        assert!(anomaly_score(&jump) > 0.9);
1024        let mut drop = flat;
1025        drop.push(0);
1026        assert_eq!(anomaly_score(&drop), 0.0);
1027        assert_eq!(anomaly_score(&[1, 2]), 0.0);
1028    }
1029
1030    /// Audit finding 14: a group that has just appeared is not an anomaly (its history reads 0 before it
1031    /// existed); real growth after it appeared still is.
1032    #[test]
1033    fn a_new_group_is_not_an_anomaly() {
1034        let mut appeared = vec![0u64; 10];
1035        appeared.push(3 * GIB);
1036        assert!(
1037            anomaly_score(&appeared) > 0.9,
1038            "the raw series does look like a spike"
1039        );
1040        assert_eq!(group_anomaly_score(&appeared), 0.0);
1041        appeared.extend([3 * GIB; 5]);
1042        assert_eq!(group_anomaly_score(&appeared), 0.0, "steady since it appeared");
1043        appeared.push(9 * GIB);
1044        assert!(group_anomaly_score(&appeared) > 0.9, "grew after it appeared");
1045        assert_eq!(group_anomaly_score(&[]), 0.0);
1046        assert_eq!(group_anomaly_score(&[0, 0, 0]), 0.0);
1047
1048        // through the candidate builder, with a real history
1049        let snap = |with_new: bool, t: u64| {
1050            let mut s = Snapshot {
1051                taken_at_ms: t,
1052                ..Default::default()
1053            };
1054            let mut ids = vec!["app:old"];
1055            if with_new {
1056                ids.push("app:new");
1057            }
1058            for id in ids {
1059                s.groups.push(Group {
1060                    id: id.into(),
1061                    label: id.into(),
1062                    totals: crate::model::GroupTotals {
1063                        footprint: Measured::exact(3 * GIB, "t"),
1064                        ..Default::default()
1065                    },
1066                    ..Default::default()
1067                });
1068            }
1069            s
1070        };
1071        let mut h = History::new(3_600_000);
1072        for i in 0..10u64 {
1073            h.push_snapshot(&snap(false, 1_000 + i * 2_000));
1074        }
1075        let now = snap(true, 21_000);
1076        h.push_snapshot(&now);
1077        let ctx = RankContext {
1078            history: Some(&h),
1079            ..Default::default()
1080        };
1081        let with = group_candidates_with(&now, &ctx);
1082        let without = group_candidates_with(&now, &RankContext::default());
1083        let sal = |c: &[Candidate], id: &str| c.iter().find(|c| c.id == id).unwrap().salience;
1084        assert_eq!(sal(&with, "app:new"), sal(&without, "app:new"));
1085        assert_eq!(sal(&with, "app:old"), sal(&without, "app:old"));
1086    }
1087
1088    #[test]
1089    fn explanations_with_facts() {
1090        let parts = ScoreParts {
1091            salience: 0.23,
1092            affinity: 0.5,
1093            total: 0.73,
1094            ..Default::default()
1095        };
1096        let facts = RankFacts {
1097            footprint: Some(2_800_000_000),
1098            process_count: 14,
1099            opens_this_week: Some(9),
1100            units: UnitSystem::Si,
1101            ..Default::default()
1102        };
1103        assert_eq!(
1104            explain_rank_for(3, &parts, &facts),
1105            "3rd: you opened it 9× this week (affinity) · holds 2.8 GB (salience) · 14 processes grouped."
1106        );
1107        assert_eq!(ordinal(11), "11th");
1108        assert_eq!(ordinal(22), "22nd");
1109        assert_eq!(
1110            explain_rank(1, &ScoreParts::default()),
1111            "1st: no strong signal (default order)."
1112        );
1113    }
1114}