Skip to main content

aios_agent/backends/predictive/
types.rs

1//! Data types for the next-app predictive model.
2
3use std::collections::BTreeMap;
4
5use serde::{Deserialize, Serialize};
6
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct NextAppModelArtifact {
9    pub schema_version: String,
10    pub model_id: String,
11    pub dataset_id: String,
12    pub trained_at_ms: i64,
13    pub config: NextAppModelConfig,
14    pub app_vocab: Vec<String>,
15    pub global_popularity: Vec<AppScore>,
16    pub naive_bayes: NaiveBayesModel,
17    pub markov: MarkovModel,
18    /// Log-lift feature ensemble. The JSON field name remains `xgboost` for
19    /// backward compatibility with existing artifacts, but the implementation
20    /// is a lightweight deterministic feature-lift model, not an XGBoost
21    /// gradient-boosted tree ensemble.
22    #[serde(rename = "xgboost")]
23    pub feature_lift: FeatureLiftModel,
24    /// Per-user app-usage frequency ranking (MFU), keyed by user id. Unlike the
25    /// per-user Markov table this is unconditional on the current app: it ranks
26    /// the apps a user opens most often overall. Defaults to empty for backward
27    /// compatibility with older artifacts.
28    #[serde(default)]
29    pub user_frequency: BTreeMap<String, Vec<AppScore>>,
30    /// Hard recency pointer: the single most recent next-app observed per
31    /// `"{user}\t{current}"` key in training order (last write wins). Unlike the
32    /// per-user Markov distribution this is a one-app "what did this user open
33    /// last time from here" signal, a strong top-1 predictor on repetitive
34    /// personal usage. Defaults to empty for backward compatibility.
35    #[serde(default)]
36    pub user_recency: BTreeMap<String, String>,
37    /// Context-aware Markov transitions keyed by temporal features. Keys are
38    /// `"{current}\t{hour}"` or `"{current}\t{weekday}"`, values are ranked
39    /// next-app distributions. This captures time-of-day and day-of-week
40    /// patterns that the global Markov table averages over. Defaults to empty
41    /// for backward compatibility with older artifacts.
42    #[serde(default)]
43    pub markov_context: BTreeMap<String, Vec<AppScore>>,
44    /// Learned reciprocal-rank-fusion combiner for the ensemble algorithm. The
45    /// weights are fit offline on a held-out validation slice (never on the
46    /// test split) and locked into the artifact, so runtime inference is pure
47    /// and deterministic with no extra dependencies. Defaults to empty, in
48    /// which case the ensemble falls back to the legacy fixed-weight fusion so
49    /// older committed artifacts keep working.
50    #[serde(default)]
51    pub ensemble_combiner: EnsembleCombiner,
52    /// Learned logistic candidate reranker over the same component features as
53    /// the ensemble. Empty means "use `ensemble_combiner` / legacy fusion".
54    #[serde(default)]
55    pub ensemble_logistic: LogisticRerankerModel,
56    pub training_summary: TrainingSummary,
57}
58
59#[derive(Debug, Clone, Serialize, Deserialize)]
60pub struct NextAppModelConfig {
61    pub horizon_secs: u64,
62    pub history_len: usize,
63}
64
65impl Default for NextAppModelConfig {
66    fn default() -> Self {
67        Self {
68            horizon_secs: 30,
69            history_len: 5,
70        }
71    }
72}
73
74#[derive(Debug, Clone, Serialize, Deserialize)]
75pub struct TrainingSummary {
76    pub examples: usize,
77    pub users: usize,
78    pub apps: usize,
79}
80
81#[derive(Debug, Clone, Serialize, Deserialize)]
82pub struct AppScore {
83    pub app: String,
84    pub score: f32,
85}
86
87#[derive(Debug, Clone, Serialize, Deserialize)]
88pub struct NaiveBayesModel {
89    pub class_log_priors: Vec<f32>,
90    pub unknown_feature_log_probs: Vec<f32>,
91    pub feature_log_probs: BTreeMap<String, Vec<f32>>,
92}
93
94#[derive(Debug, Clone, Serialize, Deserialize)]
95pub struct MarkovModel {
96    pub global_transitions: BTreeMap<String, Vec<AppScore>>,
97    pub user_transitions: BTreeMap<String, Vec<AppScore>>,
98    /// Global order-2 transitions keyed `"{prev}\t{current}" -> next`. This is
99    /// the strongest single next-app signal on LSApp and is global, so it
100    /// survives cold-start (unseen users) where per-user tables are empty.
101    /// Defaults to empty for backward compatibility with older artifacts.
102    #[serde(default)]
103    pub global_transitions_order2: BTreeMap<String, Vec<AppScore>>,
104}
105
106/// Learned reciprocal-rank-fusion combiner over the ensemble's component
107/// rankers. `components` and `weights` are parallel vectors; unknown component
108/// names are ignored at inference so the schema can evolve. An empty combiner
109/// means "use the legacy fixed-weight fusion".
110#[derive(Debug, Clone, Default, Serialize, Deserialize)]
111pub struct EnsembleCombiner {
112    pub components: Vec<String>,
113    pub weights: Vec<f32>,
114}
115
116impl EnsembleCombiner {
117    pub fn is_empty(&self) -> bool {
118        self.components.is_empty() || self.components.len() != self.weights.len()
119    }
120
121    pub fn weight_of(&self, component: &str) -> Option<f32> {
122        self.components
123            .iter()
124            .position(|c| c == component)
125            .map(|idx| self.weights[idx])
126    }
127}
128
129/// Pairwise-trained logistic reranker over candidate-level ensemble features.
130/// `feature_names` and `weights` are parallel vectors; an empty model means the
131/// artifact should use the RRF combiner or legacy fixed fusion instead.
132#[derive(Debug, Clone, Default, Serialize, Deserialize)]
133pub struct LogisticRerankerModel {
134    pub feature_names: Vec<String>,
135    pub weights: Vec<f32>,
136}
137
138impl LogisticRerankerModel {
139    pub fn is_empty(&self) -> bool {
140        self.feature_names.is_empty() || self.feature_names.len() != self.weights.len()
141    }
142}
143
144/// Lightweight deterministic feature-lift ensemble.
145///
146/// This is **not** an XGBoost gradient-boosted tree. It selects the top-k most
147/// frequent categorical features from the training data and stores per-feature
148/// log-lift scores for each app. At inference time the active features' lifts
149/// are added to the base (log-prior) scores. The artifact JSON field is still
150/// labeled `xgboost` for backward compatibility with existing artifacts.
151#[derive(Debug, Clone, Serialize, Deserialize)]
152pub struct FeatureLiftModel {
153    pub base_scores: Vec<f32>,
154    pub trees: Vec<FeatureLiftTree>,
155}
156
157#[derive(Debug, Clone, Serialize, Deserialize)]
158pub struct FeatureLiftTree {
159    pub feature_key: String,
160    pub yes_scores: Vec<AppScore>,
161}
162
163#[derive(Debug, Clone, Copy, PartialEq, Eq)]
164pub enum NextAppAlgorithm {
165    NaiveBayes,
166    Markov,
167    /// Log-lift feature ensemble (the artifact field is still serialized as
168    /// `xgboost` for compatibility, but the model is not XGBoost).
169    FeatureLift,
170    Ensemble,
171}
172
173#[derive(Debug, Clone)]
174pub struct NextAppTrainingExample {
175    pub user_id: String,
176    pub current_app: String,
177    pub history: Vec<String>,
178    pub hour_bucket: u8,
179    pub weekday: u8,
180    pub event_type: String,
181    pub label_app: String,
182}
183
184#[derive(Debug, Clone, Default)]
185pub struct PredictionFeatures {
186    pub user_id: Option<String>,
187    pub current_app: Option<String>,
188    pub history: Vec<String>,
189    pub hour_bucket: Option<u8>,
190    pub weekday: Option<u8>,
191    pub event_type: Option<String>,
192}