1use 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
21#[serde(rename_all = "camelCase")]
22pub struct Arms<T> {
23 pub control: T,
25 pub variant: T,
27}
28
29impl<T> Arms<T> {
30 pub fn get(&self, arm: Arm) -> &T {
32 match arm {
33 Arm::Control => &self.control,
34 Arm::Variant => &self.variant,
35 }
36 }
37
38 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#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
50#[serde(rename_all = "camelCase")]
51pub struct ArmCounts {
52 pub exposures: Arms<u64>,
54 pub events: BTreeMap<String, Arms<u64>>,
56}
57
58#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
61#[serde(rename_all = "camelCase")]
62pub struct GuardedMetric {
63 pub guardrail: String,
65 pub metric: String,
67 pub threshold: f64,
69 pub tolerance: Tolerance,
71}
72
73#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
75#[serde(rename_all = "camelCase", tag = "status", rename_all_fields = "camelCase")]
76pub enum ExperimentStatus {
77 Running,
79 Stopped {
81 decision: Decision,
83 at: DateTime<Utc>,
85 #[serde(default, skip_serializing_if = "Option::is_none")]
87 paused_job: Option<String>,
88 },
89}
90
91impl ExperimentStatus {
92 pub fn is_running(&self) -> bool {
94 matches!(self, Self::Running)
95 }
96}
97
98#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
101#[serde(rename_all = "camelCase")]
102pub struct ExperimentRecord {
103 pub site: Uuid,
105 pub plan: ExperimentPlan,
107 pub config: ExperimentConfig,
109 pub guardrails: Vec<GuardedMetric>,
111 pub charter_version: u32,
113 pub status: ExperimentStatus,
115 pub started_at: DateTime<Utc>,
117 pub counted_to: NaiveDate,
119 pub counts: ArmCounts,
121 pub state: ExperimentState,
123 #[serde(default, skip_serializing_if = "Option::is_none")]
125 pub latest: Option<ExperimentReport>,
126}
127
128impl ExperimentRecord {
129 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#[async_trait]
141pub trait ExperimentStore: Send + Sync {
142 async fn put(&self, record: &ExperimentRecord) -> Result<()>;
148
149 async fn get(&self, site: Uuid, id: &str) -> Result<Option<ExperimentRecord>>;
155
156 async fn list(&self, site: Uuid) -> Result<Vec<ExperimentRecord>>;
162}
163
164#[derive(Debug, Default)]
166pub struct InMemoryExperimentStore {
167 records: RwLock<BTreeMap<(Uuid, String), ExperimentRecord>>,
168}
169
170impl InMemoryExperimentStore {
171 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#[derive(Debug, Clone)]
204pub struct FileExperimentStore {
205 dir: PathBuf,
206}
207
208impl FileExperimentStore {
209 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 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}