Skip to main content

adk_website/experiments/
runner.rs

1//! The experiment runner (spec 3.5 §7.12, A-I15, §7.21): starts experiments, feeds each
2//! day's cumulative per-arm counts to the analyzer, stops them, pauses the job on a guardrail
3//! breach and writes the weekly review's evidence.
4
5use std::collections::BTreeMap;
6use std::fmt::Write as _;
7use std::sync::Arc;
8
9use adk_core::audit_log::{AuditActor, AuditTrail};
10use adk_core::principal::SubjectRef;
11use adk_core::schedule::MissedFirePolicy;
12use adk_core::{AdkError, Clock, ErrorCategory, ErrorComponent, NewRun, Result, SystemClock};
13use adk_eval::experiments::{
14    Decision, ExperimentAnalyzer, ExperimentReport, Look, Sample, StopReason,
15};
16use adk_kernel::QueueClass;
17use adk_kernel::charter::{
18    AutonomyLadder, CharterEvent, CharterEventSink, CharterStore, JobControl, KpiSource, KpiStore,
19    audit,
20};
21use adk_kernel::wake::{Trigger, Wake};
22use adk_server::background::{WorkflowExecutor, WorkflowState};
23use async_trait::async_trait;
24use chrono::{DateTime, NaiveDate, Utc};
25use serde::{Deserialize, Serialize};
26use serde_json::{Value, json};
27use tokio::sync::Mutex;
28use tokio_util::sync::CancellationToken;
29use uuid::Uuid;
30
31use super::store::{ArmCounts, ExperimentRecord, ExperimentStatus, ExperimentStore};
32use super::{Arm, EXPERIMENTS_WORKFLOW, ExperimentPlan, invalid};
33
34/// Called when an experiment stops (spec 3.5 §7.12), after the job is paused and the record
35/// is stored: the product publishes a release so the control is served alone at once rather
36/// than at the next release.
37#[async_trait]
38pub trait ExperimentStopHook: Send + Sync {
39    /// `record` has stopped.
40    ///
41    /// # Errors
42    ///
43    /// Returns the error that kept the release from being published; the experiment stays
44    /// stopped and the next build serves the control alone.
45    async fn stopped(&self, record: &ExperimentRecord) -> Result<()>;
46}
47
48/// What a look did (spec 3.5 §7.12).
49#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
50#[serde(rename_all = "camelCase")]
51pub struct LookOutcome {
52    /// The experiment.
53    pub experiment: String,
54    /// The whole days this look added.
55    pub days: u32,
56    /// The record after the look, its latest report included.
57    pub record: ExperimentRecord,
58    /// Whether this look stopped the experiment.
59    pub stopped: bool,
60}
61
62/// Runs a site's experiments (spec 3.5 §7.12, A-I15).
63///
64/// | Step | What it does |
65/// |---|---|
66/// | [`start`](Self::start) | Maps the plan onto the charter in force: the primary KPI's metric and direction, each guardrail with its tolerance from the KPI baselines; fixes the analysis; refuses while the job is paused, an id already used, or a page another running experiment holds |
67/// | [`look`](Self::look) | Reads the per-arm counts of the whole days since the last look from the plan's KPI source, adds them to the totals, and analyses the totals as one cumulative `Look`, resuming the stored `ExperimentState` |
68/// | Guardrail breach | Pauses the job through the kernel's `JobControl` before anything else, records `website.job.paused`, emits `CharterEvent::JobPaused` (P2) and lowers the job one level on the ladder (A-I15, §7.11) |
69/// | Any final decision | Stops the experiment: the next build serves the control alone; the stop hook can publish that release at once |
70/// | [`review`](Self::review) | One entry per experiment that ran in the week: its decision and the analyzer's evidence block |
71///
72/// Run [`look_all`](Self::look_all) once a day: register the runner with
73/// `KernelBuilder::workflows` and its [`trigger`](Self::trigger) with `KernelBuilder::trigger`,
74/// or call it from the product's own loop.
75///
76/// # Example
77///
78/// ```rust,ignore
79/// let runner = ExperimentRunner::new(site, charters, experiments)
80///     .with_source(Arc::new(BeaconKpi::new(edge.beacon())))
81///     .with_kpis(kpis)
82///     .with_control(kit.pauses.clone())
83///     .with_ladder(ladder)
84///     .with_events(alarms);
85/// runner.start(plan).await?;
86/// let outcomes = runner.look_all().await?;
87/// ```
88pub struct ExperimentRunner {
89    site: Uuid,
90    charters: Arc<dyn CharterStore>,
91    store: Arc<dyn ExperimentStore>,
92    sources: BTreeMap<String, Arc<dyn KpiSource>>,
93    kpis: Option<Arc<dyn KpiStore>>,
94    control: Option<Arc<dyn JobControl>>,
95    ladder: Option<AutonomyLadder>,
96    events: Option<Arc<dyn CharterEventSink>>,
97    audit: Option<AuditTrail>,
98    on_stop: Option<Arc<dyn ExperimentStopHook>>,
99    clock: Arc<dyn Clock>,
100    lock: Mutex<()>,
101}
102
103impl std::fmt::Debug for ExperimentRunner {
104    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105        f.debug_struct("ExperimentRunner")
106            .field("site", &self.site)
107            .field("sources", &self.sources.keys().collect::<Vec<_>>())
108            .finish_non_exhaustive()
109    }
110}
111
112impl ExperimentRunner {
113    /// A runner of `site`'s experiments under its charters, keeping records in `store`, with
114    /// no sources, job control, ladder, events, audit or stop hook, on the system clock.
115    pub fn new(
116        site: Uuid,
117        charters: Arc<dyn CharterStore>,
118        store: Arc<dyn ExperimentStore>,
119    ) -> Self {
120        Self {
121            site,
122            charters,
123            store,
124            sources: BTreeMap::new(),
125            kpis: None,
126            control: None,
127            ladder: None,
128            events: None,
129            audit: None,
130            on_stop: None,
131            clock: Arc::new(SystemClock),
132            lock: Mutex::new(()),
133        }
134    }
135
136    /// Reads per-arm counts from `source` for plans that name it (`beacon` by default).
137    #[must_use]
138    pub fn with_source(mut self, source: Arc<dyn KpiSource>) -> Self {
139        self.sources.insert(source.name().to_string(), source);
140        self
141    }
142
143    /// Reads the baselines the KPI tracker locked, beside the charter's own.
144    #[must_use]
145    pub fn with_kpis(mut self, kpis: Arc<dyn KpiStore>) -> Self {
146        self.kpis = Some(kpis);
147        self
148    }
149
150    /// Pauses the job through `control` on a guardrail breach (A-I15).
151    #[must_use]
152    pub fn with_control(mut self, control: Arc<dyn JobControl>) -> Self {
153        self.control = Some(control);
154        self
155    }
156
157    /// Lowers the job one level on `ladder` on a guardrail breach (spec 3.5 §7.11).
158    #[must_use]
159    pub fn with_ladder(mut self, ladder: AutonomyLadder) -> Self {
160        self.ladder = Some(ladder);
161        self
162    }
163
164    /// Emits the pause on `sink`, such as the product's alarm router (P2).
165    #[must_use]
166    pub fn with_events(mut self, sink: Arc<dyn CharterEventSink>) -> Self {
167        self.events = Some(sink);
168        self
169    }
170
171    /// Records `website.job.paused` on `trail`.
172    #[must_use]
173    pub fn with_audit(mut self, trail: AuditTrail) -> Self {
174        self.audit = Some(trail);
175        self
176    }
177
178    /// Calls `hook` when an experiment stops.
179    #[must_use]
180    pub fn with_stop_hook(mut self, hook: Arc<dyn ExperimentStopHook>) -> Self {
181        self.on_stop = Some(hook);
182        self
183    }
184
185    /// Reads time from `clock`.
186    #[must_use]
187    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
188        self.clock = clock;
189        self
190    }
191
192    /// The site.
193    pub fn site(&self) -> Uuid {
194        self.site
195    }
196
197    /// The record store, which the [`ExperimentGenerator`](super::ExperimentGenerator) reads.
198    pub fn store(&self) -> &Arc<dyn ExperimentStore> {
199        &self.store
200    }
201
202    /// Starts `plan` under the charter in force (spec 3.5 §7.12).
203    ///
204    /// # Errors
205    ///
206    /// Returns `website.experiment.invalid` for an invalid plan or one the charter cannot
207    /// measure (see [`ExperimentPlan::config`]), `website.experiment.exists` for an id
208    /// already used on the site or a page another running experiment holds,
209    /// `website.experiment.paused` while the job is paused (A-I15), and
210    /// `website.experiment.no_charter` before the first charter commit.
211    pub async fn start(&self, plan: ExperimentPlan) -> Result<ExperimentRecord> {
212        let _guard = self.lock.lock().await;
213        plan.validate()?;
214        if let Some(control) = &self.control
215            && let Some(reason) = control.paused(self.site, &plan.job).await.map_err(kernel)?
216        {
217            return Err(AdkError::new(
218                ErrorComponent::Tool,
219                ErrorCategory::Forbidden,
220                "website.experiment.paused",
221                format!(
222                    "job {} is paused ({reason}); an owner resumes it before a new experiment \
223                     starts (A-I15)",
224                    plan.job
225                ),
226            ));
227        }
228        let current = self.charters.current(self.site).await.map_err(kernel)?.ok_or_else(|| {
229            AdkError::new(
230                ErrorComponent::Tool,
231                ErrorCategory::NotFound,
232                "website.experiment.no_charter",
233                "the site has no committed charter; an experiment measures the charter's KPIs",
234            )
235        })?;
236        for record in self.store.list(self.site).await? {
237            let clash = record.plan.id == plan.id;
238            let same_page =
239                record.status.is_running() && record.plan.control_file()? == plan.control_file()?;
240            if clash || same_page {
241                return Err(AdkError::new(
242                    ErrorComponent::Tool,
243                    ErrorCategory::InvalidInput,
244                    "website.experiment.exists",
245                    if clash {
246                        format!(
247                            "experiment id '{}' is already used on this site; ids are never \
248                             reused, so give the new experiment its own id",
249                            plan.id
250                        )
251                    } else {
252                        format!(
253                            "experiment '{}' is running on {}; one experiment runs on a page at \
254                             a time",
255                            record.plan.id, plan.page
256                        )
257                    },
258                ));
259            }
260        }
261        let baselines = self.baselines(&current.charter).await?;
262        let (config, guardrails) = plan.config(&current.charter, &baselines)?;
263        let analyzer =
264            ExperimentAnalyzer::new(config.clone()).map_err(|error| invalid(error.to_string()))?;
265        let now = self.clock.now();
266        let record = ExperimentRecord {
267            site: self.site,
268            plan,
269            config,
270            guardrails,
271            charter_version: current.charter.version,
272            status: ExperimentStatus::Running,
273            started_at: now,
274            counted_to: now.date_naive(),
275            counts: ArmCounts::default(),
276            state: analyzer.state().clone(),
277            latest: None,
278        };
279        self.store.put(&record).await?;
280        tracing::info!(site.id = %self.site, experiment = %record.plan.id, page = %record.plan.page, "experiment started");
281        Ok(record)
282    }
283
284    /// Each charter metric's baseline: the charter's, else the one the tracker locked.
285    async fn baselines(&self, charter: &awp_types::Charter) -> Result<BTreeMap<String, f64>> {
286        let mut baselines = BTreeMap::new();
287        for kpi in &charter.kpis {
288            let mut value = kpi.baseline.as_ref().map(|baseline| baseline.value);
289            if value.is_none()
290                && let Some(kpis) = &self.kpis
291            {
292                value = kpis
293                    .state(self.site, &kpi.id)
294                    .await
295                    .map_err(kernel)?
296                    .and_then(|state| state.baseline.map(|baseline| baseline.value));
297            }
298            if let Some(value) = value {
299                baselines.entry(kpi.metric.0.clone()).or_insert(value);
300            }
301        }
302        Ok(baselines)
303    }
304
305    /// The record of experiment `id`.
306    ///
307    /// # Errors
308    ///
309    /// Returns the store's error.
310    pub async fn get(&self, id: &str) -> Result<Option<ExperimentRecord>> {
311        self.store.get(self.site, id).await
312    }
313
314    /// Every experiment of the site.
315    ///
316    /// # Errors
317    ///
318    /// Returns the store's error.
319    pub async fn list(&self) -> Result<Vec<ExperimentRecord>> {
320        self.store.list(self.site).await
321    }
322
323    /// Looks at experiment `id` (spec 3.5 §7.12): adds the whole days since the last look
324    /// to its totals and analyses them; `None` when no whole day has passed since the last
325    /// look. A stopped experiment returns its final record unchanged.
326    ///
327    /// # Errors
328    ///
329    /// Returns `website.experiment.unknown` for an unknown id,
330    /// `website.experiment.no_source` when the plan's source is not registered, a source's
331    /// or the store's error, and the analyzer's refusal of a look; a failed look changes
332    /// nothing.
333    pub async fn look(&self, id: &str) -> Result<Option<LookOutcome>> {
334        let _guard = self.lock.lock().await;
335        self.look_locked(id).await
336    }
337
338    /// Looks at every running experiment once (spec 3.5 §7.12); one experiment's failure is
339    /// logged and does not stop the others.
340    ///
341    /// # Errors
342    ///
343    /// Returns the store's error.
344    pub async fn look_all(&self) -> Result<Vec<LookOutcome>> {
345        let _guard = self.lock.lock().await;
346        let mut outcomes = Vec::new();
347        for record in self.store.list(self.site).await? {
348            if !record.status.is_running() {
349                continue;
350            }
351            match self.look_locked(&record.plan.id).await {
352                Ok(Some(outcome)) => outcomes.push(outcome),
353                Ok(None) => {}
354                Err(error) => {
355                    tracing::warn!(experiment = %record.plan.id, error = %error, "experiment look failed; the next look reads the same days again");
356                }
357            }
358        }
359        Ok(outcomes)
360    }
361
362    async fn look_locked(&self, id: &str) -> Result<Option<LookOutcome>> {
363        let mut record = self.store.get(self.site, id).await?.ok_or_else(|| {
364            AdkError::new(
365                ErrorComponent::Tool,
366                ErrorCategory::NotFound,
367                "website.experiment.unknown",
368                format!("no experiment '{id}' on this site"),
369            )
370        })?;
371        if !record.status.is_running() {
372            return Ok(Some(LookOutcome {
373                experiment: id.to_string(),
374                days: 0,
375                record,
376                stopped: false,
377            }));
378        }
379        let now = self.clock.now();
380        let today = now.date_naive();
381        let days = (today - record.counted_to).num_days();
382        if days <= 0 {
383            return Ok(None);
384        }
385        let plan = record.plan.clone();
386        let source = self.sources.get(&plan.source).ok_or_else(|| {
387            AdkError::new(
388                ErrorComponent::Tool,
389                ErrorCategory::NotFound,
390                "website.experiment.no_source",
391                format!(
392                    "no KPI source named '{}' counts experiment '{id}'; register it with \
393                     `with_source`",
394                    plan.source
395                ),
396            )
397        })?;
398        let from = midnight(record.counted_to);
399        let to = midnight(today);
400        let mut counts = record.counts.clone();
401        for arm in [Arm::Control, Arm::Variant] {
402            *counts.exposures.get_mut(arm) +=
403                self.count(source.as_ref(), &plan.exposure_event(arm), from, to).await?;
404            let metrics = std::iter::once(&record.config.primary.id)
405                .chain(record.guardrails.iter().map(|guarded| &guarded.metric));
406            for metric in metrics {
407                *counts.events.entry(metric.clone()).or_default().get_mut(arm) +=
408                    self.count(source.as_ref(), &plan.event(arm, metric), from, to).await?;
409            }
410        }
411        let mut look = Look::new();
412        for (metric, events) in &counts.events {
413            // A unit is an exposed tab session; a goal reached without an exposure (another
414            // tab, a script that ran late) cannot raise the rate above one.
415            let sample = |arm: Arm| {
416                let units = *counts.exposures.get(arm);
417                Sample::proportion(units, (*events.get(arm)).min(units))
418            };
419            look = look.with_metric(metric.clone(), sample(Arm::Control), sample(Arm::Variant));
420        }
421        let mut analyzer = ExperimentAnalyzer::resume(record.config.clone(), record.state.clone())
422            .map_err(|error| invalid(error.to_string()))?;
423        let report = analyzer.observe(&look).map_err(|error| invalid(error.to_string()))?;
424        record.counts = counts;
425        record.counted_to = today;
426        record.state = analyzer.state().clone();
427        record.latest = Some(report.clone());
428        let stopped = report.decision.is_final();
429        if stopped {
430            let mut paused_job = None;
431            if let Decision::KeepControl { reason: StopReason::GuardrailBreach { guardrails } } =
432                &report.decision
433            {
434                // A-I15: the job is paused before its next action, ahead of everything else.
435                self.pause(&record, guardrails, &report, now).await?;
436                paused_job = Some(plan.job.clone());
437            }
438            record.status = ExperimentStatus::Stopped {
439                decision: report.decision.clone(),
440                at: now,
441                paused_job,
442            };
443        }
444        self.store.put(&record).await?;
445        tracing::info!(
446            site.id = %self.site,
447            experiment = %id,
448            look = report.look,
449            decision = %report.decision,
450            "experiment looked at"
451        );
452        if stopped
453            && let Some(hook) = &self.on_stop
454            && let Err(error) = hook.stopped(&record).await
455        {
456            tracing::warn!(experiment = %id, error = %error, "the stop hook failed; the next build serves the control alone");
457        }
458        Ok(Some(LookOutcome {
459            experiment: id.to_string(),
460            days: u32::try_from(days).unwrap_or(u32::MAX),
461            record,
462            stopped,
463        }))
464    }
465
466    /// Reads one event's count over `[from, to)`.
467    async fn count(
468        &self,
469        source: &dyn KpiSource,
470        event: &str,
471        from: DateTime<Utc>,
472        to: DateTime<Utc>,
473    ) -> Result<u64> {
474        let value =
475            source.read(self.site, &format!("events:{event}"), from, to).await.map_err(kernel)?;
476        Ok(value
477            .filter(|value| value.is_finite() && *value > 0.0)
478            .map_or(0, |value| value.round() as u64))
479    }
480
481    /// Pauses the job for the breached `metrics` and records why (A-I15, spec 3.5 §7.11).
482    async fn pause(
483        &self,
484        record: &ExperimentRecord,
485        metrics: &[String],
486        report: &ExperimentReport,
487        now: DateTime<Utc>,
488    ) -> Result<()> {
489        let job = &record.plan.job;
490        let breached: Vec<_> =
491            record.guardrails.iter().filter(|guarded| metrics.contains(&guarded.metric)).collect();
492        let names: Vec<&str> = breached.iter().map(|g| g.guardrail.as_str()).collect();
493        let reason = format!(
494            "experiment {} breached the {} guardrail{}: the variant made it worse beyond the \
495             charter's headroom, so the control is kept",
496            record.plan.id,
497            names.join(", "),
498            if names.len() == 1 { "" } else { "s" }
499        );
500        if let Some(control) = &self.control {
501            control.pause(self.site, job, &reason).await.map_err(kernel)?;
502        }
503        for guarded in &breached {
504            let value = report
505                .guardrails
506                .iter()
507                .find(|analysis| analysis.metric == guarded.metric)
508                .map(|analysis| analysis.effect.variant);
509            crate::audit::record(
510                self.audit.as_ref(),
511                audit::JOB_PAUSED,
512                AuditActor::subject(SubjectRef::service("website:experiments")),
513                json!({
514                    "site": self.site,
515                    "job": job,
516                    "guardrail": guarded.guardrail,
517                    "metric": guarded.metric,
518                    "value": value,
519                    "threshold": guarded.threshold,
520                    "charterVersion": record.charter_version,
521                    "experiment": record.plan.id,
522                }),
523            )
524            .await;
525        }
526        tracing::warn!(site.id = %self.site, experiment = %record.plan.id, job = %job, guardrails = ?names, "experiment guardrail breached; job paused");
527        if let Some(events) = &self.events {
528            events
529                .emit(&CharterEvent::JobPaused {
530                    site: self.site,
531                    job: job.clone(),
532                    reason: reason.clone(),
533                    at: now,
534                })
535                .await;
536        }
537        if let Some(ladder) = &self.ladder {
538            for guarded in &breached {
539                if let Err(error) =
540                    ladder.guardrail_breach(self.site, job, &guarded.guardrail).await
541                {
542                    tracing::warn!(job = %job, error = %error, "could not lower the job after the experiment's guardrail breach");
543                }
544            }
545        }
546        Ok(())
547    }
548
549    /// The weekly review's entries for `[from, to)` (spec 3.5 §7.21): every experiment that
550    /// ran in the window, with its decision and the analyzer's evidence block.
551    ///
552    /// # Errors
553    ///
554    /// Returns the store's error.
555    pub async fn review(&self, from: DateTime<Utc>, to: DateTime<Utc>) -> Result<Vec<String>> {
556        let mut entries = Vec::new();
557        for record in self.store.list(self.site).await? {
558            let ran = record.started_at < to && record.stopped_at().is_none_or(|at| at >= from);
559            if ran {
560                entries.push(review_entry(&record));
561            }
562        }
563        Ok(entries)
564    }
565
566    /// The standing trigger of the daily look on the cron expression `expr` (six fields,
567    /// UTC; `"0 30 3 * * *"` is daily at 03:30), on the maintenance queue of app
568    /// `app_name`.
569    pub fn trigger(&self, app_name: &str, expr: &str) -> Trigger {
570        let run = NewRun::new(
571            QueueClass::MAINTENANCE,
572            app_name,
573            "website:experiments",
574            EXPERIMENTS_WORKFLOW,
575            json!({ "site": self.site }),
576        );
577        Trigger::new(
578            format!("{EXPERIMENTS_WORKFLOW}:{}", self.site),
579            Wake::Cron { expr: expr.to_string(), missed: MissedFirePolicy::FireOnce },
580            run,
581        )
582    }
583}
584
585/// One experiment's weekly review entry: a line for the owner, then the evidence block.
586fn review_entry(record: &ExperimentRecord) -> String {
587    let plan = &record.plan;
588    let mut entry = format!("Experiment `{}` on {}", plan.id, plan.page);
589    if !plan.hypothesis.is_empty() {
590        let _ = write!(entry, " — {}", plan.hypothesis);
591    }
592    let _ = write!(entry, " (started {}): ", record.started_at.date_naive());
593    match &record.status {
594        ExperimentStatus::Running => entry.push_str("running"),
595        ExperimentStatus::Stopped { decision, at, paused_job } => {
596            let _ = write!(entry, "stopped {}, {decision}", at.date_naive());
597            if let Some(job) = paused_job {
598                let _ = write!(
599                    entry,
600                    "; the {job} job is paused until you resume it, and the control is served"
601                );
602            } else if decision.keeps_control() {
603                entry.push_str("; the control is served");
604            }
605        }
606    }
607    entry.push('.');
608    match &record.latest {
609        Some(report) => {
610            entry.push_str("\n\n  ```text\n");
611            for line in report.to_string().lines() {
612                let _ = writeln!(entry, "  {line}");
613            }
614            entry.push_str("  ```");
615        }
616        None => entry.push_str(" No whole day counted yet."),
617    }
618    entry
619}
620
621/// Midnight UTC at the start of `day`.
622fn midnight(day: NaiveDate) -> DateTime<Utc> {
623    day.and_hms_opt(0, 0, 0).map_or_else(Utc::now, |time| time.and_utc())
624}
625
626fn kernel(error: adk_kernel::KernelError) -> AdkError {
627    AdkError::new(
628        ErrorComponent::Tool,
629        ErrorCategory::Unavailable,
630        "website.experiment.kernel",
631        error.to_string(),
632    )
633}
634
635#[async_trait]
636impl WorkflowExecutor for ExperimentRunner {
637    fn has_workflow(&self, workflow_id: &str) -> bool {
638        workflow_id == EXPERIMENTS_WORKFLOW
639    }
640
641    async fn execute(
642        &self,
643        workflow_id: &str,
644        input: WorkflowState,
645        cancel_token: CancellationToken,
646    ) -> std::result::Result<Value, String> {
647        if workflow_id != EXPERIMENTS_WORKFLOW {
648            return Err(format!("{workflow_id} is not the experiments look"));
649        }
650        let site = input.get("site").and_then(Value::as_str).and_then(|s| s.parse::<Uuid>().ok());
651        if site != Some(self.site) {
652            return Err(format!(
653                "a `{EXPERIMENTS_WORKFLOW}` run names its site as {{\"site\": \"{}\"}}",
654                self.site
655            ));
656        }
657        tokio::select! {
658            () = cancel_token.cancelled() => Err("cancelled".to_string()),
659            outcomes = self.look_all() => {
660                let outcomes = outcomes.map_err(|error| error.to_string())?;
661                let looks: Vec<Value> = outcomes
662                    .iter()
663                    .map(|outcome| json!({
664                        "experiment": outcome.experiment,
665                        "days": outcome.days,
666                        "stopped": outcome.stopped,
667                        "decision": outcome.record.latest.as_ref().map(|report| report.decision.clone()),
668                    }))
669                    .collect();
670                Ok(json!({ "looks": looks }))
671            }
672        }
673    }
674}