Skip to main content

adk_website/experiments/
store.rs

1//! Experiment records between looks (spec 3.5 §7.12): the plan, the fixed analysis, the
2//! cumulative per-arm counts, the analyzer's `ExperimentState` and the latest report.
3
4use std::collections::BTreeMap;
5use std::path::PathBuf;
6
7use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
8use adk_eval::experiments::{
9    Decision, ExperimentConfig, ExperimentReport, ExperimentState, Tolerance,
10};
11use async_trait::async_trait;
12use chrono::{DateTime, NaiveDate, Utc};
13use serde::{Deserialize, Serialize};
14use tokio::sync::RwLock;
15use uuid::Uuid;
16
17use super::{Arm, ExperimentPlan};
18
19/// A value per arm (spec 3.5 §7.12).
20#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
21#[serde(rename_all = "camelCase")]
22pub struct Arms<T> {
23    /// The control's.
24    pub control: T,
25    /// The variant's.
26    pub variant: T,
27}
28
29impl<T> Arms<T> {
30    /// The value of `arm`.
31    pub fn get(&self, arm: Arm) -> &T {
32        match arm {
33            Arm::Control => &self.control,
34            Arm::Variant => &self.variant,
35        }
36    }
37
38    /// The value of `arm`, to change.
39    pub fn get_mut(&mut self, arm: Arm) -> &mut T {
40        match arm {
41            Arm::Control => &mut self.control,
42            Arm::Variant => &mut self.variant,
43        }
44    }
45}
46
47/// The cumulative counts of an experiment since it started (spec 3.5 §7.12): exposures, and
48/// the goal events of each metric, per arm.
49#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
50#[serde(rename_all = "camelCase")]
51pub struct ArmCounts {
52    /// Tab sessions shown each arm.
53    pub exposures: Arms<u64>,
54    /// Goal events per metric.
55    pub events: BTreeMap<String, Arms<u64>>,
56}
57
58/// A charter guardrail an experiment monitors, as it was fixed at the start (spec 3.5 §7.12,
59/// A-I15).
60#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
61#[serde(rename_all = "camelCase")]
62pub struct GuardedMetric {
63    /// The charter guardrail's id.
64    pub guardrail: String,
65    /// The metric it watches.
66    pub metric: String,
67    /// The charter's threshold.
68    pub threshold: f64,
69    /// How much worse than the control the variant may be.
70    pub tolerance: Tolerance,
71}
72
73/// Where an experiment stands (spec 3.5 §7.12).
74#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
75#[serde(rename_all = "camelCase", tag = "status", rename_all_fields = "camelCase")]
76pub enum ExperimentStatus {
77    /// Its variant is served and its counts are read every day.
78    Running,
79    /// It reached a final decision; the next build serves the control alone.
80    Stopped {
81        /// The decision.
82        decision: Decision,
83        /// When.
84        at: DateTime<Utc>,
85        /// The job a guardrail breach paused (A-I15).
86        #[serde(default, skip_serializing_if = "Option::is_none")]
87        paused_job: Option<String>,
88    },
89}
90
91impl ExperimentStatus {
92    /// Whether the experiment is running.
93    pub fn is_running(&self) -> bool {
94        matches!(self, Self::Running)
95    }
96}
97
98/// Everything about one experiment that outlives a look (spec 3.5 §7.12). It serialises to
99/// camelCase JSON, its latest report included, for the web home.
100#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
101#[serde(rename_all = "camelCase")]
102pub struct ExperimentRecord {
103    /// The site.
104    pub site: Uuid,
105    /// The plan.
106    pub plan: ExperimentPlan,
107    /// The analysis fixed at the start.
108    pub config: ExperimentConfig,
109    /// The guardrails it monitors.
110    pub guardrails: Vec<GuardedMetric>,
111    /// The charter version it started under.
112    pub charter_version: u32,
113    /// Where it stands.
114    pub status: ExperimentStatus,
115    /// When it started.
116    pub started_at: DateTime<Utc>,
117    /// The first day not yet counted: every whole day before it is in `counts`.
118    pub counted_to: NaiveDate,
119    /// The cumulative counts.
120    pub counts: ArmCounts,
121    /// The analyzer's state between looks.
122    pub state: ExperimentState,
123    /// The latest look's report.
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub latest: Option<ExperimentReport>,
126}
127
128impl ExperimentRecord {
129    /// When it stopped, if it has.
130    pub fn stopped_at(&self) -> Option<DateTime<Utc>> {
131        match &self.status {
132            ExperimentStatus::Running => None,
133            ExperimentStatus::Stopped { at, .. } => Some(*at),
134        }
135    }
136}
137
138/// Keeps experiment records (spec 3.5 §7.12): the runner writes one after every look and the
139/// generator reads which experiments are running.
140#[async_trait]
141pub trait ExperimentStore: Send + Sync {
142    /// Stores `record`, replacing the one with its site and id.
143    ///
144    /// # Errors
145    ///
146    /// Returns the store's error.
147    async fn put(&self, record: &ExperimentRecord) -> Result<()>;
148
149    /// The record of experiment `id` on `site`.
150    ///
151    /// # Errors
152    ///
153    /// Returns the store's error.
154    async fn get(&self, site: Uuid, id: &str) -> Result<Option<ExperimentRecord>>;
155
156    /// Every record of `site`, by id.
157    ///
158    /// # Errors
159    ///
160    /// Returns the store's error.
161    async fn list(&self, site: Uuid) -> Result<Vec<ExperimentRecord>>;
162}
163
164/// Experiment records in process memory, for tests and single-process sites.
165#[derive(Debug, Default)]
166pub struct InMemoryExperimentStore {
167    records: RwLock<BTreeMap<(Uuid, String), ExperimentRecord>>,
168}
169
170impl InMemoryExperimentStore {
171    /// No records.
172    pub fn new() -> Self {
173        Self::default()
174    }
175}
176
177#[async_trait]
178impl ExperimentStore for InMemoryExperimentStore {
179    async fn put(&self, record: &ExperimentRecord) -> Result<()> {
180        self.records.write().await.insert((record.site, record.plan.id.clone()), record.clone());
181        Ok(())
182    }
183
184    async fn get(&self, site: Uuid, id: &str) -> Result<Option<ExperimentRecord>> {
185        Ok(self.records.read().await.get(&(site, id.to_string())).cloned())
186    }
187
188    async fn list(&self, site: Uuid) -> Result<Vec<ExperimentRecord>> {
189        Ok(self
190            .records
191            .read()
192            .await
193            .iter()
194            .filter(|((owner, _), _)| *owner == site)
195            .map(|(_, record)| record.clone())
196            .collect())
197    }
198}
199
200/// Experiment records as JSON files, `{dir}/{site}/{id}.json`, each replaced atomically by a
201/// write to a temporary file and a rename: a site's data directory keeps its experiments
202/// across restarts.
203#[derive(Debug, Clone)]
204pub struct FileExperimentStore {
205    dir: PathBuf,
206}
207
208impl FileExperimentStore {
209    /// A store under `dir`, created on the first write.
210    pub fn new(dir: impl Into<PathBuf>) -> Self {
211        Self { dir: dir.into() }
212    }
213
214    fn site_dir(&self, site: Uuid) -> PathBuf {
215        self.dir.join(site.to_string())
216    }
217}
218
219fn io_error(path: &std::path::Path, error: impl std::fmt::Display) -> AdkError {
220    AdkError::new(
221        ErrorComponent::Tool,
222        ErrorCategory::Unavailable,
223        "website.experiment.store",
224        format!(
225            "the experiment store at '{}' failed: {error}; check the directory exists and is \
226             writable",
227            path.display()
228        ),
229    )
230}
231
232#[async_trait]
233impl ExperimentStore for FileExperimentStore {
234    async fn put(&self, record: &ExperimentRecord) -> Result<()> {
235        // Ids are validated plans' ids: lowercase letters, digits and '-', so a safe name.
236        record.plan.validate()?;
237        let dir = self.site_dir(record.site);
238        tokio::fs::create_dir_all(&dir).await.map_err(|e| io_error(&dir, e))?;
239        let path = dir.join(format!("{}.json", record.plan.id));
240        let temp = dir.join(format!(".{}.json.tmp", record.plan.id));
241        let bytes = serde_json::to_vec_pretty(record).map_err(|e| io_error(&path, e))?;
242        tokio::fs::write(&temp, bytes).await.map_err(|e| io_error(&temp, e))?;
243        tokio::fs::rename(&temp, &path).await.map_err(|e| io_error(&path, e))
244    }
245
246    async fn get(&self, site: Uuid, id: &str) -> Result<Option<ExperimentRecord>> {
247        if !id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') {
248            return Ok(None);
249        }
250        let path = self.site_dir(site).join(format!("{id}.json"));
251        match tokio::fs::read(&path).await {
252            Ok(bytes) => serde_json::from_slice(&bytes).map(Some).map_err(|e| io_error(&path, e)),
253            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
254            Err(error) => Err(io_error(&path, error)),
255        }
256    }
257
258    async fn list(&self, site: Uuid) -> Result<Vec<ExperimentRecord>> {
259        let dir = self.site_dir(site);
260        let mut entries = match tokio::fs::read_dir(&dir).await {
261            Ok(entries) => entries,
262            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
263            Err(error) => return Err(io_error(&dir, error)),
264        };
265        let mut records = Vec::new();
266        while let Some(entry) = entries.next_entry().await.map_err(|e| io_error(&dir, e))? {
267            let name = entry.file_name().to_string_lossy().into_owned();
268            if let Some(id) = name.strip_suffix(".json").filter(|id| !id.starts_with('.'))
269                && let Some(record) = self.get(site, id).await?
270            {
271                records.push(record);
272            }
273        }
274        records.sort_by(|a, b| a.plan.id.cmp(&b.plan.id));
275        Ok(records)
276    }
277}