use std::collections::BTreeMap;
use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
use adk_eval::experiments::{
AnalysisMethod, DEFAULT_PLANNED_UNITS_PER_ARM, ExperimentConfig, GuardrailSpec,
MetricDirection, MetricSpec, Tolerance,
};
use awp_types::{Breach, Charter, Direction, Guardrail};
use serde::{Deserialize, Serialize};
mod build;
mod publish;
mod runner;
mod store;
mod tools;
pub use build::ExperimentGenerator;
pub use publish::RepublishOnStop;
pub use runner::{ExperimentRunner, ExperimentStopHook, LookOutcome};
pub use store::{
ArmCounts, Arms, ExperimentRecord, ExperimentStatus, ExperimentStore, FileExperimentStore,
GuardedMetric, InMemoryExperimentStore,
};
pub use tools::experiment_tools;
pub const EXPERIMENTS_JOB: &str = "experiments";
pub const SCRIPT_PATH: &str = "/_awp/experiments.js";
pub const VARIANT_DIR: &str = "_exp";
pub const EXPERIMENTS_WORKFLOW: &str = "website.experiments";
pub const MAX_ID_LEN: usize = 24;
const MAX_EVENT_LEN: usize = 64;
const MAX_RELATIVE_DROP: f64 = 0.99;
pub const SCRIPT: &str = include_str!("experiments/experiments.js");
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Arm {
Control,
Variant,
}
impl Arm {
pub fn letter(self) -> &'static str {
match self {
Self::Control => "a",
Self::Variant => "b",
}
}
}
pub fn bucket_hash(key: &str) -> u32 {
key.encode_utf16()
.fold(0x811c_9dc5_u32, |hash, unit| (hash ^ u32::from(unit)).wrapping_mul(0x0100_0193))
}
pub fn assign(experiment: &str, bucket: &str, allocation: f64) -> Arm {
let position = f64::from(bucket_hash(&format!("{experiment}:{bucket}"))) / 4_294_967_296.0;
if position < allocation { Arm::Variant } else { Arm::Control }
}
pub fn metric_direction(direction: Direction) -> MetricDirection {
match direction {
Direction::Down => MetricDirection::LowerIsBetter,
_ => MetricDirection::HigherIsBetter,
}
}
pub fn guardrail_direction(breach: Breach) -> MetricDirection {
match breach {
Breach::Below => MetricDirection::HigherIsBetter,
_ => MetricDirection::LowerIsBetter,
}
}
pub fn guardrail_tolerance(guardrail: &Guardrail, baseline: Option<f64>) -> Tolerance {
let Some(baseline) = baseline.filter(|value| value.is_finite() && *value > 0.0) else {
return Tolerance::Absolute(0.0);
};
let ratio = guardrail.threshold / baseline;
if !ratio.is_finite() {
return Tolerance::Absolute(0.0);
}
match guardrail_direction(guardrail.breach) {
MetricDirection::LowerIsBetter => Tolerance::Relative((ratio - 1.0).max(0.0)),
MetricDirection::HigherIsBetter => {
Tolerance::Relative((1.0 - ratio).clamp(0.0, MAX_RELATIVE_DROP))
}
}
}
pub fn guardrail_spec(guardrail: &Guardrail, baseline: Option<f64>) -> GuardrailSpec {
GuardrailSpec::new(
MetricSpec::proportion(guardrail.metric.0.clone(), guardrail_direction(guardrail.breach)),
guardrail_tolerance(guardrail, baseline),
)
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Replacement {
pub find: String,
pub replace: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExperimentPlan {
pub id: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub hypothesis: String,
pub job: String,
pub page: String,
pub variant: Vec<Replacement>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub goal_pages: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub item: Option<String>,
pub primary_kpi: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub guardrails: Vec<String>,
pub allocation: f64,
#[serde(default)]
pub method: AnalysisMethod,
pub planned_units_per_arm: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_units_per_arm: Option<u64>,
pub source: String,
}
impl ExperimentPlan {
pub fn new(
id: impl Into<String>,
page: impl Into<String>,
primary_kpi: impl Into<String>,
) -> Self {
Self {
id: id.into(),
hypothesis: String::new(),
job: EXPERIMENTS_JOB.to_string(),
page: page.into(),
variant: Vec::new(),
goal_pages: Vec::new(),
item: None,
primary_kpi: primary_kpi.into(),
guardrails: Vec::new(),
allocation: 0.5,
method: AnalysisMethod::default(),
planned_units_per_arm: DEFAULT_PLANNED_UNITS_PER_ARM,
max_units_per_arm: None,
source: "beacon".to_string(),
}
}
#[must_use]
pub fn hypothesis(mut self, hypothesis: impl Into<String>) -> Self {
self.hypothesis = hypothesis.into();
self
}
#[must_use]
pub fn replace(mut self, find: impl Into<String>, replace: impl Into<String>) -> Self {
self.variant.push(Replacement { find: find.into(), replace: replace.into() });
self
}
#[must_use]
pub fn goal_page(mut self, page: impl Into<String>) -> Self {
self.goal_pages.push(page.into());
self
}
#[must_use]
pub fn item(mut self, id: impl Into<String>) -> Self {
self.item = Some(id.into());
self
}
#[must_use]
pub fn guardrail(mut self, id: impl Into<String>) -> Self {
self.guardrails.push(id.into());
self
}
#[must_use]
pub fn job(mut self, job: impl Into<String>) -> Self {
self.job = job.into();
self
}
#[must_use]
pub fn allocation(mut self, share: f64) -> Self {
self.allocation = share;
self
}
#[must_use]
pub fn method(mut self, method: AnalysisMethod) -> Self {
self.method = method;
self
}
#[must_use]
pub fn planned_units_per_arm(mut self, units: u64) -> Self {
self.planned_units_per_arm = units;
self
}
#[must_use]
pub fn max_units_per_arm(mut self, units: u64) -> Self {
self.max_units_per_arm = Some(units);
self
}
#[must_use]
pub fn source(mut self, source: impl Into<String>) -> Self {
self.source = source.into();
self
}
pub fn event(&self, arm: Arm, metric: &str) -> String {
format!("exp.{}.{}.{metric}", self.id, arm.letter())
}
pub fn exposure_event(&self, arm: Arm) -> String {
self.event(arm, "exposure")
}
pub fn control_file(&self) -> Result<String> {
page_file(&self.id, &self.page)
}
pub fn variant_file(&self) -> Result<String> {
Ok(format!("{VARIANT_DIR}/{}/{}", self.id, self.control_file()?))
}
pub fn variant_url(&self) -> String {
format!("/{VARIANT_DIR}/{}{}", self.id, self.page)
}
pub fn validate(&self) -> Result<()> {
if self.id.is_empty()
|| self.id.len() > MAX_ID_LEN
|| !self.id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
{
return Err(invalid(format!(
"experiment id '{}' must be 1 to {MAX_ID_LEN} lowercase letters, digits or '-'",
self.id
)));
}
self.control_file()?;
for page in &self.goal_pages {
page_file(&self.id, page)?;
}
if self.variant.is_empty() {
return Err(invalid(format!(
"experiment '{}' changes nothing; add the variant's changes with `replace`",
self.id
)));
}
for change in &self.variant {
if change.find.is_empty() || change.find == change.replace {
return Err(invalid(format!(
"experiment '{}' has a change that finds nothing or changes nothing",
self.id
)));
}
if let Some(found) = active_content(&change.replace) {
return Err(invalid(format!(
"experiment '{}' would add {found} to the variant; a variant changes text \
and markup only (spec 3.5 §7.12)",
self.id
)));
}
}
if !(self.allocation > 0.0 && self.allocation < 1.0) {
return Err(invalid(format!(
"experiment '{}' sends {} of buckets to the variant; use a share in (0, 1)",
self.id, self.allocation
)));
}
if self.job.trim().is_empty() || self.source.trim().is_empty() {
return Err(invalid(format!("experiment '{}' needs a job and a source", self.id)));
}
Ok(())
}
pub fn config(
&self,
charter: &Charter,
baselines: &BTreeMap<String, f64>,
) -> Result<(ExperimentConfig, Vec<GuardedMetric>)> {
self.validate()?;
let Some(kpi) = charter.kpis.iter().find(|kpi| kpi.id == self.primary_kpi) else {
let known: Vec<&str> = charter.kpis.iter().map(|kpi| kpi.id.as_str()).collect();
return Err(invalid(format!(
"charter version {} has no KPI '{}'; name one of {known:?}",
charter.version, self.primary_kpi
)));
};
let primary = kpi.metric.0.clone();
self.check_metric(&primary)?;
let mut config = ExperimentConfig::new(
self.id.clone(),
MetricSpec::proportion(primary.clone(), metric_direction(kpi.direction)),
)
.with_method(self.method)
.with_planned_units_per_arm(self.planned_units_per_arm);
if let Some(max) = self.max_units_per_arm {
config = config.with_max_units_per_arm(max);
}
let chosen: Vec<&Guardrail> = if self.guardrails.is_empty() {
charter
.guardrails
.iter()
.filter(|guardrail| guardrail.jobs.is_empty() || guardrail.jobs.contains(&self.job))
.collect()
} else {
let mut chosen = Vec::new();
for id in &self.guardrails {
let Some(guardrail) = charter.guardrails.iter().find(|g| &g.id == id) else {
return Err(invalid(format!(
"charter version {} has no guardrail '{id}'",
charter.version
)));
};
chosen.push(guardrail);
}
chosen
};
let mut guarded = Vec::new();
for guardrail in chosen {
let metric = guardrail.metric.0.clone();
if metric == primary {
return Err(invalid(format!(
"guardrail '{}' watches the primary metric '{metric}'; an experiment cannot \
guard the metric it tries to move",
guardrail.id
)));
}
if guarded.iter().any(|g: &GuardedMetric| g.metric == metric) {
continue;
}
self.check_metric(&metric)?;
let spec = guardrail_spec(guardrail, baselines.get(&metric).copied());
guarded.push(GuardedMetric {
guardrail: guardrail.id.clone(),
metric,
threshold: guardrail.threshold,
tolerance: spec.tolerance,
});
config = config.with_guardrail(spec);
}
config.validate().map_err(|error| invalid(error.to_string()))?;
Ok((config, guarded))
}
fn check_metric(&self, metric: &str) -> Result<()> {
let event = self.event(Arm::Control, metric);
let valid = metric != "exposure"
&& event.len() <= MAX_EVENT_LEN
&& metric
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"._-".contains(&b));
if valid {
Ok(())
} else {
Err(invalid(format!(
"metric '{metric}' cannot be counted per arm: its event '{event}' must be at most \
{MAX_EVENT_LEN} lowercase letters, digits, '.', '_' or '-', and not 'exposure'; \
shorten the experiment id or rename the metric"
)))
}
}
}
fn page_file(id: &str, path: &str) -> Result<String> {
let relative = path.strip_prefix('/').ok_or_else(|| {
invalid(format!("experiment '{id}': page '{path}' must be a URL path starting with '/'"))
})?;
let clean = !relative.split('/').any(|segment| segment == ".." || segment == ".")
&& !relative.contains("//")
&& relative.bytes().all(|b| b.is_ascii_graphic() && !b"\"'<>\\?#&%".contains(&b));
if !clean {
return Err(invalid(format!(
"experiment '{id}': page '{path}' must be a plain path without queries, fragments or \
dot segments"
)));
}
if relative.is_empty() || relative.ends_with('/') {
Ok(format!("{relative}index.html"))
} else if relative.ends_with(".html") {
Ok(relative.to_string())
} else {
Err(invalid(format!(
"experiment '{id}': page '{path}' names no page file; end it with '/' or '.html'"
)))
}
}
fn active_content(html: &str) -> Option<&'static str> {
let lower = html.to_ascii_lowercase();
for (element, name) in [
("<script", "a script"),
("<iframe", "a frame"),
("<frame", "a frame"),
("<object", "an embedded object"),
("<embed", "an embedded object"),
("<link", "a linked resource"),
("<meta", "a meta element"),
("<base", "a base element"),
("<form", "a form"),
("<style", "a style sheet"),
] {
if lower.contains(element) {
return Some(name);
}
}
let mut rest = lower.as_str();
while let Some(start) = rest.find('<') {
let after = &rest[start + 1..];
let end = after.find('>').unwrap_or(after.len());
let tag = &after[..end];
if ["javascript:", "vbscript:", "data:"].iter().any(|scheme| tag.contains(scheme)) {
return Some("a script URL");
}
if has_event_handler(tag) {
return Some("an event handler");
}
rest = &after[end..];
}
None
}
fn has_event_handler(tag: &str) -> bool {
let bytes = tag.as_bytes();
(1..bytes.len()).any(|index| {
let boundary =
matches!(bytes[index - 1], b' ' | b'\t' | b'\n' | b'\r' | b'/' | b'"' | b'\'');
if !boundary || !bytes[index..].starts_with(b"on") {
return false;
}
let letters = bytes[index + 2..].iter().take_while(|b| b.is_ascii_lowercase()).count();
letters > 0 && bytes[index + 2 + letters..].trim_ascii_start().starts_with(b"=")
})
}
pub(crate) fn invalid(message: impl Into<String>) -> AdkError {
AdkError::new(
ErrorComponent::Tool,
ErrorCategory::InvalidInput,
"website.experiment.invalid",
message.into(),
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_hash_matches_fnv_1a_test_vectors() {
assert_eq!(bucket_hash(""), 0x811c_9dc5);
assert_eq!(bucket_hash("a"), 0xe40c_292c);
assert_eq!(bucket_hash("foobar"), 0xbf9c_f968);
}
#[test]
fn pages_map_to_their_files() {
let plan = |page: &str| ExperimentPlan::new("h", page, "k").replace("a", "b");
assert_eq!(plan("/").control_file().unwrap(), "index.html");
assert_eq!(plan("/pricing/").control_file().unwrap(), "pricing/index.html");
assert_eq!(plan("/about.html").variant_file().unwrap(), "_exp/h/about.html");
assert_eq!(plan("/pricing/").variant_url(), "/_exp/h/pricing/");
for bad in ["pricing/", "/pricing", "/a/../b/", "/a?b=1", "/\"x/"] {
assert!(plan(bad).validate().is_err(), "{bad}");
}
}
#[test]
fn a_variant_adds_no_active_content() {
for html in [
"<script>x()</script>",
"<img src=x onerror=alert(1)>",
"<a href=\"javascript:x()\">",
"<IFRAME src=x>",
"<p ONCLICK = \"x\">",
"<form action=/x>",
] {
assert!(active_content(html).is_some(), "{html}");
}
for html in ["<h1>Bread at 5am</h1>", "<p>Join 2,000 readers on Monday</p>", "only"] {
assert_eq!(active_content(html), None, "{html}");
}
}
}