adk_website/experiments.rs
1//! Web experiments on the site (spec 3.5 §7.12, A-I15, S11): the charter's KPIs and
2//! guardrails as an `adk-eval` experiment, variants as separate static files, stable
3//! assignment of an anonymous bucket, exposures and goals counted through the edge beacon, a
4//! daily look at the cumulative counts, and the decision with its evidence in the weekly
5//! review.
6//!
7//! | Part | What it does | Spec 3.5 |
8//! |---|---|---|
9//! | [`ExperimentPlan`] | The hypothesis, the control page, the variant's changes, the primary KPI and the guardrails, by charter id | §7.12 |
10//! | [`metric_direction`], [`guardrail_spec`] | The charter's KPI direction and guardrails as the analyzer's metrics and tolerances | §7.6, §7.12 |
11//! | [`assign`], [`bucket_hash`] | A stable hash of an anonymous bucket picks the arm, at the edge or in the client | §7.12 |
12//! | [`ExperimentGenerator`] | Wraps the site's generator: each running experiment's variant is its own static file under `/_exp/{id}/`, and its pages load `/_awp/experiments.js` | §7.8, §7.12 |
13//! | [`ExperimentRunner`] | Starts experiments, reads each day's per-arm counts, feeds the cumulative totals to `ExperimentAnalyzer` as a `Look`, keeps its `ExperimentState`, pauses the job on a guardrail breach, writes the review's evidence | §7.12, A-I15, §7.21 |
14//! | [`ExperimentStore`] | Every experiment's record between looks: in memory or as JSON files | §7.12 |
15//! | [`experiment_tools`] | The Growth agent's `experiment_start` and `experiment_report` over the runner | §7.12, §7.20 |
16//!
17//! # How an experiment runs
18//!
19//! 1. The Growth agent's `experiments` job writes a plan; [`ExperimentRunner::start`] maps it
20//! onto the charter in force and fixes the analysis before the first look.
21//! 2. The next release carries the variant: [`ExperimentGenerator`] copies the control page,
22//! applies the plan's [`Replacement`]s, marks the copy `noindex` (its canonical link still
23//! names the control), and adds the script to both.
24//! 3. In the browser the script hashes the experiment id and a random bucket kept in the
25//! tab's `sessionStorage`; the variant arm is sent to the variant's file. Each tab session
26//! sends one `exp.{id}.{arm}.exposure` event, and one `exp.{id}.{arm}.{metric}` event per
27//! goal reached (an element marked `data-awp-goal="{metric}"`). No cookie, no identifier
28//! and no address leaves the page.
29//! 4. Each day [`ExperimentRunner::look`] reads the new whole days of those counts from the
30//! `beacon` KPI source, adds them to the experiment's totals and analyses the totals.
31//! 5. A guardrail breach keeps the control and pauses the job through the kernel's
32//! `JobControl` before anything else (A-I15); every final decision stops the experiment,
33//! so the next build serves the control alone. The weekly review shows the decision and
34//! the analyzer's evidence block.
35//!
36//! The unit of analysis is a tab session's exposure: a session that reaches a goal counts as
37//! one event of its arm, so both metrics are proportions of exposures.
38//!
39//! # Guardrails from the charter
40//!
41//! A charter guardrail is an absolute limit on a site metric ("unsubscribes above 0.75%");
42//! an experiment guardrail limits how much worse the variant may be than the control. The
43//! mapping keeps the charter's headroom: a guardrail whose metric has a baseline `b` allows
44//! the variant to move the metric by at most the share that would carry the site from `b`
45//! to the threshold `t` once adopted — `t/b − 1` above the baseline for a limit the metric
46//! must stay under, `1 − t/b` below it for one it must stay over. A guardrail without a
47//! baseline, or whose baseline already breaches it, breaches on any proven harm.
48//!
49//! # Example
50//!
51//! ```rust
52//! use adk_website::experiments::{Arm, ExperimentPlan, assign};
53//!
54//! let plan = ExperimentPlan::new("headline", "/", "signups")
55//! .hypothesis("Saying when the bread is baked lifts sign-ups")
56//! .replace("<h1>Juniper Bakery</h1>", "<h1>Bread out of the oven at 5am</h1>")
57//! .guardrail("unsubscribes");
58//! assert!(plan.validate().is_ok());
59//! assert_eq!(plan.event(Arm::Variant, "newsletter.signups"), "exp.headline.b.newsletter.signups");
60//! assert_eq!(plan.variant_file().unwrap(), "_exp/headline/index.html");
61//!
62//! // The same bucket always lands in the same arm.
63//! assert_eq!(assign("headline", "9f2c41d0", 0.5), assign("headline", "9f2c41d0", 0.5));
64//! ```
65
66use std::collections::BTreeMap;
67
68use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
69use adk_eval::experiments::{
70 AnalysisMethod, DEFAULT_PLANNED_UNITS_PER_ARM, ExperimentConfig, GuardrailSpec,
71 MetricDirection, MetricSpec, Tolerance,
72};
73use awp_types::{Breach, Charter, Direction, Guardrail};
74use serde::{Deserialize, Serialize};
75
76mod build;
77mod publish;
78mod runner;
79mod store;
80mod tools;
81
82pub use build::ExperimentGenerator;
83pub use publish::RepublishOnStop;
84pub use runner::{ExperimentRunner, ExperimentStopHook, LookOutcome};
85pub use store::{
86 ArmCounts, Arms, ExperimentRecord, ExperimentStatus, ExperimentStore, FileExperimentStore,
87 GuardedMetric, InMemoryExperimentStore,
88};
89pub use tools::experiment_tools;
90
91/// The job that runs experiments (spec 3.5 §7.20).
92pub const EXPERIMENTS_JOB: &str = "experiments";
93
94/// Where the experiment script is served (spec 3.5 §7.12).
95pub const SCRIPT_PATH: &str = "/_awp/experiments.js";
96
97/// The directory every variant's files are served under: `/_exp/{id}/` (spec 3.5 §7.12).
98pub const VARIANT_DIR: &str = "_exp";
99
100/// The kernel workflow of the daily look at every running experiment (spec 3.5 §7.12).
101pub const EXPERIMENTS_WORKFLOW: &str = "website.experiments";
102
103/// The longest experiment id: an event name `exp.{id}.{arm}.{metric}` stays within the
104/// beacon's 64 characters with room for the metric.
105pub const MAX_ID_LEN: usize = 24;
106
107/// The beacon's longest event name.
108const MAX_EVENT_LEN: usize = 64;
109
110/// The largest relative drop a guardrail on a metric that must stay over its threshold
111/// tolerates; the analyzer refuses a drop of 100% or more.
112const MAX_RELATIVE_DROP: f64 = 0.99;
113
114/// The client script served at [`SCRIPT_PATH`].
115pub const SCRIPT: &str = include_str!("experiments/experiments.js");
116
117/// An arm of an experiment (spec 3.5 §7.12): the control (A) or the variant (B).
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
119#[serde(rename_all = "camelCase")]
120pub enum Arm {
121 /// The page as it is: A.
122 Control,
123 /// The page with the plan's changes: B.
124 Variant,
125}
126
127impl Arm {
128 /// The arm's letter in event names: `a` or `b`.
129 pub fn letter(self) -> &'static str {
130 match self {
131 Self::Control => "a",
132 Self::Variant => "b",
133 }
134 }
135}
136
137/// FNV-1a over the UTF-16 code units of `key`: the hash the client script computes with
138/// `charCodeAt` and `Math.imul`, so the edge and the browser assign a bucket alike (spec 3.5
139/// §7.12).
140///
141/// # Example
142///
143/// ```rust
144/// use adk_website::experiments::bucket_hash;
145///
146/// assert_eq!(bucket_hash(""), 0x811c_9dc5);
147/// assert_eq!(bucket_hash("a"), 0xe40c_292c);
148/// ```
149pub fn bucket_hash(key: &str) -> u32 {
150 key.encode_utf16()
151 .fold(0x811c_9dc5_u32, |hash, unit| (hash ^ u32::from(unit)).wrapping_mul(0x0100_0193))
152}
153
154/// The arm of `bucket` in `experiment` when `allocation` of the buckets see the variant
155/// (spec 3.5 §7.12): a stable hash of an anonymous bucket, so a bucket keeps its arm for the
156/// experiment's life and experiments split independently.
157///
158/// The bucket is anonymous: the client script draws a random one per tab session and never
159/// sends it; an edge that assigns uses a value it does not store.
160///
161/// # Example
162///
163/// ```rust
164/// use adk_website::experiments::{Arm, assign};
165///
166/// assert_eq!(assign("headline", "any bucket", 0.0), Arm::Control);
167/// assert_eq!(assign("headline", "any bucket", 1.0), Arm::Variant);
168/// ```
169pub fn assign(experiment: &str, bucket: &str, allocation: f64) -> Arm {
170 let position = f64::from(bucket_hash(&format!("{experiment}:{bucket}"))) / 4_294_967_296.0;
171 if position < allocation { Arm::Variant } else { Arm::Control }
172}
173
174/// The charter's KPI direction as the analyzer's metric direction (spec 3.5 §7.6, §7.12):
175/// `Up` is higher-is-better and `Down` lower-is-better.
176///
177/// # Example
178///
179/// ```rust
180/// use adk_eval::experiments::MetricDirection;
181/// use adk_website::experiments::metric_direction;
182/// use awp_types::Direction;
183///
184/// assert_eq!(metric_direction(Direction::Down), MetricDirection::LowerIsBetter);
185/// ```
186pub fn metric_direction(direction: Direction) -> MetricDirection {
187 match direction {
188 Direction::Down => MetricDirection::LowerIsBetter,
189 _ => MetricDirection::HigherIsBetter,
190 }
191}
192
193/// The direction a charter guardrail protects (spec 3.5 §7.6): a limit the metric must stay
194/// under is lower-is-better; one it must stay over is higher-is-better.
195pub fn guardrail_direction(breach: Breach) -> MetricDirection {
196 match breach {
197 Breach::Below => MetricDirection::HigherIsBetter,
198 _ => MetricDirection::LowerIsBetter,
199 }
200}
201
202/// How much worse than the control the variant may be on a charter guardrail's metric whose
203/// baseline is `baseline` (spec 3.5 §7.12, A-I15): the share of the charter's headroom
204/// between the baseline and the threshold; with no positive baseline, or none left, any
205/// proven harm breaches.
206///
207/// # Example
208///
209/// ```rust
210/// use std::time::Duration;
211/// use adk_eval::experiments::Tolerance;
212/// use adk_website::experiments::guardrail_tolerance;
213/// use awp_types::{Breach, Guardrail, GuardrailAction};
214///
215/// let unsubscribes = Guardrail {
216/// id: "unsubscribes".into(),
217/// metric: "email.unsubscribes".into(),
218/// threshold: 0.0075,
219/// breach: Breach::Above,
220/// window: Duration::from_secs(7 * 86_400),
221/// action: GuardrailAction::PauseJob,
222/// jobs: vec!["experiments".into()],
223/// };
224/// // From a 0.5% baseline the site may rise 50% before it crosses 0.75%.
225/// let Tolerance::Relative(share) = guardrail_tolerance(&unsubscribes, Some(0.005)) else {
226/// unreachable!()
227/// };
228/// assert!((share - 0.5).abs() < 1e-12);
229/// assert_eq!(guardrail_tolerance(&unsubscribes, None), Tolerance::Absolute(0.0));
230/// ```
231pub fn guardrail_tolerance(guardrail: &Guardrail, baseline: Option<f64>) -> Tolerance {
232 let Some(baseline) = baseline.filter(|value| value.is_finite() && *value > 0.0) else {
233 return Tolerance::Absolute(0.0);
234 };
235 let ratio = guardrail.threshold / baseline;
236 if !ratio.is_finite() {
237 return Tolerance::Absolute(0.0);
238 }
239 match guardrail_direction(guardrail.breach) {
240 MetricDirection::LowerIsBetter => Tolerance::Relative((ratio - 1.0).max(0.0)),
241 MetricDirection::HigherIsBetter => {
242 Tolerance::Relative((1.0 - ratio).clamp(0.0, MAX_RELATIVE_DROP))
243 }
244 }
245}
246
247/// A charter guardrail as an experiment guardrail on the proportion of exposures that reach
248/// its metric (spec 3.5 §7.12, A-I15); see [`guardrail_tolerance`].
249pub fn guardrail_spec(guardrail: &Guardrail, baseline: Option<f64>) -> GuardrailSpec {
250 GuardrailSpec::new(
251 MetricSpec::proportion(guardrail.metric.0.clone(), guardrail_direction(guardrail.breach)),
252 guardrail_tolerance(guardrail, baseline),
253 )
254}
255
256/// A literal change the variant makes to the control page (spec 3.5 §7.12).
257#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
258#[serde(rename_all = "camelCase")]
259pub struct Replacement {
260 /// HTML the control page contains.
261 pub find: String,
262 /// What the variant shows instead.
263 pub replace: String,
264}
265
266/// An experiment the `experiments` job proposes (spec 3.5 §7.12, §7.20): one page, one
267/// variant, the KPI it should move and the guardrails that stop it.
268///
269/// Metrics and guardrails are fixed when the experiment starts; an id is never reused.
270#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
271#[serde(rename_all = "camelCase")]
272pub struct ExperimentPlan {
273 /// The experiment's id: lowercase letters, digits and `-`, at most [`MAX_ID_LEN`].
274 pub id: String,
275 /// What the variant is expected to do, in the owner's terms.
276 #[serde(default, skip_serializing_if = "String::is_empty")]
277 pub hypothesis: String,
278 /// The job that runs it, paused on a guardrail breach.
279 pub job: String,
280 /// The control page's URL path, such as `/` or `/pricing/`.
281 pub page: String,
282 /// The variant's changes to the control page.
283 pub variant: Vec<Replacement>,
284 /// Further pages that load the script to count goals, such as a sign-up confirmation.
285 #[serde(default, skip_serializing_if = "Vec::is_empty")]
286 pub goal_pages: Vec<String>,
287 /// The content item rendered as the control page; [`RepublishOnStop`] republishes it
288 /// when the experiment stops, so the control is served alone at once.
289 #[serde(default, skip_serializing_if = "Option::is_none")]
290 pub item: Option<String>,
291 /// The charter KPI the variant should move.
292 pub primary_kpi: String,
293 /// The charter guardrails to monitor; empty means every guardrail of the job.
294 #[serde(default, skip_serializing_if = "Vec::is_empty")]
295 pub guardrails: Vec<String>,
296 /// The share of buckets that see the variant, in `(0, 1)`.
297 pub allocation: f64,
298 /// How the primary metric is analysed; guardrails always use the sequential test.
299 #[serde(default)]
300 pub method: AnalysisMethod,
301 /// The exposures per arm the experiment expects, where its boundary is tightest.
302 pub planned_units_per_arm: u64,
303 /// When set, the experiment stops and keeps the control at this many exposures per arm.
304 #[serde(default, skip_serializing_if = "Option::is_none")]
305 pub max_units_per_arm: Option<u64>,
306 /// The KPI source that counts the per-arm events, `beacon` by default.
307 pub source: String,
308}
309
310impl ExperimentPlan {
311 /// A plan for `page` that moves the KPI `primary_kpi`, split evenly, analysed with the
312 /// sequential test, counted by the beacon, run by the `experiments` job.
313 pub fn new(
314 id: impl Into<String>,
315 page: impl Into<String>,
316 primary_kpi: impl Into<String>,
317 ) -> Self {
318 Self {
319 id: id.into(),
320 hypothesis: String::new(),
321 job: EXPERIMENTS_JOB.to_string(),
322 page: page.into(),
323 variant: Vec::new(),
324 goal_pages: Vec::new(),
325 item: None,
326 primary_kpi: primary_kpi.into(),
327 guardrails: Vec::new(),
328 allocation: 0.5,
329 method: AnalysisMethod::default(),
330 planned_units_per_arm: DEFAULT_PLANNED_UNITS_PER_ARM,
331 max_units_per_arm: None,
332 source: "beacon".to_string(),
333 }
334 }
335
336 /// Sets the hypothesis.
337 #[must_use]
338 pub fn hypothesis(mut self, hypothesis: impl Into<String>) -> Self {
339 self.hypothesis = hypothesis.into();
340 self
341 }
342
343 /// Adds a change the variant makes: every `find` in the control page becomes `replace`.
344 #[must_use]
345 pub fn replace(mut self, find: impl Into<String>, replace: impl Into<String>) -> Self {
346 self.variant.push(Replacement { find: find.into(), replace: replace.into() });
347 self
348 }
349
350 /// Adds a page that loads the script only to count goals.
351 #[must_use]
352 pub fn goal_page(mut self, page: impl Into<String>) -> Self {
353 self.goal_pages.push(page.into());
354 self
355 }
356
357 /// Names the content item rendered as the control page.
358 #[must_use]
359 pub fn item(mut self, id: impl Into<String>) -> Self {
360 self.item = Some(id.into());
361 self
362 }
363
364 /// Monitors the charter guardrail `id`.
365 #[must_use]
366 pub fn guardrail(mut self, id: impl Into<String>) -> Self {
367 self.guardrails.push(id.into());
368 self
369 }
370
371 /// Sets the job that runs it.
372 #[must_use]
373 pub fn job(mut self, job: impl Into<String>) -> Self {
374 self.job = job.into();
375 self
376 }
377
378 /// Sets the share of buckets that see the variant.
379 #[must_use]
380 pub fn allocation(mut self, share: f64) -> Self {
381 self.allocation = share;
382 self
383 }
384
385 /// Sets how the primary metric is analysed.
386 #[must_use]
387 pub fn method(mut self, method: AnalysisMethod) -> Self {
388 self.method = method;
389 self
390 }
391
392 /// Sets the exposures per arm the experiment expects.
393 #[must_use]
394 pub fn planned_units_per_arm(mut self, units: u64) -> Self {
395 self.planned_units_per_arm = units;
396 self
397 }
398
399 /// Stops the experiment, keeping the control, at `units` exposures per arm.
400 #[must_use]
401 pub fn max_units_per_arm(mut self, units: u64) -> Self {
402 self.max_units_per_arm = Some(units);
403 self
404 }
405
406 /// Counts the per-arm events from the KPI source named `source`.
407 #[must_use]
408 pub fn source(mut self, source: impl Into<String>) -> Self {
409 self.source = source.into();
410 self
411 }
412
413 /// The event the client sends when a tab session of `arm` reaches `metric`.
414 pub fn event(&self, arm: Arm, metric: &str) -> String {
415 format!("exp.{}.{}.{metric}", self.id, arm.letter())
416 }
417
418 /// The event the client sends once per tab session shown `arm`.
419 pub fn exposure_event(&self, arm: Arm) -> String {
420 self.event(arm, "exposure")
421 }
422
423 /// The control page's file in the build, such as `index.html` for `/`.
424 ///
425 /// # Errors
426 ///
427 /// Returns `website.experiment.invalid` for a path that names no page file.
428 pub fn control_file(&self) -> Result<String> {
429 page_file(&self.id, &self.page)
430 }
431
432 /// The variant's file in the build: the control's under `_exp/{id}/`.
433 ///
434 /// # Errors
435 ///
436 /// As [`control_file`](Self::control_file).
437 pub fn variant_file(&self) -> Result<String> {
438 Ok(format!("{VARIANT_DIR}/{}/{}", self.id, self.control_file()?))
439 }
440
441 /// The variant's URL path: the control's under `/_exp/{id}`.
442 pub fn variant_url(&self) -> String {
443 format!("/{VARIANT_DIR}/{}{}", self.id, self.page)
444 }
445
446 /// Checks the plan.
447 ///
448 /// # Errors
449 ///
450 /// Returns `website.experiment.invalid` naming the first problem: an id outside
451 /// `[a-z0-9-]` or longer than [`MAX_ID_LEN`], a page path that names no page file, no
452 /// change or a change that finds nothing, a change that adds script, frames, embeds,
453 /// forms or event handlers, an allocation outside `(0, 1)`, or an empty job or source.
454 pub fn validate(&self) -> Result<()> {
455 if self.id.is_empty()
456 || self.id.len() > MAX_ID_LEN
457 || !self.id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
458 {
459 return Err(invalid(format!(
460 "experiment id '{}' must be 1 to {MAX_ID_LEN} lowercase letters, digits or '-'",
461 self.id
462 )));
463 }
464 self.control_file()?;
465 for page in &self.goal_pages {
466 page_file(&self.id, page)?;
467 }
468 if self.variant.is_empty() {
469 return Err(invalid(format!(
470 "experiment '{}' changes nothing; add the variant's changes with `replace`",
471 self.id
472 )));
473 }
474 for change in &self.variant {
475 if change.find.is_empty() || change.find == change.replace {
476 return Err(invalid(format!(
477 "experiment '{}' has a change that finds nothing or changes nothing",
478 self.id
479 )));
480 }
481 if let Some(found) = active_content(&change.replace) {
482 return Err(invalid(format!(
483 "experiment '{}' would add {found} to the variant; a variant changes text \
484 and markup only (spec 3.5 §7.12)",
485 self.id
486 )));
487 }
488 }
489 if !(self.allocation > 0.0 && self.allocation < 1.0) {
490 return Err(invalid(format!(
491 "experiment '{}' sends {} of buckets to the variant; use a share in (0, 1)",
492 self.id, self.allocation
493 )));
494 }
495 if self.job.trim().is_empty() || self.source.trim().is_empty() {
496 return Err(invalid(format!("experiment '{}' needs a job and a source", self.id)));
497 }
498 Ok(())
499 }
500
501 /// The analysis this plan fixes under `charter` (spec 3.5 §7.12): the primary KPI's metric
502 /// in its direction and every guardrail with its tolerance from `baselines` (metric →
503 /// baseline value), and the guardrails it monitors.
504 ///
505 /// # Errors
506 ///
507 /// Returns `website.experiment.invalid` for a KPI or guardrail the charter does not
508 /// have, a metric whose event name would not fit the beacon, or a configuration the
509 /// analyzer refuses.
510 pub fn config(
511 &self,
512 charter: &Charter,
513 baselines: &BTreeMap<String, f64>,
514 ) -> Result<(ExperimentConfig, Vec<GuardedMetric>)> {
515 self.validate()?;
516 let Some(kpi) = charter.kpis.iter().find(|kpi| kpi.id == self.primary_kpi) else {
517 let known: Vec<&str> = charter.kpis.iter().map(|kpi| kpi.id.as_str()).collect();
518 return Err(invalid(format!(
519 "charter version {} has no KPI '{}'; name one of {known:?}",
520 charter.version, self.primary_kpi
521 )));
522 };
523 let primary = kpi.metric.0.clone();
524 self.check_metric(&primary)?;
525 let mut config = ExperimentConfig::new(
526 self.id.clone(),
527 MetricSpec::proportion(primary.clone(), metric_direction(kpi.direction)),
528 )
529 .with_method(self.method)
530 .with_planned_units_per_arm(self.planned_units_per_arm);
531 if let Some(max) = self.max_units_per_arm {
532 config = config.with_max_units_per_arm(max);
533 }
534 let chosen: Vec<&Guardrail> = if self.guardrails.is_empty() {
535 charter
536 .guardrails
537 .iter()
538 .filter(|guardrail| guardrail.jobs.is_empty() || guardrail.jobs.contains(&self.job))
539 .collect()
540 } else {
541 let mut chosen = Vec::new();
542 for id in &self.guardrails {
543 let Some(guardrail) = charter.guardrails.iter().find(|g| &g.id == id) else {
544 return Err(invalid(format!(
545 "charter version {} has no guardrail '{id}'",
546 charter.version
547 )));
548 };
549 chosen.push(guardrail);
550 }
551 chosen
552 };
553 let mut guarded = Vec::new();
554 for guardrail in chosen {
555 let metric = guardrail.metric.0.clone();
556 if metric == primary {
557 return Err(invalid(format!(
558 "guardrail '{}' watches the primary metric '{metric}'; an experiment cannot \
559 guard the metric it tries to move",
560 guardrail.id
561 )));
562 }
563 if guarded.iter().any(|g: &GuardedMetric| g.metric == metric) {
564 continue;
565 }
566 self.check_metric(&metric)?;
567 let spec = guardrail_spec(guardrail, baselines.get(&metric).copied());
568 guarded.push(GuardedMetric {
569 guardrail: guardrail.id.clone(),
570 metric,
571 threshold: guardrail.threshold,
572 tolerance: spec.tolerance,
573 });
574 config = config.with_guardrail(spec);
575 }
576 config.validate().map_err(|error| invalid(error.to_string()))?;
577 Ok((config, guarded))
578 }
579
580 /// Refuses a metric whose event name the beacon would refuse.
581 fn check_metric(&self, metric: &str) -> Result<()> {
582 let event = self.event(Arm::Control, metric);
583 let valid = metric != "exposure"
584 && event.len() <= MAX_EVENT_LEN
585 && metric
586 .bytes()
587 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"._-".contains(&b));
588 if valid {
589 Ok(())
590 } else {
591 Err(invalid(format!(
592 "metric '{metric}' cannot be counted per arm: its event '{event}' must be at most \
593 {MAX_EVENT_LEN} lowercase letters, digits, '.', '_' or '-', and not 'exposure'; \
594 shorten the experiment id or rename the metric"
595 )))
596 }
597 }
598}
599
600/// The build file of page `path`: `index.html` under a directory path, the path itself for
601/// a `.html` file.
602fn page_file(id: &str, path: &str) -> Result<String> {
603 let relative = path.strip_prefix('/').ok_or_else(|| {
604 invalid(format!("experiment '{id}': page '{path}' must be a URL path starting with '/'"))
605 })?;
606 let clean = !relative.split('/').any(|segment| segment == ".." || segment == ".")
607 && !relative.contains("//")
608 && relative.bytes().all(|b| b.is_ascii_graphic() && !b"\"'<>\\?#&%".contains(&b));
609 if !clean {
610 return Err(invalid(format!(
611 "experiment '{id}': page '{path}' must be a plain path without queries, fragments or \
612 dot segments"
613 )));
614 }
615 if relative.is_empty() || relative.ends_with('/') {
616 Ok(format!("{relative}index.html"))
617 } else if relative.ends_with(".html") {
618 Ok(relative.to_string())
619 } else {
620 Err(invalid(format!(
621 "experiment '{id}': page '{path}' names no page file; end it with '/' or '.html'"
622 )))
623 }
624}
625
626/// The first element or attribute in `html` that loads or runs code.
627fn active_content(html: &str) -> Option<&'static str> {
628 let lower = html.to_ascii_lowercase();
629 for (element, name) in [
630 ("<script", "a script"),
631 ("<iframe", "a frame"),
632 ("<frame", "a frame"),
633 ("<object", "an embedded object"),
634 ("<embed", "an embedded object"),
635 ("<link", "a linked resource"),
636 ("<meta", "a meta element"),
637 ("<base", "a base element"),
638 ("<form", "a form"),
639 ("<style", "a style sheet"),
640 ] {
641 if lower.contains(element) {
642 return Some(name);
643 }
644 }
645 // Attributes are inside tags; text outside them may say anything.
646 let mut rest = lower.as_str();
647 while let Some(start) = rest.find('<') {
648 let after = &rest[start + 1..];
649 let end = after.find('>').unwrap_or(after.len());
650 let tag = &after[..end];
651 if ["javascript:", "vbscript:", "data:"].iter().any(|scheme| tag.contains(scheme)) {
652 return Some("a script URL");
653 }
654 if has_event_handler(tag) {
655 return Some("an event handler");
656 }
657 rest = &after[end..];
658 }
659 None
660}
661
662/// Whether the inside of a tag has an `on…=` attribute.
663fn has_event_handler(tag: &str) -> bool {
664 let bytes = tag.as_bytes();
665 (1..bytes.len()).any(|index| {
666 let boundary =
667 matches!(bytes[index - 1], b' ' | b'\t' | b'\n' | b'\r' | b'/' | b'"' | b'\'');
668 if !boundary || !bytes[index..].starts_with(b"on") {
669 return false;
670 }
671 let letters = bytes[index + 2..].iter().take_while(|b| b.is_ascii_lowercase()).count();
672 letters > 0 && bytes[index + 2 + letters..].trim_ascii_start().starts_with(b"=")
673 })
674}
675
676/// A refused plan or look.
677pub(crate) fn invalid(message: impl Into<String>) -> AdkError {
678 AdkError::new(
679 ErrorComponent::Tool,
680 ErrorCategory::InvalidInput,
681 "website.experiment.invalid",
682 message.into(),
683 )
684}
685
686#[cfg(test)]
687mod tests {
688 use super::*;
689
690 #[test]
691 fn the_hash_matches_fnv_1a_test_vectors() {
692 // FNV-1a 32-bit vectors from the reference implementation (ASCII, one unit a byte).
693 assert_eq!(bucket_hash(""), 0x811c_9dc5);
694 assert_eq!(bucket_hash("a"), 0xe40c_292c);
695 assert_eq!(bucket_hash("foobar"), 0xbf9c_f968);
696 }
697
698 #[test]
699 fn pages_map_to_their_files() {
700 let plan = |page: &str| ExperimentPlan::new("h", page, "k").replace("a", "b");
701 assert_eq!(plan("/").control_file().unwrap(), "index.html");
702 assert_eq!(plan("/pricing/").control_file().unwrap(), "pricing/index.html");
703 assert_eq!(plan("/about.html").variant_file().unwrap(), "_exp/h/about.html");
704 assert_eq!(plan("/pricing/").variant_url(), "/_exp/h/pricing/");
705 for bad in ["pricing/", "/pricing", "/a/../b/", "/a?b=1", "/\"x/"] {
706 assert!(plan(bad).validate().is_err(), "{bad}");
707 }
708 }
709
710 #[test]
711 fn a_variant_adds_no_active_content() {
712 for html in [
713 "<script>x()</script>",
714 "<img src=x onerror=alert(1)>",
715 "<a href=\"javascript:x()\">",
716 "<IFRAME src=x>",
717 "<p ONCLICK = \"x\">",
718 "<form action=/x>",
719 ] {
720 assert!(active_content(html).is_some(), "{html}");
721 }
722 for html in ["<h1>Bread at 5am</h1>", "<p>Join 2,000 readers on Monday</p>", "only"] {
723 assert_eq!(active_content(html), None, "{html}");
724 }
725 }
726}