# Experiments

> Test variants of a feature against each other on a feature flag, with exposures, conversion, funnel, count, value and ratio metrics, Bayesian or frequentist results, a sample ratio check, holdouts and no-code web tests.

Source: https://apphelm.dev/docs/experiments

An experiment splits people between the variants of a [feature flag](https://apphelm.dev/docs/feature-flags), counts each person from the moment they are exposed, and compares what they do afterwards. When the result is clear you ship the winning variant, which sets the flag so everyone gets it.

An experiment always runs on a flag you already check in your code, so there is nothing extra to install. AppHelm needs two things from your app: the **exposure** (the person saw a variant) and the **metric events** (what they did next).

## How an experiment works

| Part | What it is |
| --- | --- |
| Flag | Splits people into variants. A multivariate flag gives one variant per arm; a boolean flag gives `on` and `off`. |
| Control | The variant called `control`, otherwise `off`, otherwise the flag's first variant. People outside the flag's rollout read `control` too, so they count in the control arm. |
| Exposure | The event that puts a person in the experiment: by default `apphelm.flag_evaluated`, which the SDKs send when your code reads the flag. |
| Metrics | Up to 6. The first is the **primary metric** the verdict is decided on; the rest are secondary. |
| Window | How long after their first exposure a person's events count: 1 to 2,160 hours, 168 (7 days) by default. Each metric can set its own. |
| Stats engine | Bayesian (the default) or frequentist. Both are always computed; the setting picks which one leads and decides the verdict. |

An experiment is `draft`, `running` or `stopped`. Only one experiment can run on a flag at a time.

## Create an experiment

### Create the flag
Open **Flags** and create a flag with the variants you want to compare, for example a multivariate flag `pricing-test` with variants `control` and `annual-first`. Set the rollout to the share of people who should take part. Multivariate flags need a plan that includes them; a boolean flag works on every plan and compares `on` with `off`.

### Read the flag where the difference shows
Check the flag in the code that renders the variant (see [Read the variant](#read-the-variant)). That read is what records the exposure.

### Create the experiment
Open **Experiments** and press **New experiment**. Choose the flag, write a hypothesis, and choose the primary metric, for example the conversion event `subscription_started`. Add secondary metrics if you need them. Press **Save draft**.

If you don't have a flag yet, **Create flag + experiment** makes a multivariate flag at 100% rollout and the experiment in one step.

### Size it
The calculator in the form estimates how many people each variant needs and how many days that takes, from the last 14 days of traffic. It assumes a two-sided 5% test with 80% power. Set a **minimum detectable effect** (the smallest relative lift you care about, `0.1` is 10%) and a planned end date.

### Start it
Press **Start**. If the flag is a draft or disabled, starting the experiment activates it. Results begin to fill in as people are exposed.

> **Nothing stops on its own:** The planned end date is a reminder, not a timer. After that date the results show a warning to stop or ship; the experiment keeps running until you act.

## Read the variant

Read the variant with the flag APIs you already use. For a flag a running experiment depends on, the read also records the exposure. The answer is the variant's key for a multivariate flag, `true` for an enabled boolean flag, and `false` for off, control, a holdout and any failure.

Next.js — app/pricing/page.tsx:
```tsx
"use client";
import { useFeatureFlagVariant } from "@sansavision/apphelm/react";

export default function Pricing() {
  const variant = useFeatureFlagVariant("pricing-test"); // reading records the exposure
  return variant === "annual-first" ? <AnnualFirst /> : <MonthlyFirst />;
}
```

React:
```tsx
import { useFeatureFlagVariant } from "@sansavision/apphelm/react";

function Pricing() {
  const variant = useFeatureFlagVariant("pricing-test"); // false until flags load
  return variant === "annual-first" ? <AnnualFirst /> : <MonthlyFirst />;
}
```

Vue / Nuxt — Pricing.vue (script setup):
```ts
import { useFeatureFlagVariant } from "@sansavision/apphelm/vue";

const variant = useFeatureFlagVariant("pricing-test"); // ComputedRef<string | boolean>
```

Svelte / SvelteKit — Pricing.svelte:
```ts
// `apphelm` is the object createApphelm() returned in your layout.
const variant = apphelm.featureFlagVariant("pricing-test"); // a store: use $variant in markup
```

JavaScript (browser):
```js
await analytics.flagsReady;
const variant = analytics.getFeatureFlag("pricing-test"); // "annual-first", true or false
```

React Native / Expo:
```ts
const variant = await mobile.getFeatureFlag("pricing-test"); // "annual-first", true or false
```

iOS (Swift):
```swift
let value = await apphelm.getFeatureFlag("pricing-test") // FlagValue: .variant("annual-first"), .enabled or .disabled
if value.variant == "annual-first" { showAnnualFirst() }
```

Android (Kotlin):
```kotlin
val variant = Apphelm.getFeatureFlag("pricing-test") // "annual-first", true or false; never blocks
```

Flutter:
```dart
final variant = apphelm.getFeatureFlag('pricing-test'); // 'annual-first', true, false or null
```

Node.js:
```ts
const variant = await apphelm.getFeatureFlag("pricing-test", user.id); // "annual-first", true or false
```

Python:
```python
# get_feature_flag records the exposure; is_enabled does not.
variant = apphelm.get_feature_flag("org_…", "prd_…", "pricing-test", user.id)
```

Java / Kotlin (JVM):
```kotlin
val variant = apphelm.person(user.id).getFeatureFlag("pricing-test") // blocking, fail-closed
```

Go:
```go
variant := client.GetFeatureFlag(ctx, "pricing-test", user.ID, nil) // "annual-first", true or false
```

Ruby:
```ruby
variant = APPHELM.get_feature_flag("pricing-test", user.id)
```

PHP:
```php
$variant = $apphelm->getFeatureFlag('pricing-test', (string) $user->id);
```

.NET (C#):
```csharp
var value = await apphelm.GetFeatureFlagAsync("pricing-test", user.Id);
if (value.Variant == "annual-first") ShowAnnualFirst();
```

Rust:
```rust
if let FlagValue::Variant(variant) = apphelm.get_feature_flag("pricing-test", &user.id, &FlagOptions::new()) {
    show_variant(&variant);
}
```

Elixir:
```elixir
variant = Apphelm.get_feature_flag("pricing-test", user.id) # "annual-first", true or false
```

HTTP (curl):
```bash
# Evaluating records no event. Send the exposure yourself:
curl -X POST https://apphelm.dev/api/v1/events \
  -H "Authorization: Bearer $APPHELM_API_KEY" -H "Content-Type: application/json" \
  --data '{"workspaceId":"org_…","productId":"prd_…","eventName":"apphelm.flag_evaluated","properties":{"distinct_id":"user-123","flag_key":"pricing-test","variant":"annual-first"}}'
```

## Exposures

A person enters the experiment at their **first** exposure event. Results count people, not reads, and only events after that first exposure (inside the window) count towards a metric.

When each SDK sends `apphelm.flag_evaluated`:

| Platform | Sent when | Sent once per |
| --- | --- | --- |
| Browser (and React, Vue, Svelte, Next.js) | The page first reads a flag with `isEnabled`, `getFeatureFlag`, `getFeatureFlagPayload` or the hooks. It does this for every flag, not only experiment flags, and needs analytics consent. Experiment flags also send `apphelm.experiment_exposed`. | Flag per page load (cleared by `reset()`) |
| Node, Go, Ruby, PHP, .NET, Rust, Elixir, JVM | `getFeatureFlag` or `isEnabled` reads a flag a running experiment uses | Flag, person and variant (the last 10,000 are remembered) |
| Python | `get_feature_flag` reads a flag a running experiment uses. `is_enabled` never sends one. | Flag, person and variant |
| React Native, Android, Flutter | `getFeatureFlag`, `isEnabled` or `isFeatureEnabled` reads a flag a running experiment uses. Payload reads send none. | Flag, variant and person |
| iOS | `getFeatureFlag` or `isEnabled` reads a flag a running experiment uses | Flag and variant per client |

Server, mobile and Flutter SDKs take a `sendExposure` (`send_exposure`) option to force the exposure on or off for one read. Browser flags always send it.

### Record an exposure yourself

Local evaluation never marks flags as experiment flags, so after deciding a flag in memory, or in any other way, record the exposure yourself:

Node.js:
```ts
const flags = await apphelm.localFlags({ productId: "prd_…" });
const row = await flags.evaluate("pricing-test", user.id);
await apphelm.recordExposure({ flagKey: "pricing-test", distinctId: user.id, variant: row.variant, enabled: row.enabled });
```

React Native / Expo:
```ts
mobile.recordExposure("pricing-test", "annual-first");
```

iOS (Swift):
```swift
apphelm.recordExposure(flagKey: "pricing-test", variant: "annual-first")
```

Android (Kotlin):
```kotlin
Apphelm.client?.recordExposure("pricing-test", "annual-first")
```

Flutter:
```dart
apphelm.recordExposure('pricing-test', 'annual-first');
```

Python:
```python
apphelm.record_exposure("org_…", "prd_…", "pricing-test", user.id, "annual-first")
```

Java / Kotlin (JVM):
```kotlin
apphelm.person(user.id).recordExposure("pricing-test", "annual-first")
```

Go:
```go
_ = client.RecordExposure("pricing-test", user.ID, "annual-first", true)
```

Ruby:
```ruby
APPHELM.record_exposure("pricing-test", user.id, "annual-first")
```

PHP:
```php
$apphelm->recordExposure('pricing-test', (string) $user->id, 'annual-first');
```

.NET (C#):
```csharp
apphelm.RecordExposure("pricing-test", user.Id, "annual-first");
```

Rust:
```rust
apphelm.record_exposure("pricing-test", &user.id, Some("annual-first"), true)?;
```

Elixir:
```elixir
Apphelm.record_exposure("pricing-test", user.id, "annual-first")
```

The browser SDK has no `recordExposure`: it records every flag the page reads.

### Choose the exposure event

In the experiment form, **Exposure** decides which event puts a person in:

- **When the product reads the flag**: `apphelm.flag_evaluated` (the default).
- **The experiment exposure event**: `apphelm.experiment_exposed`, which the browser sends only for experiment flags.
- **A custom event**, such as `pricing_page_viewed`. It must carry `flag_key` and `variant` properties.

Exposure events are never treated as autocapture, so turning autocapture off or sampling it never empties an experiment. They are ordinary events otherwise and count towards your event allowance.

## Metrics

Each metric is computed per exposed person, from events inside its window after their first exposure.

| Kind | In the form | Counts | Fields |
| --- | --- | --- | --- |
| `conversion` | Conversion: did they send an event | Share of people who sent the event | `event` |
| `funnel` | Funnel: did they finish steps in order | Share who completed every step in order | `steps` (2 to 5 events) |
| `count` | Count: events per person | Average number of events per person | `event` |
| `mean` | Value: a numeric property per person (revenue) | Average per-person sum of a numeric property | `event`, `property`, optional `winsorizePercentile` (0.9 to 0.9999) |
| `ratio` | Ratio: one total divided by another | Sum of the numerator over sum of the denominator | `numerator` and `denominator`, each `{ event, property? }` |

Every metric also takes an optional `name` and `windowHours`. Winsorising caps each person's value at that percentile of the people who have a value, so one very large order can't decide a revenue test.

Only events received live, or imported from a connected data source, count. Imported history from before the experiment never does.

Secondary metrics are exploratory. Their p-values are adjusted with Benjamini-Hochberg for the number of metrics, and the verdict is always decided on the primary metric.

## Results and statistics

Open an experiment to see each variant's people, metric value, lift against control and interval, and a verdict. The same analysis comes back as `analysis` from the API.

**Bayesian** (the default):

- Conversion and funnel metrics use a Beta-Binomial model with a uniform Beta(1, 1) prior. Counts use Gamma-Poisson with a Gamma(1, 1) prior. Values and ratios use a normal approximation (the delta method for ratios).
- Each variant gets a probability to be best, a chance to beat control, a 95% credible interval and an expected loss.
- The verdict is **significant** when every variant has at least 100 exposed people, the leader's probability to be best is at least 90%, and its expected loss is under 1% relative to control.

**Frequentist**:

- Conversion uses a two-proportion z-test with a Wilson 95% interval. Counts, values and ratios use Welch's t-test. The interval on relative lift uses the delta method.
- The verdict is **significant** when p < 0.05 and both the variant and control have at least 100 people. A significant negative lift reports control as the pick.

Priors and thresholds are fixed. There is no CUPED variance reduction and no sequential testing.

The verdict is one of:

| Verdict | Meaning |
| --- | --- |
| `waiting` | No exposures yet |
| `invalid` | Something makes the results untrustworthy, such as a sample ratio mismatch |
| `collecting` | Too few people to decide |
| `significant` | A variant is ahead by the engine's rule |
| `not_significant` | Enough people, no clear difference |

### Warnings

| Warning | When it shows | What to do |
| --- | --- | --- |
| `sample_ratio_mismatch` | The exposures don't match the configured split (chi-square p < 0.001) | One variant records its exposure differently, or fails before reading the flag. Fix that before trusting any result. |
| `minimum_sample` | A variant has fewer than 100 exposed people | Keep it running |
| `sample_size_not_reached` | Fewer people than the minimum detectable effect needs | Keep it running. Reading results before then inflates false positives. |
| `multiple_variants` | 1% or more of people were exposed to more than one variant | They are left out of the results. Make sure people are identified before the flag is read. |
| `no_control` | No control variant has exposures | Make sure control reads the flag too |
| `planned_end_passed` | The planned end date has passed | Stop or ship |

The sample ratio check runs when the flag's rollout gives each variant a known share. It is skipped when the flag has a segment, rules or an environment, and when fewer than two variants have a share.

> **Decide when you planned to:** Checking results every day and stopping the first time a variant looks ahead finds winners that aren't there. AppHelm doesn't correct for this. Set the minimum detectable effect and planned end date before you start, and decide then.

People exposed to more than one variant, people in the holdout, and variants the flag doesn't define are reported separately and never mixed into an arm.

## Holdouts

A holdout keeps a share of people out of **every** running experiment in a product, so you can measure the combined effect of everything you ship. It is set per product, from 1% to 50%.

- The same people are held out of every experiment: assignment is a hash of the product, the person's id and the holdout's salt, never the flag.
- People in the holdout read every running experiment's flag as off (`false`, reason `experiment_holdout`) and are reported as holdout people, not as control.
- Setting it to 0 turns it off. Raising it later keeps everyone who was already held out.
- It applies only to flags of running experiments, only to evaluations AppHelm makes. **Local evaluation on a server does not apply the holdout.**

Set it in the **Holdout** panel on the Experiments page, or through the API:

```bash
curl -X PUT https://apphelm.dev/api/v1/experiment-holdouts \
  -H "Authorization: Bearer $APPHELM_API_KEY" -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
  --data '{"productId":"prd_…","percent":5}'
```

## Stop or ship

- **Stop** ends the experiment and disables its flag, so everyone falls back to the off path. A stopped experiment can be started again; its results then measure from the restart.
- **Ship a variant** records the decision and sets the flag so everyone gets the winner. It needs a note saying why.

What shipping does to the flag:

| Flag and variant | Result |
| --- | --- |
| Multivariate, any variant | Active, 100% rollout, the winner at 100% and other variants at 0% |
| Boolean, `on` | Active at 100% |
| Any other variant, such as `off` or `control` | Disabled, rollout unchanged |

Targeting (segment, rules, environments) is kept. A shipped experiment can't be edited or restarted. When the rollout is complete, remove the losing code paths and archive the flag.

You can ship only an experiment that has run. While it runs, the flag's variants can't change and the flag can't be archived.

## Web experiments

For a page you can change without a deploy, a **redirect** or **visual** experiment applies variants in the browser from rules you set in AppHelm. Install the browser SDK and call `applyWebExperiments` as early as you can, with the client it created (with React, the client `useApphelm()` returns):

```ts
import { createBrowserSdk } from "@sansavision/apphelm/browser";
import { applyWebExperiments } from "@sansavision/apphelm/web-experiments";

const analytics = createBrowserSdk({ key: "ahl_pub_…", workspaceId: "org_…", productId: "prd_…" });
void applyWebExperiments(analytics, { key: "ahl_pub_…", productId: "prd_…" });
```

`applyWebExperiments` hides the page (for at most `antiFlickerMs`, 1,500 ms by default; 0 never hides it), loads the running web experiments and waits for flags. Then, for each experiment whose page rule matches the path, it reads the flag, which records the exposure, and:

- **Redirect** sends the variant to its URL with `location.replace`, keeping the query string and hash.
- **Visual** applies the variant's transforms to every element its CSS selector matches, now and as elements are added later: `text` (plain text, never HTML), `attributes`, `style` and `hidden`.

Off, control and holdout change nothing. The page rule is an exact path, or a prefix ending in `*`; none means every page.

| Option | Default | What it does |
| --- | --- | --- |
| `key` | required | The browser project key (`ahl_pub_…`). Its product decides which experiments load. |
| `endpoint` | `https://apphelm.dev` | Where to load the rules |
| `antiFlickerMs` | 1500 | How long the page may stay hidden |
| `experiments` | fetched | Pass the rules yourself instead of fetching them |

It returns `{ applied, redirectedTo, stop() }`. Limits: 10 variants, 20 transforms per variant, 10 attributes per transform, and 20 running web experiments per product. Event handler, `srcdoc` and `style` attributes, and `javascript:`, `data:` and `vbscript:` URLs are refused. There is no point-and-click editor: you enter selectors and changes in the form.

> **One transform per element:** Each element is changed by the first transform that matches it. If two transforms in a variant select the same element, the second is skipped, so combine them into one.

## API, MCP and CLI

Experiments are in the [API reference](https://apphelm.dev/docs/api) under Experiments. Reading needs a key with `experiments:read` (included by default); changing needs `experiments:write`, which you grant explicitly, on a workspace key whose creator is a member. Every change takes an `Idempotency-Key` header (8 to 160 characters).

| Endpoint | What it does |
| --- | --- |
| `GET /api/v1/experiments?productId=` | List experiments (up to 200), with the product's holdout. `analysis=false` skips results. |
| `POST /api/v1/experiments` | Create a draft |
| `GET /api/v1/experiments/{id}` | One experiment with its `analysis` |
| `PATCH /api/v1/experiments/{id}` | Change it. Changing metrics, exposure or window on a running experiment recomputes its results. |
| `POST /api/v1/experiments/{id}/launch` | Start it |
| `POST /api/v1/experiments/{id}/stop` | Stop it |
| `POST /api/v1/experiments/{id}/ship` | Ship `{ "variant": "…", "note": "…" }` |
| `GET` / `PUT /api/v1/experiment-holdouts` | Read or set the product's holdout |

```bash
curl -X POST https://apphelm.dev/api/v1/experiments \
  -H "Authorization: Bearer $APPHELM_API_KEY" -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
  --data '{"productId":"prd_…","flagId":"flg_…","name":"Annual plan first","hypothesis":"Showing annual first raises paid starts.",
           "metrics":[{"kind":"conversion","event":"subscription_started"},{"kind":"mean","event":"order_paid","property":"amount","winsorizePercentile":0.99}],
           "minimumDetectableEffect":0.1,"plannedEndAt":"2026-12-31"}'
```

A create needs a conversion event or at least one metric. There is no delete; stop an experiment you no longer need.

The [MCP server](https://apphelm.dev/docs/mcp) has `apphelm_list_experiments`, `apphelm_get_experiment_results`, `apphelm_create_experiment`, `apphelm_update_experiment`, `apphelm_launch_experiment`, `apphelm_stop_experiment` and `apphelm_ship_experiment_variant`. The [CLI](https://apphelm.dev/docs/cli) has `apphelm experiments list`, `get`, `results`, `launch`, `stop` and `ship <id> --variant <key> --note <why>`. Neither sets the holdout.

## Best practices

- **Read the flag where the variants differ.** An exposure on a page the person never reaches dilutes the result. In the browser every flag read is an exposure, so don't read experiment flags on screens that don't use them.
- **Identify before reading the flag.** A person who reads the flag as anonymous and again after sign-in under another id can land in two variants and is dropped from the results.
- **Pick one primary metric** and decide on it. Treat secondary metrics as hints.
- **Size the test first** with the calculator, then wait for the planned end date.
- **Treat a sample ratio warning as a bug.** It almost always means one variant fails or records its exposure differently.
- **Ship, then clean up.** Shipping sets the flag; remove the old code and archive the flag afterwards.

## Troubleshooting

| Symptom | Likely cause | What to do |
| --- | --- | --- |
| No people in the results | No exposures arrive: the flag is read with Python `is_enabled`, with local evaluation, or before consent in the browser | Use `get_feature_flag`, call `recordExposure` after local evaluation, and check analytics consent. Look for `apphelm.flag_evaluated` events in the event list. |
| Everyone is in control | The flag's rollout is low (people outside it read `control`), or the variant never matches your code | Check the rollout and that your code compares the exact variant keys |
| `sample_ratio_mismatch` | One variant loses exposures, for example it crashes or redirects before reading the flag | Read the flag before the variant's code runs, the same way in every variant |
| Many `multiple_variants` people | Ids change between reads | Call `identify` before reading the flag, with the same id on every device |
| Start fails with `flag_in_experiment` | Another experiment is running on the flag | Stop or ship it first |
| Start fails with `flag_archived` or `flag_killed` | The flag can't serve variants | Restore the flag, or use another one |
| Start fails with `web_config_incomplete` | A redirect test has no redirect URL, or a visual test has no transform | Add one to at least one variant |
| Ship fails with `experiment_not_started` | The experiment never ran | Start it first |
| A write answers 403 or 422 | The key lacks `experiments:write`, isn't a workspace key, or has no creator; or the `Idempotency-Key` header is missing | Create a workspace key with `experiments:write` and send an `Idempotency-Key` |
