use std::collections::BTreeMap;
use std::path::PathBuf;
use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
use adk_eval::experiments::{
Decision, ExperimentConfig, ExperimentReport, ExperimentState, Tolerance,
};
use async_trait::async_trait;
use chrono::{DateTime, NaiveDate, Utc};
use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;
use uuid::Uuid;
use super::{Arm, ExperimentPlan};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Arms<T> {
pub control: T,
pub variant: T,
}
impl<T> Arms<T> {
pub fn get(&self, arm: Arm) -> &T {
match arm {
Arm::Control => &self.control,
Arm::Variant => &self.variant,
}
}
pub fn get_mut(&mut self, arm: Arm) -> &mut T {
match arm {
Arm::Control => &mut self.control,
Arm::Variant => &mut self.variant,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ArmCounts {
pub exposures: Arms<u64>,
pub events: BTreeMap<String, Arms<u64>>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GuardedMetric {
pub guardrail: String,
pub metric: String,
pub threshold: f64,
pub tolerance: Tolerance,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "status", rename_all_fields = "camelCase")]
pub enum ExperimentStatus {
Running,
Stopped {
decision: Decision,
at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
paused_job: Option<String>,
},
}
impl ExperimentStatus {
pub fn is_running(&self) -> bool {
matches!(self, Self::Running)
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExperimentRecord {
pub site: Uuid,
pub plan: ExperimentPlan,
pub config: ExperimentConfig,
pub guardrails: Vec<GuardedMetric>,
pub charter_version: u32,
pub status: ExperimentStatus,
pub started_at: DateTime<Utc>,
pub counted_to: NaiveDate,
pub counts: ArmCounts,
pub state: ExperimentState,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub latest: Option<ExperimentReport>,
}
impl ExperimentRecord {
pub fn stopped_at(&self) -> Option<DateTime<Utc>> {
match &self.status {
ExperimentStatus::Running => None,
ExperimentStatus::Stopped { at, .. } => Some(*at),
}
}
}
#[async_trait]
pub trait ExperimentStore: Send + Sync {
async fn put(&self, record: &ExperimentRecord) -> Result<()>;
async fn get(&self, site: Uuid, id: &str) -> Result<Option<ExperimentRecord>>;
async fn list(&self, site: Uuid) -> Result<Vec<ExperimentRecord>>;
}
#[derive(Debug, Default)]
pub struct InMemoryExperimentStore {
records: RwLock<BTreeMap<(Uuid, String), ExperimentRecord>>,
}
impl InMemoryExperimentStore {
pub fn new() -> Self {
Self::default()
}
}
#[async_trait]
impl ExperimentStore for InMemoryExperimentStore {
async fn put(&self, record: &ExperimentRecord) -> Result<()> {
self.records.write().await.insert((record.site, record.plan.id.clone()), record.clone());
Ok(())
}
async fn get(&self, site: Uuid, id: &str) -> Result<Option<ExperimentRecord>> {
Ok(self.records.read().await.get(&(site, id.to_string())).cloned())
}
async fn list(&self, site: Uuid) -> Result<Vec<ExperimentRecord>> {
Ok(self
.records
.read()
.await
.iter()
.filter(|((owner, _), _)| *owner == site)
.map(|(_, record)| record.clone())
.collect())
}
}
#[derive(Debug, Clone)]
pub struct FileExperimentStore {
dir: PathBuf,
}
impl FileExperimentStore {
pub fn new(dir: impl Into<PathBuf>) -> Self {
Self { dir: dir.into() }
}
fn site_dir(&self, site: Uuid) -> PathBuf {
self.dir.join(site.to_string())
}
}
fn io_error(path: &std::path::Path, error: impl std::fmt::Display) -> AdkError {
AdkError::new(
ErrorComponent::Tool,
ErrorCategory::Unavailable,
"website.experiment.store",
format!(
"the experiment store at '{}' failed: {error}; check the directory exists and is \
writable",
path.display()
),
)
}
#[async_trait]
impl ExperimentStore for FileExperimentStore {
async fn put(&self, record: &ExperimentRecord) -> Result<()> {
record.plan.validate()?;
let dir = self.site_dir(record.site);
tokio::fs::create_dir_all(&dir).await.map_err(|e| io_error(&dir, e))?;
let path = dir.join(format!("{}.json", record.plan.id));
let temp = dir.join(format!(".{}.json.tmp", record.plan.id));
let bytes = serde_json::to_vec_pretty(record).map_err(|e| io_error(&path, e))?;
tokio::fs::write(&temp, bytes).await.map_err(|e| io_error(&temp, e))?;
tokio::fs::rename(&temp, &path).await.map_err(|e| io_error(&path, e))
}
async fn get(&self, site: Uuid, id: &str) -> Result<Option<ExperimentRecord>> {
if !id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') {
return Ok(None);
}
let path = self.site_dir(site).join(format!("{id}.json"));
match tokio::fs::read(&path).await {
Ok(bytes) => serde_json::from_slice(&bytes).map(Some).map_err(|e| io_error(&path, e)),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(io_error(&path, error)),
}
}
async fn list(&self, site: Uuid) -> Result<Vec<ExperimentRecord>> {
let dir = self.site_dir(site);
let mut entries = match tokio::fs::read_dir(&dir).await {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(error) => return Err(io_error(&dir, error)),
};
let mut records = Vec::new();
while let Some(entry) = entries.next_entry().await.map_err(|e| io_error(&dir, e))? {
let name = entry.file_name().to_string_lossy().into_owned();
if let Some(id) = name.strip_suffix(".json").filter(|id| !id.starts_with('.'))
&& let Some(record) = self.get(site, id).await?
{
records.push(record);
}
}
records.sort_by(|a, b| a.plan.id.cmp(&b.plan.id));
Ok(records)
}
}